list_node.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef EXECUTABLE_SEMANTICS_INTERPRETER_LIST_NODE_H_
  5. #define EXECUTABLE_SEMANTICS_INTERPRETER_LIST_NODE_H_
  6. namespace Carbon {
  7. template <class T>
  8. struct ListNode {
  9. ListNode(T e, ListNode* n) : curr(e), next(n) {}
  10. const T curr;
  11. ListNode* const next;
  12. // ListNode cells are part of a "persistent data structure" and are thus
  13. // immutable.
  14. ListNode& operator=(const ListNode&) = delete;
  15. ListNode& operator=(ListNode&&) = delete;
  16. };
  17. // A forward iterator over elements of a `ListNode` list.
  18. template <class T>
  19. struct ListNodeIterator {
  20. using value_type = T;
  21. using difference_type = std::ptrdiff_t;
  22. using pointer = const T*;
  23. using reference = const T&;
  24. using iterator_category = std::forward_iterator_tag;
  25. ListNodeIterator(ListNode<T>* x) : p(x) {}
  26. ListNodeIterator(const ListNodeIterator& iter) : p(iter.p) {}
  27. ListNodeIterator& operator++() {
  28. p = p->next;
  29. return *this;
  30. }
  31. ListNodeIterator operator++(int) {
  32. ListNodeIterator tmp(*this);
  33. operator++();
  34. return tmp;
  35. }
  36. bool operator==(const ListNodeIterator& rhs) const { return p == rhs.p; }
  37. bool operator!=(const ListNodeIterator& rhs) const { return p != rhs.p; }
  38. const T& operator*() { return p->curr; }
  39. const T* operator->() { return &p->curr; }
  40. private:
  41. ListNode<T>* p;
  42. };
  43. template <class T>
  44. auto Length(ListNode<T>* ls) -> unsigned int {
  45. if (ls) {
  46. return 1 + Length(ls->next);
  47. } else {
  48. return 0;
  49. }
  50. }
  51. } // namespace Carbon
  52. #endif // EXECUTABLE_SEMANTICS_INTERPRETER_LIST_NODE_H_