dictionary.h 1.8 KB

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