Compare commits

..

7 Commits

Author SHA1 Message Date
f95dd7d204 Fix overflowed() 2025-02-27 13:42:05 +01:00
b529056a4a Fix tests on VS 2025-02-27 13:42:04 +01:00
ee144b89a2 Deduplicate static strings 2025-02-27 13:42:04 +01:00
08b2400592 Store static string in a dedicated pool 2025-02-27 13:42:04 +01:00
907bb43481 Use strlen() for literals too 2025-02-27 13:41:25 +01:00
7dfa163695 Update changelog 2025-02-27 13:41:25 +01:00
905176ea17 Remove JsonString third argument 2025-02-27 13:41:07 +01:00
52 changed files with 291 additions and 578 deletions

View File

@ -93,40 +93,44 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
include: include:
- clang: "3.9"
runner: ubuntu-20.04
archive: bionic
- clang: "4.0"
runner: ubuntu-20.04
archive: bionic
- clang: "5.0"
runner: ubuntu-20.04
archive: bionic
- clang: "6.0"
runner: ubuntu-20.04
archive: bionic
- clang: "7" - clang: "7"
runner: ubuntu-22.04 runner: ubuntu-20.04
archive: focal
- clang: "8" - clang: "8"
cxxflags: -fsanitize=leak -fno-sanitize-recover=all cxxflags: -fsanitize=leak -fno-sanitize-recover=all
runner: ubuntu-22.04 runner: ubuntu-20.04
archive: focal
- clang: "9" - clang: "9"
cxxflags: -fsanitize=undefined -fno-sanitize-recover=all cxxflags: -fsanitize=undefined -fno-sanitize-recover=all
runner: ubuntu-22.04 runner: ubuntu-20.04
archive: focal
- clang: "10" - clang: "10"
cxxflags: -fsanitize=address -fno-sanitize-recover=all cxxflags: -fsanitize=address -fno-sanitize-recover=all
runner: ubuntu-22.04 runner: ubuntu-20.04
archive: focal
- clang: "11" - clang: "11"
runner: ubuntu-22.04 runner: ubuntu-22.04
- clang: "12" - clang: "12"
runner: ubuntu-22.04 runner: ubuntu-22.04
- clang: "13" - clang: "13"
runner: ubuntu-22.04 runner: ubuntu-22.04
- clang: 14 - clang: "14"
- clang: 15 runner: ubuntu-22.04
- clang: 16 - clang: "15"
- clang: 17 runner: ubuntu-22.04
- clang: 18 runs-on: ${{ matrix.runner }}
- clang: 19
runs-on: ${{ matrix.runner || 'ubuntu-latest' }}
steps: steps:
- name: Add archive repositories - name: Add archive repositories
if: matrix.archive if: matrix.archive
run: | run: |
sudo gpg --keyserver keyserver.ubuntu.com --recv-keys 3B4FE6ACC0B21F32
sudo gpg --export 3B4FE6ACC0B21F32 | sudo tee /etc/apt/trusted.gpg.d/ubuntu-keyring.gpg > /dev/null
sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ ${{ matrix.archive }} main' sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ ${{ matrix.archive }} main'
sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ ${{ matrix.archive }} universe' sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ ${{ matrix.archive }} universe'
- name: Install Clang ${{ matrix.clang }} - name: Install Clang ${{ matrix.clang }}
@ -134,6 +138,7 @@ jobs:
sudo apt-get update sudo apt-get update
sudo apt-get install -y clang-${{ matrix.clang }} sudo apt-get install -y clang-${{ matrix.clang }}
- name: Install libc++ ${{ matrix.clang }} - name: Install libc++ ${{ matrix.clang }}
if: matrix.clang >= 11
run: sudo apt-get install -y libc++-${{ matrix.clang }}-dev libc++abi-${{ matrix.clang }}-dev run: sudo apt-get install -y libc++-${{ matrix.clang }}-dev libc++abi-${{ matrix.clang }}-dev
- name: Install libunwind ${{ matrix.clang }} - name: Install libunwind ${{ matrix.clang }}
if: matrix.clang == 12 # dependency is missing in Ubuntu 22.04 if: matrix.clang == 12 # dependency is missing in Ubuntu 22.04
@ -158,7 +163,7 @@ jobs:
conf_test: conf_test:
name: Test configuration on Linux name: Test configuration on Linux
needs: [gcc, clang] needs: [gcc, clang]
runs-on: ubuntu-22.04 runs-on: ubuntu-20.04
steps: steps:
- name: Install - name: Install
run: | run: |
@ -252,7 +257,7 @@ jobs:
board: arduino:avr:uno board: arduino:avr:uno
- core: arduino:samd - core: arduino:samd
board: arduino:samd:mkr1000 board: arduino:samd:mkr1000
runs-on: ubuntu-22.04 runs-on: ubuntu-20.04
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
@ -407,7 +412,7 @@ jobs:
arm: arm:
name: GCC for ARM processor name: GCC for ARM processor
needs: gcc needs: gcc
runs-on: ubuntu-22.04 runs-on: ubuntu-20.04
steps: steps:
- name: Install - name: Install
run: | run: |
@ -426,7 +431,7 @@ jobs:
coverage: coverage:
needs: gcc needs: gcc
name: Coverage name: Coverage
runs-on: ubuntu-22.04 runs-on: ubuntu-20.04
steps: steps:
- name: Install - name: Install
run: sudo apt-get install -y lcov ninja-build run: sudo apt-get install -y lcov ninja-build
@ -458,7 +463,7 @@ jobs:
valgrind: valgrind:
needs: gcc needs: gcc
name: Valgrind name: Valgrind
runs-on: ubuntu-22.04 runs-on: ubuntu-20.04
steps: steps:
- name: Install - name: Install
run: | run: |
@ -480,24 +485,24 @@ jobs:
clang-tidy: clang-tidy:
needs: clang needs: clang
name: Clang-Tidy name: Clang-Tidy
runs-on: ubuntu-latest runs-on: ubuntu-20.04
steps: steps:
- name: Install - name: Install
run: sudo apt-get install -y clang-tidy libc++-dev libc++abi-dev run: sudo apt-get install -y clang-tidy cmake ninja-build
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Configure - name: Configure
run: cmake -G Ninja -DCMAKE_CXX_CLANG_TIDY="clang-tidy;--warnings-as-errors=*" -DCMAKE_BUILD_TYPE=Debug . run: cmake -G Ninja -DCMAKE_CXX_CLANG_TIDY="clang-tidy-10;--warnings-as-errors=*" -DCMAKE_BUILD_TYPE=Debug .
env: env:
CC: clang CC: clang-10
CXX: clang++ CXX: clang++-10
- name: Check - name: Check
run: cmake --build . -- -k 0 run: cmake --build . -- -k 0
amalgamate: amalgamate:
needs: gcc needs: gcc
name: Amalgamate ArduinoJson.h name: Amalgamate ArduinoJson.h
runs-on: ubuntu-22.04 runs-on: ubuntu-20.04
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
@ -573,7 +578,7 @@ jobs:
codeql: codeql:
name: CodeQL name: CodeQL
runs-on: ubuntu-22.04 runs-on: ubuntu-20.04
needs: gcc needs: gcc
permissions: permissions:

View File

@ -8,7 +8,7 @@ on:
jobs: jobs:
release: release:
name: Create release name: Create release
runs-on: ubuntu-22.04 runs-on: ubuntu-20.04
steps: steps:
- name: Set variables - name: Set variables
id: init id: init

View File

