git.iko.soy/rowtype-yoga/purescript-native
on cpp help sign in
91 lines 2.7 kB history raw
1///////////////////////////////////////////////////////////////////////////////
2//
3// Module : dictionary.h
4// Copyright : (c) Andy Arvanitis 2018
5// License : BSD
6//
7// Maintainer : Andy Arvanitis
8// Stability : experimental
9// Portability :
10//
11// A simple dictionary optimized for this runtime's particular use –
12// *not* intended for general use or as a replacement for containers
13// such as std::map or std::unordered_map. It relies on the following
14// assumptions:
15//
16// 1) Keys are C-type string literals. No copying or (memory management)
17// of the keys occurs
18// 2) The number of elements in the container is generally small – say,
19// under 20. There is no sorting and a linear search is used to
20// locate elements
21//
22///////////////////////////////////////////////////////////////////////////////
23//
24#ifndef purescript_dictionary_H
25#define purescript_dictionary_H
27#include <cstring>
28#include <vector>
29#include <utility>
30#if !defined(NDEBUG)
31#include <string>
32#endif
34namespace purescript {
35 namespace _template_ {
37 template <typename T>
38 class dict_t : public std::vector<std::pair<const char *, T>> {
40 static auto null() -> const T& {
41 static const T value;
42 return value;
43 }
45 public:
46 using std::vector<std::pair<const char *, T>>::vector;
48 auto operator[](const char key[]) const -> const T& {
49 for (auto it = this->cbegin(), end=this->cend(); it != end; it++) {
50 const auto& elem_key = it->first;
51 if (elem_key == key || !std::strcmp(elem_key, key)) {
52 return it->second;
53 }
54 }
55#if !defined(NDEBUG) && !defined(PURESCRIPT_DISABLE_EXCEPTIONS)
56 throw std::runtime_error("dictionary key \"" + std::string(key) + "\" not found");
57#endif
58 return null();
59 }
61 auto at(const char key[]) const -> const T& {
62 return (*this)[key];
63 }
65 auto operator[](const char key[]) -> T& {
66 const auto end = this->end();
67 for (auto it = this->begin(); it != end; it++) {
68 const auto& elem_key = it->first;
69 if (elem_key == key || !std::strcmp(elem_key, key)) {
70 return it->second;
71 }
72 }
73 return this->emplace(end, key, T())->second;
74 }
76 auto contains(const char key[]) const -> bool {
77 for (auto it = this->cbegin(), end=this->cend(); it != end; it++) {
78 const auto& elem_key = it->first;
79 if (elem_key == key || !std::strcmp(elem_key, key)) {
80 return true;
81 }
82 }
83 return false;
84 }
86 };
88 } // namespace _template_
89} // namespace purescript
91#endif // purescript_dictionary_H