Recycle removed slots

This commit is contained in:
Benoit Blanchon
2023-07-20 17:54:38 +02:00
parent 781e449e78
commit 727a1013ca
8 changed files with 94 additions and 0 deletions

View File

@ -5,6 +5,8 @@
#include <ArduinoJson.h>
#include <catch.hpp>
#include "Allocators.hpp"
TEST_CASE("JsonArray::clear()") {
SECTION("No-op on null JsonArray") {
JsonArray array;
@ -22,4 +24,25 @@ TEST_CASE("JsonArray::clear()") {
REQUIRE(array.size() == 0);
REQUIRE(array.isNull() == false);
}
SECTION("Removed elements are recycled") {
SpyingAllocator allocator;
JsonDocument doc(&allocator);
JsonArray array = doc.to<JsonArray>();
// fill the pool entirely
for (int i = 0; i < ARDUINOJSON_POOL_CAPACITY; i++)
array.add(i);
// clear and fill again
array.clear();
for (int i = 0; i < ARDUINOJSON_POOL_CAPACITY; i++)
array.add(i);
REQUIRE(
allocator.log() ==
AllocatorLog() << AllocatorLog::Allocate(sizeofPoolList())
<< AllocatorLog::Allocate(sizeofPool()) // only one pool
);
}
}

View File

@ -5,6 +5,8 @@
#include <ArduinoJson.h>
#include <catch.hpp>
#include "Allocators.hpp"
TEST_CASE("JsonArray::remove()") {
JsonDocument doc;
JsonArray array = doc.to<JsonArray>();
@ -87,3 +89,25 @@ TEST_CASE("JsonArray::remove()") {
unboundArray.remove(unboundArray.begin());
}
}
TEST_CASE("Removed elements are recycled") {
SpyingAllocator allocator;
JsonDocument doc(&allocator);
JsonArray array = doc.to<JsonArray>();
// fill the pool entirely
for (int i = 0; i < ARDUINOJSON_POOL_CAPACITY; i++)
array.add(i);
// free one slot in the pool
array.remove(0);
// add one element; it should use the free slot
array.add(42);
REQUIRE(
allocator.log() ==
AllocatorLog() << AllocatorLog::Allocate(sizeofPoolList())
<< AllocatorLog::Allocate(sizeofPool()) // only one pool
);
}

View File

@ -23,6 +23,24 @@ TEST_CASE("ResourceManager::allocSlot()") {
REQUIRE(s1 != s2);
}
SECTION("Returns the same slot after calling freeSlot()") {
ResourceManager resources;
auto s1 = resources.allocSlot();
auto s2 = resources.allocSlot();
resources.freeSlot(s1);
resources.freeSlot(s2);
auto s3 = resources.allocSlot();
auto s4 = resources.allocSlot();
auto s5 = resources.allocSlot();
REQUIRE(s2.id() != s1.id());
REQUIRE(s3.id() == s2.id());
REQUIRE(s4.id() == s1.id());
REQUIRE(s5.id() != s1.id());
REQUIRE(s5.id() != s2.id());
}
SECTION("Returns aligned pointers") {
ResourceManager resources;