exip  Alpha 0.5.4
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
dynamicArray.c
Go to the documentation of this file.
1 /*==================================================================*\
2 | EXIP - Embeddable EXI Processor in C |
3 |--------------------------------------------------------------------|
4 | This work is licensed under BSD 3-Clause License |
5 | The full license terms and conditions are located in LICENSE.txt |
6 \===================================================================*/
7 
18 #include "dynamicArray.h"
19 #include "memManagement.h"
20 
21 errorCode createDynArray(DynArray* dynArray, size_t entrySize, uint16_t chunkEntries)
22 {
23  void** base = (void **)(dynArray + 1);
24  Index* count = (Index*)(base + 1);
25 
26  *base = EXIP_MALLOC(entrySize*chunkEntries);
27  if(*base == NULL)
29 
30  dynArray->entrySize = entrySize;
31  *count = 0;
32  dynArray->chunkEntries = chunkEntries;
33  dynArray->arrayEntries = chunkEntries;
34 
35  return EXIP_OK;
36 }
37 
39 {
40  void** base;
41  Index* count;
42 
43  if(dynArray == NULL)
44  return EXIP_NULL_POINTER_REF;
45 
46  base = (void **)(dynArray + 1);
47  count = (Index*)(base + 1);
48  if(dynArray->arrayEntries == *count) // The dynamic array must be extended first
49  {
50  size_t addedEntries;
51 
52  addedEntries = (dynArray->chunkEntries == 0)?DEFAULT_NUMBER_CHUNK_ENTRIES:dynArray->chunkEntries;
53 
54  if(*base == NULL)
55  {
56  *base = EXIP_MALLOC(dynArray->entrySize * addedEntries);
57  if(*base == NULL)
59  }
60  else
61  {
62  *base = EXIP_REALLOC(*base, dynArray->entrySize * (*count + addedEntries));
63  if(*base == NULL)
65  }
66 
67  dynArray->arrayEntries = dynArray->arrayEntries + addedEntries;
68  }
69 
70  *entry = (void*)((unsigned char *)(*base) + (*count * dynArray->entrySize));
71 
72  *entryID = *count;
73 
74  *count += 1;
75  return EXIP_OK;
76 }
77 
79 {
80  errorCode tmp_err_code;
81  void *emptyEntry;
82 
83  TRY(addEmptyDynEntry(dynArray, &emptyEntry, entryID));
84 
85  memcpy(emptyEntry, entry, dynArray->entrySize);
86  return EXIP_OK;
87 }
88 
90 {
91  void** base;
92  Index* count;
93 
94  if(dynArray == NULL)
95  return EXIP_NULL_POINTER_REF;
96 
97  base = (void **)(dynArray + 1);
98  count = (Index*)(base + 1);
99 
100  if(entryID == *count - 1)
101  {
102  *count -= 1;
103  }
104  else if(*count - 1 - entryID >= 0)
105  {
106  /* Shuffle the array down to fill the removed entry */
107  memcpy(((unsigned char *)*base) + entryID * dynArray->entrySize,
108  ((unsigned char *)*base) + entryID * dynArray->entrySize + dynArray->entrySize,
109  (*count - 1 - entryID) * dynArray->entrySize);
110  *count -= 1;
111  }
112  else
114 
115  return EXIP_OK;
116 }
117 
119 {
120  void** base = (void **)(dynArray + 1);
121  EXIP_MFREE(*base);
122 }