alloc.cpp 2.0 KB

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