-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedMap.h
107 lines (85 loc) · 2.29 KB
/
LinkedMap.h
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
#ifndef OTF_LINKEDMAP_H
#define OTF_LINKEDMAP_H
#include <Arduino.h>
#define KEY_MAX_LENGTH 100
namespace OTF {
template<class T>
class LinkedMapNode;
template<class T>
class LinkedMap {
friend class OpenThingsFramework;
friend class Response;
private:
LinkedMapNode<T> *head = nullptr;
LinkedMapNode<T> *tail = nullptr;
void _add(LinkedMapNode<T> *node) {
if (head == nullptr) {
head = node;
tail = head;
} else {
tail->next = node;
tail = tail->next;
}
}
T _find(const char *key, bool keyInFlash = false) const {
LinkedMapNode<T> *node = head;
while (node != nullptr) {
if ((keyInFlash ? strcmp_P(node->key, key) : strcmp(node->key, key)) == 0) {
return node->value;
}
node = node->next;
}
// Indicate the key could not be found.
return nullptr;
}
public:
~LinkedMap() {
LinkedMapNode<T> *node = head;
while (node != nullptr) {
LinkedMapNode<T> *next = node->next;
delete node;
node = next;
}
}
void add(const char *key, T value) {
_add(new LinkedMapNode<T>(key, value));
}
void add(const __FlashStringHelper *key, T value) {
_add(new LinkedMapNode<T>(key, value));
}
T find(const __FlashStringHelper *key) const {
return _find((char *) key, true);
}
T find(const char *key) const {
return _find(key, false);
}
};
template<class T>
class LinkedMapNode {
private:
/** Indicates if the key was copied into RAM from flash memory and needs to be freed when the object is destroyed. */
bool keyFromFlash = false;
public:
const char *key = nullptr;
T value;
LinkedMapNode<T> *next = nullptr;
LinkedMapNode(const __FlashStringHelper *key, T value) {
keyFromFlash = true;
char *_key = new char[KEY_MAX_LENGTH];
strncpy_P(_key, (char *) key, KEY_MAX_LENGTH);
this->key = (const char *) _key;
this->value = value;
}
LinkedMapNode(const char *key, T value) {
this->key = key;
this->value = value;
}
~LinkedMapNode() {
// Delete the key if it was copied into RAM from flash memory.
if (keyFromFlash) {
delete key;
}
}
};
}// namespace OTF
#endif