1 /***********************************************************************
3 * l2tp/handlers/dstring.c
5 * Implements simple buffer which grows to accomodate accumulated string
8 * Copyright (C) 2002 by Roaring Penguin Software Inc.
10 * This software may be distributed under the terms of the GNU General
11 * Public License, Version 2, or (at your option) any later version.
15 ***********************************************************************/
17 static char const RCSID
[] =
18 "$Id: dstring.c,v 1.1.48.1 2005/08/08 12:05:25 honor Exp $";
20 #define INITIAL_SIZE 128
28 expand_for_size(dynstring
*str
, size_t len
)
32 if (len
>= str
->alloc_size
* GROW_FACTOR
) {
35 newlen
= str
->alloc_size
* GROW_FACTOR
;
38 str
->data
= realloc(str
->data
, newlen
);
45 str
->alloc_size
= newlen
;
49 /**********************************************************************
50 * %FUNCTION: dynstring_init
52 * str -- a dynstring structure
54 * 0 on success; -1 on failure
56 * Initializes dynamic string
57 ***********************************************************************/
59 dynstring_init(dynstring
*str
)
61 str
->data
= malloc(INITIAL_SIZE
);
62 if (!str
->data
) return -1;
64 str
->alloc_size
= INITIAL_SIZE
;
70 /**********************************************************************
71 * %FUNCTION: dynstring_free
73 * str -- a dynstring structure
77 * Frees resources used by dynamic string
78 ***********************************************************************/
80 dynstring_free(dynstring
*str
)
90 /**********************************************************************
91 * %FUNCTION: dynstring_append
93 * str -- dynamic string
94 * s2 -- string to append
96 * -1 on failure; 0 on success
99 ***********************************************************************/
101 dynstring_append(dynstring
*str
, char const *s2
)
103 return dynstring_append_len(str
, s2
, strlen(s2
));
106 /**********************************************************************
107 * %FUNCTION: dynstring_append_len
109 * str -- dynamic string
110 * s2 -- string to append
111 * len -- length of s2
113 * -1 on failure; 0 on success
116 ***********************************************************************/
118 dynstring_append_len(dynstring
*str
, char const *s2
, size_t len
)
121 if (!str
->data
) return -1;
123 if (len
+ str
->actual_size
>= str
->alloc_size
) {
124 if (expand_for_size(str
, str
->actual_size
+ len
) < 0) {
129 memcpy(str
->data
+ str
->actual_size
, s2
, len
);
130 str
->actual_size
+= len
;
131 str
->data
[str
->actual_size
] = 0;
136 dynstring_data(dynstring
*str
)