Add HMAC
[iotcloud.git] / version2 / src / C / IoTString.h
1 #ifndef IOTSTRING_H
2 #define IOTSTRING_H
3
4 #include "array.h"
5 #include <string.h>
6 /**
7  * IoTString wraps the underlying char string.
8  * @author Brian Demsky <bdemsky@uci.edu>
9  * @version 1.0
10  */
11
12 inline int hashCharArray(Array<char> *array) {
13         uint len = array->length();
14         int hash = 0;
15         for (uint i = 0; i < len; i++) {
16                 hash = 31 * hash + array->get(i);
17         }
18         return hash;
19 }
20
21 class IoTString {
22 private:
23         Array<char> *array;
24         IoTString() {}
25         int hashvalue;
26         /**
27          * Builds an IoTString object around the char array.  This
28          * constructor makes a copy, so the caller is free to modify the char array.
29          */
30
31 public:
32         IoTString(Array<char> *_array) :
33                 array(new Array<char>(_array)),
34                 hashvalue(hashCharArray(array)) {
35         }
36
37         IoTString(const char *_array) {
38                 int32_t len = strlen(_array);
39                 array = new Array<char>(len);
40                 strcpy(array->internalArray(), _array);
41                 hashvalue = hashCharArray(array);
42         }
43
44         IoTString(IoTString *string) :
45                 array(new Array<char>(string->array)),
46                 hashvalue(hashCharArray(array)) {
47         }
48
49         ~IoTString() {
50                 delete array;
51         }
52
53         /**
54          * Internal method to grab a reference to our char array.  Caller
55          * must not modify it.
56          */
57
58         Array<char> *internalBytes() { return array; }
59
60         /**
61          * Returns a copy of the underlying char string.
62          */
63
64         Array<char> *getBytes() { return new Array<char>(array); }
65
66         /**
67          * Returns the length in chars of the IoTString.
68          */
69
70         bool equals(IoTString *str) {
71                 uint strlength = str->array->length();
72                 uint thislength = array->length();
73                 if (strlength != thislength)
74                         return false;
75
76                 int result = memcmp(str->array->internalArray(), array->internalArray(), strlength);
77                 return result == 0;
78         }
79
80         int hashValue() { return hashvalue;}
81         int length() { return array->length(); }
82         friend IoTString *IoTString_shallow(Array<char> *_array);
83 };
84
85 inline IoTString *IoTString_shallow(Array<char> *_array) {
86         IoTString *str = new IoTString();
87         str->array = _array;
88         return str;
89 }
90
91 inline int hashString(IoTString *a) {
92         return a->hashValue();
93 }
94
95 inline bool StringEquals(IoTString *a, IoTString *b) {
96         return a->equals(b);
97 }
98 #endif