]> git.sur5r.net Git - cc65/blob - src/common/strbuf.c
Fixed LinuxDoc Tools issues in some verbatim blocks in the Atari document.
[cc65] / src / common / strbuf.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 strbuf.c                                  */
4 /*                                                                           */
5 /*                       Variable sized string buffers                       */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2001-2012, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 52                                           */
11 /*                D-70794 Filderstadt                                        */
12 /* EMail:         uz@cc65.org                                                */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <string.h>
37 #include <ctype.h>
38
39 /* common */
40 #include "chartype.h"
41 #include "strbuf.h"
42 #include "va_copy.h"
43 #include "xmalloc.h"
44 #include "xsprintf.h"
45
46
47
48 /*****************************************************************************/
49 /*                                   Data                                    */
50 /*****************************************************************************/
51
52
53
54 /* An empty string buf */
55 const StrBuf EmptyStrBuf = STATIC_STRBUF_INITIALIZER;
56
57
58
59 /*****************************************************************************/
60 /*                                   Code                                    */
61 /*****************************************************************************/
62
63
64
65 #if !defined(HAVE_INLINE)
66 StrBuf* SB_Init (StrBuf* B)
67 /* Initialize a string buffer */
68 {
69     *B = EmptyStrBuf;
70     return B;
71 }
72 #endif
73
74
75
76 StrBuf* SB_InitFromString (StrBuf* B, const char* S)
77 /* Initialize a string buffer from a literal string. Beware: The buffer won't
78 ** store a copy but a pointer to the actual string.
79 */
80 {
81     B->Allocated = 0;
82     B->Len       = strlen (S);
83     B->Index     = 0;
84     B->Buf       = (char*) S;
85     return B;
86 }
87
88
89
90 void SB_Done (StrBuf* B)
91 /* Free the data of a string buffer (but not the struct itself) */
92 {
93     if (B->Allocated) {
94         xfree (B->Buf);
95     }
96 }
97
98
99
100 StrBuf* NewStrBuf (void)
101 /* Allocate, initialize and return a new StrBuf */
102 {
103     /* Allocate a new string buffer */
104     StrBuf* B = xmalloc (sizeof (StrBuf));
105
106     /* Initialize the struct... */
107     SB_Init (B);
108
109     /* ...and return it */
110     return B;
111 }
112
113
114
115 void FreeStrBuf (StrBuf* B)
116 /* Free a string buffer */
117 {
118     /* Allow NULL pointers */
119     if (B) {
120         SB_Done (B);
121         xfree (B);
122     }
123 }
124
125
126
127 void SB_Realloc (StrBuf* B, unsigned NewSize)
128 /* Reallocate the string buffer space, make sure at least NewSize bytes are
129 ** available.
130 */
131 {
132     /* Get the current size, use a minimum of 8 bytes */
133     unsigned NewAllocated = B->Allocated;
134     if (NewAllocated == 0) {
135         NewAllocated = 8;
136     }
137
138     /* Round up to the next power of two */
139     while (NewAllocated < NewSize) {
140         NewAllocated *= 2;
141     }
142
143     /* Reallocate the buffer. Beware: The allocated size may be zero while the
144     ** length is not. This means that we have a buffer that wasn't allocated
145     ** on the heap.
146     */
147     if (B->Allocated) {
148         /* Just reallocate the block */
149         B->Buf   = xrealloc (B->Buf, NewAllocated);
150     } else {
151         /* Allocate a new block and copy */
152         B->Buf   = memcpy (xmalloc (NewAllocated), B->Buf, B->Len);
153     }
154
155     /* Remember the new block size */
156     B->Allocated = NewAllocated;
157 }
158
159
160
161 static void SB_CheapRealloc (StrBuf* B, unsigned NewSize)
162 /* Reallocate the string buffer space, make sure at least NewSize bytes are
163 ** available. This function won't copy the old buffer contents over to the new
164 ** buffer and may be used if the old contents are overwritten later.
165 */
166 {
167     /* Get the current size, use a minimum of 8 bytes */
168     unsigned NewAllocated = B->Allocated;
169     if (NewAllocated == 0) {
170         NewAllocated = 8;
171     }
172
173     /* Round up to the next power of two */
174     while (NewAllocated < NewSize) {
175         NewAllocated *= 2;
176     }
177
178     /* Free the old buffer if there is one */
179     if (B->Allocated) {
180         xfree (B->Buf);
181     }
182
183     /* Allocate a fresh block */
184     B->Buf = xmalloc (NewAllocated);
185
186     /* Remember the new block size */
187     B->Allocated = NewAllocated;
188 }
189
190
191
192 #if !defined(HAVE_INLINE)
193 char SB_At (const StrBuf* B, unsigned Index)
194 /* Get a character from the buffer */
195 {
196     PRECONDITION (Index < B->Len);
197     return B->Buf[Index];
198 }
199 #endif
200
201
202
203 void SB_Drop (StrBuf* B, unsigned Count)
204 /* Drop characters from the end of the string. */
205 {
206     PRECONDITION (Count <= B->Len);
207     B->Len -= Count;
208     if (B->Index > B->Len) {
209         B->Index = B->Len;
210     }
211 }
212
213
214
215 void SB_Terminate (StrBuf* B)
216 /* Zero terminate the given string buffer. NOTE: The terminating zero is not
217 ** accounted for in B->Len, if you want that, you have to use AppendChar!
218 */
219 {
220     unsigned NewLen = B->Len + 1;
221     if (NewLen > B->Allocated) {
222         SB_Realloc (B, NewLen);
223     }
224     B->Buf[B->Len] = '\0';
225 }
226
227
228
229 void SB_CopyBuf (StrBuf* Target, const char* Buf, unsigned Size)
230 /* Copy Buf to Target, discarding the old contents of Target */
231 {
232     if (Size) {
233         if (Target->Allocated < Size) {
234             SB_CheapRealloc (Target, Size);
235         }
236         memcpy (Target->Buf, Buf, Size);
237     }
238     Target->Len = Size;
239 }
240
241
242
243 #if !defined(HAVE_INLINE)
244 void SB_CopyStr (StrBuf* Target, const char* S)
245 /* Copy S to Target, discarding the old contents of Target */
246 {
247     SB_CopyBuf (Target, S, strlen (S));
248 }
249 #endif
250
251
252
253 #if !defined(HAVE_INLINE)
254 void SB_Copy (StrBuf* Target, const StrBuf* Source)
255 /* Copy Source to Target, discarding the old contents of Target */
256 {
257     SB_CopyBuf (Target, Source->Buf, Source->Len);
258     Target->Index = Source->Index;
259 }
260 #endif
261
262
263
264 void SB_AppendChar (StrBuf* B, int C)
265 /* Append a character to a string buffer */
266 {
267     unsigned NewLen = B->Len + 1;
268     if (NewLen > B->Allocated) {
269         SB_Realloc (B, NewLen);
270     }
271     B->Buf[B->Len] = (char) C;
272     B->Len = NewLen;
273 }
274
275
276
277 void SB_AppendBuf (StrBuf* B, const char* S, unsigned Size)
278 /* Append a character buffer to the end of the string buffer */
279 {
280     unsigned NewLen = B->Len + Size;
281     if (NewLen > B->Allocated) {
282         SB_Realloc (B, NewLen);
283     }
284     memcpy (B->Buf + B->Len, S, Size);
285     B->Len = NewLen;
286 }
287
288
289
290 #if !defined(HAVE_INLINE)
291 void SB_AppendStr (StrBuf* B, const char* S)
292 /* Append a string to the end of the string buffer */
293 {
294     SB_AppendBuf (B, S, strlen (S));
295 }
296 #endif
297
298
299
300 #if !defined(HAVE_INLINE)
301 void SB_Append (StrBuf* Target, const StrBuf* Source)
302 /* Append the contents of Source to Target */
303 {
304     SB_AppendBuf (Target, Source->Buf, Source->Len);
305 }
306 #endif
307
308
309
310 #if !defined(HAVE_INLINE)
311 void SB_Cut (StrBuf* B, unsigned Len)
312 /* Cut the contents of B at the given length. If the current length of the
313 ** buffer is smaller than Len, nothing will happen.
314 */
315 {
316     if (Len < B->Len) {
317         B->Len = Len;
318     }
319 }
320 #endif
321
322
323
324 void SB_Slice (StrBuf* Target, const StrBuf* Source, unsigned Start, unsigned Len)
325 /* Copy a slice from Source into Target. The current contents of Target are
326 ** destroyed. If Start is greater than the length of Source, or if Len
327 ** characters aren't available, the result will be a buffer with less than Len
328 ** bytes.
329 */
330 {
331     /* Calculate the length of the resulting buffer */
332     if (Start >= Source->Len) {
333         /* Target will be empty */
334         SB_Clear (Target);
335         return;
336     }
337     if (Start + Len > Source->Len) {
338         Len = Source->Len - Start;
339     }
340
341     /* Make sure we have enough room in the target string buffer */
342     if (Len > Target->Allocated) {
343         SB_Realloc (Target, Len);
344     }
345
346     /* Copy the slice */
347     memcpy (Target->Buf, Source->Buf + Start, Len);
348     Target->Len = Len;
349 }
350
351
352
353 void SB_Move (StrBuf* Target, StrBuf* Source)
354 /* Move the complete contents of Source to target. This will delete the old
355 ** contents of Target, and Source will be empty after the call.
356 */
357 {
358     /* Free the target string */
359     if (Target->Allocated) {
360         xfree (Target->Buf);
361     }
362
363     /* Move all data from Source to Target */
364     *Target = *Source;
365
366     /* Clear Source */
367     SB_Init (Source);
368 }
369
370
371
372 void SB_ToLower (StrBuf* S)
373 /* Convert all characters in S to lower case */
374 {
375     unsigned I;
376     char* B = S->Buf;
377     for (I = 0; I < S->Len; ++I, ++B) {
378         if (IsUpper (*B)) {
379             *B = tolower (*B);
380         }
381     }
382 }
383
384
385
386 void SB_ToUpper (StrBuf* S)
387 /* Convert all characters in S to upper case */
388 {
389     unsigned I;
390     char* B = S->Buf;
391     for (I = 0; I < S->Len; ++I, ++B) {
392         if (IsLower (*B)) {
393             *B = toupper (*B);
394         }
395     }
396 }
397
398
399
400 int SB_Compare (const StrBuf* S1, const StrBuf* S2)
401 /* Do a lexical compare of S1 and S2. See strcmp for result codes. */
402 {
403     int Result;
404     if (S1->Len < S2->Len) {
405         Result = memcmp (S1->Buf, S2->Buf, S1->Len);
406         if (Result == 0) {
407             /* S1 considered lesser because it's shorter */
408             Result = -1;
409         }
410     } else if (S1->Len > S2->Len) {
411         Result = memcmp (S1->Buf, S2->Buf, S2->Len);
412         if (Result == 0) {
413             /* S2 considered lesser because it's shorter */
414             Result = 1;
415         }
416     } else {
417         Result = memcmp (S1->Buf, S2->Buf, S1->Len);
418     }
419     return Result;
420 }
421
422
423
424 int SB_CompareStr (const StrBuf* S1, const char* S2)
425 /* Do a lexical compare of S1 and S2. See strcmp for result codes. */
426 {
427     int Result;
428     unsigned S2Len = strlen (S2);
429     if (S1->Len < S2Len) {
430         Result = memcmp (S1->Buf, S2, S1->Len);
431         if (Result == 0) {
432             /* S1 considered lesser because it's shorter */
433             Result = -1;
434         }
435     } else if (S1->Len > S2Len) {
436         Result = memcmp (S1->Buf, S2, S2Len);
437         if (Result == 0) {
438             /* S2 considered lesser because it's shorter */
439             Result = 1;
440         }
441     } else {
442         Result = memcmp (S1->Buf, S2, S1->Len);
443     }
444     return Result;
445 }
446
447
448
449 void SB_VPrintf (StrBuf* S, const char* Format, va_list ap)
450 /* printf function with S as target. The function is safe, which means that
451 ** the current contents of S are discarded, and are allocated again with
452 ** a matching size for the output. The function will call FAIL when problems
453 ** are detected (anything that let xsnprintf return -1).
454 */
455 {
456     va_list tmp;
457     int SizeNeeded;
458
459     /* Since we must determine the space needed anyway, we will try with
460     ** the currently allocated memory. If the call succeeds, we've saved
461     ** an allocation. If not, we have to reallocate and try again.
462     */
463     va_copy (tmp, ap);
464     SizeNeeded = xvsnprintf (S->Buf, S->Allocated, Format, tmp);
465     va_end (tmp);
466
467     /* Check the result, the xvsnprintf function should not fail */
468     CHECK (SizeNeeded >= 0);
469
470     /* Check if we must reallocate */
471     if ((unsigned) SizeNeeded >= S->Allocated) {
472         /* Must retry. Use CheapRealloc to avoid copying */
473         SB_CheapRealloc (S, SizeNeeded + 1);    /* Account for '\0' */
474         (void) xvsnprintf (S->Buf, S->Allocated, Format, ap);
475     }
476
477     /* Update string buffer variables */
478     S->Len = SizeNeeded;
479     S->Index = 0;
480 }
481
482
483
484 void SB_Printf (StrBuf* S, const char* Format, ...)
485 /* vprintf function with S as target. The function is safe, which means that
486 ** the current contents of S are discarded, and are allocated again with
487 ** a matching size for the output. The function will call FAIL when problems
488 ** are detected (anything that let xsnprintf return -1).
489 */
490 {
491     va_list ap;
492     va_start (ap, Format);
493     SB_VPrintf (S, Format, ap);
494     va_end (ap);
495 }