ccc961b7b47db1f13762cd4ca05081627ae2c50b
[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 tarball for details.
8  */
9
10 #include "libbb.h"
11
12 /* Resize (grow) malloced vector.
13  *
14  *  #define magic packed two parameters into one:
15  *  sizeof = sizeof_and_shift >> 8
16  *  shift  = (sizeof_and_shift) & 0xff
17  *  (TODO: encode "I want it zeroed" in lowest bit?)
18  *
19  * Lets say shift = 4. 1 << 4 == 0x10.
20  * If idx == 0, 0x10, 0x20 etc, vector[] is resized to next higher
21  * idx step, plus one: if idx == 0x20, vector[] is resized to 0x31,
22  * thus last usable element is vector[0x30].
23  *
24  * In other words: after xrealloc_vector(v, 4, idx) it's ok to use
25  * at least v[idx] and v[idx+1], for all idx values.
26  */
27 void* FAST_FUNC xrealloc_vector_helper(void *vector, unsigned sizeof_and_shift, int idx)
28 {
29         int mask = 1 << (uint8_t)sizeof_and_shift;
30
31         if (!(idx & (mask - 1))) {
32                 sizeof_and_shift >>= 8;
33                 vector = xrealloc(vector, sizeof_and_shift * (idx + mask + 1));
34         }
35         return vector;
36 }