b9d719628c41c2ad9c90990e034c881c5a8042e3
[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         type get(uint index) const {
57                 return array[index];
58         }
59
60         void set(uint index, type item) {
61                 array[index] = item;
62         }
63
64         uint length() const {
65                 return size;
66         }
67
68         type *internalArray() {
69                 return array;
70         }
71
72 private:
73         type *array;
74         uint size;
75 };
76
77 template<typename type>
78 void System_arraycopy(Array<type> * src, int32_t srcPos, Array<type> *dst, int32_t dstPos, int32_t len) {
79         if (srcPos + len > src->length() ||
80                         dstPos + len > dst->length())
81                 ASSERT(0);
82         uint bytesToCopy = len * sizeof(type);
83         memcpy(&dst->internalArray()[dstPos], &src->internalArray()[srcPos], bytesToCopy);
84 }
85 #endif