Denis Vlasenko | dbef117 | 2008-07-08 20:41:57 +0000 | [diff] [blame] | 1 | /* vi: set sw=4 ts=4: */ |
| 2 | /* |
| 3 | * Utility routines. |
| 4 | * |
| 5 | * Copyright (C) 2008 Denys Vlasenko |
| 6 | * |
Denys Vlasenko | 0ef64bd | 2010-08-16 20:14:46 +0200 | [diff] [blame^] | 7 | * Licensed under GPLv2, see file LICENSE in this source tree. |
Denis Vlasenko | dbef117 | 2008-07-08 20:41:57 +0000 | [diff] [blame] | 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 |
Denis Vlasenko | dbef117 | 2008-07-08 20:41:57 +0000 | [diff] [blame] | 17 | * |
| 18 | * Lets say shift = 4. 1 << 4 == 0x10. |
| 19 | * If idx == 0, 0x10, 0x20 etc, vector[] is resized to next higher |
| 20 | * idx step, plus one: if idx == 0x20, vector[] is resized to 0x31, |
| 21 | * thus last usable element is vector[0x30]. |
| 22 | * |
Denys Vlasenko | 1502a8b | 2009-10-27 10:01:01 +0100 | [diff] [blame] | 23 | * In other words: after xrealloc_vector(v, 4, idx), with any idx, |
| 24 | * it's ok to use at least v[idx] and v[idx+1]. |
| 25 | * v[idx+2] etc generally are not ok. |
Denis Vlasenko | 2784228 | 2008-08-04 13:20:36 +0000 | [diff] [blame] | 26 | * |
| 27 | * New elements are zeroed out, but only if realloc was done |
| 28 | * (not on every call). You can depend on v[idx] and v[idx+1] being |
| 29 | * zeroed out if you use it like this: |
| 30 | * v = xrealloc_vector(v, 4, idx); |
| 31 | * v[idx].some_fields = ...; - the rest stays 0/NULL |
| 32 | * idx++; |
| 33 | * If you do not advance idx like above, you should be more careful. |
| 34 | * Next call to xrealloc_vector(v, 4, idx) may or may not zero out v[idx]. |
Denis Vlasenko | dbef117 | 2008-07-08 20:41:57 +0000 | [diff] [blame] | 35 | */ |
| 36 | void* FAST_FUNC xrealloc_vector_helper(void *vector, unsigned sizeof_and_shift, int idx) |
| 37 | { |
| 38 | int mask = 1 << (uint8_t)sizeof_and_shift; |
| 39 | |
| 40 | if (!(idx & (mask - 1))) { |
Denis Vlasenko | 2784228 | 2008-08-04 13:20:36 +0000 | [diff] [blame] | 41 | sizeof_and_shift >>= 8; /* sizeof(vector[0]) */ |
Denis Vlasenko | dbef117 | 2008-07-08 20:41:57 +0000 | [diff] [blame] | 42 | vector = xrealloc(vector, sizeof_and_shift * (idx + mask + 1)); |
Denis Vlasenko | 728161b | 2008-08-06 08:44:09 +0000 | [diff] [blame] | 43 | memset((char*)vector + (sizeof_and_shift * idx), 0, sizeof_and_shift * (mask + 1)); |
Denis Vlasenko | dbef117 | 2008-07-08 20:41:57 +0000 | [diff] [blame] | 44 | } |
| 45 | return vector; |
| 46 | } |