@ -4,6 +4,8 @@ ArduinoJson: change log
HEAD HEAD
---- ----
* Fix conversion from static string to number
* Slightly reduce code size
* Optimize storage of static strings * Optimize storage of static strings
> ### BREAKING CHANGES > ### BREAKING CHANGES
@ -38,23 +40,6 @@ HEAD
> doc["key"] = str; // same as previous line for supported string classes (`String`, `std::string`, etc.) > doc["key"] = str; // same as previous line for supported string classes (`String`, `std::string`, etc.)
> ``` > ```
v7.4.1 (2025-04-11)
------
* Fix crash with tiny Flash strings (issue #2170)
v7.4.0 (2025-04-09)
------
* Optimize storage of tiny strings (up to 3 characters)
* Fix support for `const char[]` (issue #2166)
v7.3.1 (2025-02-27)
------
* Fix conversion from static string to number
* Slightly reduce code size
v7.3.0 (2024-12-29) v7.3.0 (2024-12-29)
------ ------

View File

@ -10,7 +10,7 @@ if(ESP_PLATFORM)
return() return()
endif() endif()
project(ArduinoJson VERSION 7.4.1) project(ArduinoJson VERSION 7.3.0)
if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME)
include(CTest) include(CTest)

View File

@ -80,7 +80,7 @@ ArduinoJson is a C++ JSON library for Arduino and IoT (Internet Of Things).
* Continuously tested on * Continuously tested on
* [Visual Studio 2017, 2019, 2022](https://ci.appveyor.com/project/bblanchon/arduinojson/branch/7.x) * [Visual Studio 2017, 2019, 2022](https://ci.appveyor.com/project/bblanchon/arduinojson/branch/7.x)
* [GCC 4.8, 5, 6, 7, 8, 9, 10, 11, 12](https://github.com/bblanchon/ArduinoJson/actions?query=workflow%3A%22Continuous+Integration%22) * [GCC 4.8, 5, 6, 7, 8, 9, 10, 11, 12](https://github.com/bblanchon/ArduinoJson/actions?query=workflow%3A%22Continuous+Integration%22)
* [Clang 7 to 19](https://github.com/bblanchon/ArduinoJson/actions?query=workflow%3A%22Continuous+Integration%22) * [Clang 3.9, 4.0, 5.0, 6.0, 7, 8, 9, 10, 11, 12, 13, 14, 15](https://github.com/bblanchon/ArduinoJson/actions?query=workflow%3A%22Continuous+Integration%22)
* [Continuously fuzzed with Google OSS Fuzz](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:arduinojson) * [Continuously fuzzed with Google OSS Fuzz](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:arduinojson)
* Passes all default checks of [clang-tidy](https://releases.llvm.org/10.0.0/tools/clang/tools/extra/docs/clang-tidy/) * Passes all default checks of [clang-tidy](https://releases.llvm.org/10.0.0/tools/clang/tools/extra/docs/clang-tidy/)
* Well documented * Well documented

View File

@ -1,4 +1,4 @@
version: 7.4.1.{build} version: 7.3.0.{build}
environment: environment:
matrix: matrix:
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2022 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2022

View File

@ -12,7 +12,7 @@ static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN");
static_assert(ARDUINOJSON_USE_DOUBLE == 0, "ARDUINOJSON_USE_DOUBLE"); static_assert(ARDUINOJSON_USE_DOUBLE == 0, "ARDUINOJSON_USE_DOUBLE");
static_assert(sizeof(ArduinoJson::detail::VariantData) == 6, "slot size"); static_assert(ArduinoJson::detail::ResourceManager::slotSize == 6, "slot size");
void setup() {} void setup() {}
void loop() {} void loop() {}

View File

@ -10,7 +10,7 @@ static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN");
static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE"); static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE");
static_assert(sizeof(VariantData) == 8, "slot size"); static_assert(ArduinoJson::detail::ResourceManager::slotSize == 8, "slot size");
void setup() {} void setup() {}
void loop() {} void loop() {}

View File

@ -10,6 +10,7 @@ static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN");
static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE"); static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE");
static_assert(sizeof(ArduinoJson::detail::VariantData) == 16, "slot size"); static_assert(ArduinoJson::detail::ResourceManager::slotSize == 16,
"slot size");
int main() {} int main() {}

View File

@ -10,6 +10,6 @@ static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN");
static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE"); static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE");
static_assert(sizeof(ArduinoJson::detail::VariantData) == 8, "slot size"); static_assert(ArduinoJson::detail::ResourceManager::slotSize == 8, "slot size");
int main() {} int main() {}

View File

@ -46,7 +46,7 @@ TEST_CASE("BasicJsonDocument") {
deserializeJson(doc, "{\"hello\":\"world\"}"); deserializeJson(doc, "{\"hello\":\"world\"}");
REQUIRE(doc.as<std::string>() == "{\"hello\":\"world\"}"); REQUIRE(doc.as<std::string>() == "{\"hello\":\"world\"}");
doc.clear(); doc.clear();
REQUIRE(allocatorLog == "AARARDDD"); REQUIRE(allocatorLog == "ARAARDDD");
} }
SECTION("copy") { SECTION("copy") {

View File

@ -269,10 +269,10 @@ inline size_t sizeofPoolList(size_t n = ARDUINOJSON_INITIAL_POOL_COUNT) {
return sizeof(MemoryPool<VariantData>) * n; return sizeof(MemoryPool<VariantData>) * n;
} }
template <typename T = ArduinoJson::detail::VariantData>
inline size_t sizeofPool( inline size_t sizeofPool(
ArduinoJson::detail::SlotCount n = ARDUINOJSON_POOL_CAPACITY) { ArduinoJson::detail::SlotCount n = ARDUINOJSON_POOL_CAPACITY) {
return ArduinoJson::detail::MemoryPool<T>::slotsToBytes(n); using namespace ArduinoJson::detail;
return MemoryPool<VariantData>::slotsToBytes(n);
} }
inline size_t sizeofStaticStringPool( inline size_t sizeofStaticStringPool(

View File

@ -8,7 +8,7 @@
#include "Allocators.hpp" #include "Allocators.hpp"
#include "Literals.hpp" #include "Literals.hpp"
using namespace ArduinoJson::detail; using ArduinoJson::detail::sizeofArray;
TEST_CASE("JsonArray::add(T)") { TEST_CASE("JsonArray::add(T)") {
SpyingAllocator spy; SpyingAllocator spy;
@ -33,8 +33,7 @@ TEST_CASE("JsonArray::add(T)") {
REQUIRE(array[0].is<double>()); REQUIRE(array[0].is<double>());
REQUIRE_FALSE(array[0].is<bool>()); REQUIRE_FALSE(array[0].is<bool>());
REQUIRE(spy.log() == AllocatorLog{ REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofPool<VariantData>()), Allocate(sizeofPool()),
Allocate(sizeofPool<EightByteValue>()),
}); });
} }

View File

@ -7,7 +7,7 @@
#include "Allocators.hpp" #include "Allocators.hpp"
using namespace ArduinoJson::detail; using ArduinoJson::detail::sizeofArray;
TEST_CASE("deserialize JSON array") { TEST_CASE("deserialize JSON array") {
SpyingAllocator spy; SpyingAllocator spy;
@ -92,12 +92,8 @@ TEST_CASE("deserialize JSON array") {
REQUIRE(arr[0].as<double>() == Approx(4.2123456)); REQUIRE(arr[0].as<double>() == Approx(4.2123456));
REQUIRE(arr[1] == -7E89); REQUIRE(arr[1] == -7E89);
REQUIRE(spy.log() == AllocatorLog{ REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofPool<VariantData>()), Allocate(sizeofPool()),
Allocate(sizeofPool<EightByteValue>()), Reallocate(sizeofPool(), sizeofPool(4)),
Reallocate(sizeofPool<VariantData>(),
sizeofPool<VariantData>(2)),
Reallocate(sizeofPool<EightByteValue>(),
sizeofPool<EightByteValue>(2)),
}); });
} }

View File

