map.hpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #pragma once
  2. #include <nall/set.hpp>
  3. namespace nall {
  4. template<typename T, typename U> struct map {
  5. struct node_t {
  6. T key;
  7. U value;
  8. node_t() = default;
  9. node_t(const T& key) : key(key) {}
  10. node_t(const T& key, const U& value) : key(key), value(value) {}
  11. auto operator< (const node_t& source) const -> bool { return key < source.key; }
  12. auto operator==(const node_t& source) const -> bool { return key == source.key; }
  13. };
  14. auto find(const T& key) const -> maybe<U&> {
  15. if(auto node = root.find({key})) return node().value;
  16. return nothing;
  17. }
  18. auto insert(const T& key, const U& value) -> void { root.insert({key, value}); }
  19. auto remove(const T& key) -> void { root.remove({key}); }
  20. auto size() const -> unsigned { return root.size(); }
  21. auto reset() -> void { root.reset(); }
  22. auto begin() -> typename set<node_t>::iterator { return root.begin(); }
  23. auto end() -> typename set<node_t>::iterator { return root.end(); }
  24. auto begin() const -> const typename set<node_t>::iterator { return root.begin(); }
  25. auto end() const -> const typename set<node_t>::iterator { return root.end(); }
  26. protected:
  27. set<node_t> root;
  28. };
  29. template<typename T, typename U> struct bimap {
  30. auto find(const T& key) const -> maybe<U&> { return tmap.find(key); }
  31. auto find(const U& key) const -> maybe<T&> { return umap.find(key); }
  32. auto insert(const T& key, const U& value) -> void { tmap.insert(key, value); umap.insert(value, key); }
  33. auto remove(const T& key) -> void { if(auto p = tmap.find(key)) { umap.remove(p().value); tmap.remove(key); } }
  34. auto remove(const U& key) -> void { if(auto p = umap.find(key)) { tmap.remove(p().value); umap.remove(key); } }
  35. auto size() const -> unsigned { return tmap.size(); }
  36. auto reset() -> void { tmap.reset(); umap.reset(); }
  37. auto begin() -> typename set<typename map<T, U>::node_t>::iterator { return tmap.begin(); }
  38. auto end() -> typename set<typename map<T, U>::node_t>::iterator { return tmap.end(); }
  39. auto begin() const -> const typename set<typename map<T, U>::node_t>::iterator { return tmap.begin(); }
  40. auto end() const -> const typename set<typename map<T, U>::node_t>::iterator { return tmap.end(); }
  41. protected:
  42. map<T, U> tmap;
  43. map<U, T> umap;
  44. };
  45. }