OSDN Git Service

Daily bump.
[pf3gnuchains/gcc-fork.git] / gcc / dyn-string.c
1 /* An abstract string datatype.
2    Copyright (C) 1998 Free Software Foundation, Inc.
3    Contributed by Mark Mitchell (mark@markmitchell.com).
4
5    This file is part of GNU CC.
6    
7    GNU CC is free software; you can redistribute it and/or modify it
8    under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11
12    GNU CC is distributed in the hope that it will be useful, but
13    WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15    General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GNU CC; see the file COPYING.  If not, write to the Free
19    Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "dyn-string.h"
24
25 extern char *xmalloc ();
26 extern char *xrealloc ();
27
28 /* Create a new dynamic string capable of holding at least SPACE
29    characters, including the terminating NUL.  If SPACE is 0, it
30    will be silently increased to 1.  */
31
32 dyn_string_t 
33 dyn_string_new (space)
34      int space;
35 {
36   dyn_string_t result = (dyn_string_t) xmalloc (sizeof (struct dyn_string));
37  
38   if (space == 0)
39     /* We need at least one byte in which to store the terminating
40        NUL.  */
41     space = 1;
42
43   result->allocated = space;
44   result->s = (char*) xmalloc (space);
45   result->length = 0;
46   result->s[0] = '\0';
47
48   return result;
49 }
50
51 /* Free the memory used by DS.  */
52
53 void 
54 dyn_string_delete (ds)
55      dyn_string_t ds;
56 {
57   free (ds->s);
58   free (ds);
59 }
60
61 /* Append the NUL-terminated string S to DS, resizing DS if
62    necessary.  */
63
64 dyn_string_t 
65 dyn_string_append (ds, s)
66      dyn_string_t ds;
67      char *s;
68 {
69   int len = strlen (s);
70   dyn_string_resize (ds, ds->length + len + 1 /* '\0' */);
71   strcpy (ds->s + ds->length, s);
72   ds->length += len;
73
74   return ds;
75 }
76
77 /* Increase the capacity of DS so that it can hold at least SPACE
78    characters, including the terminating NUL.  This function will not
79    (at present) reduce the capacity of DS.  */
80
81 dyn_string_t 
82 dyn_string_resize (ds, space)
83      dyn_string_t ds;
84      int space;
85 {
86   int new_allocated = ds->allocated;
87
88   while (space > new_allocated)
89     new_allocated *= 2;
90     
91   if (new_allocated != ds->allocated)
92     {
93       /* We actually need more space.  */
94       ds->allocated = new_allocated;
95       ds->s = (char*) xrealloc (ds->s, ds->allocated);
96     }
97
98   return ds;
99 }