-
Notifications
You must be signed in to change notification settings - Fork 302
/
extendablebuffer.c
132 lines (116 loc) · 2.63 KB
/
extendablebuffer.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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <string.h>
#include "extendablebuffer.h"
#include "utils.h"
int ExtendableBuffer_Init(ExtendableBuffer *eb, _32BIT_UINT InitSize, _32BIT_INT GuardSize)
{
if( eb == NULL )
{
return 0;
}
if( InitSize == 0 )
{
eb -> Data = NULL;
} else {
eb -> Data = SafeMalloc(InitSize);
if( eb -> Data == NULL )
{
return -1;
}
}
eb -> InitialSize = InitSize;
eb -> GuardSize = GuardSize;
eb -> Allocated = InitSize;
eb -> Used = 0;
return 0;
}
BOOL ExtendableBuffer_GuarantyLeft(ExtendableBuffer *eb, _32BIT_UINT GuarantiedSize)
{
if( eb == NULL )
{
return FALSE;
}
if( eb -> Allocated - eb -> Used >= GuarantiedSize)
{
return TRUE;
} else {
if( eb -> GuardSize > 0 && eb -> Allocated > eb -> GuardSize )
{
return FALSE;
} else {
int NewSize = eb -> Allocated + ((eb -> Allocated / 2) > GuarantiedSize ? (eb -> Allocated / 2) : GuarantiedSize);
if( SafeRealloc((void **)&(eb -> Data), NewSize) != 0 )
{
return FALSE;
} else {
eb -> Allocated = NewSize;
return TRUE;
}
}
}
}
char *ExtendableBuffer_Expand(ExtendableBuffer *eb, _32BIT_UINT ExpandedSize)
{
if( ExtendableBuffer_GuarantyLeft(eb, ExpandedSize) == TRUE )
{
int OldUsed = eb -> Used;
eb -> Used += ExpandedSize;
return (char *)(eb -> Data + OldUsed);
} else {
return NULL;
}
}
/* Offset returned */
_32BIT_INT ExtendableBuffer_Add(ExtendableBuffer *eb, const char *Data, _32BIT_UINT DataLength)
{
volatile char *Here;
if( eb == NULL )
{
return -1;
}
Here = ExtendableBuffer_Expand(eb, DataLength);
if( Here == NULL )
{
return -1;
}
memcpy((void *)Here, (const void *)Data, DataLength);
return (char *)Here - ExtendableBuffer_GetData(eb);
}
char *ExtendableBuffer_Eliminate(ExtendableBuffer *eb, _32BIT_UINT Start, _32BIT_UINT Length)
{
if( eb == NULL )
{
return NULL;
}
memmove((void *)(eb -> Data + Start), (const void *)(eb -> Data + Start + Length), eb -> Used - Start - Length);
eb -> Used -= Length;
return (char *)(eb -> Data);
}
void ExtendableBuffer_Reset(ExtendableBuffer *eb)
{
if( eb != NULL )
{
if( eb -> GuardSize > 0 && eb -> Allocated > eb -> GuardSize )
{
if( eb -> InitialSize == 0 )
{
SafeFree((void *)(eb -> Data));
eb -> Data = NULL;
} else {
if( SafeRealloc((void **)&(eb -> Data), eb -> InitialSize) != 0 )
{
return;
}
}
eb -> Allocated = eb -> InitialSize;
}
eb -> Used = 0;
}
}
void ExtendableBuffer_Free(ExtendableBuffer *eb)
{
if( eb != NULL )
{
SafeFree((void *)(eb -> Data));
eb -> Data = NULL;
}
}