ResourceManager: extract functions to manipulate StringNodes

This commit is contained in:
Benoit Blanchon
2023-06-19 11:14:47 +02:00
parent 972f665b07
commit 3e0ba2028c
2 changed files with 40 additions and 19 deletions

View File

@ -118,32 +118,21 @@ class ResourceManager {
}
StringNode* allocString(size_t length) {
auto node = reinterpret_cast<StringNode*>(
allocator_->allocate(sizeofString(length)));
if (node) {
node->length = uint16_t(length);
node->references = 1;
} else {
auto node = StringNode::create(length, allocator_);
if (!node)
overflowed_ = true;
}
return node;
}
StringNode* reallocString(StringNode* node, size_t length) {
ARDUINOJSON_ASSERT(node != nullptr);
auto newNode = reinterpret_cast<StringNode*>(
allocator_->reallocate(node, sizeofString(length)));
if (newNode) {
newNode->length = uint16_t(length);
} else {
node = StringNode::resize(node, length, allocator_);
if (!node)
overflowed_ = true;
allocator_->deallocate(node);
}
return newNode;
return node;
}
void deallocString(StringNode* node) {
allocator_->deallocate(node);
StringNode::destroy(node, allocator_);
}
void dereferenceString(const char* s) {
@ -155,7 +144,7 @@ class ResourceManager {
prev->next = node->next;
else
strings_ = node->next;
allocator_->deallocate(node);
StringNode::destroy(node, allocator_);
}
return;
}

View File

@ -4,7 +4,9 @@
#pragma once
#include <ArduinoJson/Memory/Allocator.hpp>
#include <ArduinoJson/Namespace.hpp>
#include <ArduinoJson/Polyfills/assert.hpp>
#include <stdint.h> // uint16_t
@ -15,11 +17,41 @@ struct StringNode {
uint16_t length;
uint16_t references;
char data[1];
static constexpr size_t sizeForLength(size_t n) {
return n + 1 + offsetof(StringNode, data);
}
static StringNode* create(size_t length, Allocator* allocator) {
auto node = reinterpret_cast<StringNode*>(
allocator->allocate(sizeForLength(length)));
if (node) {
node->length = uint16_t(length);
node->references = 1;
}
return node;
}
static StringNode* resize(StringNode* node, size_t length,
Allocator* allocator) {
ARDUINOJSON_ASSERT(node != nullptr);
auto newNode = reinterpret_cast<StringNode*>(
allocator->reallocate(node, sizeForLength(length)));
if (newNode)
newNode->length = uint16_t(length);
else
allocator->deallocate(node);
return newNode;
}
static void destroy(StringNode* node, Allocator* allocator) {
allocator->deallocate(node);
}
};
// Returns the size (in bytes) of an string with n characters.
constexpr size_t sizeofString(size_t n) {
return n + 1 + offsetof(StringNode, data);
return StringNode::sizeForLength(n);
}
ARDUINOJSON_END_PRIVATE_NAMESPACE