Repository navigation
Expand file tree
/
Copy pathStorage.cpp
More file actions
116 lines (95 loc) · 2.36 KB
/
Copy pathStorage.cpp
File metadata and controls
116 lines (95 loc) · 2.36 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
// borrowed from https://github.com/fragglet/DoomEd (Simon Howard)
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "Storage.h"
void Storage::addElement(void *anElement)
{
// Equivalent to insert at the end:
insertElement(anElement, elements);
}
unsigned int Storage::count()
{
return elements;
}
const char *Storage::description()
{
return _description;
}
void *Storage::elementAt(unsigned int index)
{
if (index >= elements)
{
return NULL;
}
return data + elementSize * index;
}
void Storage::empty()
{
elements = 0;
}
void Storage::dealloc()
{
free(data);
data = NULL;
}
Storage * Storage::initCount(unsigned int count,
unsigned int elementSizeInBytes,
const char *description)
{
Storage * storage = (Storage *)malloc(sizeof(*storage));
if ( storage == NULL )
printf("failed to allocate Storage (%s)\n", description);
storage->_description = description;
storage->elementSize = elementSizeInBytes;
storage->elements = count;
if ( count != 0 ) {
storage->data = (uint8_t *)calloc(count, elementSizeInBytes);
} else {
storage->data = NULL;
}
return storage;
}
void Storage::insertElement(void *anElement, unsigned int index)
{
// Sanity check insert range; a maximum value of 'elements' is
// okay to insert at the end of the array.
if (index > elements)
{
return;
}
// Increase array size and move the latter part of the array
// down by one.
if ( elements == 0 ) {
data = (uint8_t *)malloc(elementSize);
} else {
data = (uint8_t *)realloc(data, elementSize * (elements + 1));
}
memmove(data + elementSize * (index + 1),
data + elementSize * index,
elementSize * (elements - index));
// Copy in the new element.
memmove(data + elementSize * index, anElement, elementSize);
++elements;
}
void Storage::removeElementAt(unsigned int index)
{
if (index >= elements)
{
return;
}
// Move latter half of array down towards the start, and decrement
// the array size.
memmove(data + elementSize * index,
data + elementSize * (index + 1),
elementSize * (elements - index - 1));
--elements;
}
void Storage::replaceElementAt(unsigned int index, void *anElement)
{
if (index >= elements)
{
return;
}
memmove(data + elementSize * index, anElement, elementSize);
}