Ignore the usually-ignored files in git
[findutils.git] / lib / extendbuf.c
blob079e6b73c6fc98a9b3fcd9c38c700655b4710662
1 /* extendbuf.c -- manage a dynamically-allocated buffer
3 Copyright 2004 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 2, or (at your option)
8 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, write to the Free Software Foundation,
17 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
19 /* Written by James Yougnman <jay@gnu.org>. */
21 #include <config.h>
24 #include <stddef.h>
25 #include <stdlib.h>
26 #include <assert.h>
27 #include <errno.h>
29 #include "xalloc.h"
30 #include "extendbuf.h"
33 /* We initially use a small default size to ensure that this code
34 * gets exercised.
36 #ifndef SIZE_DEFAULT
37 # define SIZE_DEFAULT 16
38 #endif
40 static size_t
41 decide_size(size_t current, size_t wanted)
43 size_t newsize;
45 if (0 == current)
46 newsize = SIZE_DEFAULT;
47 else
48 newsize = current;
50 while (newsize < wanted)
52 if (2 * newsize < newsize)
53 xalloc_die ();
54 newsize *= 2;
56 return newsize;
60 void *
61 extendbuf(void* existing, size_t wanted, size_t *allocated)
63 int saved_errno;
64 size_t newsize;
65 void *result; /* leave uninitialised to allow static code checkers to identify bugs */
67 saved_errno = errno;
69 assert(wanted > 0u);
70 newsize = decide_size(*allocated, wanted);
72 if ( (*allocated) == 0 )
74 /* Sanity check: If there is no existing allocation size, there
75 * must be no existing allocated buffer.
77 assert(NULL == existing);
79 (*allocated) = newsize;
80 result = xmalloc(newsize);
82 else
84 if (newsize != (*allocated) )
86 (*allocated) = newsize;
87 result = xrealloc (existing, newsize);
90 else
92 result = existing;
96 if (result)
98 /* xmalloc() or xrealloc() may have changed errno, but in the
99 success case we want to preserve the previous value.
101 errno = saved_errno;
103 return result;