xrealloc_vector.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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), with any idx,
  22. * it's ok to use at least v[idx] and v[idx+1].
  23. * v[idx+2] etc generally are not ok.
  24. *
  25. * New elements are zeroed out, but only if realloc was done
  26. * (not on every call). You can depend on v[idx] and v[idx+1] being
  27. * zeroed out if you use it like this:
  28. * v = xrealloc_vector(v, 4, idx);
  29. * v[idx].some_fields = ...; - the rest stays 0/NULL
  30. * idx++;
  31. * If you do not advance idx like above, you should be more careful.
  32. * Next call to xrealloc_vector(v, 4, idx) may or may not zero out v[idx].
  33. */
  34. void* FAST_FUNC xrealloc_vector_helper(void *vector, unsigned sizeof_and_shift, int idx)
  35. {
  36. int mask = 1 << (uint8_t)sizeof_and_shift;
  37. if (!(idx & (mask - 1))) {
  38. sizeof_and_shift >>= 8; /* sizeof(vector[0]) */
  39. vector = xrealloc(vector, sizeof_and_shift * (idx + mask + 1));
  40. memset((char*)vector + (sizeof_and_shift * idx), 0, sizeof_and_shift * (mask + 1));
  41. }
  42. return vector;
  43. }