First attempt at debianization
[erwise] / Cl / WWWLibrary / HTChunk.c
1 /*              Chunk handling: Flexible arrays
2 **              ===============================
3 **
4 */
5
6 #include "HTUtils.h"
7 #include "HTChunk.h"
8 #include <stdio.h>
9 /*      Create a chunk with a certain allocation unit
10 **      --------------
11 */
12 PUBLIC HTChunk * HTChunkCreate ARGS1 (int,grow)
13 {
14     HTChunk * ch = (HTChunk *) malloc(sizeof(HTChunk));
15     if (!ch) return 0;
16     ch->data = 0;
17     ch->growby = grow;
18     ch->size = 0;
19     ch->allocated = 0;
20     return ch;
21 }
22
23
24 /*      Clear a chunk of all data
25 **      --------------------------
26 */
27 PUBLIC void HTChunkClear ARGS1 (HTChunk *,ch)
28 {
29     if (ch->data) {
30         free(ch->data);
31         ch->data = 0;
32     }
33     ch->size = 0;
34     ch->allocated = 0;
35 }
36
37
38 /*      Append a character
39 **      ------------------
40 */
41 PUBLIC void HTChunkPutc ARGS2 (HTChunk *,ch, char,c)
42 {
43     if (ch->size >= ch->allocated) {
44         ch->allocated = ch->allocated + ch->growby;
45         ch->data = ch->data ? (char *)realloc(ch->data, ch->allocated)
46                             : (char *)malloc(ch->allocated);
47       if (!ch->data) outofmem(__FILE__, "HTChunkPutc");
48     }
49     ch->data[ch->size++] = c;
50 }
51
52
53 /*      Ensure a certain size
54 **      ---------------------
55 */
56 PUBLIC void HTChunkEnsure ARGS2 (HTChunk *,ch, int,needed)
57 {
58     if (needed <= ch->allocated) return;
59     ch->allocated = needed-1 - ((needed-1) % ch->growby)
60                              + ch->growby; /* Round up */
61     ch->data = ch->data ? (char *)realloc(ch->data, ch->allocated)
62                         : (char *)malloc(ch->allocated);
63     if (ch->data == NULL) outofmem(__FILE__, "HTChunkEnsure");
64 }
65
66
67 /*      Terminate a chunk
68 **      -----------------
69 */
70 PUBLIC void HTChunkTerminate ARGS1 (HTChunk *,ch)
71 {
72     HTChunkPutc(ch, (char)0);
73 }
74
75
76 /*      Append a string
77 **      ---------------
78 */
79 PUBLIC void HTChunkPuts ARGS2 (HTChunk *,ch, CONST char *,s)
80 {
81     CONST char * p;
82     for (p=s; *p; p++)
83         HTChunkPutc(ch, *p);
84 }