summaryrefslogtreecommitdiff
path: root/lib/varstring.c
blob: b84f67f306c4c65393614438378cb242d6808398 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* varstring.c: variable-length strings.

Copyright (C) 1992, 2011 Free Software Foundation, Inc.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */

#include "config.h"

#include "varstring.h"


/* You use variable-length stringsd by calling `init_string' first, then
   assigning to particular elements via `set_string_element'. The string
   will initially be `INITIAL_SIZE' characters, and be incremented in
   blocks of size `INCREMENT_SIZE'.  */

#define INITIAL_SIZE 16
#define INCREMENT_SIZE 64

variable_string
vs_init ()
{
  variable_string vs;

  VS_CHARS (vs) = xmalloc (INITIAL_SIZE);
  *VS_CHARS (vs) = 0;
  VS_ALLOCATED (vs) = INITIAL_SIZE;
  VS_USED (vs) = 0;

  return vs;
}


/* Free the data we've allocated for VS.  */

void
vs_free (variable_string *vs)
{
  free (VS_CHARS (*vs));
  VS_CHARS (*vs) = NULL;
}


/* We do not put a NULL after we insert NEW_CHAR at the (zero-based)
   index LOC.  The caller is responsible for that.  */

void
vs_set_char (variable_string *vs, unsigned loc, char new_char)
{
  /* Do we need more space?  */
  if (loc >= VS_ALLOCATED (*vs))
    { /* Yes.  Make sure to allocate enough.  */
      unsigned extra = MAX (INCREMENT_SIZE, loc - VS_ALLOCATED (*vs) + 1);
      VS_CHARS (*vs) = xrealloc (VS_CHARS (*vs), VS_ALLOCATED (*vs) + extra);
      VS_ALLOCATED (*vs) += extra;
    }

  VS_CHARS (*vs)[loc] = new_char;
  VS_USED (*vs) = loc + 1;
}


/* Append NEW_CHAR to VS.  */

void
vs_append_char (variable_string *vs, char new_char)
{
  vs_set_char (vs, VS_USED (*vs), new_char);
}


variable_string
vs_concat (variable_string vs1, variable_string vs2)
{
  variable_string vs;
  unsigned used = VS_USED (vs1) + VS_USED (vs2);
  
  VS_CHARS (vs) = xmalloc (used + 1);
  memcpy (VS_CHARS (vs), VS_CHARS (vs1), VS_USED (vs1));
  memcpy (VS_CHARS (vs) + VS_USED (vs1), VS_CHARS (vs2), VS_USED (vs2));
  VS_ALLOCATED (vs) = used + 1;
  VS_USED (vs) = used;

  return vs;
}