alloc.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2018
  3. // MIT License
  4. #include <ArduinoJson.h>
  5. #include <catch.hpp>
  6. #include <sstream>
  7. static bool isAligned(void* ptr) {
  8. const size_t mask = sizeof(void*) - 1;
  9. size_t addr = reinterpret_cast<size_t>(ptr);
  10. return (addr & mask) == 0;
  11. }
  12. std::stringstream allocatorLog;
  13. struct SpyingAllocator : DefaultAllocator {
  14. void* allocate(size_t n) {
  15. allocatorLog << "A" << (n - DynamicJsonBuffer::EmptyBlockSize);
  16. return DefaultAllocator::allocate(n);
  17. }
  18. void deallocate(void* p) {
  19. allocatorLog << "F";
  20. return DefaultAllocator::deallocate(p);
  21. }
  22. };
  23. TEST_CASE("DynamicJsonBuffer::alloc()") {
  24. SECTION("Returns different pointers") {
  25. DynamicJsonBuffer buffer;
  26. void* p1 = buffer.alloc(1);
  27. void* p2 = buffer.alloc(2);
  28. REQUIRE(p1 != p2);
  29. }
  30. SECTION("Doubles allocation size when full") {
  31. allocatorLog.str("");
  32. {
  33. DynamicJsonBufferBase<SpyingAllocator> buffer(1);
  34. buffer.alloc(1);
  35. buffer.alloc(1);
  36. }
  37. REQUIRE(allocatorLog.str() == "A1A2FF");
  38. }
  39. SECTION("Resets allocation size after clear()") {
  40. allocatorLog.str("");
  41. {
  42. DynamicJsonBufferBase<SpyingAllocator> buffer(1);
  43. buffer.alloc(1);
  44. buffer.alloc(1);
  45. buffer.clear();
  46. buffer.alloc(1);
  47. }
  48. REQUIRE(allocatorLog.str() == "A1A2FFA1F");
  49. }
  50. SECTION("Makes a big allocation when needed") {
  51. allocatorLog.str("");
  52. {
  53. DynamicJsonBufferBase<SpyingAllocator> buffer(1);
  54. buffer.alloc(42);
  55. }
  56. REQUIRE(allocatorLog.str() == "A42F");
  57. }
  58. SECTION("Alignment") {
  59. // make room for two but not three
  60. DynamicJsonBuffer tinyBuf(2 * sizeof(void*) + 1);
  61. REQUIRE(isAligned(tinyBuf.alloc(1))); // this on is aligned by design
  62. REQUIRE(isAligned(tinyBuf.alloc(1))); // this one fits in the first block
  63. REQUIRE(isAligned(tinyBuf.alloc(1))); // this one requires a new block
  64. }
  65. }