forked from alex-agency/hydroponics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleMap.h
More file actions
133 lines (118 loc) · 2.69 KB
/
SimpleMap.h
File metadata and controls
133 lines (118 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#ifndef SIMPLEMAP_H
#define SIMPLEMAP_H
#include <string.h>
template<typename K>
struct defcmp {
bool operator()(const K& k1, const K& k2) {
return k1 == k2;
}
};
template<typename K, typename V, uint8_t capacity, typename comparator = defcmp<K> >
class SimpleMap
{
public:
/**
* Initialize map
*/
SimpleMap() {
currentIndex = 0;
}
/**
* Get the size of this map
*/
uint8_t size() const {
return currentIndex;
}
/**
* Get a key at a specified index
*/
K keyAt(uint8_t idx) {
return keys[idx];
}
/**
* Get a value at a specified index
*/
V valueAt(uint8_t idx) {
return values[idx];
}
/**
* Check if a new assignment will overflow this map
*/
bool willOverflow() {
return (currentIndex + 1 > capacity);
}
/**
* An indexer for accessing and assigning a value to a key
* If a key is used that exists, it returns the value for that key
* If there exists no value for that key, the key is added
*/
V& operator[](const K& key) {
if ( contains(key) ) {
return values[indexOf(key)];
}
else if (currentIndex < capacity) {
keys[currentIndex] = key;
values[currentIndex] = nil;
currentIndex++;
return values[currentIndex - 1];
}
return nil;
}
/**
* Get the index of a key
*/
unsigned int indexOf(K key) {
for (int i = 0; i < currentIndex; i++) {
if ( cmp(key, keys[i]) ) {
return i;
}
}
return -1;
}
/**
* Check if a key is contained within this map
*/
bool contains(K key) {
for (int i = 0; i < currentIndex; i++) {
if ( cmp(key, keys[i]) ) {
return true;
}
}
return false;
}
/**
* Check if a key is contained within this map
*/
void remove(K key) {
int index = indexOf(key);
if ( contains(key) ) {
for (uint8_t i = index; i < capacity - 1; i++) {
keys[i] = keys[i + 1];
values[i] = values[i + 1];
}
currentIndex--;
}
}
void setNullValue(V nullv) {
nil = nullv;
}
/*const char* toString() const {
static char buffer[30];
strcpy(buffer, "{");
for(uint8_t i=0; i<currentIndex; i++) {
if (i > 0) {
strcat(buffer, PSTR(", "));
}
snprintf_P(buffer,sizeof(buffer),PSTR("%s?=%d"),buffer, values[i]);
}
strcat(buffer, PSTR("}"));
return buffer;
}*/
private:
K keys[capacity];
V values[capacity];
V nil;
uint8_t currentIndex;
comparator cmp;
};
#endif // __SIMPLEMAP_H__