1 /* extendbuf.c -- manage a dynamically-allocated buffer
3 Copyright 2004, 2010, 2011 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 /* Written by James Yougnman <jay@gnu.org>. */
20 /* config.h must be included first. */
32 #include "extendbuf.h"
35 /* We initially use a small default size to ensure that this code
39 # define SIZE_DEFAULT 16
43 decide_size (size_t current, size_t wanted)
48 newsize = SIZE_DEFAULT;
52 while (newsize < wanted)
54 if (2 * newsize < newsize)
63 extendbuf (void* existing, size_t wanted, size_t *allocated)
67 void *result; /* leave uninitialized to allow static code checkers to identify bugs */
72 newsize = decide_size (*allocated, wanted);
74 if ( (*allocated) == 0 )
76 /* Sanity check: If there is no existing allocation size, there
77 * must be no existing allocated buffer.
79 assert (NULL == existing);
81 (*allocated) = newsize;
82 result = malloc (newsize);
86 if (newsize != (*allocated) )
88 (*allocated) = newsize;
89 result = realloc (existing, newsize);
103 /* malloc () or realloc () may have changed errno, but in the
104 success case we want to preserve the previous value.
113 xextendbuf (void* existing, size_t wanted, size_t *allocated)
115 void *p = extendbuf (existing, wanted, allocated);