edits
[iotcloud.git] / version2 / src / C / array.h
1 #ifndef ARRAY_H
2 #define ARRAY_H
3 #include <inttypes.h>
4 #include "common.h"
5
6 typedef uint32_t uint;
7
8 template<typename type>
9 class Array {
10 public:
11         Array() :
12                 array(NULL),
13                 size(0) {
14         }
15
16         Array(uint32_t _size) :
17                 array((type *) ourcalloc(1, sizeof(type) * _size)),
18                 size(_size)
19         {
20         }
21
22         Array(type *_array, uint _size) :
23                 array((type *) ourmalloc(sizeof(type) * _size)),
24                 size(_size) {
25                 memcpy(array, _array, _size * sizeof(type));
26         }
27
28         Array(Array<type> *_array) :
29                 array((type *) ourmalloc(sizeof(type) * _array->size)),
30                 size(_array->size) {
31                 memcpy(array, _array->array, size * sizeof(type));
32         }
33
34         void init(uint _size) {
35                 array = (type *) ourcalloc(1, sizeof(type) * _size);
36                 size = _size;
37         }
38
39         void init(type *_array, uint _size) {
40                 array = (type *) ourmalloc(sizeof(type) * _size);
41                 size = _size;
42                 memcpy(array, _array, _size * sizeof(type));
43         }
44
45         void init(Array<type> *_array) {
46                 array = (type *) ourmalloc(sizeof(type) * _array->size);
47                 size = _array->size;
48                 memcpy(array, _array->array, size * sizeof(type));
49         }
50
51         ~Array() {
52                 if (array)
53                         ourfree(array);
54         }
55
56         bool equals(Array<type> * _array) {
57                 if (_array->size != size)
58                         return false;
59                 int cmp=memcmp(array, _array->array, size * sizeof(type));
60                 return cmp == 0;
61         }
62         
63         type get(uint index) const {
64                 return array[index];
65         }
66
67         void set(uint index, type item) {
68                 array[index] = item;
69         }
70
71         uint length() const {
72                 return size;
73         }
74
75         type *internalArray() {
76                 return array;
77         }
78
79 private:
80         type *array;
81         uint size;
82 };
83
84 template<typename type>
85 void System_arraycopy(Array<type> * src, int32_t srcPos, Array<type> *dst, int32_t dstPos, int32_t len) {
86         if (srcPos + len > src->length() ||
87                         dstPos + len > dst->length())
88                 ASSERT(0);
89         uint bytesToCopy = len * sizeof(type);
90         memcpy(&dst->internalArray()[dstPos], &src->internalArray()[srcPos], bytesToCopy);
91 }
92 #endif