comparison dynamicstring.c @ 0:04124a4423d4 noffle

[svn] Initial revision
author enz
date Tue, 04 Jan 2000 11:35:42 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:04124a4423d4
1 /*
2 dynamicstring.c
3
4 $Id: dynamicstring.c 3 2000-01-04 11:35:42Z enz $
5 */
6
7 #include "dynamicstring.h"
8
9 #include <sys/types.h>
10 #include "log.h"
11
12 struct DynStr
13 {
14 size_t len; /* Current length (without trailing '\0') */
15 size_t max; /* Max length that fits into buffer (incl. trailing '\0') */
16 char *str;
17 };
18
19 static void
20 reallocStr( DynStr *self, size_t max )
21 {
22 if ( max <= self->max )
23 return;
24 if ( ! ( self->str = (char *)realloc( self->str, max ) ) )
25 {
26 Log_err( "Realloc of DynStr failed" );
27 exit( EXIT_FAILURE );
28 }
29 if ( self->max == 0 ) /* First allocation? */
30 *(self->str) = '\0';
31 self->max = max;
32 }
33
34 DynStr *
35 new_DynStr( size_t reserve )
36 {
37 DynStr *s;
38
39 if ( ! ( s = (DynStr *) malloc( sizeof( DynStr ) ) ) )
40 {
41 Log_err( "Allocation of DynStr failed" );
42 exit( EXIT_FAILURE );
43 }
44 s->len = 0;
45 s->max = 0;
46 s->str = NULL;
47 if ( reserve > 0 )
48 reallocStr( s, reserve + 1 );
49 return s;
50 }
51
52 void
53 del_DynStr( DynStr *self )
54 {
55 if ( ! self )
56 return;
57 free( self->str );
58 self->str = NULL;
59 free( self );
60 }
61
62 size_t
63 DynStr_len( const DynStr *self )
64 {
65 return self->len;
66 }
67
68 const char *
69 DynStr_str( const DynStr *self )
70 {
71 return self->str;
72 }
73
74 void
75 DynStr_app( DynStr *self, const char *s )
76 {
77 size_t len;
78
79 len = strlen( s );
80 if ( self->len + len + 1 > self->max )
81 reallocStr( self, self->len * 2 + len + 1 );
82 strcpy( self->str + self->len, s );
83 self->len += len;
84 }
85
86 void
87 DynStr_appDynStr( DynStr *self, const DynStr *s )
88 {
89 if ( self->len + s->len + 1 > self->max )
90 reallocStr( self, self->len * 2 + s->len + 1 );
91 memcpy( self->str + self->len, s->str, s->len + 1 );
92 self->len += s->len;
93 }
94
95 void
96 DynStr_appLn( DynStr *self, const char *s )
97 {
98 DynStr_app( self, s );
99 DynStr_app( self, "\n" );
100 }
101
102 void
103 DynStr_appN( DynStr *self, const char *s, size_t n )
104 {
105 size_t len = self->len;
106
107 if ( len + n + 1 > self->max )
108 reallocStr( self, len * 2 + n + 1 );
109 strncat( self->str + len, s, n );
110 self->len = len + strlen( self->str + len );
111 }
112
113 void
114 DynStr_clear( DynStr *self )
115 {
116 self->len = 0;
117 if ( self->max > 0 )
118 *(self->str) = '\0';
119 }
120