alloc.cpp 2.0 KB

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