Skip to content

Commit aa1aee7

Browse files
committed
Test StringBuffer independently
1 parent 93e0a9e commit aa1aee7

File tree

3 files changed

+53
-1
lines changed

3 files changed

+53
-1
lines changed

extras/tests/ResourceManager/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ add_executable(ResourceManagerTests
88
saveString.cpp
99
shrinkToFit.cpp
1010
size.cpp
11+
StringBuffer.cpp
1112
StringBuilder.cpp
1213
swap.cpp
1314
)
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// ArduinoJson - https://arduinojson.org
2+
// Copyright © 2014-2025, Benoit BLANCHON
3+
// MIT License
4+
5+
#include <ArduinoJson/Memory/StringBuffer.hpp>
6+
#include <catch.hpp>
7+
8+
#include "Allocators.hpp"
9+
#include "Literals.hpp"
10+
11+
using namespace ArduinoJson::detail;
12+
13+
TEST_CASE("StringBuffer") {
14+
SpyingAllocator spy;
15+
ResourceManager resources(&spy);
16+
StringBuffer sb(&resources);
17+
VariantData variant;
18+
19+
SECTION("Tiny string") {
20+
auto ptr = sb.reserve(3);
21+
strcpy(ptr, "hi!");
22+
sb.save(&variant);
23+
24+
REQUIRE(variant.type() == VariantType::TinyString);
25+
REQUIRE(variant.asString() == "hi!");
26+
}
27+
28+
SECTION("Tiny string can't contain NUL") {
29+
auto ptr = sb.reserve(3);
30+
memcpy(ptr, "a\0b", 3);
31+
sb.save(&variant);
32+
33+
REQUIRE(variant.type() == VariantType::OwnedString);
34+
35+
auto str = variant.asString();
36+
REQUIRE(str.size() == 3);
37+
REQUIRE(str.c_str()[0] == 'a');
38+
REQUIRE(str.c_str()[1] == 0);
39+
REQUIRE(str.c_str()[2] == 'b');
40+
}
41+
42+
SECTION("Tiny string can't have 4 characters") {
43+
auto ptr = sb.reserve(4);
44+
strcpy(ptr, "alfa");
45+
sb.save(&variant);
46+
47+
REQUIRE(variant.type() == VariantType::OwnedString);
48+
REQUIRE(variant.asString() == "alfa");
49+
}
50+
}

src/ArduinoJson/Memory/StringBuffer.hpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ class StringBuffer {
3838
}
3939

4040
void save(VariantData* data) {
41-
if (size_ <= tinyStringMaxLength)
41+
ARDUINOJSON_ASSERT(node_ != nullptr);
42+
if (isTinyString(node_->data, size_))
4243
data->setTinyString(node_->data, static_cast<uint8_t>(size_));
4344
else
4445
data->setOwnedString(commitStringNode());

0 commit comments

Comments
 (0)