Start 1.33.0 development cycle
[oweals/busybox.git] / libbb / xrealloc_vector.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Utility routines.
4  *
5  * Copyright (C) 2008 Denys Vlasenko
6  *
7  * Licensed under GPLv2, see file LICENSE in this source tree.
8  */
9 #include "libbb.h"
10
11 /* Resize (grow) malloced vector.
12  *
13  *  #define magic packed two parameters into one:
14  *  sizeof = sizeof_and_shift >> 8
15  *  shift  = (sizeof_and_shift) & 0xff
16  *
17  * Lets say shift = 4. 1 << 4 == 0x10.
18  * If idx == 0, 0x10, 0x20 etc, vector[] is resized to next higher
19  * idx step, plus one: if idx == 0x20, vector[] is resized to 0x31,
20  * thus last usable element is vector[0x30].
21  *
22  * In other words: after xrealloc_vector(v, 4, idx), with any idx,
23  * it's ok to use at least v[idx] and v[idx+1].
24  * v[idx+2] etc generally are not ok.
25  *
26  * New elements are zeroed out, but only if realloc was done
27  * (not on every call). You can depend on v[idx] and v[idx+1] being
28  * zeroed out if you use it like this:
29  *  v = xrealloc_vector(v, 4, idx);
30  *  v[idx].some_fields = ...; - the rest stays 0/NULL
31  *  idx++;
32  * If you do not advance idx like above, you should be more careful.
33  * Next call to xrealloc_vector(v, 4, idx) may or may not zero out v[idx].
34  */
35 void* FAST_FUNC xrealloc_vector_helper(void *vector, unsigned sizeof_and_shift, int idx)
36 {
37         int mask = 1 << (uint8_t)sizeof_and_shift;
38
39         if (!(idx & (mask - 1))) {
40                 sizeof_and_shift >>= 8; /* sizeof(vector[0]) */
41                 vector = xrealloc(vector, sizeof_and_shift * (idx + mask + 1));
42                 memset((char*)vector + (sizeof_and_shift * idx), 0, sizeof_and_shift * (mask + 1));
43         }
44         return vector;
45 }