dictionary.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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_DICTIONARY_H_
  5. #define EXECUTABLE_SEMANTICS_INTERPRETER_DICTIONARY_H_
  6. #include <list>
  7. #include <optional>
  8. #include <string>
  9. #include "executable_semantics/common/arena.h"
  10. #include "executable_semantics/interpreter/list_node.h"
  11. namespace Carbon {
  12. // A persistent dictionary with a simple implementation.
  13. // Copying the dictionary is O(1) time.
  14. template <class K, class V>
  15. class Dictionary {
  16. public:
  17. // Create an empty dictionary.
  18. Dictionary() { head = nullptr; }
  19. // Return the value associated with the given key.
  20. // Time complexity: O(n) where n is the number of times
  21. // any value has been set across all keys.
  22. auto Get(const K& key) -> std::optional<V> {
  23. for (auto kv : *this) {
  24. if (kv.first == key) {
  25. return kv.second;
  26. }
  27. }
  28. return std::nullopt;
  29. }
  30. // Associate the value v with key k in the dictionary.
  31. // Time complexity: O(1).
  32. auto Set(const K& k, const V& v) -> void {
  33. head = global_arena->New<ListNode<std::pair<K, V>>>(std::make_pair(k, v),
  34. head);
  35. }
  36. typedef ListNodeIterator<std::pair<K, V>> Iterator;
  37. // The position of the first element of the dictionary
  38. // or `end()` if the dictionary is empty.
  39. auto begin() const -> Iterator { return Iterator(head); }
  40. // The position one past that of the last element.
  41. auto end() const -> Iterator { return Iterator(nullptr); }
  42. private:
  43. Dictionary(ListNode<std::pair<K, V>>* h) : head(h) {}
  44. ListNode<std::pair<K, V>>* head;
  45. };
  46. } // namespace Carbon
  47. #endif // EXECUTABLE_SEMANTICS_INTERPRETER_DICTIONARY_H_