@ -121,7 +121,7 @@ TEST_CASE("deserializeJson() returns NoMemory if string length overflows") {
} }
} }
TEST_CASE("deserializeJson() returns NoMemory if 8-bit slot allocation fails") { TEST_CASE("deserializeJson() returns NoMemory if extension allocation fails") {
JsonDocument doc(FailingAllocator::instance()); JsonDocument doc(FailingAllocator::instance());
SECTION("uint32_t should pass") { SECTION("uint32_t should pass") {

View File

@ -26,8 +26,8 @@ TEST_CASE("deserializeJson(char*)") {
REQUIRE(spy.log() == REQUIRE(spy.log() ==
AllocatorLog{ AllocatorLog{
Allocate(sizeofStringBuffer()), Allocate(sizeofStringBuffer()),
Allocate(sizeofPool()),
Reallocate(sizeofStringBuffer(), sizeofString("hello")), Reallocate(sizeofStringBuffer(), sizeofString("hello")),
Allocate(sizeofPool()),
Allocate(sizeofStringBuffer()), Allocate(sizeofStringBuffer()),
Reallocate(sizeofStringBuffer(), sizeofString("world")), Reallocate(sizeofStringBuffer(), sizeofString("world")),
Reallocate(sizeofPool(), sizeofObject(1)), Reallocate(sizeofPool(), sizeofObject(1)),

View File

@ -292,23 +292,22 @@ TEST_CASE("deserialize JSON object") {
} }
SECTION("Repeated key") { SECTION("Repeated key") {
DeserializationError err = DeserializationError err = deserializeJson(doc, "{a:{b:{c:1}},a:2}");
deserializeJson(doc, "{alfa:{bravo:{charlie:1}},alfa:2}");
REQUIRE(err == DeserializationError::Ok); REQUIRE(err == DeserializationError::Ok);
REQUIRE(doc.as<std::string>() == "{\"alfa\":2}"); REQUIRE(doc.as<std::string>() == "{\"a\":2}");
REQUIRE(spy.log() == REQUIRE(spy.log() ==
AllocatorLog{ AllocatorLog{
Allocate(sizeofStringBuffer()), Allocate(sizeofStringBuffer()),
Reallocate(sizeofStringBuffer(), sizeofString("a")),
Allocate(sizeofPool()), Allocate(sizeofPool()),
Reallocate(sizeofStringBuffer(), sizeofString("alfa")),
Allocate(sizeofStringBuffer()), Allocate(sizeofStringBuffer()),
Reallocate(sizeofStringBuffer(), sizeofString("bravo")), Reallocate(sizeofStringBuffer(), sizeofString("b")),
Allocate(sizeofStringBuffer()), Allocate(sizeofStringBuffer()),
Reallocate(sizeofStringBuffer(), sizeofString("charlie")), Reallocate(sizeofStringBuffer(), sizeofString("c")),
Allocate(sizeofStringBuffer()), Allocate(sizeofStringBuffer()),
Deallocate(sizeofString("bravo")), Deallocate(sizeofString("b")),
Deallocate(sizeofString("charlie")), Deallocate(sizeofString("c")),
Deallocate(sizeofStringBuffer()), Deallocate(sizeofStringBuffer()),
Reallocate(sizeofPool(), sizeofObject(2) + sizeofObject(1)), Reallocate(sizeofPool(), sizeofObject(2) + sizeofObject(1)),
}); });
@ -379,7 +378,7 @@ TEST_CASE("deserialize JSON object under memory constraints") {
} }
SECTION("pool allocation fails") { SECTION("pool allocation fails") {
timebomb.setCountdown(1); timebomb.setCountdown(2);
char input[] = "{\"a\":1}"; char input[] = "{\"a\":1}";
DeserializationError err = deserializeJson(doc, input); DeserializationError err = deserializeJson(doc, input);
@ -390,11 +389,11 @@ TEST_CASE("deserialize JSON object under memory constraints") {
SECTION("string allocation fails") { SECTION("string allocation fails") {
timebomb.setCountdown(3); timebomb.setCountdown(3);
char input[] = "{\"alfa\":\"bravo\"}"; char input[] = "{\"a\":\"b\"}";
DeserializationError err = deserializeJson(doc, input); DeserializationError err = deserializeJson(doc, input);
REQUIRE(err == DeserializationError::NoMemory); REQUIRE(err == DeserializationError::NoMemory);
REQUIRE(doc.as<std::string>() == "{\"alfa\":null}"); REQUIRE(doc.as<std::string>() == "{\"a\":null}");
} }
} }

View File

@ -133,8 +133,8 @@ TEST_CASE("Allocation of the key fails") {
REQUIRE(spy.log() == REQUIRE(spy.log() ==
AllocatorLog{ AllocatorLog{
Allocate(sizeofStringBuffer()), Allocate(sizeofStringBuffer()),
Allocate(sizeofPool()),
Reallocate(sizeofStringBuffer(), sizeofString("hello")), Reallocate(sizeofStringBuffer(), sizeofString("hello")),
Allocate(sizeofPool()),
AllocateFail(sizeofStringBuffer()), AllocateFail(sizeofStringBuffer()),
ReallocateFail(sizeofPool(), sizeofObject(1)), ReallocateFail(sizeofPool(), sizeofObject(1)),
}); });
@ -155,8 +155,8 @@ TEST_CASE("Allocation of the key fails") {
REQUIRE(spy.log() == REQUIRE(spy.log() ==
AllocatorLog{ AllocatorLog{
Allocate(sizeofStringBuffer()), Allocate(sizeofStringBuffer()),
Allocate(sizeofPool()),
Reallocate(sizeofStringBuffer(), sizeofString("hello")), Reallocate(sizeofStringBuffer(), sizeofString("hello")),
Allocate(sizeofPool()),
AllocateFail(sizeofStringBuffer()), AllocateFail(sizeofStringBuffer()),
ReallocateFail(sizeofPool(), sizeofObject(1)), ReallocateFail(sizeofPool(), sizeofObject(1)),
}); });

View File

@ -69,8 +69,6 @@ TEST_CASE("JsonDocument assignment") {
doc2 = std::move(doc1); doc2 = std::move(doc1);
REQUIRE(doc2.as<std::string>() == "{\"hello\":\"world\"}"); REQUIRE(doc2.as<std::string>() == "{\"hello\":\"world\"}");
// NOLINTNEXTLINE(clang-analyzer-cplusplus.Move)
REQUIRE(doc1.as<std::string>() == "null"); REQUIRE(doc1.as<std::string>() == "null");
} }
REQUIRE(spyingAllocator.log() == AllocatorLog{ REQUIRE(spyingAllocator.log() == AllocatorLog{

View File

@ -44,8 +44,6 @@ TEST_CASE("JsonDocument constructor") {
JsonDocument doc2(std::move(doc1)); JsonDocument doc2(std::move(doc1));
REQUIRE(doc2.as<std::string>() == "The size of this string is 32!!"); REQUIRE(doc2.as<std::string>() == "The size of this string is 32!!");
// NOLINTNEXTLINE(clang-analyzer-cplusplus.Move)
REQUIRE(doc1.as<std::string>() == "null"); REQUIRE(doc1.as<std::string>() == "null");
} }
REQUIRE(spyingAllocator.log() == AllocatorLog{ REQUIRE(spyingAllocator.log() == AllocatorLog{

View File

@ -89,13 +89,6 @@ TEST_CASE("JsonDocument::set()") {
}); });
} }
SECTION("Flash tiny string") { // issue #2170
doc.set(F("abc"));
REQUIRE(doc.as<const char*>() == "abc"_s);
REQUIRE(spy.log() == AllocatorLog{});
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY #ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("VLA") { SECTION("VLA") {
size_t i = 16; size_t i = 16;

View File

@ -179,15 +179,15 @@ TEST_CASE("JsonDocument::shrinkToFit()") {
} }
SECTION("owned string in object") { SECTION("owned string in object") {
doc["key1"_s] = "value"_s; doc["key"_s] = "value"_s;
doc.shrinkToFit(); doc.shrinkToFit();
REQUIRE(doc.as<std::string>() == "{\"key1\":\"value\"}"); REQUIRE(doc.as<std::string>() == "{\"key\":\"value\"}");
REQUIRE(spyingAllocator.log() == REQUIRE(spyingAllocator.log() ==
AllocatorLog{ AllocatorLog{
Allocate(sizeofPool()), Allocate(sizeofPool()),
Allocate(sizeofString("key1")), Allocate(sizeofString("key")),
Allocate(sizeofString("value")), Allocate(sizeofString("value")),
Reallocate(sizeofPool(), sizeofPool(2)), Reallocate(sizeofPool(), sizeofPool(2)),
}); });

View File

@ -88,13 +88,13 @@ TEST_CASE("JsonObject::set()") {
JsonDocument doc3(&timebomb); JsonDocument doc3(&timebomb);
JsonObject obj3 = doc3.to<JsonObject>(); JsonObject obj3 = doc3.to<JsonObject>();
obj1["alpha"_s] = 1; obj1["a"_s] = 1;
obj1["beta"_s] = 2; obj1["b"_s] = 2;
bool success = obj3.set(obj1); bool success = obj3.set(obj1);
REQUIRE(success == false); REQUIRE(success == false);
REQUIRE(doc3.as<std::string>() == "{\"alpha\":1}"); REQUIRE(doc3.as<std::string>() == "{\"a\":1}");
} }
SECTION("copy fails in the middle of an array") { SECTION("copy fails in the middle of an array") {

View File

@ -199,7 +199,7 @@ TEST_CASE("JsonVariant::as()") {
REQUIRE(variant.as<JsonString>() == "hello"); REQUIRE(variant.as<JsonString>() == "hello");
} }
SECTION("set(std::string(\"4.2\")) (tiny string optimization)") { SECTION("set(std::string(\"4.2\"))") {
variant.set("4.2"_s); variant.set("4.2"_s);
REQUIRE(variant.as<bool>() == true); REQUIRE(variant.as<bool>() == true);
@ -211,18 +211,6 @@ TEST_CASE("JsonVariant::as()") {
REQUIRE(variant.as<JsonString>().isStatic() == false); REQUIRE(variant.as<JsonString>().isStatic() == false);
} }
SECTION("set(std::string(\"123.45\"))") {
variant.set("123.45"_s);
REQUIRE(variant.as<bool>() == true);
REQUIRE(variant.as<long>() == 123L);
REQUIRE(variant.as<double>() == Approx(123.45));
REQUIRE(variant.as<const char*>() == "123.45"_s);
REQUIRE(variant.as<std::string>() == "123.45"_s);
REQUIRE(variant.as<JsonString>() == "123.45");
REQUIRE(variant.as<JsonString>().isStatic() == false);
}
SECTION("set(\"true\")") { SECTION("set(\"true\")") {
variant.set("true"); variant.set("true");

View File

@ -8,7 +8,7 @@
#include "Allocators.hpp" #include "Allocators.hpp"
#include "Literals.hpp" #include "Literals.hpp"
using namespace ArduinoJson::detail; using ArduinoJson::detail::sizeofObject;
enum ErrorCode { ERROR_01 = 1, ERROR_10 = 10 }; enum ErrorCode { ERROR_01 = 1, ERROR_10 = 10 };
@ -65,18 +65,6 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
}); });
} }
SECTION("char* (tiny string optimization)") {
char str[16];
strcpy(str, "abc");
bool result = variant.set(str);
strcpy(str, "def");
REQUIRE(result == true);
REQUIRE(variant == "abc"); // stores by copy
REQUIRE(spy.log() == AllocatorLog{});
}
SECTION("(char*)0") { SECTION("(char*)0") {
bool result = variant.set(static_cast<char*>(0)); bool result = variant.set(static_cast<char*>(0));
@ -197,10 +185,10 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true); REQUIRE(result == true);
REQUIRE(variant.is<double>() == true); REQUIRE(variant.is<double>() == true);
REQUIRE(variant.as<double>() == 1.2); REQUIRE(variant.as<double>() == 1.2);
REQUIRE(spy.log() == AllocatorLog{ REQUIRE(spy.log() ==
Allocate(sizeofPool<EightByteValue>()), AllocatorLog{
Reallocate(sizeofPool<EightByteValue>(), Allocate(sizeofPool()),
sizeofPool<EightByteValue>(1)), Reallocate(sizeofPool(), sizeofPool(1)), // one extension slot
}); });
} }
@ -220,10 +208,10 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true); REQUIRE(result == true);
REQUIRE(variant.is<int64_t>() == true); REQUIRE(variant.is<int64_t>() == true);
REQUIRE(variant.as<int64_t>() == -2147483649LL); REQUIRE(variant.as<int64_t>() == -2147483649LL);
REQUIRE(spy.log() == AllocatorLog{ REQUIRE(spy.log() ==
Allocate(sizeofPool<EightByteValue>()), AllocatorLog{
Reallocate(sizeofPool<EightByteValue>(), Allocate(sizeofPool()),
sizeofPool<EightByteValue>(1)), Reallocate(sizeofPool(), sizeofPool(1)), // one extension slot
}); });
} }
@ -243,10 +231,10 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true); REQUIRE(result == true);
REQUIRE(variant.is<uint64_t>() == true); REQUIRE(variant.is<uint64_t>() == true);
REQUIRE(variant.as<uint64_t>() == 4294967296); REQUIRE(variant.as<uint64_t>() == 4294967296);
REQUIRE(spy.log() == AllocatorLog{ REQUIRE(spy.log() ==
Allocate(sizeofPool<EightByteValue>()), AllocatorLog{
Reallocate(sizeofPool<EightByteValue>(), Allocate(sizeofPool()),
sizeofPool<EightByteValue>(1)), Reallocate(sizeofPool(), sizeofPool(1)), // one extension slot
}); });
} }
@ -378,7 +366,7 @@ TEST_CASE("JsonVariant::set() releases the previous value") {
} }
SECTION("float") { SECTION("float") {
v.set(1.2f); v.set(1.2);
REQUIRE(spy.log() == AllocatorLog{ REQUIRE(spy.log() == AllocatorLog{
Deallocate(sizeofString("world")), Deallocate(sizeofString("world")),
}); });
@ -393,7 +381,7 @@ TEST_CASE("JsonVariant::set() releases the previous value") {
} }
} }
TEST_CASE("JsonVariant::set() reuses 8-bit slot") { TEST_CASE("JsonVariant::set() reuses extension slot") {
SpyingAllocator spy; SpyingAllocator spy;
JsonDocument doc(&spy); JsonDocument doc(&spy);
JsonVariant variant = doc.to<JsonVariant>(); JsonVariant variant = doc.to<JsonVariant>();

View File

@ -7,7 +7,6 @@ add_executable(MiscTests
conflicts.cpp conflicts.cpp
issue1967.cpp issue1967.cpp
issue2129.cpp issue2129.cpp
issue2166.cpp
JsonString.cpp JsonString.cpp
NoArduinoHeader.cpp NoArduinoHeader.cpp
printable.cpp printable.cpp

View File

@ -128,7 +128,6 @@ TEST_CASE("IsString<T>") {
CHECK(IsString<const __FlashStringHelper*>::value == true); CHECK(IsString<const __FlashStringHelper*>::value == true);
CHECK(IsString<const char*>::value == true); CHECK(IsString<const char*>::value == true);
CHECK(IsString<const char[8]>::value == true); CHECK(IsString<const char[8]>::value == true);
CHECK(IsString<const char[]>::value == true);
CHECK(IsString<::String>::value == true); CHECK(IsString<::String>::value == true);
CHECK(IsString<::StringSumHelper>::value == true); CHECK(IsString<::StringSumHelper>::value == true);
CHECK(IsString<const EmptyStruct*>::value == false); CHECK(IsString<const EmptyStruct*>::value == false);

View File

@ -1,22 +0,0 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2025, Benoit BLANCHON
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
struct CCLASS {
static const char mszKey[];
};
TEST_CASE("Issue #2166") {
JsonDocument doc;
doc[CCLASS::mszKey] = 12;
REQUIRE(doc.as<std::string>() == "{\"test3\":12}");
JsonObject obj = doc.to<JsonObject>();
obj[CCLASS::mszKey] = 12;
REQUIRE(doc.as<std::string>() == "{\"test3\":12}");
}
const char CCLASS::mszKey[] = "test3";

View File

@ -5,11 +5,8 @@
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <catch.hpp> #include <catch.hpp>
#include "Allocators.hpp"
TEST_CASE("deserialize MsgPack array") { TEST_CASE("deserialize MsgPack array") {
SpyingAllocator spy; JsonDocument doc;
JsonDocument doc(&spy);
SECTION("fixarray") { SECTION("fixarray") {
SECTION("empty") { SECTION("empty") {
@ -33,24 +30,6 @@ TEST_CASE("deserialize MsgPack array") {
REQUIRE(array[0] == 1); REQUIRE(array[0] == 1);
REQUIRE(array[1] == 2); REQUIRE(array[1] == 2);
} }
SECTION("tiny strings") {
DeserializationError error =
deserializeMsgPack(doc, "\x92\xA3xxx\xA3yyy");
REQUIRE(error == DeserializationError::Ok);
REQUIRE(doc.is<JsonArray>());
REQUIRE(doc.size() == 2);
REQUIRE(doc[0] == "xxx");
REQUIRE(doc[1] == "yyy");
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofPool()),
Allocate(sizeofString("xxx")),
// Buffer is reused for the next string
Deallocate(sizeofString("xxx")),
Reallocate(sizeofPool(), sizeofPool(2)),
});
}
} }
SECTION("array 16") { SECTION("array 16") {

View File

@ -348,14 +348,13 @@ TEST_CASE("deserializeMsgPack() under memory constaints") {
SECTION("{}") { SECTION("{}") {
checkError(0, "\x80", DeserializationError::Ok); checkError(0, "\x80", DeserializationError::Ok);
} }
SECTION("{Hello:1}") { SECTION("{H:1}") {
checkError(1, "\x81\xA5Hello\x01", DeserializationError::NoMemory); checkError(1, "\x81\xA1H\x01", DeserializationError::NoMemory);
checkError(2, "\x81\xA5Hello\x01", DeserializationError::Ok); checkError(2, "\x81\xA1H\x01", DeserializationError::Ok);
} }
SECTION("{Hello:1,World:2}") { SECTION("{H:1,W:2}") {
checkError(2, "\x82\xA5Hello\x01\xA5World\x02", checkError(2, "\x82\xA1H\x01\xA1W\x02", DeserializationError::NoMemory);
DeserializationError::NoMemory); checkError(3, "\x82\xA1H\x01\xA1W\x02", DeserializationError::Ok);
checkError(3, "\x82\xA5Hello\x01\xA5World\x02", DeserializationError::Ok);
} }
} }
@ -363,16 +362,14 @@ TEST_CASE("deserializeMsgPack() under memory constaints") {
SECTION("{}") { SECTION("{}") {
checkError(0, "\xDE\x00\x00", DeserializationError::Ok); checkError(0, "\xDE\x00\x00", DeserializationError::Ok);
} }
SECTION("{Hello:1}") { SECTION("{H:1}") {
checkError(1, "\xDE\x00\x01\xA5Hello\x01", checkError(1, "\xDE\x00\x01\xA1H\x01", DeserializationError::NoMemory);
DeserializationError::NoMemory); checkError(2, "\xDE\x00\x01\xA1H\x01", DeserializationError::Ok);
checkError(2, "\xDE\x00\x01\xA5Hello\x01", DeserializationError::Ok);
} }
SECTION("{Hello:1,World:2}") { SECTION("{H:1,W:2}") {
checkError(2, "\xDE\x00\x02\xA5Hello\x01\xA5World\x02", checkError(2, "\xDE\x00\x02\xA1H\x01\xA1W\x02",
DeserializationError::NoMemory); DeserializationError::NoMemory);
checkError(3, "\xDE\x00\x02\xA5Hello\x01\xA5World\x02", checkError(3, "\xDE\x00\x02\xA1H\x01\xA1W\x02", DeserializationError::Ok);
DeserializationError::Ok);
} }
} }
@ -385,8 +382,8 @@ TEST_CASE("deserializeMsgPack() under memory constaints") {
DeserializationError::NoMemory); DeserializationError::NoMemory);
checkError(2, "\xDF\x00\x00\x00\x01\xA1H\x01", DeserializationError::Ok); checkError(2, "\xDF\x00\x00\x00\x01\xA1H\x01", DeserializationError::Ok);
} }
SECTION("{Hello:1,World:2}") { SECTION("{H:1,W:2}") {
checkError(2, "\xDF\x00\x00\x00\x02\xA5Hello\x01\xA5World\x02", checkError(2, "\xDF\x00\x00\x00\x02\xA1H\x01\xA1W\x02",
DeserializationError::NoMemory); DeserializationError::NoMemory);
checkError(3, "\xDF\x00\x00\x00\x02\xA1H\x01\xA1W\x02", checkError(3, "\xDF\x00\x00\x00\x02\xA1H\x01\xA1W\x02",
DeserializationError::Ok); DeserializationError::Ok);

View File

@ -9,7 +9,6 @@ add_executable(ResourceManagerTests
saveString.cpp saveString.cpp
shrinkToFit.cpp shrinkToFit.cpp
size.cpp size.cpp
StringBuffer.cpp
StringBuilder.cpp StringBuilder.cpp
swap.cpp swap.cpp
) )

View File

@ -1,50 +0,0 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2025, Benoit BLANCHON
// MIT License
#include <ArduinoJson.hpp>
#include <catch.hpp>
#include "Allocators.hpp"
#include "Literals.hpp"
using namespace ArduinoJson::detail;
TEST_CASE("StringBuffer") {
SpyingAllocator spy;
ResourceManager resources(&spy);
StringBuffer sb(&resources);
VariantData variant;
SECTION("Tiny string") {
auto ptr = sb.reserve(3);
strcpy(ptr, "hi!");
sb.save(&variant);
REQUIRE(variant.type() == VariantType::TinyString);
REQUIRE(variant.asString(&resources) == "hi!");
}
SECTION("Tiny string can't contain NUL") {
auto ptr = sb.reserve(3);
memcpy(ptr, "a\0b", 3);
sb.save(&variant);
REQUIRE(variant.type() == VariantType::OwnedString);
auto str = variant.asString(&resources);
REQUIRE(str.size() == 3);
REQUIRE(str.c_str()[0] == 'a');
REQUIRE(str.c_str()[1] == 0);
REQUIRE(str.c_str()[2] == 'b');
}
SECTION("Tiny string can't have 4 characters") {
auto ptr = sb.reserve(4);
strcpy(ptr, "alfa");
sb.save(&variant);
REQUIRE(variant.type() == VariantType::OwnedString);
REQUIRE(variant.asString(&resources) == "alfa");
}
}

View File

@ -2,12 +2,11 @@
// Copyright © 2014-2025, Benoit BLANCHON // Copyright © 2014-2025, Benoit BLANCHON
// MIT License // MIT License
#include <ArduinoJson.hpp> #include <ArduinoJson/Memory/StringBuilder.hpp>
#include <catch.hpp> #include <catch.hpp>
#include "Allocators.hpp" #include "Allocators.hpp"
using namespace ArduinoJson;
using namespace ArduinoJson::detail; using namespace ArduinoJson::detail;
TEST_CASE("StringBuilder") { TEST_CASE("StringBuilder") {
@ -17,36 +16,17 @@ TEST_CASE("StringBuilder") {
SECTION("Empty string") { SECTION("Empty string") {
StringBuilder str(&resources); StringBuilder str(&resources);
VariantData data;
str.startString(); str.startString();
str.save(&data); str.save();
REQUIRE(resources.size() == sizeofString(""));
REQUIRE(resources.overflowed() == false); REQUIRE(resources.overflowed() == false);
REQUIRE(spyingAllocator.log() == AllocatorLog{ REQUIRE(spyingAllocator.log() ==
AllocatorLog{
Allocate(sizeofStringBuffer()), Allocate(sizeofStringBuffer()),
Reallocate(sizeofStringBuffer(), sizeofString("")),
}); });
REQUIRE(data.type() == VariantType::TinyString);
}
SECTION("Tiny string") {
StringBuilder str(&resources);
str.startString();
str.append("url");
REQUIRE(str.isValid() == true);
REQUIRE(str.str() == "url");
REQUIRE(spyingAllocator.log() == AllocatorLog{
Allocate(sizeofStringBuffer()),
});
VariantData data;
str.save(&data);
REQUIRE(resources.overflowed() == false);
REQUIRE(data.type() == VariantType::TinyString);
REQUIRE(data.asString(&resources) == "url");
} }
SECTION("Short string fits in first allocation") { SECTION("Short string fits in first allocation") {
@ -116,72 +96,48 @@ TEST_CASE("StringBuilder") {
} }
} }
static VariantData saveString(StringBuilder& builder, const char* s) { static StringNode* addStringToPool(ResourceManager& resources, const char* s) {
VariantData data; StringBuilder str(&resources);
builder.startString(); str.startString();
builder.append(s); str.append(s);
builder.save(&data); return str.save();
return data;
} }
TEST_CASE("StringBuilder::save() deduplicates strings") { TEST_CASE("StringBuilder::save() deduplicates strings") {
SpyingAllocator spy; ResourceManager resources;
ResourceManager resources(&spy);
StringBuilder builder(&resources);
SECTION("Basic") { SECTION("Basic") {
auto s1 = saveString(builder, "hello"); auto s1 = addStringToPool(resources, "hello");
auto s2 = saveString(builder, "world"); auto s2 = addStringToPool(resources, "world");
auto s3 = saveString(builder, "hello"); auto s3 = addStringToPool(resources, "hello");
REQUIRE(s1.asString(&resources) == "hello"); REQUIRE(s1 == s3);
REQUIRE(s2.asString(&resources) == "world"); REQUIRE(s2 != s3);
REQUIRE(+s1.asString(&resources).c_str() == REQUIRE(s1->references == 2);
+s3.asString(&resources).c_str()); // same address REQUIRE(s2->references == 1);
REQUIRE(s3->references == 2);
REQUIRE(spy.log() == REQUIRE(resources.size() == sizeofString("hello") + sizeofString("world"));
AllocatorLog{
Allocate(sizeofStringBuffer()),
Reallocate(sizeofStringBuffer(), sizeofString("hello")),
Allocate(sizeofStringBuffer()),
Reallocate(sizeofStringBuffer(), sizeofString("world")),
Allocate(sizeofStringBuffer()),
});
} }
SECTION("Requires terminator") { SECTION("Requires terminator") {
auto s1 = saveString(builder, "hello world"); auto s1 = addStringToPool(resources, "hello world");
auto s2 = saveString(builder, "hello"); auto s2 = addStringToPool(resources, "hello");
REQUIRE(s1.asString(&resources) == "hello world"); REQUIRE(s2 != s1);
REQUIRE(s2.asString(&resources) == "hello"); REQUIRE(s1->references == 1);
REQUIRE(+s2.asString(&resources).c_str() != REQUIRE(s2->references == 1);
+s1.asString(&resources).c_str()); // different address REQUIRE(resources.size() ==
sizeofString("hello world") + sizeofString("hello"));
REQUIRE(spy.log() ==
AllocatorLog{
Allocate(sizeofStringBuffer()),
Reallocate(sizeofStringBuffer(), sizeofString("hello world")),
Allocate(sizeofStringBuffer()),
Reallocate(sizeofStringBuffer(), sizeofString("hello")),
});
} }
SECTION("Don't overrun") { SECTION("Don't overrun") {
auto s1 = saveString(builder, "hello world"); auto s1 = addStringToPool(resources, "hello world");
auto s2 = saveString(builder, "worl"); auto s2 = addStringToPool(resources, "wor");
REQUIRE(s1.asString(&resources) == "hello world"); REQUIRE(s2 != s1);
REQUIRE(s2.asString(&resources) == "worl"); REQUIRE(s1->references == 1);
REQUIRE(s2.asString(&resources).c_str() != REQUIRE(s2->references == 1);
s1.asString(&resources).c_str()); // different address REQUIRE(resources.size() ==
sizeofString("hello world") + sizeofString("wor"));
REQUIRE(spy.log() ==
AllocatorLog{
Allocate(sizeofStringBuffer()),
Reallocate(sizeofStringBuffer(), sizeofString("hello world")),
Allocate(sizeofStringBuffer()),
Reallocate(sizeofStringBuffer(), sizeofString("worl")),
});
} }
} }

View File

@ -1,7 +1,7 @@
version: "7.4.1" version: "7.3.0"
description: >- description: >-
A simple and efficient JSON library for embedded C++. A simple and efficient JSON library for embedded C++.
★ 6898 stars on GitHub! ★ 6785 stars on GitHub!
Supports serialization, deserialization, MessagePack, streams, filtering, and more. Supports serialization, deserialization, MessagePack, streams, filtering, and more.
Fully tested and documented. Fully tested and documented.
url: https://arduinojson.org/ url: https://arduinojson.org/

View File

@ -1,13 +1,13 @@
{ {
"name": "ArduinoJson", "name": "ArduinoJson",
"keywords": "json, rest, http, web", "keywords": "json, rest, http, web",
"description": "A simple and efficient JSON library for embedded C++. ⭐ 6898 stars on GitHub! Supports serialization, deserialization, MessagePack, streams, filtering, and more. Fully tested and documented.", "description": "A simple and efficient JSON library for embedded C++. ⭐ 6785 stars on GitHub! Supports serialization, deserialization, MessagePack, streams, filtering, and more. Fully tested and documented.",
"homepage": "https://arduinojson.org/?utm_source=meta&utm_medium=library.json", "homepage": "https://arduinojson.org/?utm_source=meta&utm_medium=library.json",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/bblanchon/ArduinoJson.git" "url": "https://github.com/bblanchon/ArduinoJson.git"
}, },
"version": "7.4.1", "version": "7.3.0",
"authors": { "authors": {
"name": "Benoit Blanchon", "name": "Benoit Blanchon",
"url": "https://blog.benoitblanchon.fr" "url": "https://blog.benoitblanchon.fr"

View File

@ -1,9 +1,9 @@
name=ArduinoJson name=ArduinoJson
version=7.4.1 version=7.3.0
author=Benoit Blanchon <blog.benoitblanchon.fr> author=Benoit Blanchon <blog.benoitblanchon.fr>
maintainer=Benoit Blanchon <blog.benoitblanchon.fr> maintainer=Benoit Blanchon <blog.benoitblanchon.fr>
sentence=A simple and efficient JSON library for embedded C++. sentence=A simple and efficient JSON library for embedded C++.
paragraph=⭐ 6898 stars on GitHub! Supports serialization, deserialization, MessagePack, streams, filtering, and more. Fully tested and documented. paragraph=⭐ 6785 stars on GitHub! Supports serialization, deserialization, MessagePack, streams, filtering, and more. Fully tested and documented.
category=Data Processing category=Data Processing
url=https://arduinojson.org/?utm_source=meta&utm_medium=library.properties url=https://arduinojson.org/?utm_source=meta&utm_medium=library.properties
architectures=* architectures=*

View File

@ -73,7 +73,7 @@ inline bool ArrayData::addValue(const T& value, ResourceManager* resources) {
// Returns the size (in bytes) of an array with n elements. // Returns the size (in bytes) of an array with n elements.
constexpr size_t sizeofArray(size_t n) { constexpr size_t sizeofArray(size_t n) {
return n * sizeof(VariantData); return n * ResourceManager::slotSize;
} }
ARDUINOJSON_END_PRIVATE_NAMESPACE ARDUINOJSON_END_PRIVATE_NAMESPACE

View File

@ -274,9 +274,9 @@
#endif #endif
#if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_DOUBLE #if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_DOUBLE
# define ARDUINOJSON_USE_8_BYTE_POOL 1 # define ARDUINOJSON_USE_EXTENSIONS 1
#else #else
# define ARDUINOJSON_USE_8_BYTE_POOL 0 # define ARDUINOJSON_USE_EXTENSIONS 0
#endif #endif
#if defined(nullptr) #if defined(nullptr)

View File

@ -275,11 +275,13 @@ class JsonDeserializer {
if (memberFilter.allow()) { if (memberFilter.allow()) {
auto member = object.getMember(adaptString(key), resources_); auto member = object.getMember(adaptString(key), resources_);
if (!member) { if (!member) {
auto keyVariant = object.addPair(&member, resources_); // Save key in memory pool.
if (!keyVariant) auto savedKey = stringBuilder_.save();
return DeserializationError::NoMemory;
stringBuilder_.save(keyVariant); // Allocate slot in object
member = object.addMember(savedKey, resources_);
if (!member)
return DeserializationError::NoMemory;
} else { } else {
member->clear(resources_); member->clear(resources_);
} }
@ -388,7 +390,7 @@ class JsonDeserializer {
if (err) if (err)
return err; return err;
stringBuilder_.save(&variant); variant.setOwnedString(stringBuilder_.save());
return DeserializationError::Ok; return DeserializationError::Ok;
} }

View File

@ -18,7 +18,16 @@ class VariantData;
class VariantWithId; class VariantWithId;
class ResourceManager { class ResourceManager {
union SlotData {
VariantData variant;
#if ARDUINOJSON_USE_EXTENSIONS
VariantExtension extension;
#endif
};
public: public:
constexpr static size_t slotSize = sizeof(SlotData);
ResourceManager(Allocator* allocator = DefaultAllocator::instance()) ResourceManager(Allocator* allocator = DefaultAllocator::instance())
: allocator_(allocator), overflowed_(false) {} : allocator_(allocator), overflowed_(false) {}
@ -26,9 +35,6 @@ class ResourceManager {
stringPool_.clear(allocator_); stringPool_.clear(allocator_);
variantPools_.clear(allocator_); variantPools_.clear(allocator_);
staticStringsPools_.clear(allocator_); staticStringsPools_.clear(allocator_);
#if ARDUINOJSON_USE_8_BYTE_POOL
eightBytePools_.clear(allocator_);
#endif
} }
ResourceManager(const ResourceManager&) = delete; ResourceManager(const ResourceManager&) = delete;
@ -38,9 +44,6 @@ class ResourceManager {
swap(a.stringPool_, b.stringPool_); swap(a.stringPool_, b.stringPool_);
swap(a.variantPools_, b.variantPools_); swap(a.variantPools_, b.variantPools_);
swap(a.staticStringsPools_, b.staticStringsPools_); swap(a.staticStringsPools_, b.staticStringsPools_);
#if ARDUINOJSON_USE_8_BYTE_POOL
swap(a.eightBytePools_, b.eightBytePools_);
#endif
swap_(a.allocator_, b.allocator_); swap_(a.allocator_, b.allocator_);
swap_(a.overflowed_, b.overflowed_); swap_(a.overflowed_, b.overflowed_);
} }
@ -61,10 +64,10 @@ class ResourceManager {
void freeVariant(Slot<VariantData> slot); void freeVariant(Slot<VariantData> slot);
VariantData* getVariant(SlotId id) const; VariantData* getVariant(SlotId id) const;
#if ARDUINOJSON_USE_8_BYTE_POOL #if ARDUINOJSON_USE_EXTENSIONS
Slot<EightByteValue> allocEightByte(); Slot<VariantExtension> allocExtension();
void freeEightByte(SlotId slot); void freeExtension(SlotId slot);
EightByteValue* getEightByte(SlotId id) const; VariantExtension* getExtension(SlotId id) const;
#endif #endif
template <typename TAdaptedString> template <typename TAdaptedString>
@ -133,28 +136,19 @@ class ResourceManager {
variantPools_.clear(allocator_); variantPools_.clear(allocator_);
stringPool_.clear(allocator_); stringPool_.clear(allocator_);
staticStringsPools_.clear(allocator_); staticStringsPools_.clear(allocator_);
#if ARDUINOJSON_USE_8_BYTE_POOL
eightBytePools_.clear(allocator_);
#endif
} }
void shrinkToFit() { void shrinkToFit() {
variantPools_.shrinkToFit(allocator_); variantPools_.shrinkToFit(allocator_);
staticStringsPools_.shrinkToFit(allocator_); staticStringsPools_.shrinkToFit(allocator_);
#if ARDUINOJSON_USE_8_BYTE_POOL
eightBytePools_.shrinkToFit(allocator_);
#endif
} }
private: private:
Allocator* allocator_; Allocator* allocator_;
bool overflowed_; bool overflowed_;
StringPool stringPool_; StringPool stringPool_;
MemoryPoolList<VariantData> variantPools_; MemoryPoolList<SlotData> variantPools_;
MemoryPoolList<const char*> staticStringsPools_; MemoryPoolList<const char*> staticStringsPools_;
#if ARDUINOJSON_USE_8_BYTE_POOL
MemoryPoolList<EightByteValue> eightBytePools_;
#endif
}; };
ARDUINOJSON_END_PRIVATE_NAMESPACE ARDUINOJSON_END_PRIVATE_NAMESPACE

View File

@ -12,41 +12,40 @@
ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
inline Slot<VariantData> ResourceManager::allocVariant() { inline Slot<VariantData> ResourceManager::allocVariant() {
auto slot = variantPools_.allocSlot(allocator_); auto p = variantPools_.allocSlot(allocator_);
if (!slot) { if (!p) {
overflowed_ = true; overflowed_ = true;
return {}; return {};
} }
new (slot.ptr()) VariantData(); return {new (&p->variant) VariantData, p.id()};
return slot;
} }
inline void ResourceManager::freeVariant(Slot<VariantData> slot) { inline void ResourceManager::freeVariant(Slot<VariantData> variant) {
slot->clear(this); variant->clear(this);
variantPools_.freeSlot(slot); variantPools_.freeSlot({alias_cast<SlotData*>(variant.ptr()), variant.id()});
} }
inline VariantData* ResourceManager::getVariant(SlotId id) const { inline VariantData* ResourceManager::getVariant(SlotId id) const {
return reinterpret_cast<VariantData*>(variantPools_.getSlot(id)); return reinterpret_cast<VariantData*>(variantPools_.getSlot(id));
} }
#if ARDUINOJSON_USE_8_BYTE_POOL #if ARDUINOJSON_USE_EXTENSIONS
inline Slot<EightByteValue> ResourceManager::allocEightByte() { inline Slot<VariantExtension> ResourceManager::allocExtension() {
auto slot = eightBytePools_.allocSlot(allocator_); auto p = variantPools_.allocSlot(allocator_);
if (!slot) { if (!p) {
overflowed_ = true; overflowed_ = true;
return {}; return {};
} }
return slot; return {&p->extension, p.id()};
} }
inline void ResourceManager::freeEightByte(SlotId id) { inline void ResourceManager::freeExtension(SlotId id) {
auto p = getEightByte(id); auto p = getExtension(id);
eightBytePools_.freeSlot({p, id}); variantPools_.freeSlot({reinterpret_cast<SlotData*>(p), id});
} }
inline EightByteValue* ResourceManager::getEightByte(SlotId id) const { inline VariantExtension* ResourceManager::getExtension(SlotId id) const {
return eightBytePools_.getSlot(id); return &variantPools_.getSlot(id)->extension;
} }
#endif #endif

View File

@ -32,26 +32,7 @@ class StringBuffer {
return node_->data; return node_->data;
} }
JsonString str() const { StringNode* save() {
ARDUINOJSON_ASSERT(node_ != nullptr);
return JsonString(node_->data, node_->length);
}
void save(VariantData* data) {
ARDUINOJSON_ASSERT(node_ != nullptr);
const char* s = node_->data;
if (isTinyString(s, size_))
data->setTinyString(adaptString(s, size_));
else
data->setOwnedString(commitStringNode());
}
void saveRaw(VariantData* data) {
data->setRawString(commitStringNode());
}
private:
StringNode* commitStringNode() {
ARDUINOJSON_ASSERT(node_ != nullptr); ARDUINOJSON_ASSERT(node_ != nullptr);
node_->data[size_] = 0; node_->data[size_] = 0;
auto node = resources_->getString(adaptString(node_->data, size_)); auto node = resources_->getString(adaptString(node_->data, size_));
@ -71,6 +52,13 @@ class StringBuffer {
return node; return node;
} }
JsonString str() const {
ARDUINOJSON_ASSERT(node_ != nullptr);
return JsonString(node_->data, node_->length);
}
private:
ResourceManager* resources_; ResourceManager* resources_;
StringNode* node_ = nullptr; StringNode* node_ = nullptr;
size_t size_ = 0; size_t size_ = 0;

View File

@ -25,18 +25,10 @@ class StringBuilder {
node_ = resources_->createString(initialCapacity); node_ = resources_->createString(initialCapacity);
} }
void save(VariantData* variant) { StringNode* save() {
ARDUINOJSON_ASSERT(variant != nullptr);
ARDUINOJSON_ASSERT(node_ != nullptr); ARDUINOJSON_ASSERT(node_ != nullptr);
node_->data[size_] = 0;
char* p = node_->data; StringNode* node = resources_->getString(adaptString(node_->data, size_));
if (isTinyString(p, size_)) {
variant->setTinyString(adaptString(p, size_));
return;
}
p[size_] = 0;
StringNode* node = resources_->getString(adaptString(p, size_));
if (!node) { if (!node) {
node = resources_->resizeString(node_, size_); node = resources_->resizeString(node_, size_);
ARDUINOJSON_ASSERT(node != nullptr); // realloc to smaller can't fail ARDUINOJSON_ASSERT(node != nullptr); // realloc to smaller can't fail
@ -45,7 +37,7 @@ class StringBuilder {
} else { } else {
node->references++; node->references++;
} }
variant->setOwnedString(node); return node;
} }
void append(const char* s) { void append(const char* s) {

View File

@ -305,7 +305,7 @@ class MsgPackDeserializer {
if (err) if (err)
return err; return err;
stringBuffer_.save(variant); variant->setOwnedString(stringBuffer_.save());
return DeserializationError::Ok; return DeserializationError::Ok;
} }
@ -334,7 +334,7 @@ class MsgPackDeserializer {
if (err) if (err)
return err; return err;
stringBuffer_.saveRaw(variant); variant->setRawString(stringBuffer_.save());
return DeserializationError::Ok; return DeserializationError::Ok;
} }
@ -403,16 +403,19 @@ class MsgPackDeserializer {
JsonString key = stringBuffer_.str(); JsonString key = stringBuffer_.str();
TFilter memberFilter = filter[key.c_str()]; TFilter memberFilter = filter[key.c_str()];
VariantData* member = 0; VariantData* member;
if (memberFilter.allow()) { if (memberFilter.allow()) {
ARDUINOJSON_ASSERT(object != 0); ARDUINOJSON_ASSERT(object != 0);
auto keyVariant = object->addPair(&member, resources_); // Save key in memory pool.
if (!keyVariant) auto savedKey = stringBuffer_.save();
return DeserializationError::NoMemory;
stringBuffer_.save(keyVariant); member = object->addMember(savedKey, resources_);
if (!member)
return DeserializationError::NoMemory;
} else {
member = 0;
} }
err = parseVariant(member, memberFilter, nestingLimit.decrement()); err = parseVariant(member, memberFilter, nestingLimit.decrement());

View File

@ -10,11 +10,9 @@ ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
class ObjectData : public CollectionData { class ObjectData : public CollectionData {
public: public:
template <typename TAdaptedString> template <typename TAdaptedString> // also works with StringNode*
VariantData* addMember(TAdaptedString key, ResourceManager* resources); VariantData* addMember(TAdaptedString key, ResourceManager* resources);
VariantData* addPair(VariantData** value, ResourceManager* resources);
template <typename TAdaptedString> template <typename TAdaptedString>
VariantData* getOrAddMember(TAdaptedString key, ResourceManager* resources); VariantData* getOrAddMember(TAdaptedString key, ResourceManager* resources);

View File

@ -68,25 +68,9 @@ inline VariantData* ObjectData::addMember(TAdaptedString key,
return valueSlot.ptr(); return valueSlot.ptr();
} }
inline VariantData* ObjectData::addPair(VariantData** value,
ResourceManager* resources) {
auto keySlot = resources->allocVariant();
if (!keySlot)
return nullptr;
auto valueSlot = resources->allocVariant();
if (!valueSlot)
return nullptr;
*value = valueSlot.ptr();
CollectionData::appendPair(keySlot, valueSlot, resources);
return keySlot.ptr();
}
// Returns the size (in bytes) of an object with n members. // Returns the size (in bytes) of an object with n members.
constexpr size_t sizeofObject(size_t n) { constexpr size_t sizeofObject(size_t n) {
return 2 * n * sizeof(VariantData); return 2 * n * ResourceManager::slotSize;
} }
ARDUINOJSON_END_PRIVATE_NAMESPACE ARDUINOJSON_END_PRIVATE_NAMESPACE

View File

@ -76,16 +76,6 @@ struct StringAdapter<TChar*, enable_if_t<IsChar<TChar>::value>> {
} }
}; };
template <typename TChar>
struct StringAdapter<TChar[], enable_if_t<IsChar<TChar>::value>> {
using AdaptedString = RamString;
static AdaptedString adapt(const TChar* p) {
auto str = reinterpret_cast<const char*>(p);
return AdaptedString(str, str ? ::strlen(str) : 0);
}
};
template <size_t N> template <size_t N>
struct StringAdapter<const char (&)[N]> { struct StringAdapter<const char (&)[N]> {
using AdaptedString = RamString; using AdaptedString = RamString;

View File

@ -230,9 +230,9 @@ class StringBuilderPrint : public Print {
copier_.startString(); copier_.startString();
} }
void save(VariantData* data) { StringNode* save() {
ARDUINOJSON_ASSERT(!overflowed()); ARDUINOJSON_ASSERT(!overflowed());
copier_.save(data); return copier_.save();
} }
size_t write(uint8_t c) { size_t write(uint8_t c) {
@ -268,7 +268,7 @@ inline void convertToJson(const ::Printable& src, JsonVariant dst) {
src.printTo(print); src.printTo(print);
if (print.overflowed()) if (print.overflowed())
return; return;
print.save(data); data->setOwnedString(print.save());
} }
#endif #endif

View File

@ -16,13 +16,14 @@ ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
enum class VariantTypeBits : uint8_t { enum class VariantTypeBits : uint8_t {
OwnedStringBit = 0x01, // 0000 0001 OwnedStringBit = 0x01, // 0000 0001
NumberBit = 0x08, // 0000 1000 NumberBit = 0x08, // 0000 1000
EightByteBit = 0x10, // 0001 0000 #if ARDUINOJSON_USE_EXTENSIONS
ExtensionBit = 0x10, // 0001 0000
#endif
CollectionMask = 0x60, CollectionMask = 0x60,
}; };
enum class VariantType : uint8_t { enum class VariantType : uint8_t {
Null = 0, // 0000 0000 Null = 0, // 0000 0000
TinyString = 0x02, // 0000 0010
RawString = 0x03, // 0000 0011 RawString = 0x03, // 0000 0011
LinkedString = 0x04, // 0000 0100 LinkedString = 0x04, // 0000 0100
OwnedString = 0x05, // 0000 0101 OwnedString = 0x05, // 0000 0101
@ -45,8 +46,6 @@ inline bool operator&(VariantType type, VariantTypeBits bit) {
return (uint8_t(type) & uint8_t(bit)) != 0; return (uint8_t(type) & uint8_t(bit)) != 0;
} }
const size_t tinyStringMaxLength = 3;
union VariantContent { union VariantContent {
VariantContent() {} VariantContent() {}
@ -59,11 +58,10 @@ union VariantContent {
ObjectData asObject; ObjectData asObject;
CollectionData asCollection; CollectionData asCollection;
struct StringNode* asOwnedString; struct StringNode* asOwnedString;
char asTinyString[tinyStringMaxLength + 1];
}; };
#if ARDUINOJSON_USE_8_BYTE_POOL #if ARDUINOJSON_USE_EXTENSIONS
union EightByteValue { union VariantExtension {
# if ARDUINOJSON_USE_LONG_LONG # if ARDUINOJSON_USE_LONG_LONG
uint64_t asUint64; uint64_t asUint64;
int64_t asInt64; int64_t asInt64;
@ -72,9 +70,6 @@ union EightByteValue {
double asDouble; double asDouble;
# endif # endif
}; };
static_assert(sizeof(EightByteValue) == 8,
"sizeof(EightByteValue) must be 8 bytes");
#endif #endif
ARDUINOJSON_END_PRIVATE_NAMESPACE ARDUINOJSON_END_PRIVATE_NAMESPACE

View File

@ -17,16 +17,6 @@ ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
template <typename T> template <typename T>
T parseNumber(const char* s); T parseNumber(const char* s);
template <typename T>
static bool isTinyString(const T& s, size_t n) {
if (n > tinyStringMaxLength)
return false;
bool containsNul = false;
for (uint8_t i = 0; i < uint8_t(n); i++)
containsNul |= !s[i];
return !containsNul;
}
class VariantData { class VariantData {
VariantContent content_; // must be first to allow cast from array to variant VariantContent content_; // must be first to allow cast from array to variant
VariantType type_; VariantType type_;
@ -53,8 +43,8 @@ class VariantData {
template <typename TVisitor> template <typename TVisitor>
typename TVisitor::result_type accept( typename TVisitor::result_type accept(
TVisitor& visit, const ResourceManager* resources) const { TVisitor& visit, const ResourceManager* resources) const {
#if ARDUINOJSON_USE_8_BYTE_POOL #if ARDUINOJSON_USE_EXTENSIONS
auto eightByteValue = getEightByte(resources); auto extension = getExtension(resources);
#else #else
(void)resources; // silence warning (void)resources; // silence warning
#endif #endif
@ -64,7 +54,7 @@ class VariantData {
#if ARDUINOJSON_USE_DOUBLE #if ARDUINOJSON_USE_DOUBLE
case VariantType::Double: case VariantType::Double:
return visit.visit(eightByteValue->asDouble); return visit.visit(extension->asDouble);
#endif #endif
case VariantType::Array: case VariantType::Array:
@ -73,9 +63,6 @@ class VariantData {
case VariantType::Object: case VariantType::Object:
return visit.visit(content_.asObject); return visit.visit(content_.asObject);
case VariantType::TinyString:
return visit.visit(JsonString(content_.asTinyString));
case VariantType::LinkedString: case VariantType::LinkedString:
return visit.visit(JsonString(asLinkedString(resources), true)); return visit.visit(JsonString(asLinkedString(resources), true));
@ -95,10 +82,10 @@ class VariantData {
#if ARDUINOJSON_USE_LONG_LONG #if ARDUINOJSON_USE_LONG_LONG
case VariantType::Int64: case VariantType::Int64:
return visit.visit(eightByteValue->asInt64); return visit.visit(extension->asInt64);
case VariantType::Uint64: case VariantType::Uint64:
return visit.visit(eightByteValue->asUint64); return visit.visit(extension->asUint64);
#endif #endif
case VariantType::Boolean: case VariantType::Boolean:
@ -145,8 +132,8 @@ class VariantData {
} }
bool asBoolean(const ResourceManager* resources) const { bool asBoolean(const ResourceManager* resources) const {
#if ARDUINOJSON_USE_8_BYTE_POOL #if ARDUINOJSON_USE_EXTENSIONS
auto eightByteValue = getEightByte(resources); auto extension = getExtension(resources);
#else #else
(void)resources; // silence warning (void)resources; // silence warning
#endif #endif
@ -160,14 +147,14 @@ class VariantData {
return content_.asFloat != 0; return content_.asFloat != 0;
#if ARDUINOJSON_USE_DOUBLE #if ARDUINOJSON_USE_DOUBLE
case VariantType::Double: case VariantType::Double:
return eightByteValue->asDouble != 0; return extension->asDouble != 0;
#endif #endif
case VariantType::Null: case VariantType::Null:
return false; return false;
#if ARDUINOJSON_USE_LONG_LONG #if ARDUINOJSON_USE_LONG_LONG
case VariantType::Uint64: case VariantType::Uint64:
case VariantType::Int64: case VariantType::Int64:
return eightByteValue->asUint64 != 0; return extension->asUint64 != 0;
#endif #endif
default: default:
return true; return true;
@ -193,8 +180,8 @@ class VariantData {
template <typename T> template <typename T>
T asFloat(const ResourceManager* resources) const { T asFloat(const ResourceManager* resources) const {
static_assert(is_floating_point<T>::value, "T must be a floating point"); static_assert(is_floating_point<T>::value, "T must be a floating point");
#if ARDUINOJSON_USE_8_BYTE_POOL #if ARDUINOJSON_USE_EXTENSIONS
auto eightByteValue = getEightByte(resources); auto extension = getExtension(resources);
#else #else
(void)resources; // silence warning (void)resources; // silence warning
#endif #endif
@ -208,13 +195,10 @@ class VariantData {
return static_cast<T>(content_.asInt32); return static_cast<T>(content_.asInt32);
#if ARDUINOJSON_USE_LONG_LONG #if ARDUINOJSON_USE_LONG_LONG
case VariantType::Uint64: case VariantType::Uint64:
return static_cast<T>(eightByteValue->asUint64); return static_cast<T>(extension->asUint64);
case VariantType::Int64: case VariantType::Int64:
return static_cast<T>(eightByteValue->asInt64); return static_cast<T>(extension->asInt64);
#endif #endif
case VariantType::TinyString:
str = content_.asTinyString;
break;
case VariantType::LinkedString: case VariantType::LinkedString:
str = asLinkedString(resources); str = asLinkedString(resources);
break; break;
@ -225,7 +209,7 @@ class VariantData {
return static_cast<T>(content_.asFloat); return static_cast<T>(content_.asFloat);
#if ARDUINOJSON_USE_DOUBLE #if ARDUINOJSON_USE_DOUBLE
case VariantType::Double: case VariantType::Double:
return static_cast<T>(eightByteValue->asDouble); return static_cast<T>(extension->asDouble);
#endif #endif
default: default:
return 0.0; return 0.0;
@ -238,8 +222,8 @@ class VariantData {
template <typename T> template <typename T>
T asIntegral(const ResourceManager* resources) const { T asIntegral(const ResourceManager* resources) const {
static_assert(is_integral<T>::value, "T must be an integral type"); static_assert(is_integral<T>::value, "T must be an integral type");
#if ARDUINOJSON_USE_8_BYTE_POOL #if ARDUINOJSON_USE_EXTENSIONS
auto eightByteValue = getEightByte(resources); auto extension = getExtension(resources);
#else #else
(void)resources; // silence warning (void)resources; // silence warning
#endif #endif
@ -253,13 +237,10 @@ class VariantData {
return convertNumber<T>(content_.asInt32); return convertNumber<T>(content_.asInt32);
#if ARDUINOJSON_USE_LONG_LONG #if ARDUINOJSON_USE_LONG_LONG
case VariantType::Uint64: case VariantType::Uint64:
return convertNumber<T>(eightByteValue->asUint64); return convertNumber<T>(extension->asUint64);
case VariantType::Int64: case VariantType::Int64:
return convertNumber<T>(eightByteValue->asInt64); return convertNumber<T>(extension->asInt64);
#endif #endif
case VariantType::TinyString:
str = content_.asTinyString;
break;
case VariantType::LinkedString: case VariantType::LinkedString:
str = asLinkedString(resources); str = asLinkedString(resources);
break; break;
@ -270,7 +251,7 @@ class VariantData {
return convertNumber<T>(content_.asFloat); return convertNumber<T>(content_.asFloat);
#if ARDUINOJSON_USE_DOUBLE #if ARDUINOJSON_USE_DOUBLE
case VariantType::Double: case VariantType::Double:
return convertNumber<T>(eightByteValue->asDouble); return convertNumber<T>(extension->asDouble);
#endif #endif
default: default:
return 0; return 0;
@ -302,8 +283,6 @@ class VariantData {
JsonString asString(const ResourceManager* resources) const { JsonString asString(const ResourceManager* resources) const {
switch (type_) { switch (type_) {
case VariantType::TinyString:
return JsonString(content_.asTinyString);
case VariantType::LinkedString: case VariantType::LinkedString:
return JsonString(asLinkedString(resources), true); return JsonString(asLinkedString(resources), true);
case VariantType::OwnedString: case VariantType::OwnedString:
@ -314,8 +293,8 @@ class VariantData {
} }
} }
#if ARDUINOJSON_USE_8_BYTE_POOL #if ARDUINOJSON_USE_EXTENSIONS
const EightByteValue* getEightByte(const ResourceManager* resources) const; const VariantExtension* getExtension(const ResourceManager* resources) const;
#endif #endif
VariantData* getElement(size_t index, VariantData* getElement(size_t index,
@ -378,7 +357,7 @@ class VariantData {
template <typename T> template <typename T>
bool isInteger(const ResourceManager* resources) const { bool isInteger(const ResourceManager* resources) const {
#if ARDUINOJSON_USE_LONG_LONG #if ARDUINOJSON_USE_LONG_LONG
auto eightByteValue = getEightByte(resources); auto extension = getExtension(resources);
#else #else
(void)resources; // silence warning (void)resources; // silence warning
#endif #endif
@ -391,10 +370,10 @@ class VariantData {
#if ARDUINOJSON_USE_LONG_LONG #if ARDUINOJSON_USE_LONG_LONG
case VariantType::Uint64: case VariantType::Uint64:
return canConvertNumber<T>(eightByteValue->asUint64); return canConvertNumber<T>(extension->asUint64);
case VariantType::Int64: case VariantType::Int64:
return canConvertNumber<T>(eightByteValue->asInt64); return canConvertNumber<T>(extension->asInt64);
#endif #endif
default: default:
@ -418,8 +397,7 @@ class VariantData {
bool isString() const { bool isString() const {
return type_ == VariantType::LinkedString || return type_ == VariantType::LinkedString ||
type_ == VariantType::OwnedString || type_ == VariantType::OwnedString;
type_ == VariantType::TinyString;
} }
size_t nesting(const ResourceManager* resources) const { size_t nesting(const ResourceManager* resources) const {
@ -512,6 +490,11 @@ class VariantData {
template <typename TAdaptedString> template <typename TAdaptedString>
bool setString(TAdaptedString value, ResourceManager* resources); bool setString(TAdaptedString value, ResourceManager* resources);
bool setString(StringNode* s, ResourceManager*) {
setOwnedString(s);
return true;
}
template <typename TAdaptedString> template <typename TAdaptedString>
static void setString(VariantData* var, TAdaptedString value, static void setString(VariantData* var, TAdaptedString value,
ResourceManager* resources) { ResourceManager* resources) {
@ -523,23 +506,6 @@ class VariantData {
bool setLinkedString(const char* s, ResourceManager* resources); bool setLinkedString(const char* s, ResourceManager* resources);
template <typename TAdaptedString>
void setTinyString(const TAdaptedString& s) {
ARDUINOJSON_ASSERT(type_ == VariantType::Null); // must call clear() first
ARDUINOJSON_ASSERT(s.size() <= tinyStringMaxLength);
type_ = VariantType::TinyString;
auto n = uint8_t(s.size());
for (uint8_t i = 0; i < n; i++) {
char c = s[i];
ARDUINOJSON_ASSERT(c != 0); // no NUL in tiny string
content_.asTinyString[i] = c;
}
content_.asTinyString[n] = 0;
}
void setOwnedString(StringNode* s) { void setOwnedString(StringNode* s) {
ARDUINOJSON_ASSERT(type_ == VariantType::Null); // must call clear() first ARDUINOJSON_ASSERT(type_ == VariantType::Null); // must call clear() first
ARDUINOJSON_ASSERT(s); ARDUINOJSON_ASSERT(s);

View File

@ -43,11 +43,6 @@ inline bool VariantData::setString(TAdaptedString value,
if (value.isStatic()) if (value.isStatic())
return setLinkedString(value.data(), resources); return setLinkedString(value.data(), resources);
if (isTinyString(value, value.size())) {
setTinyString(value);
return true;
}
auto dup = resources->saveString(value); auto dup = resources->saveString(value);
if (dup) { if (dup) {
setOwnedString(dup); setOwnedString(dup);
@ -61,9 +56,9 @@ inline void VariantData::clear(ResourceManager* resources) {
if (type_ & VariantTypeBits::OwnedStringBit) if (type_ & VariantTypeBits::OwnedStringBit)
resources->dereferenceString(content_.asOwnedString->data); resources->dereferenceString(content_.asOwnedString->data);
#if ARDUINOJSON_USE_8_BYTE_POOL #if ARDUINOJSON_USE_EXTENSIONS
if (type_ & VariantTypeBits::EightByteBit) if (type_ & VariantTypeBits::ExtensionBit)
resources->freeEightByte(content_.asSlotId); resources->freeExtension(content_.asSlotId);
#endif #endif
auto collection = asCollection(); auto collection = asCollection();
@ -73,12 +68,12 @@ inline void VariantData::clear(ResourceManager* resources) {
type_ = VariantType::Null; type_ = VariantType::Null;
} }
#if ARDUINOJSON_USE_8_BYTE_POOL #if ARDUINOJSON_USE_EXTENSIONS
inline const EightByteValue* VariantData::getEightByte( inline const VariantExtension* VariantData::getExtension(
const ResourceManager* resources) const { const ResourceManager* resources) const {
return type_ & VariantTypeBits::EightByteBit return type_ & VariantTypeBits::ExtensionBit
? resources->getEightByte(content_.asSlotId) ? resources->getExtension(content_.asSlotId)
: 0; : nullptr;
} }
#endif #endif
@ -101,12 +96,12 @@ enable_if_t<sizeof(T) == 8, bool> VariantData::setFloat(
type_ = VariantType::Float; type_ = VariantType::Float;
content_.asFloat = valueAsFloat; content_.asFloat = valueAsFloat;
} else { } else {
auto slot = resources->allocEightByte(); auto extension = resources->allocExtension();
if (!slot) if (!extension)
return false; return false;
type_ = VariantType::Double; type_ = VariantType::Double;
content_.asSlotId = slot.id(); content_.asSlotId = extension.id();
slot->asDouble = value; extension->asDouble = value;
} }
#else #else
type_ = VariantType::Float; type_ = VariantType::Float;
@ -127,12 +122,12 @@ enable_if_t<is_signed<T>::value, bool> VariantData::setInteger(
} }
#if ARDUINOJSON_USE_LONG_LONG #if ARDUINOJSON_USE_LONG_LONG
else { else {
auto slot = resources->allocEightByte(); auto extension = resources->allocExtension();
if (!slot) if (!extension)
return false; return false;
type_ = VariantType::Int64; type_ = VariantType::Int64;
content_.asSlotId = slot.id(); content_.asSlotId = extension.id();
slot->asInt64 = value; extension->asInt64 = value;
} }
#endif #endif
return true; return true;
@ -150,12 +145,12 @@ enable_if_t<is_unsigned<T>::value, bool> VariantData::setInteger(
} }
#if ARDUINOJSON_USE_LONG_LONG #if ARDUINOJSON_USE_LONG_LONG
else { else {
auto slot = resources->allocEightByte(); auto extension = resources->allocExtension();
if (!slot) if (!extension)
return false; return false;
type_ = VariantType::Uint64; type_ = VariantType::Uint64;
content_.asSlotId = slot.id(); content_.asSlotId = extension.id();
slot->asUint64 = value; extension->asUint64 = value;
} }
#endif #endif
return true; return true;

View File

@ -4,8 +4,8 @@
#pragma once #pragma once
#define ARDUINOJSON_VERSION "7.4.1" #define ARDUINOJSON_VERSION "7.3.0"
#define ARDUINOJSON_VERSION_MAJOR 7 #define ARDUINOJSON_VERSION_MAJOR 7
#define ARDUINOJSON_VERSION_MINOR 4 #define ARDUINOJSON_VERSION_MINOR 3
#define ARDUINOJSON_VERSION_REVISION 1 #define ARDUINOJSON_VERSION_REVISION 0
#define ARDUINOJSON_VERSION_MACRO V741 #define ARDUINOJSON_VERSION_MACRO V730