about summary refs log tree commit diff stats
path: root/WWW/Library/Implementation/HTChunk.c
blob: fc46ac4a21169ecaa805d5bec2a53e1e97890177 (plain) (blame)
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
/*		Chunk handling:	Flexible arrays
**		===============================
**
*/

#include "HTUtils.h"
#include "HTChunk.h"
/*#include <stdio.h> included by HTUtils.h -- FM */

#include "LYLeaks.h"

#define FREE(x) if (x) {free(x); x = NULL;}

/*	Create a chunk with a certain allocation unit
**	--------------
*/
PUBLIC HTChunk * HTChunkCreate ARGS1 (int,grow)
{
    HTChunk * ch = (HTChunk *) calloc(1, sizeof(HTChunk));
    if (ch == NULL)
        outofmem(__FILE__, "creation of chunk");

    ch->data = 0;
    ch->growby = grow;
    ch->size = 0;
    ch->allocated = 0;
    return ch;
}


/*	Clear a chunk of all data
**	--------------------------
*/
PUBLIC void HTChunkClear ARGS1 (HTChunk *,ch)
{
    FREE(ch->data);
    ch->size = 0;
    ch->allocated = 0;
}


/*	Free a chunk
**	------------
*/
PUBLIC void HTChunkFree ARGS1 (HTChunk *,ch)
{
    FREE(ch->data);
    FREE(ch);
}


/*	Append a character
**	------------------
*/
PUBLIC void HTChunkPutc ARGS2 (HTChunk *,ch, char,c)
{
    if (ch->size >= ch->allocated) {
	ch->allocated = ch->allocated + ch->growby;
        ch->data = ch->data ? (char *)realloc(ch->data, ch->allocated)
			    : (char *)calloc(1, ch->allocated);
      if (!ch->data)
          outofmem(__FILE__, "HTChunkPutc");
    }
    ch->data[ch->size++] = c;
}


/*	Ensure a certain size
**	---------------------
*/
PUBLIC void HTChunkEnsure ARGS2 (HTChunk *,ch, int,needed)
{
    if (needed <= ch->allocated) return;
    ch->allocated = needed-1 - ((needed-1) % ch->growby)
    			     + ch->growby; /* Round up */
    ch->data = ch->data ? (char *)realloc(ch->data, ch->allocated)
			: (char *)calloc(1, ch->allocated);
    if (ch->data == NULL)
        outofmem(__FILE__, "HTChunkEnsure");
}


/*	Terminate a chunk
**	-----------------
*/
PUBLIC void HTChunkTerminate ARGS1 (HTChunk *,ch)
{
    HTChunkPutc(ch, (char)0);
}


/*	Append a string
**	---------------
*/
PUBLIC void HTChunkPuts ARGS2 (HTChunk *,ch, CONST char *,s)
{
    CONST char * p;
    for (p=s; *p; p++)
        HTChunkPutc(ch, *p);
}