Applied patch from Jim Meyering; rename dirfd to dir_fd to avoid shadowing problem
[findutils.git] / lib / extendbuf.c
blob8b7edaf0d0a40ae6557b79fd982c9d7636008b59
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 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 #include <config.h>
23 #include <stddef.h>
24 #include <stdlib.h>
25 #include <assert.h>
26 #include <errno.h>
28 #include "xalloc.h"
29 #include "extendbuf.h"
32 /* We initially use a small default size to ensure that this code
33 * gets exercised.
35 #ifndef SIZE_DEFAULT
36 # define SIZE_DEFAULT 16
37 #endif
39 static size_t
40 decide_size(size_t current, size_t wanted)
42 size_t newsize;
44 if (0 == current)
45 newsize = SIZE_DEFAULT;
46 else
47 newsize = current;
49 while (newsize < wanted)
51 if (2 * newsize < newsize)
52 xalloc_die ();
53 newsize *= 2;
55 return newsize;
59 void *
60 extendbuf(void* existing, size_t wanted, size_t *allocated)
62 int saved_errno;
63 size_t newsize;
64 void *result; /* leave uninitialised to allow static code checkers to identify bugs */
66 saved_errno = errno;
68 assert (wanted > 0u);
69 newsize = decide_size(*allocated, wanted);
71 if ( (*allocated) == 0 )
73 /* Sanity check: If there is no existing allocation size, there
74 * must be no existing allocated buffer.
76 assert (NULL == existing);
78 (*allocated) = newsize;
79 result = xmalloc(newsize);
81 else
83 if (newsize != (*allocated) )
85 (*allocated) = newsize;
86 result = xrealloc (existing, newsize);
89 else
91 result = existing;
95 if (result)
97 /* xmalloc() or xrealloc() may have changed errno, but in the
98 success case we want to preserve the previous value.
100 errno = saved_errno;
102 return result;