lzham_vector.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // File: lzham_vector.cpp
  2. // See Copyright Notice and license at the end of include/lzham.h
  3. #include "lzham_core.h"
  4. #include "lzham_vector.h"
  5. namespace lzham
  6. {
  7. bool elemental_vector::increase_capacity(uint min_new_capacity, bool grow_hint, uint element_size, object_mover pMover, bool nofail)
  8. {
  9. LZHAM_ASSERT(m_size <= m_capacity);
  10. #if LZHAM_64BIT_POINTERS
  11. LZHAM_ASSUME(sizeof(void*) == sizeof(uint64));
  12. LZHAM_ASSERT(min_new_capacity < (0x400000000ULL / element_size));
  13. #else
  14. LZHAM_ASSUME(sizeof(void*) == sizeof(uint32));
  15. LZHAM_ASSERT(min_new_capacity < (0x7FFF0000U / element_size));
  16. #endif
  17. if (m_capacity >= min_new_capacity)
  18. return true;
  19. // new_capacity must be 64-bit when compiling on x64.
  20. size_t new_capacity = (size_t)min_new_capacity;
  21. if ((grow_hint) && (!math::is_power_of_2(static_cast<uint64>(new_capacity))))
  22. new_capacity = static_cast<uint>(math::next_pow2(static_cast<uint64>(new_capacity)));
  23. LZHAM_ASSERT(new_capacity && (new_capacity > m_capacity));
  24. const size_t desired_size = element_size * new_capacity;
  25. size_t actual_size;
  26. if (!pMover)
  27. {
  28. void* new_p = lzham_realloc(m_p, desired_size, &actual_size, true);
  29. if (!new_p)
  30. {
  31. if (nofail)
  32. return false;
  33. char buf[256];
  34. sprintf_s(buf, sizeof(buf), "vector: lzham_realloc() failed allocating %u bytes", desired_size);
  35. LZHAM_FAIL(buf);
  36. }
  37. m_p = new_p;
  38. }
  39. else
  40. {
  41. void* new_p = lzham_malloc(desired_size, &actual_size);
  42. if (!new_p)
  43. {
  44. if (nofail)
  45. return false;
  46. char buf[256];
  47. sprintf_s(buf, sizeof(buf), "vector: lzham_malloc() failed allocating %u bytes", desired_size);
  48. LZHAM_FAIL(buf);
  49. }
  50. (*pMover)(new_p, m_p, m_size);
  51. if (m_p)
  52. lzham_free(m_p);
  53. m_p = new_p;
  54. }
  55. if (actual_size > desired_size)
  56. m_capacity = static_cast<uint>(actual_size / element_size);
  57. else
  58. m_capacity = static_cast<uint>(new_capacity);
  59. return true;
  60. }
  61. } // namespace lzham