-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.c
63 lines (62 loc) · 2.07 KB
/
list.c
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
#include <stdlib.h>
#include <string.h>
#include "list.h"
Element ARRAYLIST_Get(PARRAYLIST list, int index){
Element element=(Element) malloc(list->ElementSize);
memcpy(element,list->Pointer+(list->ElementSize*index),list->ElementSize);
return element;
}
void ARRAYLIST_Set(PARRAYLIST list, int index, Element element){
if (list->Capacity<=index){
ARRAYLIST_Reset(list,index+1);
}
if (index>list->Position){
list->Position+=index+1;
memcpy(list->Pointer-4,&list->Position,4);
}
memcpy(list->Pointer+(list->ElementSize*index),element,list->ElementSize);
}
void ARRAYLIST_Add(PARRAYLIST list, Element element){
if (list->Capacity<=list->Position){
ARRAYLIST_Reset(list,list->Capacity*2);
}
memcpy(list->Pointer+(list->ElementSize*list->Position),element,list->ElementSize);
list->Position++;
memcpy(list->Pointer-4,&list->Position,4);
}
PARRAYLIST AllocArrayList(int InitialSize, void* InitialData, int ElementSize){
PARRAYLIST list=(PARRAYLIST) malloc(sizeof(ARRAYLIST));
if (InitialData==NULL){
Element Pointer=(Element) malloc(InitialSize*ElementSize);
memset(Pointer,0,InitialSize*ElementSize);\
list->Pointer=Pointer+4;
list->Position=0;
list->SelfAllocated=BOOL_TRUE;
} else{
int Position=0;
memcpy(&Position,InitialData,4);
list->Pointer=InitialData+4;
list->Position=Position;
list->SelfAllocated=BOOL_FALSE;
}
list->ElementSize=ElementSize;
list->Capacity=InitialSize;
list->Get=ARRAYLIST_Get;
list->Set=ARRAYLIST_Set;
list->Add=ARRAYLIST_Add;
return list;
}
void ARRAYLIST_Reset(PARRAYLIST list, int capacity){
Element Pointer=(Element) malloc(capacity*list->ElementSize);
memset(Pointer,0,capacity*list->ElementSize);
memcpy(Pointer,list->Pointer,list->Capacity*list->ElementSize);
free(list->Pointer);
list->Capacity=capacity;
list->Pointer=Pointer;
}
void FreeArrayList(PARRAYLIST list){
if (list->SelfAllocated==BOOL_TRUE){
free(list->Pointer);
}
free(list);
}