3
0

xrealloc_vector.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. #include "libbb.h"
  10. /* Resize (grow) malloced vector.
  11. *
  12. * #define magic packed two parameters into one:
  13. * sizeof = sizeof_and_shift >> 8
  14. * shift = (sizeof_and_shift) & 0xff
  15. *
  16. * Lets say shift = 4. 1 << 4 == 0x10.
  17. * If idx == 0, 0x10, 0x20 etc, vector[] is resized to next higher
  18. * idx step, plus one: if idx == 0x20, vector[] is resized to 0x31,
  19. * thus last usable element is vector[0x30].
  20. *
  21. * In other words: after xrealloc_vector(v, 4, idx) it's ok to use
  22. * at least v[idx] and v[idx+1], for all idx values.
  23. *
  24. * New elements are zeroed out, but only if realloc was done
  25. * (not on every call). You can depend on v[idx] and v[idx+1] being
  26. * zeroed out if you use it like this:
  27. * v = xrealloc_vector(v, 4, idx);
  28. * v[idx].some_fields = ...; - the rest stays 0/NULL
  29. * idx++;
  30. * If you do not advance idx like above, you should be more careful.
  31. * Next call to xrealloc_vector(v, 4, idx) may or may not zero out v[idx].
  32. */
  33. void* FAST_FUNC xrealloc_vector_helper(void *vector, unsigned sizeof_and_shift, int idx)
  34. {
  35. int mask = 1 << (uint8_t)sizeof_and_shift;
  36. if (!(idx & (mask - 1))) {
  37. sizeof_and_shift >>= 8; /* sizeof(vector[0]) */
  38. vector = xrealloc(vector, sizeof_and_shift * (idx + mask + 1));
  39. memset((char*)vector + (sizeof_and_shift * idx), 0, sizeof_and_shift * (mask + 1));
  40. }
  41. return vector;
  42. }