Compare commits

...

49 Commits

Author SHA1 Message Date
f9fe8557f1 Set version to 7.2.1 2024-11-15 09:05:29 +01:00
e007d71b4f Fix operator[](variant) ignoring NUL characters 2024-11-14 14:56:47 +01:00
67a512a923 Clean up tests of adaptString() 2024-11-14 14:22:51 +01:00
9cf4f3871d Remove unused overload of stringCompare() and stringEquals() 2024-11-14 14:17:13 +01:00
31253dbe13 Add more tests with VLAs 2024-11-08 09:37:49 +01:00
1110d62128 Fix VLA support in JsonDocument::set() 2024-11-08 09:37:23 +01:00
c6c0649d70 Replace typedef with using 2024-10-23 15:54:08 +02:00
61ec2c4f95 Reduce boilerplate for failing build tests 2024-10-23 15:47:59 +02:00
0dd6231b3f Forbid deserializeJson(JsonArray|JsonObject, ...)
Closes #2135
2024-10-23 15:41:34 +02:00
20219d74f0 Tests: don't link FailingBuilds with catch 2024-10-23 15:04:52 +02:00
64cbaa6ff7 Remove the workaround for particle-iot/particle-cli#716
This reverts commit 1404b1ef70.
2024-09-28 09:58:48 +02:00
2512993617 Replace problematic symbol in idf_component.yml
Fixes #2131
2024-09-26 09:18:23 +02:00
48ee4a178b Use a const reference in is_convertible() 2024-09-21 09:22:12 +02:00
cd4b2b2463 Set version to 7.2.0 2024-09-18 10:48:50 +02:00
f806a42cc2 Add support for escape sequence \'
Fixes #2124
2024-09-17 10:33:47 +02:00
c1a507c158 Set ARDUINOJSON_POOL_CAPACITY from ARDUINOJSON_SLOT_ID_SIZE
This avoids the integer overflow when `ARDUINOJSON_SLOT_ID_SIZE=1` on 64-bit architectures.
2024-09-11 21:08:51 +02:00
a1809d0f31 Replace sizeof(VariantData) with sizeof(SlotData) 2024-09-10 18:26:58 +02:00
d92eee8736 Deprecate containsKey() in favor of doc["key"].is<T>()
See #2121
2024-09-06 17:32:09 +02:00
dd1d96e28f Group calls to getExtension()
This slightly reduces the code size.
2024-09-05 12:15:10 +02:00
3b64197869 MsgPackDeserializer: check extension allocation result 2024-09-04 14:34:02 +02:00
1f7a3f3174 JsonDeserializer: use float when the value has few digits 2024-09-04 14:33:14 +02:00
fd6314e132 Move some numbers tests to use_double_0.cpp 2024-09-04 14:29:19 +02:00
e4e2557b76 Move test of decomposeFloat() 2024-09-03 13:27:39 +02:00
3b6bf45b8a Serialize float with less decimal places than double 2024-09-03 11:44:35 +02:00
65ba36622c Add VariantType 2024-09-02 17:56:19 +02:00
33452c1f37 Test JsonVariant::as<T>() with extension slots 2024-08-27 16:08:47 +02:00
ee02c0d573 Test extension slot allocation failure 2024-08-27 16:08:47 +02:00
0278e94fce Set ARDUINOJSON_USE_DOUBLE to 0 by default on 8-bit architectures 2024-08-27 15:46:12 +02:00
7643dadaec WIP 2024-08-27 14:40:24 +02:00
c0bebe35f1 Improve message when user forgets third arg of serializeJson() et al.
See #1449, #1491, #1543, #1665, and #2122
2024-08-27 12:22:53 +02:00
b5bcb37657 Use enable_if_t instead of enable_if 2024-08-27 10:00:09 +02:00
b4a5b053ca Merge conf_test for linux and windows
This reverts commit 83516e1740.
2024-08-27 08:03:55 +02:00
e297932a98 Store 64-bit numbers (double and long long) in an additional slot
This change allows slots to be twices maller on 32-bit architectures.
See #1650 and #2103
2024-08-27 08:02:09 +02:00
e682337655 Release VariantData resources explicitly before setting value 2024-08-26 15:09:56 +02:00
4ada3f849c Decouple parseNumber() from VariantData 2024-08-25 16:46:55 +02:00
5dd203bca4 Rename SlotWithId to Slot 2024-08-25 15:04:39 +02:00
362201241f Make MemoryPool generic 2024-08-25 14:58:23 +02:00
2be24eded8 Rename SlotWithId::slot() and VariantWithId::data() to ptr() 2024-08-25 14:54:45 +02:00
4327f72140 Remove VariantSlot 2024-08-25 14:45:59 +02:00
f7f1b9745d Hide FreeSlot in MemoryPoolList 2024-08-25 14:39:18 +02:00
cec18177b0 Move sizeofArray() and sizeofObject() 2024-08-25 14:36:38 +02:00
f2894552f2 Rename VariantPool to MemoryPool 2024-08-25 14:36:38 +02:00
d3721cb122 Make VariantSlot a union. Include next slot id in VariantData 2024-08-24 19:20:39 +02:00
ab72bb8601 Rename flags_ to type_ 2024-08-24 11:18:21 +02:00
09c89dcacf Store object members with two slots: one for the key and one for the value 2024-08-24 10:45:51 +02:00
a2b09bfbd2 Remove unused code 2024-08-23 15:28:44 +02:00
386105be90 Allocate slot before key 2024-08-23 15:27:46 +02:00
83516e1740 Split conf_test between linux and windows 2024-08-23 15:24:45 +02:00
bf99aeedb1 Add @LArkema to the list of sponsors 💖 2024-07-02 10:27:36 +02:00
140 changed files with 2591 additions and 1440 deletions

View File

@ -403,7 +403,7 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- name: Install Particle CLI
run: sudo npm install -g particle-cli particle-usb
run: sudo npm install -g particle-cli
- name: Login to Particle
run: particle login -t "${{ secrets.PARTICLE_TOKEN }}"
- name: Compile

View File

@ -61,7 +61,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Install
run: npm install -g particle-cli particle-usb
run: npm install -g particle-cli
- name: Checkout
uses: actions/checkout@v4
- name: Login

View File

@ -1,6 +1,49 @@
ArduinoJson: change log
=======================
v7.2.1 (2024-11-15)
------
* Forbid `deserializeJson(JsonArray|JsonObject, ...)` (issue #2135)
* Fix VLA support in `JsonDocument::set()`
* Fix `operator[](variant)` ignoring NUL characters
v7.2.0 (2024-09-18)
------
* Store object members with two slots: one for the key and one for the value
* Store 64-bit numbers (`double` and `long long`) in an additional slot
* Reduce the slot size (see table below)
* Improve message when user forgets third arg of `serializeJson()` et al.
* Set `ARDUINOJSON_USE_DOUBLE` to `0` by default on 8-bit architectures
* Deprecate `containsKey()` in favor of `doc["key"].is<T>()`
* Add support for escape sequence `\'` (issue #2124)
| Architecture | before | after |
|--------------|----------|----------|
| 8-bit | 8 bytes | 6 bytes |
| 32-bit | 16 bytes | 8 bytes |
| 64-bit | 24 bytes | 16 bytes |
> ### BREAKING CHANGES
>
> After being on the death row for years, the `containsKey()` method has finally been deprecated.
> You should replace `doc.containsKey("key")` with `doc["key"].is<T>()`, which not only checks that the key exists but also that the value is of the expected type.
>
> ```cpp
> // Before
> if (doc.containsKey("value")) {
> int value = doc["value"];
> // ...
> }
>
> // After
> if (doc["value"].is<int>()) {
> int value = doc["value"];
> // ...
> }
> ```
v7.1.0 (2024-06-27)
------

View File

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

View File

@ -148,6 +148,9 @@ ArduinoJson is thankful to its sponsors. Please give them a visit; they deserve
<a href="https://github.com/1technophile" rel="sponsored">
<img alt="1technophile" src="https://avatars.githubusercontent.com/u/12672732?s=40&v=4">
</a>
<a href="https://github.com/LArkema" rel="sponsored">
<img alt="LArkema" src="https://avatars.githubusercontent.com/u/38381313?s=40&v=4">
</a>
</p>
If you run a commercial project that embeds ArduinoJson, think about [sponsoring the library's development](https://github.com/sponsors/bblanchon): it ensures the code that your products rely on stays actively maintained. It can also give your project some exposure to the makers' community.

View File

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

View File

@ -6,12 +6,13 @@ static_assert(ARDUINOJSON_USE_LONG_LONG == 0, "ARDUINOJSON_USE_LONG_LONG");
static_assert(ARDUINOJSON_SLOT_ID_SIZE == 1, "ARDUINOJSON_SLOT_ID_SIZE");
static_assert(ARDUINOJSON_POOL_CAPACITY == 16, "ARDUINOJSON_POOL_CAPACITY");
static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN");
static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE");
static_assert(ARDUINOJSON_USE_DOUBLE == 0, "ARDUINOJSON_USE_DOUBLE");
static_assert(sizeof(ArduinoJson::detail::VariantSlot) == 8,
"sizeof(VariantSlot)");
static_assert(ArduinoJson::detail::ResourceManager::slotSize == 6, "slot size");
void setup() {}
void loop() {}

View File

@ -4,12 +4,13 @@ static_assert(ARDUINOJSON_USE_LONG_LONG == 1, "ARDUINOJSON_USE_LONG_LONG");
static_assert(ARDUINOJSON_SLOT_ID_SIZE == 2, "ARDUINOJSON_SLOT_ID_SIZE");
static_assert(ARDUINOJSON_POOL_CAPACITY == 128, "ARDUINOJSON_POOL_CAPACITY");
static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN");
static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE");
static_assert(sizeof(ArduinoJson::detail::VariantSlot) == 16,
"sizeof(VariantSlot)");
static_assert(ArduinoJson::detail::ResourceManager::slotSize == 8, "slot size");
void setup() {}
void loop() {}

View File

@ -4,11 +4,13 @@ static_assert(ARDUINOJSON_USE_LONG_LONG == 1, "ARDUINOJSON_USE_LONG_LONG");
static_assert(ARDUINOJSON_SLOT_ID_SIZE == 4, "ARDUINOJSON_SLOT_ID_SIZE");
static_assert(ARDUINOJSON_POOL_CAPACITY == 256, "ARDUINOJSON_POOL_CAPACITY");
static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN");
static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE");
static_assert(sizeof(ArduinoJson::detail::VariantSlot) == 24,
"sizeof(VariantSlot)");
static_assert(ArduinoJson::detail::ResourceManager::slotSize == 16,
"slot size");
int main() {}

View File

@ -4,11 +4,12 @@ static_assert(ARDUINOJSON_USE_LONG_LONG == 1, "ARDUINOJSON_USE_LONG_LONG");
static_assert(ARDUINOJSON_SLOT_ID_SIZE == 2, "ARDUINOJSON_SLOT_ID_SIZE");
static_assert(ARDUINOJSON_POOL_CAPACITY == 128, "ARDUINOJSON_POOL_CAPACITY");
static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN");
static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE");
static_assert(sizeof(ArduinoJson::detail::VariantSlot) == 16,
"sizeof(VariantSlot)");
static_assert(ArduinoJson::detail::ResourceManager::slotSize == 8, "slot size");
int main() {}

View File

@ -5,15 +5,18 @@
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_subdirectory(catch)
link_libraries(ArduinoJson)
link_libraries(ArduinoJson catch)
# Failing builds should only link with ArduinoJson, not catch
add_subdirectory(FailingBuilds)
add_subdirectory(catch)
link_libraries(catch)
include_directories(Helpers)
add_subdirectory(Cpp17)
add_subdirectory(Cpp20)
add_subdirectory(Deprecated)
add_subdirectory(FailingBuilds)
add_subdirectory(IntegrationTests)
add_subdirectory(JsonArray)
add_subdirectory(JsonArrayConst)

View File

@ -16,9 +16,10 @@ endif()
add_executable(DeprecatedTests
add.cpp
BasicJsonDocument.cpp
containsKey.cpp
createNestedArray.cpp
createNestedObject.cpp
BasicJsonDocument.cpp
DynamicJsonDocument.cpp
macros.cpp
memoryUsage.cpp

View File

@ -0,0 +1,246 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2024, Benoit BLANCHON
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
#include "Literals.hpp"
TEST_CASE("JsonDocument::containsKey()") {
JsonDocument doc;
SECTION("returns true on object") {
doc["hello"] = "world";
REQUIRE(doc.containsKey("hello") == true);
}
SECTION("returns true when value is null") {
doc["hello"] = static_cast<const char*>(0);
REQUIRE(doc.containsKey("hello") == true);
}
SECTION("returns true when key is a std::string") {
doc["hello"] = "world";
REQUIRE(doc.containsKey("hello"_s) == true);
}
SECTION("returns false on object") {
doc["world"] = "hello";
REQUIRE(doc.containsKey("hello") == false);
}
SECTION("returns false on array") {
doc.add("hello");
REQUIRE(doc.containsKey("hello") == false);
}
SECTION("returns false on null") {
REQUIRE(doc.containsKey("hello") == false);
}
SECTION("supports JsonVariant") {
doc["hello"] = "world";
doc["key"] = "hello";
REQUIRE(doc.containsKey(doc["key"]) == true);
REQUIRE(doc.containsKey(doc["foo"]) == false);
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("supports VLAs") {
size_t i = 16;
char vla[i];
strcpy(vla, "hello");
doc["hello"] = "world";
REQUIRE(doc.containsKey(vla) == true);
}
#endif
}
TEST_CASE("MemberProxy::containsKey()") {
JsonDocument doc;
auto mp = doc["hello"];
SECTION("containsKey(const char*)") {
mp["key"] = "value";
REQUIRE(mp.containsKey("key") == true);
REQUIRE(mp.containsKey("key") == true);
}
SECTION("containsKey(std::string)") {
mp["key"] = "value";
REQUIRE(mp.containsKey("key"_s) == true);
REQUIRE(mp.containsKey("key"_s) == true);
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("supports VLAs") {
size_t i = 16;
char vla[i];
strcpy(vla, "hello");
mp["hello"] = "world";
REQUIRE(mp.containsKey(vla) == true);
}
#endif
}
TEST_CASE("JsonObject::containsKey()") {
JsonDocument doc;
JsonObject obj = doc.to<JsonObject>();
obj["hello"] = 42;
SECTION("returns true only if key is present") {
REQUIRE(false == obj.containsKey("world"));
REQUIRE(true == obj.containsKey("hello"));
}
SECTION("returns false after remove()") {
obj.remove("hello");
REQUIRE(false == obj.containsKey("hello"));
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("key is a VLA") {
size_t i = 16;
char vla[i];
strcpy(vla, "hello");
REQUIRE(true == obj.containsKey(vla));
}
#endif
SECTION("key is a JsonVariant") {
doc["key"] = "hello";
REQUIRE(true == obj.containsKey(obj["key"]));
REQUIRE(false == obj.containsKey(obj["hello"]));
}
SECTION("std::string") {
REQUIRE(true == obj.containsKey("hello"_s));
}
SECTION("unsigned char[]") {
unsigned char key[] = "hello";
REQUIRE(true == obj.containsKey(key));
}
}
TEST_CASE("JsonObjectConst::containsKey()") {
JsonDocument doc;
doc["hello"] = 42;
auto obj = doc.as<JsonObjectConst>();
SECTION("supports const char*") {
REQUIRE(false == obj.containsKey("world"));
REQUIRE(true == obj.containsKey("hello"));
}
SECTION("supports std::string") {
REQUIRE(false == obj.containsKey("world"_s));
REQUIRE(true == obj.containsKey("hello"_s));
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("supports VLA") {
size_t i = 16;
char vla[i];
strcpy(vla, "hello");
REQUIRE(true == obj.containsKey(vla));
}
#endif
SECTION("supports JsonVariant") {
doc["key"] = "hello";
REQUIRE(true == obj.containsKey(obj["key"]));
REQUIRE(false == obj.containsKey(obj["hello"]));
}
}
TEST_CASE("JsonVariant::containsKey()") {
JsonDocument doc;
JsonVariant var = doc.to<JsonVariant>();
SECTION("returns false is unbound") {
CHECK_FALSE(JsonVariant().containsKey("hello"));
}
SECTION("containsKey(const char*)") {
var["hello"] = "world";
REQUIRE(var.containsKey("hello") == true);
REQUIRE(var.containsKey("world") == false);
}
SECTION("containsKey(std::string)") {
var["hello"] = "world";
REQUIRE(var.containsKey("hello"_s) == true);
REQUIRE(var.containsKey("world"_s) == false);
}
SECTION("containsKey(JsonVariant)") {
var["hello"] = "world";
var["key"] = "hello";
REQUIRE(var.containsKey(doc["key"]) == true);
REQUIRE(var.containsKey(doc["foo"]) == false);
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("supports VLAs") {
size_t i = 16;
char vla[i];
strcpy(vla, "hello");
var["hello"] = "world";
REQUIRE(var.containsKey(vla) == true);
}
#endif
}
TEST_CASE("JsonVariantConst::containsKey()") {
JsonDocument doc;
doc["hello"] = "world";
JsonVariantConst var = doc.as<JsonVariant>();
SECTION("support const char*") {
REQUIRE(var.containsKey("hello") == true);
REQUIRE(var.containsKey("world") == false);
}
SECTION("support std::string") {
REQUIRE(var.containsKey("hello"_s) == true);
REQUIRE(var.containsKey("world"_s) == false);
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("supports VLA") {
size_t i = 16;
char vla[i];
strcpy(vla, "hello");
REQUIRE(true == var.containsKey(vla));
}
#endif
SECTION("support JsonVariant") {
doc["key"] = "hello";
REQUIRE(var.containsKey(var["key"]) == true);
REQUIRE(var.containsKey(var["foo"]) == false);
}
}

View File

@ -2,7 +2,11 @@
# Copyright © 2014-2024, Benoit BLANCHON
# MIT License
macro(build_should_fail target)
macro(add_failing_build source_file)
get_filename_component(target ${source_file} NAME_WE)
add_executable(${target} ${source_file})
set_target_properties(${target}
PROPERTIES
EXCLUDE_FROM_ALL TRUE
@ -16,21 +20,13 @@ macro(build_should_fail target)
set_tests_properties(${target}
PROPERTIES
WILL_FAIL TRUE
LABELS "WillFail;Catch"
LABELS "WillFail"
)
endmacro()
add_executable(Issue978 Issue978.cpp)
build_should_fail(Issue978)
add_executable(read_long_long read_long_long.cpp)
build_should_fail(read_long_long)
add_executable(write_long_long write_long_long.cpp)
build_should_fail(write_long_long)
add_executable(variant_as_char variant_as_char.cpp)
build_should_fail(variant_as_char)
add_executable(assign_char assign_char.cpp)
build_should_fail(assign_char)
add_failing_build(Issue978.cpp)
add_failing_build(read_long_long.cpp)
add_failing_build(write_long_long.cpp)
add_failing_build(variant_as_char.cpp)
add_failing_build(assign_char.cpp)
add_failing_build(deserialize_object.cpp)

View File

@ -0,0 +1,12 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2024, Benoit BLANCHON
// MIT License
#include <ArduinoJson.h>
// See issue #2135
int main() {
JsonObject obj;
deserializeJson(obj, "");
}

View File

@ -5,8 +5,8 @@
#pragma once
#include <ArduinoJson/Memory/Allocator.hpp>
#include <ArduinoJson/Memory/MemoryPool.hpp>
#include <ArduinoJson/Memory/StringBuilder.hpp>
#include <ArduinoJson/Memory/VariantPool.hpp>
#include <sstream>
@ -265,12 +265,14 @@ class TimebombAllocator : public ArduinoJson::Allocator {
} // namespace
inline size_t sizeofPoolList(size_t n = ARDUINOJSON_INITIAL_POOL_COUNT) {
return sizeof(ArduinoJson::detail::VariantPool) * n;
using namespace ArduinoJson::detail;
return sizeof(MemoryPool<VariantData>) * n;
}
inline size_t sizeofPool(
ArduinoJson::detail::SlotCount n = ARDUINOJSON_POOL_CAPACITY) {
return ArduinoJson::detail::VariantPool::slotsToBytes(n);
using namespace ArduinoJson::detail;
return MemoryPool<VariantData>::slotsToBytes(n);
}
inline size_t sizeofStringBuffer(size_t iteration = 1) {

View File

@ -68,6 +68,12 @@ TEST_CASE("JsonArray::remove()") {
REQUIRE(array[1] == 2);
}
SECTION("remove end()") {
array.remove(array.end());
REQUIRE(3 == array.size());
}
SECTION("In a loop") {
for (JsonArray::iterator it = array.begin(); it != array.end(); ++it) {
if (*it == 2)

View File

@ -69,14 +69,32 @@ TEST_CASE("deserialize JSON array") {
REQUIRE(arr[1] == 84);
}
SECTION("Double") {
SECTION("Float") {
DeserializationError err = deserializeJson(doc, "[4.2,1e2]");
JsonArray arr = doc.as<JsonArray>();
REQUIRE(err == DeserializationError::Ok);
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == 4.2);
REQUIRE(arr[1] == 1e2);
REQUIRE(arr[0].as<float>() == Approx(4.2f));
REQUIRE(arr[1] == 1e2f);
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofPool()),
Reallocate(sizeofPool(), sizeofPool(2)),
});
}
SECTION("Double") {
DeserializationError err = deserializeJson(doc, "[4.2123456,-7E89]");
JsonArray arr = doc.as<JsonArray>();
REQUIRE(err == DeserializationError::Ok);
REQUIRE(2 == arr.size());
REQUIRE(arr[0].as<double>() == Approx(4.2123456));
REQUIRE(arr[1] == -7E89);
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofPool()),
Reallocate(sizeofPool(), sizeofPool(4)),
});
}
SECTION("Unsigned long") {

View File

@ -6,6 +6,8 @@
#include <ArduinoJson.h>
#include <catch.hpp>
#include "Allocators.hpp"
TEST_CASE("deserializeJson() returns IncompleteInput") {
const char* testCases[] = {
// strings
@ -118,3 +120,43 @@ TEST_CASE("deserializeJson() returns NoMemory if string length overflows") {
REQUIRE(err == DeserializationError::NoMemory);
}
}
TEST_CASE("deserializeJson() returns NoMemory if extension allocation fails") {
JsonDocument doc(FailingAllocator::instance());
SECTION("uint32_t should pass") {
auto err = deserializeJson(doc, "4294967295");
REQUIRE(err == DeserializationError::Ok);
}
SECTION("uint64_t should fail") {
auto err = deserializeJson(doc, "18446744073709551615");
REQUIRE(err == DeserializationError::NoMemory);
}
SECTION("int32_t should pass") {
auto err = deserializeJson(doc, "-2147483648");
REQUIRE(err == DeserializationError::Ok);
}
SECTION("int64_t should fail") {
auto err = deserializeJson(doc, "-9223372036854775808");
REQUIRE(err == DeserializationError::NoMemory);
}
SECTION("float should pass") {
auto err = deserializeJson(doc, "3.402823e38");
REQUIRE(err == DeserializationError::Ok);
}
SECTION("double should fail") {
auto err = deserializeJson(doc, "1.7976931348623157e308");
REQUIRE(err == DeserializationError::NoMemory);
}
}

View File

@ -155,15 +155,27 @@ TEST_CASE("deserialize JSON object") {
REQUIRE(obj["key2"] == -42);
}
SECTION("Double") {
SECTION("Float") {
DeserializationError err =
deserializeJson(doc, "{\"key1\":12.345,\"key2\":-7E89}");
deserializeJson(doc, "{\"key1\":12.345,\"key2\":-7E3}");
JsonObject obj = doc.as<JsonObject>();
REQUIRE(err == DeserializationError::Ok);
REQUIRE(doc.is<JsonObject>());
REQUIRE(obj.size() == 2);
REQUIRE(obj["key1"] == 12.345);
REQUIRE(obj["key1"].as<float>() == Approx(12.345f));
REQUIRE(obj["key2"] == -7E3f);
}
SECTION("Double") {
DeserializationError err =
deserializeJson(doc, "{\"key1\":12.3456789,\"key2\":-7E89}");
JsonObject obj = doc.as<JsonObject>();
REQUIRE(err == DeserializationError::Ok);
REQUIRE(doc.is<JsonObject>());
REQUIRE(obj.size() == 2);
REQUIRE(obj["key1"].as<double>() == Approx(12.3456789));
REQUIRE(obj["key2"] == -7E89);
}
@ -308,12 +320,12 @@ TEST_CASE("deserialize JSON object") {
REQUIRE(doc["a"] == 2);
}
SECTION("NUL in keys") { // we don't support NULs in keys
SECTION("NUL in keys") {
DeserializationError err =
deserializeJson(doc, "{\"x\\u0000a\":1,\"x\\u0000b\":2}");
REQUIRE(err == DeserializationError::Ok);
REQUIRE(doc.as<std::string>() == "{\"x\":2}");
REQUIRE(doc.as<std::string>() == "{\"x\\u0000a\":1,\"x\\u0000b\":2}");
}
}

View File

@ -83,6 +83,22 @@ TEST_CASE("Truncated JSON string") {
}
}
TEST_CASE("Escape single quote in single quoted string") {
JsonDocument doc;
DeserializationError err = deserializeJson(doc, "'ab\\\'cd'");
REQUIRE(err == DeserializationError::Ok);
CHECK(doc.as<std::string>() == "ab\'cd");
}
TEST_CASE("Escape double quote in double quoted string") {
JsonDocument doc;
DeserializationError err = deserializeJson(doc, "'ab\\\"cd'");
REQUIRE(err == DeserializationError::Ok);
CHECK(doc.as<std::string>() == "ab\"cd");
}
TEST_CASE("Invalid JSON string") {
const char* testCases[] = {"'\\u'", "'\\u000g'", "'\\u000'",
"'\\u000G'", "'\\u000/'", "'\\x1234'"};

View File

@ -9,7 +9,6 @@ add_executable(JsonDocumentTests
clear.cpp
compare.cpp
constructor.cpp
containsKey.cpp
ElementProxy.cpp
isNull.cpp
issue1120.cpp
@ -17,6 +16,7 @@ add_executable(JsonDocumentTests
nesting.cpp
overflowed.cpp
remove.cpp
set.cpp
shrinkToFit.cpp
size.cpp
subscript.cpp

View File

@ -7,7 +7,7 @@
#include "Literals.hpp"
typedef ArduinoJson::detail::ElementProxy<JsonDocument&> ElementProxy;
using ElementProxy = ArduinoJson::detail::ElementProxy<JsonDocument&>;
TEST_CASE("ElementProxy::add()") {
JsonDocument doc;
@ -26,13 +26,25 @@ TEST_CASE("ElementProxy::add()") {
REQUIRE(doc.as<std::string>() == "[[\"world\"]]");
}
SECTION("set(char[])") {
SECTION("add(char[])") {
char s[] = "world";
ep.add(s);
strcpy(s, "!!!!!");
REQUIRE(doc.as<std::string>() == "[[\"world\"]]");
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("set(vla)") {
size_t i = 8;
char vla[i];
strcpy(vla, "world");
ep.add(vla);
REQUIRE(doc.as<std::string>() == "[[\"world\"]]");
}
#endif
}
TEST_CASE("ElementProxy::clear()") {
@ -166,6 +178,18 @@ TEST_CASE("ElementProxy::set()") {
REQUIRE(doc.as<std::string>() == "[\"world\"]");
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("set(VLA)") {
size_t i = 8;
char vla[i];
strcpy(vla, "world");
ep.set(vla);
REQUIRE(doc.as<std::string>() == "[\"world\"]");
}
#endif
}
TEST_CASE("ElementProxy::size()") {
@ -205,6 +229,18 @@ TEST_CASE("ElementProxy::operator[]") {
REQUIRE(doc.as<std::string>() == "[null,[null,null,42]]");
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("set VLA") {
size_t i = 8;
char vla[i];
strcpy(vla, "world");
ep[0] = vla;
REQUIRE(doc.as<std::string>() == "[null,[\"world\"]]");
}
#endif
}
TEST_CASE("ElementProxy cast to JsonVariantConst") {

View File

@ -14,8 +14,8 @@
using ArduinoJson::detail::sizeofArray;
using ArduinoJson::detail::sizeofObject;
typedef ArduinoJson::detail::MemberProxy<JsonDocument&, const char*>
MemberProxy;
using MemberProxy =
ArduinoJson::detail::MemberProxy<JsonDocument&, const char*>;
TEST_CASE("MemberProxy::add()") {
JsonDocument doc;
@ -32,6 +32,18 @@ TEST_CASE("MemberProxy::add()") {
REQUIRE(doc.as<std::string>() == "{\"hello\":[\"world\"]}");
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("add(vla)") {
size_t i = 16;
char vla[i];
strcpy(vla, "world");
mp.add(vla);
REQUIRE(doc.as<std::string>() == "{\"hello\":[\"world\"]}");
}
#endif
}
TEST_CASE("MemberProxy::clear()") {
@ -93,25 +105,6 @@ TEST_CASE("MemberProxy::operator==()") {
}
}
TEST_CASE("MemberProxy::containsKey()") {
JsonDocument doc;
MemberProxy mp = doc["hello"];
SECTION("containsKey(const char*)") {
mp["key"] = "value";
REQUIRE(mp.containsKey("key") == true);
REQUIRE(mp.containsKey("key") == true);
}
SECTION("containsKey(std::string)") {
mp["key"] = "value";
REQUIRE(mp.containsKey("key"_s) == true);
REQUIRE(mp.containsKey("key"_s) == true);
}
}
TEST_CASE("MemberProxy::operator|()") {
JsonDocument doc;
@ -214,6 +207,18 @@ TEST_CASE("MemberProxy::set()") {
REQUIRE(doc.as<std::string>() == "{\"hello\":\"world\"}");
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("set(vla)") {
size_t i = 8;
char vla[i];
strcpy(vla, "world");
mp.set(vla);
REQUIRE(doc.as<std::string>() == "{\"hello\":\"world\"}");
}
#endif
}
TEST_CASE("MemberProxy::size()") {
@ -345,12 +350,12 @@ TEST_CASE("Deduplicate keys") {
}
TEST_CASE("MemberProxy under memory constraints") {
KillswitchAllocator killswitch;
SpyingAllocator spy(&killswitch);
TimebombAllocator timebomb(1);
SpyingAllocator spy(&timebomb);
JsonDocument doc(&spy);
SECTION("key allocation fails") {
killswitch.on();
SECTION("key slot allocation fails") {
timebomb.setCountdown(0);
doc["hello"_s] = "world";
@ -358,6 +363,38 @@ TEST_CASE("MemberProxy under memory constraints") {
REQUIRE(doc.size() == 0);
REQUIRE(doc.overflowed() == true);
REQUIRE(spy.log() == AllocatorLog{
AllocateFail(sizeofPool()),
});
}
SECTION("value slot allocation fails") {
timebomb.setCountdown(1);
// fill the pool entirely, but leave one slot for the key
doc["foo"][ARDUINOJSON_POOL_CAPACITY - 4] = 1;
REQUIRE(doc.overflowed() == false);
doc["hello"_s] = "world";
REQUIRE(doc.is<JsonObject>());
REQUIRE(doc.size() == 1);
REQUIRE(doc.overflowed() == true);
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofPool()),
AllocateFail(sizeofPool()),
});
}
SECTION("key string allocation fails") {
timebomb.setCountdown(1);
doc["hello"_s] = "world";
REQUIRE(doc.is<JsonObject>());
REQUIRE(doc.size() == 0);
REQUIRE(doc.overflowed() == true);
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofPool()),
AllocateFail(sizeofString("hello")),
});
}

View File

@ -79,6 +79,24 @@ TEST_CASE("JsonDocument::add(T)") {
Allocate(sizeofString("example")),
});
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("VLA") {
size_t i = 16;
char vla[i];
strcpy(vla, "example");
doc.add(vla);
doc.add(vla);
CHECK(doc[0].as<const char*>() == doc[1].as<const char*>());
REQUIRE("example"_s == doc[0]);
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofPool()),
Allocate(sizeofString("example")),
});
}
#endif
}
TEST_CASE("JsonDocument::add<T>()") {

View File

@ -22,8 +22,8 @@ TEST_CASE("JsonDocument assignment") {
REQUIRE(doc2.as<std::string>() == "{\"hello\":\"world\"}");
REQUIRE(spyingAllocator.log() == AllocatorLog{
Allocate(sizeofString("hello")),
Allocate(sizeofPool()),
Allocate(sizeofString("hello")),
Allocate(sizeofString("world")),
});
}
@ -54,8 +54,8 @@ TEST_CASE("JsonDocument assignment") {
REQUIRE(doc2.as<std::string>() == "{\"hello\":\"world\"}");
REQUIRE(spyingAllocator.log() == AllocatorLog{
Allocate(sizeofString("hello")),
Allocate(sizeofPool()),
Allocate(sizeofString("hello")),
Allocate(sizeofString("world")),
});
}
@ -72,8 +72,8 @@ TEST_CASE("JsonDocument assignment") {
REQUIRE(doc1.as<std::string>() == "null");
}
REQUIRE(spyingAllocator.log() == AllocatorLog{
Allocate(sizeofString("hello")),
Allocate(sizeofPool()),
Allocate(sizeofString("hello")),
Allocate(sizeofString("world")),
Deallocate(sizeofString("hello")),
Deallocate(sizeofString("world")),

View File

@ -1,54 +0,0 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2024, Benoit BLANCHON
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
#include "Literals.hpp"
TEST_CASE("JsonDocument::containsKey()") {
JsonDocument doc;
SECTION("returns true on object") {
doc["hello"] = "world";
REQUIRE(doc.containsKey("hello") == true);
}
SECTION("returns true when value is null") {
doc["hello"] = static_cast<const char*>(0);
REQUIRE(doc.containsKey("hello") == true);
}
SECTION("returns true when key is a std::string") {
doc["hello"] = "world";
REQUIRE(doc.containsKey("hello"_s) == true);
}
SECTION("returns false on object") {
doc["world"] = "hello";
REQUIRE(doc.containsKey("hello") == false);
}
SECTION("returns false on array") {
doc.add("hello");
REQUIRE(doc.containsKey("hello") == false);
}
SECTION("returns false on null") {
REQUIRE(doc.containsKey("hello") == false);
}
SECTION("support JsonVariant") {
doc["hello"] = "world";
doc["key"] = "hello";
REQUIRE(doc.containsKey(doc["key"]) == true);
REQUIRE(doc.containsKey(doc["foo"]) == false);
}
}

View File

@ -0,0 +1,79 @@
#define ARDUINOJSON_ENABLE_ARDUINO_STRING 1
#define ARDUINOJSON_ENABLE_PROGMEM 1
#include <ArduinoJson.h>
#include <catch.hpp>
#include "Allocators.hpp"
#include "Literals.hpp"
TEST_CASE("JsonDocument::set()") {
SpyingAllocator spy;
JsonDocument doc(&spy);
SECTION("integer") {
doc.set(42);
REQUIRE(doc.as<std::string>() == "42");
REQUIRE(spy.log() == AllocatorLog{});
}
SECTION("const char*") {
doc.set("example");
REQUIRE(doc.as<const char*>() == "example"_s);
REQUIRE(spy.log() == AllocatorLog{});
}
SECTION("std::string") {
doc.set("example"_s);
REQUIRE(doc.as<const char*>() == "example"_s);
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("example")),
});
}
SECTION("char*") {
char value[] = "example";
doc.set(value);
REQUIRE(doc.as<const char*>() == "example"_s);
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("example")),
});
}
SECTION("Arduino String") {
doc.set(String("example"));
REQUIRE(doc.as<const char*>() == "example"_s);
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("example")),
});
}
SECTION("Flash string") {
doc.set(F("example"));
REQUIRE(doc.as<const char*>() == "example"_s);
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("example")),
});
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("VLA") {
size_t i = 16;
char vla[i];
strcpy(vla, "example");
doc.set(vla);
REQUIRE(doc.as<const char*>() == "example"_s);
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("example")),
});
}
#endif
}

View File

@ -122,8 +122,8 @@ TEST_CASE("JsonDocument::shrinkToFit()") {
REQUIRE(doc.as<std::string>() == "{\"abcdefg\":42}");
REQUIRE(spyingAllocator.log() ==
AllocatorLog{
Allocate(sizeofString("abcdefg")),
Allocate(sizeofPool()),
Allocate(sizeofString("abcdefg")),
Reallocate(sizeofPool(), sizeofObject(1)),
});
}
@ -178,7 +178,7 @@ TEST_CASE("JsonDocument::shrinkToFit()") {
AllocatorLog{
Allocate(sizeofPool()),
Allocate(sizeofString("abcdefg")),
Reallocate(sizeofPool(), sizeofPool(1)),
Reallocate(sizeofPool(), sizeofPool(2)),
});
}
}

View File

@ -12,28 +12,55 @@ TEST_CASE("JsonDocument::operator[]") {
const JsonDocument& cdoc = doc;
SECTION("object") {
deserializeJson(doc, "{\"hello\":\"world\"}");
doc["abc"_s] = "ABC";
doc["abc\0d"_s] = "ABCD";
SECTION("const char*") {
REQUIRE(doc["hello"] == "world");
REQUIRE(cdoc["hello"] == "world");
REQUIRE(doc["abc"] == "ABC");
REQUIRE(cdoc["abc"] == "ABC");
}
SECTION("std::string") {
REQUIRE(doc["hello"_s] == "world");
REQUIRE(cdoc["hello"_s] == "world");
REQUIRE(doc["abc"_s] == "ABC");
REQUIRE(cdoc["abc"_s] == "ABC");
REQUIRE(doc["abc\0d"_s] == "ABCD");
REQUIRE(cdoc["abc\0d"_s] == "ABCD");
}
SECTION("JsonVariant") {
doc["key"] = "hello";
REQUIRE(doc[doc["key"]] == "world");
REQUIRE(cdoc[cdoc["key"]] == "world");
doc["key1"] = "abc";
doc["key2"] = "abc\0d"_s;
doc["key3"] = "foo";
CHECK(doc[doc["key1"]] == "ABC");
CHECK(doc[doc["key2"]] == "ABCD");
CHECK(doc[doc["key3"]] == nullptr);
CHECK(doc[doc["key4"]] == nullptr);
CHECK(cdoc[cdoc["key1"]] == "ABC");
CHECK(cdoc[cdoc["key2"]] == "ABCD");
CHECK(cdoc[cdoc["key3"]] == nullptr);
CHECK(cdoc[cdoc["key4"]] == nullptr);
}
SECTION("supports operator|") {
REQUIRE((doc["hello"] | "nope") == "world"_s);
REQUIRE((doc["world"] | "nope") == "nope"_s);
REQUIRE((doc["abc"] | "nope") == "ABC"_s);
REQUIRE((doc["def"] | "nope") == "nope"_s);
}
#if defined(HAS_VARIABLE_LENGTH_ARRAY) && \
!defined(SUBSCRIPT_CONFLICTS_WITH_BUILTIN_OPERATOR)
SECTION("supports VLAs") {
size_t i = 16;
char vla[i];
strcpy(vla, "hello");
doc[vla] = "world";
REQUIRE(doc[vla] == "world");
REQUIRE(cdoc[vla] == "world");
}
#endif
}
SECTION("array") {

View File

@ -5,7 +5,6 @@
add_executable(JsonObjectTests
clear.cpp
compare.cpp
containsKey.cpp
equals.cpp
isNull.cpp
iterator.cpp

View File

@ -1,39 +0,0 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2024, Benoit BLANCHON
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
TEST_CASE("JsonObject::containsKey()") {
JsonDocument doc;
JsonObject obj = doc.to<JsonObject>();
obj["hello"] = 42;
SECTION("returns true only if key is present") {
REQUIRE(false == obj.containsKey("world"));
REQUIRE(true == obj.containsKey("hello"));
}
SECTION("returns false after remove()") {
obj.remove("hello");
REQUIRE(false == obj.containsKey("hello"));
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("key is a VLA") {
size_t i = 16;
char vla[i];
strcpy(vla, "hello");
REQUIRE(true == obj.containsKey(vla));
}
#endif
SECTION("key is a JsonVariant") {
doc["key"] = "hello";
REQUIRE(true == obj.containsKey(obj["key"]));
REQUIRE(false == obj.containsKey(obj["hello"]));
}
}

View File

@ -52,8 +52,8 @@ TEST_CASE("JsonObject::set()") {
REQUIRE(success == true);
REQUIRE(obj2["hello"] == "world"_s);
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
Allocate(sizeofPool()),
Allocate(sizeofString("hello")),
});
}
@ -66,8 +66,8 @@ TEST_CASE("JsonObject::set()") {
REQUIRE(success == true);
REQUIRE(obj2["hello"] == "world"_s);
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
Allocate(sizeofPool()),
Allocate(sizeofString("hello")),
Allocate(sizeofString("world")),
});
}
@ -81,8 +81,8 @@ TEST_CASE("JsonObject::set()") {
REQUIRE(success == true);
REQUIRE(obj2["hello"] == "world"_s);
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
Allocate(sizeofPool()),
Allocate(sizeofString("hello")),
Allocate(sizeofString("world")),
});
}

View File

@ -34,13 +34,6 @@ TEST_CASE("std::string") {
REQUIRE("value"_s == obj["key"_s]);
}
SECTION("containsKey()") {
char json[] = "{\"key\":\"value\"}";
deserializeJson(doc, json);
JsonObject obj = doc.as<JsonObject>();
REQUIRE(true == obj.containsKey("key"_s));
}
SECTION("remove()") {
JsonObject obj = doc.to<JsonObject>();
obj["key"] = "value";

View File

@ -118,16 +118,16 @@ TEST_CASE("JsonObject::operator[]") {
SECTION("should duplicate char* key") {
obj[const_cast<char*>("hello")] = "world";
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
Allocate(sizeofPool()),
Allocate(sizeofString("hello")),
});
}
SECTION("should duplicate char* key&value") {
obj[const_cast<char*>("hello")] = const_cast<char*>("world");
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
Allocate(sizeofPool()),
Allocate(sizeofString("hello")),
Allocate(sizeofString("world")),
});
}
@ -143,16 +143,16 @@ TEST_CASE("JsonObject::operator[]") {
SECTION("should duplicate std::string key") {
obj["hello"_s] = "world";
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
Allocate(sizeofPool()),
Allocate(sizeofString("hello")),
});
}
SECTION("should duplicate std::string key&value") {
obj["hello"_s] = "world"_s;
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
Allocate(sizeofPool()),
Allocate(sizeofString("hello")),
Allocate(sizeofString("world")),
});
}
@ -160,8 +160,8 @@ TEST_CASE("JsonObject::operator[]") {
SECTION("should duplicate a non-static JsonString key") {
obj[JsonString("hello", JsonString::Copied)] = "world";
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
Allocate(sizeofPool()),
Allocate(sizeofString("hello")),
});
}
@ -253,9 +253,15 @@ TEST_CASE("JsonObject::operator[]") {
SECTION("JsonVariant") {
obj["hello"] = "world";
doc["key"] = "hello";
obj["a\0b"_s] = "ABC";
REQUIRE(obj[obj["key"]] == "world");
REQUIRE(obj[obj["foo"]] == nullptr);
doc["key1"] = "hello";
doc["key2"] = "a\0b"_s;
doc["key3"] = "foo";
REQUIRE(obj[obj["key1"]] == "world");
REQUIRE(obj[obj["key2"]] == "ABC");
REQUIRE(obj[obj["key3"]] == nullptr);
REQUIRE(obj[obj["key4"]] == nullptr);
}
}

View File

@ -3,7 +3,6 @@
# MIT License
add_executable(JsonObjectConstTests
containsKey.cpp
equals.cpp
isNull.cpp
iterator.cpp

View File

@ -1,40 +0,0 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2024, Benoit BLANCHON
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
#include "Literals.hpp"
TEST_CASE("JsonObjectConst::containsKey()") {
JsonDocument doc;
doc["hello"] = 42;
auto obj = doc.as<JsonObjectConst>();
SECTION("supports const char*") {
REQUIRE(false == obj.containsKey("world"));
REQUIRE(true == obj.containsKey("hello"));
}
SECTION("supports std::string") {
REQUIRE(false == obj.containsKey("world"_s));
REQUIRE(true == obj.containsKey("hello"_s));
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("supports VLA") {
size_t i = 16;
char vla[i];
strcpy(vla, "hello");
REQUIRE(true == obj.containsKey(vla));
}
#endif
SECTION("supports JsonVariant") {
doc["key"] = "hello";
REQUIRE(true == obj.containsKey(obj["key"]));
REQUIRE(false == obj.containsKey(obj["hello"]));
}
}

View File

@ -11,6 +11,7 @@
TEST_CASE("JsonObjectConst::operator[]") {
JsonDocument doc;
doc["hello"] = "world";
doc["a\0b"_s] = "ABC";
JsonObjectConst obj = doc.as<JsonObjectConst>();
SECTION("supports const char*") {
@ -19,6 +20,7 @@ TEST_CASE("JsonObjectConst::operator[]") {
SECTION("supports std::string") {
REQUIRE(obj["hello"_s] == "world"); // issue #2019
REQUIRE(obj["a\0b"_s] == "ABC");
}
#if defined(HAS_VARIABLE_LENGTH_ARRAY) && \
@ -28,13 +30,17 @@ TEST_CASE("JsonObjectConst::operator[]") {
char vla[i];
strcpy(vla, "hello");
REQUIRE("world"_s == obj[vla]);
REQUIRE(obj[vla] == "world"_s);
}
#endif
SECTION("supports JsonVariant") {
doc["key"] = "hello";
REQUIRE(obj[obj["key"]] == "world");
REQUIRE(obj[obj["foo"]] == nullptr);
doc["key1"] = "hello";
doc["key2"] = "a\0b"_s;
doc["key3"] = "foo";
REQUIRE(obj[obj["key1"]] == "world");
REQUIRE(obj[obj["key2"]] == "ABC");
REQUIRE(obj[obj["key3"]] == nullptr);
REQUIRE(obj[obj["key4"]] == nullptr);
}
}

View File

@ -46,6 +46,10 @@ TEST_CASE("serializeJson(JsonVariant)") {
check("fifty/fifty"_s, "\"fifty/fifty\"");
}
SECTION("Don't escape single quote") {
check("hello'world"_s, "\"hello'world\"");
}
SECTION("Escape backspace") {
check("hello\bworld"_s, "\"hello\\bworld\"");
}
@ -83,6 +87,11 @@ TEST_CASE("serializeJson(JsonVariant)") {
check(3.1415927, "3.1415927");
}
SECTION("Float") {
REQUIRE(sizeof(float) == 4);
check(3.1415927f, "3.141593");
}
SECTION("Zero") {
check(0, "0");
}

View File

@ -7,7 +7,6 @@ add_executable(JsonVariantTests
as.cpp
clear.cpp
compare.cpp
containsKey.cpp
converters.cpp
copy.cpp
is.cpp

View File

@ -46,6 +46,18 @@ TEST_CASE("JsonVariant::add(T)") {
REQUIRE(var.as<std::string>() == "{\"val\":123}");
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("supports VLAs") {
size_t i = 16;
char vla[i];
strcpy(vla, "hello");
var.add(vla);
REQUIRE(var.as<std::string>() == "[\"hello\"]");
}
#endif
}
TEST_CASE("JsonVariant::add<T>()") {

View File

@ -31,13 +31,28 @@ TEST_CASE("JsonVariant::as()") {
REQUIRE(variant.as<MsgPackExtension>().data() == nullptr);
}
SECTION("set(4.2)") {
SECTION("set(float)") {
variant.set(4.2f);
REQUIRE(variant.as<bool>());
REQUIRE(0 == variant.as<const char*>());
REQUIRE(variant.as<std::string>() == "4.2");
REQUIRE(variant.as<long>() == 4L);
REQUIRE(variant.as<float>() == 4.2f);
REQUIRE(variant.as<unsigned>() == 4U);
REQUIRE(variant.as<JsonString>().isNull());
REQUIRE(variant.as<MsgPackBinary>().data() == nullptr);
REQUIRE(variant.as<MsgPackExtension>().data() == nullptr);
}
SECTION("set(double)") {
variant.set(4.2);
REQUIRE(variant.as<bool>());
REQUIRE(0 == variant.as<const char*>());
REQUIRE(variant.as<std::string>() == "4.2");
REQUIRE(variant.as<long>() == 4L);
REQUIRE(variant.as<double>() == 4.2);
REQUIRE(variant.as<unsigned>() == 4U);
REQUIRE(variant.as<JsonString>().isNull());
REQUIRE(variant.as<MsgPackBinary>().data() == nullptr);
@ -78,43 +93,62 @@ TEST_CASE("JsonVariant::as()") {
REQUIRE(variant.as<MsgPackExtension>().data() == nullptr);
}
SECTION("set(42)") {
variant.set(42);
SECTION("set(uint32_t)") {
variant.set(4294967295U);
REQUIRE(variant.as<bool>() == true);
REQUIRE(variant.as<double>() == 42.0);
REQUIRE(variant.as<int>() == 42);
REQUIRE(variant.as<unsigned int>() == 42U); // issue #1601
REQUIRE(variant.as<std::string>() == "42");
REQUIRE(variant.as<double>() == 4294967295.0);
REQUIRE(variant.as<int32_t>() == 0);
REQUIRE(variant.as<uint32_t>() == 4294967295U);
REQUIRE(variant.as<uint64_t>() == 4294967295U);
REQUIRE(variant.as<std::string>() == "4294967295");
REQUIRE(variant.as<JsonString>().isNull());
REQUIRE(variant.as<MsgPackBinary>().data() == nullptr);
REQUIRE(variant.as<MsgPackExtension>().data() == nullptr);
}
SECTION("set(42L)") {
variant.set(42L);
SECTION("set(int32_t)") {
variant.set(-2147483648LL);
REQUIRE(variant.as<bool>() == true);
REQUIRE(variant.as<double>() == 42.0);
REQUIRE(variant.as<std::string>() == "42");
REQUIRE(variant.as<double>() == -2147483648LL);
REQUIRE(variant.as<int32_t>() == -2147483648LL);
REQUIRE(variant.as<int64_t>() == -2147483648LL);
REQUIRE(variant.as<uint32_t>() == 0);
REQUIRE(variant.as<uint64_t>() == 0);
REQUIRE(variant.as<std::string>() == "-2147483648");
REQUIRE(variant.as<JsonString>().isNull());
REQUIRE(variant.as<MsgPackBinary>().data() == nullptr);
REQUIRE(variant.as<MsgPackExtension>().data() == nullptr);
}
SECTION("set(-42L)") {
variant.set(-42L);
REQUIRE(variant.as<double>() == -42.0);
REQUIRE(variant.as<std::string>() == "-42");
REQUIRE(variant.as<JsonString>().isNull());
}
SECTION("set(42UL)") {
variant.set(42UL);
SECTION("set(uint64_t)") {
variant.set(4294967296U);
REQUIRE(variant.as<bool>() == true);
REQUIRE(variant.as<double>() == 42.0);
REQUIRE(variant.as<std::string>() == "42");
REQUIRE(variant.as<double>() == 4294967296.0);
REQUIRE(variant.as<int32_t>() == 0);
REQUIRE(variant.as<uint32_t>() == 0);
REQUIRE(variant.as<uint64_t>() == 4294967296U);
REQUIRE(variant.as<std::string>() == "4294967296");
REQUIRE(variant.as<JsonString>().isNull());
REQUIRE(variant.as<MsgPackBinary>().data() == nullptr);
REQUIRE(variant.as<MsgPackExtension>().data() == nullptr);
}
SECTION("set(int64_t)") {
variant.set(-2147483649LL);
REQUIRE(variant.as<bool>() == true);
REQUIRE(variant.as<double>() == -2147483649LL);
REQUIRE(variant.as<int32_t>() == 0);
REQUIRE(variant.as<int64_t>() == -2147483649LL);
REQUIRE(variant.as<uint32_t>() == 0);
REQUIRE(variant.as<uint64_t>() == 0);
REQUIRE(variant.as<std::string>() == "-2147483649");
REQUIRE(variant.as<JsonString>().isNull());
REQUIRE(variant.as<MsgPackBinary>().data() == nullptr);
REQUIRE(variant.as<MsgPackExtension>().data() == nullptr);
}
SECTION("set(0L)") {
@ -169,7 +203,7 @@ TEST_CASE("JsonVariant::as()") {
REQUIRE(variant.as<bool>() == true);
REQUIRE(variant.as<long>() == 4L);
REQUIRE(variant.as<double>() == 4.2);
REQUIRE(variant.as<double>() == Approx(4.2));
REQUIRE(variant.as<const char*>() == "4.2"_s);
REQUIRE(variant.as<std::string>() == "4.2"_s);
REQUIRE(variant.as<JsonString>() == "4.2");

View File

@ -1,36 +0,0 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2024, Benoit BLANCHON
// MIT License
#include <ArduinoJson.h>
#include <stdint.h>
#include <catch.hpp>
#include "Literals.hpp"
TEST_CASE("JsonVariant::containsKey()") {
JsonDocument doc;
JsonVariant var = doc.to<JsonVariant>();
SECTION("containsKey(const char*)") {
var["hello"] = "world";
REQUIRE(var.containsKey("hello") == true);
REQUIRE(var.containsKey("world") == false);
}
SECTION("containsKey(std::string)") {
var["hello"] = "world";
REQUIRE(var.containsKey("hello"_s) == true);
REQUIRE(var.containsKey("world"_s) == false);
}
SECTION("containsKey(JsonVariant)") {
var["hello"] = "world";
var["key"] = "hello";
REQUIRE(var.containsKey(doc["key"]) == true);
REQUIRE(var.containsKey(doc["foo"]) == false);
}
}

View File

@ -83,6 +83,23 @@ TEST_CASE("JsonVariant::remove(std::string)") {
REQUIRE(var.as<std::string>() == "{\"a\":1}");
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
TEST_CASE("JsonVariant::remove(VLA)") {
JsonDocument doc;
JsonVariant var = doc.to<JsonVariant>();
var["a"] = 1;
var["b"] = 2;
size_t i = 16;
char vla[i];
strcpy(vla, "b");
var.remove("b"_s);
REQUIRE(var.as<std::string>() == "{\"a\":1}");
}
#endif
TEST_CASE("JsonVariant::remove(JsonVariant) from object") {
JsonDocument doc;
JsonVariant var = doc.to<JsonVariant>();

View File

@ -13,7 +13,8 @@ using ArduinoJson::detail::sizeofObject;
enum ErrorCode { ERROR_01 = 1, ERROR_10 = 10 };
TEST_CASE("JsonVariant::set() when there is enough memory") {
JsonDocument doc;
SpyingAllocator spy;
JsonDocument doc(&spy);
JsonVariant variant = doc.to<JsonVariant>();
SECTION("const char*") {
@ -25,6 +26,7 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true);
REQUIRE(variant == "world"); // stores by pointer
REQUIRE(spy.log() == AllocatorLog{});
}
SECTION("(const char*)0") {
@ -32,6 +34,7 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true);
REQUIRE(variant.isNull());
REQUIRE(spy.log() == AllocatorLog{});
}
SECTION("char*") {
@ -43,6 +46,9 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true);
REQUIRE(variant == "hello"); // stores by copy
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
});
}
SECTION("(char*)0") {
@ -50,6 +56,7 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true);
REQUIRE(variant.isNull());
REQUIRE(spy.log() == AllocatorLog{});
}
SECTION("unsigned char*") {
@ -61,6 +68,9 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true);
REQUIRE(variant == "hello"); // stores by copy
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
});
}
SECTION("signed char*") {
@ -72,6 +82,9 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true);
REQUIRE(variant == "hello"); // stores by copy
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
});
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
@ -85,6 +98,9 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true);
REQUIRE(variant == "hello"); // stores by copy
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
});
}
#endif
@ -97,6 +113,9 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true);
REQUIRE(variant == "hello"); // stores by copy
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
});
}
SECTION("static JsonString") {
@ -108,6 +127,7 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true);
REQUIRE(variant == "world"); // stores by pointer
REQUIRE(spy.log() == AllocatorLog{});
}
SECTION("non-static JsonString") {
@ -119,6 +139,9 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true);
REQUIRE(variant == "hello"); // stores by copy
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofString("hello")),
});
}
SECTION("enum") {
@ -129,6 +152,89 @@ TEST_CASE("JsonVariant::set() when there is enough memory") {
REQUIRE(result == true);
REQUIRE(variant.is<int>() == true);
REQUIRE(variant.as<int>() == 10);
REQUIRE(spy.log() == AllocatorLog{});
}
SECTION("float") {
bool result = variant.set(1.2f);
REQUIRE(result == true);
REQUIRE(variant.is<float>() == true);
REQUIRE(variant.as<float>() == 1.2f);
REQUIRE(spy.log() == AllocatorLog{});
}
SECTION("double") {
bool result = variant.set(1.2);
doc.shrinkToFit();
REQUIRE(result == true);
REQUIRE(variant.is<double>() == true);
REQUIRE(variant.as<double>() == 1.2);
REQUIRE(spy.log() ==
AllocatorLog{
Allocate(sizeofPool()),
Reallocate(sizeofPool(), sizeofPool(1)), // one extension slot
});
}
SECTION("int32_t") {
bool result = variant.set(int32_t(42));
REQUIRE(result == true);
REQUIRE(variant.is<int32_t>() == true);
REQUIRE(variant.as<int32_t>() == 42);
REQUIRE(spy.log() == AllocatorLog{});
}
SECTION("int64_t") {
bool result = variant.set(int64_t(-2147483649LL));
doc.shrinkToFit();
REQUIRE(result == true);
REQUIRE(variant.is<int64_t>() == true);
REQUIRE(variant.as<int64_t>() == -2147483649LL);
REQUIRE(spy.log() ==
AllocatorLog{
Allocate(sizeofPool()),
Reallocate(sizeofPool(), sizeofPool(1)), // one extension slot
});
}
SECTION("uint32_t") {
bool result = variant.set(uint32_t(42));
REQUIRE(result == true);
REQUIRE(variant.is<uint32_t>() == true);
REQUIRE(variant.as<uint32_t>() == 42);
REQUIRE(spy.log() == AllocatorLog{});
}
SECTION("uint64_t") {
bool result = variant.set(uint64_t(4294967296));
doc.shrinkToFit();
REQUIRE(result == true);
REQUIRE(variant.is<uint64_t>() == true);
REQUIRE(variant.as<uint64_t>() == 4294967296);
REQUIRE(spy.log() ==
AllocatorLog{
Allocate(sizeofPool()),
Reallocate(sizeofPool(), sizeofPool(1)), // one extension slot
});
}
SECTION("JsonDocument") {
JsonDocument doc1;
doc1["hello"] = "world";
// Should copy the doc
variant.set(doc1);
doc1.clear();
std::string json;
serializeJson(doc, json);
REQUIRE(json == "{\"hello\":\"world\"}");
}
}
@ -158,22 +264,48 @@ TEST_CASE("JsonVariant::set() with not enough memory") {
REQUIRE(result == false);
REQUIRE(v.isNull());
}
}
TEST_CASE("JsonVariant::set(JsonDocument)") {
JsonDocument doc1;
doc1["hello"] = "world";
SECTION("float") {
bool result = v.set(1.2f);
JsonDocument doc2;
JsonVariant v = doc2.to<JsonVariant>();
REQUIRE(result == true);
REQUIRE(v.is<float>());
}
// Should copy the doc
v.set(doc1);
doc1.clear();
SECTION("double") {
bool result = v.set(1.2);
std::string json;
serializeJson(doc2, json);
REQUIRE(json == "{\"hello\":\"world\"}");
REQUIRE(result == false);
REQUIRE(v.isNull());
}
SECTION("int32_t") {
bool result = v.set(-42);
REQUIRE(result == true);
REQUIRE(v.is<int32_t>());
}
SECTION("int64_t") {
bool result = v.set(-2147483649LL);
REQUIRE(result == false);
REQUIRE(v.isNull());
}
SECTION("uint32_t") {
bool result = v.set(42);
REQUIRE(result == true);
REQUIRE(v.is<uint32_t>());
}
SECTION("uint64_t") {
bool result = v.set(4294967296U);
REQUIRE(result == false);
REQUIRE(v.isNull());
}
}
TEST_CASE("JsonVariant::set() releases the previous value") {
@ -220,3 +352,34 @@ TEST_CASE("JsonVariant::set() releases the previous value") {
});
}
}
TEST_CASE("JsonVariant::set() reuses extension slot") {
SpyingAllocator spy;
JsonDocument doc(&spy);
JsonVariant variant = doc.to<JsonVariant>();
variant.set(1.2);
doc.shrinkToFit();
spy.clearLog();
SECTION("double") {
bool result = variant.set(3.4);
REQUIRE(result == true);
REQUIRE(spy.log() == AllocatorLog{});
}
SECTION("int64_t") {
bool result = variant.set(-2147483649LL);
REQUIRE(result == true);
REQUIRE(spy.log() == AllocatorLog{});
}
SECTION("uint64_t") {
bool result = variant.set(4294967296U);
REQUIRE(result == true);
REQUIRE(spy.log() == AllocatorLog{});
}
}

View File

@ -99,7 +99,7 @@ TEST_CASE("vector<int>") {
}
TEST_CASE("array<int, 2>") {
typedef std::array<int, 2> array_type;
using array_type = std::array<int, 2>;
SECTION("toJson") {
array_type v;

View File

@ -116,12 +116,19 @@ TEST_CASE("JsonVariant::operator[]") {
}
SECTION("use JsonVariant as key") {
object["a"] = "a";
object["b"] = "b";
object["c"] = "b";
object["a"] = "A";
object["ab"] = "AB";
object["ab\0c"_s] = "ABC";
object["key1"] = "a";
object["key2"] = "ab";
object["key3"] = "ab\0c"_s;
object["key4"] = "foo";
REQUIRE(var[var["c"]] == "b");
REQUIRE(var[var["d"]].isNull());
REQUIRE(var[var["key1"]] == "A");
REQUIRE(var[var["key2"]] == "AB");
REQUIRE(var[var["key3"]] == "ABC");
REQUIRE(var[var["key4"]].isNull());
REQUIRE(var[var["key5"]].isNull());
}
}

View File

@ -73,10 +73,6 @@ TEST_CASE("Unbound JsonVariant") {
CHECK_FALSE(variant["key"_s].set(1));
}
SECTION("containsKey()") {
CHECK_FALSE(variant.containsKey("hello"));
}
SECTION("remove()") {
variant.remove(0);
variant.remove("hello");

View File

@ -4,7 +4,6 @@
add_executable(JsonVariantConstTests
as.cpp
containsKey.cpp
is.cpp
isnull.cpp
nesting.cpp

View File

@ -1,41 +0,0 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2024, Benoit BLANCHON
// MIT License
#include <ArduinoJson.h>
#include <stdint.h>
#include <catch.hpp>
#include "Literals.hpp"
TEST_CASE("JsonVariantConst::containsKey()") {
JsonDocument doc;
doc["hello"] = "world";
JsonVariantConst var = doc.as<JsonVariant>();
SECTION("support const char*") {
REQUIRE(var.containsKey("hello") == true);
REQUIRE(var.containsKey("world") == false);
}
SECTION("support std::string") {
REQUIRE(var.containsKey("hello"_s) == true);
REQUIRE(var.containsKey("world"_s) == false);
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("supports VLA") {
size_t i = 16;
char vla[i];
strcpy(vla, "hello");
REQUIRE(true == var.containsKey(vla));
}
#endif
SECTION("support JsonVariant") {
doc["key"] = "hello";
REQUIRE(var.containsKey(var["key"]) == true);
REQUIRE(var.containsKey(var["foo"]) == false);
}
}

View File

@ -50,20 +50,22 @@ TEST_CASE("JsonVariantConst::operator[]") {
SECTION("object") {
JsonObject object = doc.to<JsonObject>();
object["a"] = "A";
object["b"] = "B";
object["ab"_s] = "AB";
object["abc"_s] = "ABC";
object["abc\0d"_s] = "ABCD";
SECTION("supports const char*") {
REQUIRE("A"_s == var["a"]);
REQUIRE("B"_s == var["b"]);
REQUIRE(var["c"].isNull());
REQUIRE(var["ab"] == "AB"_s);
REQUIRE(var["abc"] == "ABC"_s);
REQUIRE(var["def"].isNull());
REQUIRE(var[0].isNull());
}
SECTION("supports std::string") {
REQUIRE("A"_s == var["a"_s]);
REQUIRE("B"_s == var["b"_s]);
REQUIRE(var["c"_s].isNull());
REQUIRE(var["ab"_s] == "AB"_s);
REQUIRE(var["abc"_s] == "ABC"_s);
REQUIRE(var["abc\0d"_s] == "ABCD"_s);
REQUIRE(var["def"_s].isNull());
}
#if defined(HAS_VARIABLE_LENGTH_ARRAY) && \
@ -71,16 +73,23 @@ TEST_CASE("JsonVariantConst::operator[]") {
SECTION("supports VLA") {
size_t i = 16;
char vla[i];
strcpy(vla, "a");
strcpy(vla, "abc");
REQUIRE("A"_s == var[vla]);
REQUIRE(var[vla] == "ABC"_s);
}
#endif
SECTION("supports JsonVariant") {
object["c"] = "b";
REQUIRE(var[var["c"]] == "B");
REQUIRE(var[var["d"]].isNull());
object["key1"] = "ab";
object["key2"] = "abc";
object["key3"] = "abc\0d"_s;
object["key4"] = "foo";
REQUIRE(var[var["key1"]] == "AB"_s);
REQUIRE(var[var["key2"]] == "ABC"_s);
REQUIRE(var[var["key3"]] == "ABCD"_s);
REQUIRE(var[var["key4"]].isNull());
REQUIRE(var[var["key5"]].isNull());
}
}
}

View File

@ -5,8 +5,8 @@
add_executable(MiscTests
arithmeticCompare.cpp
conflicts.cpp
FloatParts.cpp
issue1967.cpp
issue2129.cpp
JsonString.cpp
NoArduinoHeader.cpp
printable.cpp

View File

@ -12,77 +12,101 @@
#include "custom_string.hpp"
#include "weird_strcmp.hpp"
using ArduinoJson::JsonString;
using namespace ArduinoJson::detail;
TEST_CASE("ZeroTerminatedRamString") {
SECTION("null") {
ZeroTerminatedRamString s = adaptString(static_cast<const char*>(0));
TEST_CASE("adaptString()") {
SECTION("null const char*") {
auto s = adaptString(static_cast<const char*>(0));
CHECK(s.isNull() == true);
CHECK(s.size() == 0);
CHECK(s.isLinked() == true);
}
SECTION("non-null") {
ZeroTerminatedRamString s = adaptString("bravo");
SECTION("non-null const char*") {
auto s = adaptString("bravo");
CHECK(s.isNull() == false);
CHECK(s.size() == 5);
CHECK(s.isLinked() == true);
}
}
TEST_CASE("SizedRamString") {
SECTION("null") {
SizedRamString s = adaptString(static_cast<const char*>(0), 10);
SECTION("null const char* + size") {
auto s = adaptString(static_cast<const char*>(0), 10);
CHECK(s.isNull() == true);
CHECK(s.isLinked() == false);
}
SECTION("non-null") {
SizedRamString s = adaptString("bravo", 5);
SECTION("non-null const char* + size") {
auto s = adaptString("bravo", 5);
CHECK(s.isNull() == false);
CHECK(s.size() == 5);
CHECK(s.isLinked() == false);
}
}
TEST_CASE("FlashString") {
SECTION("null") {
FlashString s = adaptString(static_cast<const __FlashStringHelper*>(0));
SECTION("null Flash string") {
auto s = adaptString(static_cast<const __FlashStringHelper*>(0));
CHECK(s.isNull() == true);
CHECK(s.size() == 0);
CHECK(s.isLinked() == false);
}
SECTION("non-null") {
FlashString s = adaptString(F("bravo"));
SECTION("non-null Flash string") {
auto s = adaptString(F("bravo"));
CHECK(s.isNull() == false);
CHECK(s.size() == 5);
CHECK(s.isLinked() == false);
}
}
TEST_CASE("std::string") {
std::string orig("bravo");
SizedRamString s = adaptString(orig);
SECTION("std::string") {
std::string orig("bravo");
auto s = adaptString(orig);
CHECK(s.isNull() == false);
CHECK(s.size() == 5);
}
CHECK(s.isNull() == false);
CHECK(s.size() == 5);
CHECK(s.isLinked() == false);
}
TEST_CASE("Arduino String") {
::String orig("bravo");
SizedRamString s = adaptString(orig);
SECTION("Arduino String") {
::String orig("bravo");
auto s = adaptString(orig);
CHECK(s.isNull() == false);
CHECK(s.size() == 5);
}
CHECK(s.isNull() == false);
CHECK(s.size() == 5);
CHECK(s.isLinked() == false);
}
TEST_CASE("custom_string") {
custom_string orig("bravo");
SizedRamString s = adaptString(orig);
SECTION("custom_string") {
custom_string orig("bravo");
auto s = adaptString(orig);
CHECK(s.isNull() == false);
CHECK(s.size() == 5);
CHECK(s.isNull() == false);
CHECK(s.size() == 5);
CHECK(s.isLinked() == false);
}
SECTION("JsonString linked") {
JsonString orig("hello", JsonString::Ownership::Linked);
auto s = adaptString(orig);
CHECK(s.isNull() == false);
CHECK(s.size() == 5);
CHECK(s.isLinked() == true);
}
SECTION("JsonString copied") {
JsonString orig("hello", JsonString::Ownership::Copied);
auto s = adaptString(orig);
CHECK(s.isNull() == false);
CHECK(s.size() == 5);
CHECK(s.isLinked() == false);
}
}
struct EmptyStruct {};
@ -97,6 +121,7 @@ TEST_CASE("IsString<T>") {
CHECK(IsString<::String>::value == true);
CHECK(IsString<::StringSumHelper>::value == true);
CHECK(IsString<const EmptyStruct*>::value == false);
CHECK(IsString<JsonString>::value == true);
}
TEST_CASE("stringCompare") {

View File

@ -8,4 +8,4 @@
struct custom_char_traits : std::char_traits<char> {};
typedef std::basic_string<char, custom_char_traits> custom_string;
using custom_string = std::basic_string<char, custom_char_traits>;

View File

@ -0,0 +1,55 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2024, Benoit BLANCHON
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
template <typename T>
class Nullable {
public:
Nullable() : value_{} {}
Nullable(T value) : value_{value} {}
operator T() const {
return value_;
}
operator T&() {
return value_;
}
bool is_valid() const {
return value_ != invalid_value_;
}
T value() const {
return value_;
}
private:
T value_;
static T invalid_value_;
};
template <>
float Nullable<float>::invalid_value_ = std::numeric_limits<float>::lowest();
template <typename T>
void convertToJson(const Nullable<T>& src, JsonVariant dst) {
if (src.is_valid()) {
dst.set(src.value());
} else {
dst.clear();
}
}
TEST_CASE("Issue #2129") {
Nullable<float> nullable_value = Nullable<float>{123.4f};
JsonDocument doc;
doc["value"] = nullable_value;
REQUIRE(doc["value"].as<float>() == Approx(123.4f));
}

View File

@ -176,15 +176,6 @@ TEST_CASE("unsigned char[]") {
}
#endif
SECTION("containsKey()") {
unsigned char key[] = "hello";
JsonDocument doc;
deserializeJson(doc, "{\"hello\":\"world\"}");
JsonObject obj = doc.as<JsonObject>();
REQUIRE(true == obj.containsKey(key));
}
SECTION("remove()") {
unsigned char key[] = "hello";

View File

@ -3,15 +3,65 @@
#include <catch.hpp>
TEST_CASE("ARDUINOJSON_USE_DOUBLE == 0") {
JsonDocument doc;
JsonObject root = doc.to<JsonObject>();
namespace my {
using ArduinoJson::detail::isinf;
} // namespace my
root["pi"] = 3.14;
root["e"] = 2.72;
std::string json;
serializeJson(doc, json);
REQUIRE(json == "{\"pi\":3.14,\"e\":2.72}");
void checkFloat(const char* input, float expected) {
using ArduinoJson::detail::NumberType;
using ArduinoJson::detail::parseNumber;
CAPTURE(input);
auto result = parseNumber(input);
REQUIRE(result.type() == NumberType::Float);
REQUIRE(result.asFloat() == Approx(expected));
}
TEST_CASE("ARDUINOJSON_USE_DOUBLE == 0") {
SECTION("serializeJson()") {
JsonDocument doc;
JsonObject root = doc.to<JsonObject>();
root["pi"] = 3.14;
root["e"] = 2.72;
std::string json;
serializeJson(doc, json);
REQUIRE(json == "{\"pi\":3.14,\"e\":2.72}");
}
SECTION("parseNumber()") {
using ArduinoJson::detail::NumberType;
using ArduinoJson::detail::parseNumber;
SECTION("Large positive number") {
auto result = parseNumber("1e300");
REQUIRE(result.type() == NumberType::Float);
REQUIRE(result.asFloat() > 0);
REQUIRE(my::isinf(result.asFloat()));
}
SECTION("Large negative number") {
auto result = parseNumber("-1e300");
REQUIRE(result.type() == NumberType::Float);
REQUIRE(result.asFloat() < 0);
REQUIRE(my::isinf(result.asFloat()));
}
SECTION("Too small to be represented") {
auto result = parseNumber("1e-300");
REQUIRE(result.type() == NumberType::Float);
REQUIRE(result.asFloat() == 0);
}
SECTION("MantissaTooLongToFit") {
checkFloat("0.340282346638528861111111111111", 0.34028234663852886f);
checkFloat("34028234663852886.11111111111111", 34028234663852886.0f);
checkFloat("34028234.66385288611111111111111", 34028234.663852886f);
checkFloat("-0.340282346638528861111111111111", -0.34028234663852886f);
checkFloat("-34028234663852886.11111111111111", -34028234663852886.0f);
checkFloat("-34028234.66385288611111111111111", -34028234.663852886f);
}
}
}

View File

@ -32,11 +32,7 @@ TEST_CASE("ARDUINOJSON_USE_LONG_LONG == 0") {
deserializeMsgPack(doc, "\xcf\x00\x00\x00\x01\x00\x00\x00\x00"_s);
REQUIRE(err == DeserializationError::Ok);
#if defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ >= 8
REQUIRE(doc.as<JsonInteger>() == 0x100000000);
#else
REQUIRE(doc.isNull());
#endif
}
}
}

View File

@ -199,3 +199,44 @@ TEST_CASE(
REQUIRE(err == DeserializationError::NoMemory);
}
}
TEST_CASE(
"deserializeMsgPack() returns NoMemory if extension allocation fails") {
JsonDocument doc(FailingAllocator::instance());
SECTION("uint32_t should pass") {
auto err = deserializeMsgPack(doc, "\xceXXXX");
REQUIRE(err == DeserializationError::Ok);
}
SECTION("uint64_t should fail") {
auto err = deserializeMsgPack(doc, "\xcfXXXXXXXX");
REQUIRE(err == DeserializationError::NoMemory);
}
SECTION("int32_t should pass") {
auto err = deserializeMsgPack(doc, "\xd2XXXX");
REQUIRE(err == DeserializationError::Ok);
}
SECTION("int64_t should fail") {
auto err = deserializeMsgPack(doc, "\xd3XXXXXXXX");
REQUIRE(err == DeserializationError::NoMemory);
}
SECTION("float should pass") {
auto err = deserializeMsgPack(doc, "\xcaXXXX");
REQUIRE(err == DeserializationError::Ok);
}
SECTION("double should fail") {
auto err = deserializeMsgPack(doc, "\xcbXXXXXXXX");
REQUIRE(err == DeserializationError::NoMemory);
}
}

View File

@ -4,8 +4,9 @@
add_executable(NumbersTests
convertNumber.cpp
parseFloat.cpp
decomposeFloat.cpp
parseDouble.cpp
parseFloat.cpp
parseInteger.cpp
parseNumber.cpp
)

View File

@ -7,9 +7,9 @@
using namespace ArduinoJson::detail;
TEST_CASE("FloatParts<double>") {
TEST_CASE("decomposeFloat()") {
SECTION("1.7976931348623157E+308") {
FloatParts<double> parts(1.7976931348623157E+308);
auto parts = decomposeFloat(1.7976931348623157E+308, 9);
REQUIRE(parts.integral == 1);
REQUIRE(parts.decimal == 797693135);
REQUIRE(parts.decimalPlaces == 9);
@ -17,17 +17,15 @@ TEST_CASE("FloatParts<double>") {
}
SECTION("4.94065645841247e-324") {
FloatParts<double> parts(4.94065645841247e-324);
auto parts = decomposeFloat(4.94065645841247e-324, 9);
REQUIRE(parts.integral == 4);
REQUIRE(parts.decimal == 940656458);
REQUIRE(parts.decimalPlaces == 9);
REQUIRE(parts.exponent == -324);
}
}
TEST_CASE("FloatParts<float>") {
SECTION("3.4E+38") {
FloatParts<float> parts(3.4E+38f);
auto parts = decomposeFloat(3.4E+38f, 6);
REQUIRE(parts.integral == 3);
REQUIRE(parts.decimal == 4);
REQUIRE(parts.decimalPlaces == 1);
@ -35,7 +33,7 @@ TEST_CASE("FloatParts<float>") {
}
SECTION("1.17549435e38") {
FloatParts<float> parts(1.17549435e-38f);
auto parts = decomposeFloat(1.17549435e-38f, 6);
REQUIRE(parts.integral == 1);
REQUIRE(parts.decimal == 175494);
REQUIRE(parts.decimalPlaces == 6);

View File

@ -2,7 +2,6 @@
// Copyright © 2014-2024, Benoit BLANCHON
// MIT License
#define ARDUINOJSON_USE_DOUBLE 0
#define ARDUINOJSON_ENABLE_NAN 1
#define ARDUINOJSON_ENABLE_INFINITY 1
@ -13,7 +12,9 @@ using namespace ArduinoJson::detail;
void checkFloat(const char* input, float expected) {
CAPTURE(input);
REQUIRE(parseNumber<float>(input) == Approx(expected));
auto result = parseNumber(input);
REQUIRE(result.type() == NumberType::Float);
REQUIRE(result.asFloat() == Approx(expected));
}
void checkFloatNaN(const char* input) {
@ -59,27 +60,15 @@ TEST_CASE("parseNumber<float>()") {
SECTION("VeryLong") {
checkFloat("0.00000000000000000000000000000001", 1e-32f);
checkFloat("100000000000000000000000000000000.0", 1e+32f);
checkFloat(
"100000000000000000000000000000000.00000000000000000000000000000",
1e+32f);
}
SECTION("MantissaTooLongToFit") {
checkFloat("0.340282346638528861111111111111", 0.34028234663852886f);
checkFloat("34028234663852886.11111111111111", 34028234663852886.0f);
checkFloat("34028234.66385288611111111111111", 34028234.663852886f);
checkFloat("-0.340282346638528861111111111111", -0.34028234663852886f);
checkFloat("-34028234663852886.11111111111111", -34028234663852886.0f);
checkFloat("-34028234.66385288611111111111111", -34028234.663852886f);
}
SECTION("ExponentTooBig") {
checkFloatInf("1e39", false);
checkFloatInf("-1e39", true);
checkFloatInf("1e255", false);
checkFloat("1e-255", 0.0f);
// The following don't work because they have many digits so parseNumber()
// treats them as double. But it's not an issue because JsonVariant will use
// a float to store them.
//
// checkFloat("100000000000000000000000000000000.0", 1e+32f);
// checkFloat(
// "100000000000000000000000000000000.00000000000000000000000000000",
// 1e+32f);
}
SECTION("NaN") {
@ -94,8 +83,5 @@ TEST_CASE("parseNumber<float>()") {
checkFloatInf("inf", false);
checkFloatInf("+inf", false);
checkFloatInf("-inf", true);
checkFloatInf("1e300", false);
checkFloatInf("-1e300", true);
}
}

View File

@ -9,45 +9,55 @@ using namespace ArduinoJson;
using namespace ArduinoJson::detail;
TEST_CASE("Test unsigned integer overflow") {
VariantData first, second;
Number first, second;
// Avoids MSVC warning C4127 (conditional expression is constant)
size_t integerSize = sizeof(JsonInteger);
if (integerSize == 8) {
parseNumber("18446744073709551615", first);
parseNumber("18446744073709551616", second);
first = parseNumber("18446744073709551615");
second = parseNumber("18446744073709551616");
} else {
parseNumber("4294967295", first);
parseNumber("4294967296", second);
first = parseNumber("4294967295");
second = parseNumber("4294967296");
}
REQUIRE(first.type() == uint8_t(VALUE_IS_UNSIGNED_INTEGER));
REQUIRE(second.type() == uint8_t(VALUE_IS_FLOAT));
REQUIRE(first.type() == NumberType::UnsignedInteger);
REQUIRE(second.type() == NumberType::Double);
}
TEST_CASE("Test signed integer overflow") {
VariantData first, second;
Number first, second;
// Avoids MSVC warning C4127 (conditional expression is constant)
size_t integerSize = sizeof(JsonInteger);
if (integerSize == 8) {
parseNumber("-9223372036854775808", first);
parseNumber("-9223372036854775809", second);
first = parseNumber("-9223372036854775808");
second = parseNumber("-9223372036854775809");
} else {
parseNumber("-2147483648", first);
parseNumber("-2147483649", second);
first = parseNumber("-2147483648");
second = parseNumber("-2147483649");
}
REQUIRE(first.type() == uint8_t(VALUE_IS_SIGNED_INTEGER));
REQUIRE(second.type() == uint8_t(VALUE_IS_FLOAT));
REQUIRE(first.type() == NumberType::SignedInteger);
REQUIRE(second.type() == NumberType::Double);
}
TEST_CASE("Invalid value") {
VariantData result;
auto result = parseNumber("6a3");
parseNumber("6a3", result);
REQUIRE(result.type() == uint8_t(VALUE_IS_NULL));
REQUIRE(result.type() == NumberType::Invalid);
}
TEST_CASE("float") {
auto result = parseNumber("3.402823e38");
REQUIRE(result.type() == NumberType::Float);
}
TEST_CASE("double") {
auto result = parseNumber("1.7976931348623157e308");
REQUIRE(result.type() == NumberType::Double);
}

View File

@ -3,7 +3,6 @@
// MIT License
#include <ArduinoJson/Memory/StringBuilder.hpp>
#include <ArduinoJson/Memory/VariantPoolImpl.hpp>
#include <catch.hpp>
#include "Allocators.hpp"

View File

@ -9,28 +9,28 @@
using namespace ArduinoJson::detail;
TEST_CASE("ResourceManager::allocSlot()") {
TEST_CASE("ResourceManager::allocVariant()") {
SECTION("Returns different pointer") {
ResourceManager resources;
VariantSlot* s1 = resources.allocSlot();
REQUIRE(s1 != 0);
VariantSlot* s2 = resources.allocSlot();
REQUIRE(s2 != 0);
auto s1 = resources.allocVariant();
REQUIRE(s1.ptr() != nullptr);
auto s2 = resources.allocVariant();
REQUIRE(s2.ptr() != nullptr);
REQUIRE(s1 != s2);
REQUIRE(s1.ptr() != s2.ptr());
}
SECTION("Returns the same slot after calling freeSlot()") {
SECTION("Returns the same slot after calling freeVariant()") {
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();
auto s1 = resources.allocVariant();
auto s2 = resources.allocVariant();
resources.freeVariant(s1);
resources.freeVariant(s2);
auto s3 = resources.allocVariant();
auto s4 = resources.allocVariant();
auto s5 = resources.allocVariant();
REQUIRE(s2.id() != s1.id());
REQUIRE(s3.id() == s2.id());
@ -42,26 +42,26 @@ TEST_CASE("ResourceManager::allocSlot()") {
SECTION("Returns aligned pointers") {
ResourceManager resources;
REQUIRE(isAligned(resources.allocSlot().operator VariantSlot*()));
REQUIRE(isAligned(resources.allocSlot().operator VariantSlot*()));
REQUIRE(isAligned(resources.allocVariant().ptr()));
REQUIRE(isAligned(resources.allocVariant().ptr()));
}
SECTION("Returns null if pool list allocation fails") {
ResourceManager resources(FailingAllocator::instance());
auto variant = resources.allocSlot();
auto variant = resources.allocVariant();
REQUIRE(variant.id() == NULL_SLOT);
REQUIRE(static_cast<VariantSlot*>(variant) == nullptr);
REQUIRE(variant.ptr() == nullptr);
}
SECTION("Returns null if pool allocation fails") {
ResourceManager resources(FailingAllocator::instance());
resources.allocSlot();
resources.allocVariant();
auto variant = resources.allocSlot();
auto variant = resources.allocVariant();
REQUIRE(variant.id() == NULL_SLOT);
REQUIRE(static_cast<VariantSlot*>(variant) == nullptr);
REQUIRE(variant.ptr() == nullptr);
}
SECTION("Try overflow pool counter") {
@ -73,18 +73,18 @@ TEST_CASE("ResourceManager::allocSlot()") {
// fill all the pools
for (SlotId i = 0; i < NULL_SLOT; i++) {
auto slot = resources.allocSlot();
auto slot = resources.allocVariant();
REQUIRE(slot.id() == i); // or != NULL_SLOT
REQUIRE(static_cast<VariantSlot*>(slot) != nullptr);
REQUIRE(slot.ptr() != nullptr);
}
REQUIRE(resources.overflowed() == false);
// now all allocations should fail
for (int i = 0; i < 10; i++) {
auto slot = resources.allocSlot();
auto slot = resources.allocVariant();
REQUIRE(slot.id() == NULL_SLOT);
REQUIRE(static_cast<VariantSlot*>(slot) == nullptr);
REQUIRE(slot.ptr() == nullptr);
}
REQUIRE(resources.overflowed() == true);

View File

@ -3,7 +3,7 @@
// MIT License
#include <ArduinoJson/Memory/ResourceManager.hpp>
#include <ArduinoJson/Memory/VariantPoolImpl.hpp>
#include <ArduinoJson/Memory/ResourceManagerImpl.hpp>
#include <ArduinoJson/Strings/StringAdapters.hpp>
#include <catch.hpp>
@ -13,7 +13,7 @@ TEST_CASE("ResourceManager::clear()") {
ResourceManager resources;
SECTION("Discards allocated variants") {
resources.allocSlot();
resources.allocVariant();
resources.clear();
REQUIRE(resources.size() == 0);

View File

@ -3,7 +3,6 @@
// MIT License
#include <ArduinoJson/Memory/ResourceManager.hpp>
#include <ArduinoJson/Memory/VariantPoolImpl.hpp>
#include <ArduinoJson/Strings/StringAdapters.hpp>
#include <catch.hpp>

View File

@ -3,7 +3,7 @@
// MIT License
#include <ArduinoJson/Memory/ResourceManager.hpp>
#include <ArduinoJson/Memory/VariantPoolImpl.hpp>
#include <ArduinoJson/Memory/ResourceManagerImpl.hpp>
#include <catch.hpp>
#include "Allocators.hpp"
@ -21,14 +21,14 @@ TEST_CASE("ResourceManager::shrinkToFit()") {
}
SECTION("only one pool") {
resources.allocSlot();
resources.allocVariant();
resources.shrinkToFit();
REQUIRE(spyingAllocator.log() ==
AllocatorLog{
Allocate(sizeofPool()),
Reallocate(sizeofPool(), sizeof(VariantSlot)),
Reallocate(sizeofPool(), sizeofPool(1)),
});
}
@ -36,7 +36,7 @@ TEST_CASE("ResourceManager::shrinkToFit()") {
for (size_t i = 0;
i < ARDUINOJSON_POOL_CAPACITY * ARDUINOJSON_INITIAL_POOL_COUNT + 1;
i++)
resources.allocSlot();
resources.allocVariant();
REQUIRE(spyingAllocator.log() ==
AllocatorLog{
Allocate(sizeofPool()) * ARDUINOJSON_INITIAL_POOL_COUNT,
@ -49,7 +49,7 @@ TEST_CASE("ResourceManager::shrinkToFit()") {
REQUIRE(spyingAllocator.log() ==
AllocatorLog{
Reallocate(sizeofPool(), sizeof(VariantSlot)),
Reallocate(sizeofPool(), sizeofPool(1)),
Reallocate(sizeofPoolList(ARDUINOJSON_INITIAL_POOL_COUNT * 2),
sizeofPoolList(ARDUINOJSON_INITIAL_POOL_COUNT + 1)),
});

View File

@ -3,7 +3,7 @@
// MIT License
#include <ArduinoJson/Memory/ResourceManager.hpp>
#include <ArduinoJson/Memory/VariantPoolImpl.hpp>
#include <ArduinoJson/Memory/ResourceManagerImpl.hpp>
#include <catch.hpp>
#include "Allocators.hpp"
@ -21,10 +21,10 @@ TEST_CASE("ResourceManager::size()") {
SECTION("Doesn't grow when allocation of second pool fails") {
timebomb.setCountdown(1);
for (size_t i = 0; i < ARDUINOJSON_POOL_CAPACITY; i++)
resources.allocSlot();
resources.allocVariant();
size_t size = resources.size();
resources.allocSlot();
resources.allocVariant();
REQUIRE(size == resources.size());
}

View File

@ -4,7 +4,7 @@
#include <ArduinoJson/Memory/Alignment.hpp>
#include <ArduinoJson/Memory/ResourceManager.hpp>
#include <ArduinoJson/Memory/VariantPoolImpl.hpp>
#include <ArduinoJson/Memory/ResourceManagerImpl.hpp>
#include <catch.hpp>
#include "Allocators.hpp"
@ -14,7 +14,7 @@ using namespace ArduinoJson::detail;
static void fullPreallocatedPools(ResourceManager& resources) {
for (int i = 0;
i < ARDUINOJSON_INITIAL_POOL_COUNT * ARDUINOJSON_POOL_CAPACITY; i++)
resources.allocSlot();
resources.allocVariant();
}
TEST_CASE("ResourceManager::swap()") {
@ -23,13 +23,13 @@ TEST_CASE("ResourceManager::swap()") {
ResourceManager a(&spy);
ResourceManager b(&spy);
auto a1 = a.allocSlot();
auto b1 = b.allocSlot();
auto a1 = a.allocVariant();
auto b1 = b.allocVariant();
swap(a, b);
REQUIRE(a1->data() == b.getSlot(a1.id())->data());
REQUIRE(b1->data() == a.getSlot(b1.id())->data());
REQUIRE(a1.ptr() == b.getVariant(a1.id()));
REQUIRE(b1.ptr() == a.getVariant(b1.id()));
REQUIRE(spy.log() == AllocatorLog{
Allocate(sizeofPool()) * 2,
@ -42,12 +42,12 @@ TEST_CASE("ResourceManager::swap()") {
ResourceManager b(&spy);
fullPreallocatedPools(b);
auto a1 = a.allocSlot();
auto b1 = b.allocSlot();
auto a1 = a.allocVariant();
auto b1 = b.allocVariant();
swap(a, b);
REQUIRE(a1->data() == b.getSlot(a1.id())->data());
REQUIRE(b1->data() == a.getSlot(b1.id())->data());
REQUIRE(a1.ptr() == b.getVariant(a1.id()));
REQUIRE(b1.ptr() == a.getVariant(b1.id()));
REQUIRE(spy.log() ==
AllocatorLog{
@ -63,12 +63,12 @@ TEST_CASE("ResourceManager::swap()") {
fullPreallocatedPools(a);
ResourceManager b(&spy);
auto a1 = a.allocSlot();
auto b1 = b.allocSlot();
auto a1 = a.allocVariant();
auto b1 = b.allocVariant();
swap(a, b);
REQUIRE(a1->data() == b.getSlot(a1.id())->data());
REQUIRE(b1->data() == a.getSlot(b1.id())->data());
REQUIRE(a1.ptr() == b.getVariant(a1.id()));
REQUIRE(b1.ptr() == a.getVariant(b1.id()));
REQUIRE(spy.log() ==
AllocatorLog{
@ -85,12 +85,12 @@ TEST_CASE("ResourceManager::swap()") {
ResourceManager b(&spy);
fullPreallocatedPools(b);
auto a1 = a.allocSlot();
auto b1 = b.allocSlot();
auto a1 = a.allocVariant();
auto b1 = b.allocVariant();
swap(a, b);
REQUIRE(a1->data() == b.getSlot(a1.id())->data());
REQUIRE(b1->data() == a.getSlot(b1.id())->data());
REQUIRE(a1.ptr() == b.getVariant(a1.id()));
REQUIRE(b1.ptr() == a.getVariant(b1.id()));
}
}

View File

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

View File

@ -1,13 +1,13 @@
{
"name": "ArduinoJson",
"keywords": "json, rest, http, web",
"description": "A simple and efficient JSON library for embedded C++. ⭐ 6624 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++. ⭐ 6739 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",
"repository": {
"type": "git",
"url": "https://github.com/bblanchon/ArduinoJson.git"
},
"version": "7.1.0",
"version": "7.2.1",
"authors": {
"name": "Benoit Blanchon",
"url": "https://blog.benoitblanchon.fr"

View File

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

View File

@ -37,12 +37,12 @@
#include "ArduinoJson/Array/Utilities.hpp"
#include "ArduinoJson/Collection/CollectionImpl.hpp"
#include "ArduinoJson/Memory/ResourceManagerImpl.hpp"
#include "ArduinoJson/Memory/VariantPoolImpl.hpp"
#include "ArduinoJson/Object/MemberProxy.hpp"
#include "ArduinoJson/Object/ObjectImpl.hpp"
#include "ArduinoJson/Variant/ConverterImpl.hpp"
#include "ArduinoJson/Variant/JsonVariantCopier.hpp"
#include "ArduinoJson/Variant/VariantCompare.hpp"
#include "ArduinoJson/Variant/VariantImpl.hpp"
#include "ArduinoJson/Variant/VariantRefBaseImpl.hpp"
#include "ArduinoJson/Json/JsonDeserializer.hpp"

View File

@ -10,9 +10,7 @@ ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
class ArrayData : public CollectionData {
public:
VariantData* addElement(ResourceManager* resources) {
return addSlot(resources).data();
}
VariantData* addElement(ResourceManager* resources);
static VariantData* addElement(ArrayData* array, ResourceManager* resources) {
if (!array)
@ -51,14 +49,14 @@ class ArrayData : public CollectionData {
array->removeElement(index, resources);
}
bool copyFrom(const ArrayData& src, ResourceManager* resources);
void remove(iterator it, ResourceManager* resources) {
CollectionData::removeOne(it, resources);
}
static bool copy(ArrayData* dst, const ArrayData* src,
ResourceManager* resources) {
if (!dst || !src)
return false;
return dst->copyFrom(*src, resources);
static void remove(ArrayData* array, iterator it,
ResourceManager* resources) {
if (array)
return array->remove(it, resources);
}
private:

View File

@ -6,6 +6,7 @@
#include <ArduinoJson/Array/ArrayData.hpp>
#include <ArduinoJson/Variant/VariantCompare.hpp>
#include <ArduinoJson/Variant/VariantData.hpp>
ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
@ -19,6 +20,14 @@ inline ArrayData::iterator ArrayData::at(
return it;
}
inline VariantData* ArrayData::addElement(ResourceManager* resources) {
auto slot = resources->allocVariant();
if (!slot)
return nullptr;
CollectionData::appendOne(slot, resources);
return slot.ptr();
}
inline VariantData* ArrayData::getOrAddElement(size_t index,
ResourceManager* resources) {
auto it = createIterator(resources);
@ -50,16 +59,21 @@ inline void ArrayData::removeElement(size_t index, ResourceManager* resources) {
template <typename T>
inline bool ArrayData::addValue(T&& value, ResourceManager* resources) {
ARDUINOJSON_ASSERT(resources != nullptr);
auto slot = resources->allocSlot();
auto slot = resources->allocVariant();
if (!slot)
return false;
JsonVariant variant(slot->data(), resources);
JsonVariant variant(slot.ptr(), resources);
if (!variant.set(detail::forward<T>(value))) {
resources->freeSlot(slot);
resources->freeVariant(slot);
return false;
}
addSlot(slot, resources);
CollectionData::appendOne(slot, resources);
return true;
}
// Returns the size (in bytes) of an array with n elements.
constexpr size_t sizeofArray(size_t n) {
return n * ResourceManager::slotSize;
}
ARDUINOJSON_END_PRIVATE_NAMESPACE

View File

@ -17,7 +17,7 @@ class JsonArray : public detail::VariantOperators<JsonArray> {
friend class detail::VariantAttorney;
public:
typedef JsonArrayIterator iterator;
using iterator = JsonArrayIterator;
// Constructs an unbound reference.
JsonArray() : data_(0), resources_(0) {}

View File

@ -19,7 +19,7 @@ class JsonArrayConst : public detail::VariantOperators<JsonArrayConst> {
friend class detail::VariantAttorney;
public:
typedef JsonArrayConstIterator iterator;
using iterator = JsonArrayConstIterator;
// Returns an iterator to the first element of the array.
// https://arduinojson.org/v7/api/jsonarrayconst/begin/

View File

@ -4,6 +4,7 @@
#pragma once
#include <ArduinoJson/Memory/MemoryPool.hpp>
#include <ArduinoJson/Namespace.hpp>
#include <ArduinoJson/Polyfills/assert.hpp>
@ -12,7 +13,7 @@
ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
class VariantData;
class VariantSlot;
class ResourceManager;
class CollectionIterator {
friend class CollectionData;
@ -49,12 +50,6 @@ class CollectionIterator {
return *data();
}
const char* key() const;
bool ownsKey() const;
void setKey(StringNode*);
void setKey(const char*);
VariantData* data() {
return reinterpret_cast<VariantData*>(slot_);
}
@ -64,9 +59,9 @@ class CollectionIterator {
}
private:
CollectionIterator(VariantSlot* slot, SlotId slotId);
CollectionIterator(VariantData* slot, SlotId slotId);
VariantSlot* slot_;
VariantData* slot_;
SlotId currentId_, nextId_;
};
@ -84,9 +79,7 @@ class CollectionData {
using iterator = CollectionIterator;
iterator createIterator(const ResourceManager* resources) const {
return iterator(resources->getSlot(head_), head_);
}
iterator createIterator(const ResourceManager* resources) const;
size_t size(const ResourceManager*) const;
size_t nesting(const ResourceManager*) const;
@ -99,25 +92,20 @@ class CollectionData {
collection->clear(resources);
}
void remove(iterator it, ResourceManager* resources);
static void remove(CollectionData* collection, iterator it,
ResourceManager* resources) {
if (collection)
return collection->remove(it, resources);
}
SlotId head() const {
return head_;
}
void addSlot(SlotWithId slot, ResourceManager* resources);
protected:
iterator addSlot(ResourceManager*);
void appendOne(Slot<VariantData> slot, const ResourceManager* resources);
void appendPair(Slot<VariantData> key, Slot<VariantData> value,
const ResourceManager* resources);
void removeOne(iterator it, ResourceManager* resources);
void removePair(iterator it, ResourceManager* resources);
private:
SlotWithId getPreviousSlot(VariantSlot*, const ResourceManager*) const;
Slot<VariantData> getPreviousSlot(VariantData*, const ResourceManager*) const;
};
inline const VariantData* collectionToVariant(

View File

@ -12,66 +12,48 @@
ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
inline CollectionIterator::CollectionIterator(VariantSlot* slot, SlotId slotId)
inline CollectionIterator::CollectionIterator(VariantData* slot, SlotId slotId)
: slot_(slot), currentId_(slotId) {
nextId_ = slot_ ? slot_->next() : NULL_SLOT;
}
inline const char* CollectionIterator::key() const {
ARDUINOJSON_ASSERT(slot_ != nullptr);
return slot_->key();
}
inline void CollectionIterator::setKey(const char* s) {
ARDUINOJSON_ASSERT(slot_ != nullptr);
ARDUINOJSON_ASSERT(s != nullptr);
return slot_->setKey(s);
}
inline void CollectionIterator::setKey(StringNode* s) {
ARDUINOJSON_ASSERT(slot_ != nullptr);
ARDUINOJSON_ASSERT(s != nullptr);
return slot_->setKey(s);
}
inline bool CollectionIterator::ownsKey() const {
ARDUINOJSON_ASSERT(slot_ != nullptr);
return slot_->ownsKey();
}
inline void CollectionIterator::next(const ResourceManager* resources) {
ARDUINOJSON_ASSERT(currentId_ != NULL_SLOT);
slot_ = resources->getSlot(nextId_);
slot_ = resources->getVariant(nextId_);
currentId_ = nextId_;
if (slot_)
nextId_ = slot_->next();
}
inline CollectionData::iterator CollectionData::addSlot(
ResourceManager* resources) {
auto slot = resources->allocSlot();
if (!slot)
return {};
inline CollectionData::iterator CollectionData::createIterator(
const ResourceManager* resources) const {
return iterator(resources->getVariant(head_), head_);
}
inline void CollectionData::appendOne(Slot<VariantData> slot,
const ResourceManager* resources) {
if (tail_ != NULL_SLOT) {
auto tail = resources->getSlot(tail_);
auto tail = resources->getVariant(tail_);
tail->setNext(slot.id());
tail_ = slot.id();
} else {
head_ = slot.id();
tail_ = slot.id();
}
return iterator(slot, slot.id());
}
inline void CollectionData::addSlot(SlotWithId slot,
ResourceManager* resources) {
inline void CollectionData::appendPair(Slot<VariantData> key,
Slot<VariantData> value,
const ResourceManager* resources) {
key->setNext(value.id());
if (tail_ != NULL_SLOT) {
auto tail = resources->getSlot(tail_);
tail->setNext(slot.id());
tail_ = slot.id();
auto tail = resources->getVariant(tail_);
tail->setNext(key.id());
tail_ = value.id();
} else {
head_ = slot.id();
tail_ = slot.id();
head_ = key.id();
tail_ = value.id();
}
}
@ -79,30 +61,30 @@ inline void CollectionData::clear(ResourceManager* resources) {
auto next = head_;
while (next != NULL_SLOT) {
auto currId = next;
auto slot = resources->getSlot(next);
auto slot = resources->getVariant(next);
next = slot->next();
resources->freeSlot(SlotWithId(slot, currId));
resources->freeVariant({slot, currId});
}
head_ = NULL_SLOT;
tail_ = NULL_SLOT;
}
inline SlotWithId CollectionData::getPreviousSlot(
VariantSlot* target, const ResourceManager* resources) const {
auto prev = SlotWithId();
inline Slot<VariantData> CollectionData::getPreviousSlot(
VariantData* target, const ResourceManager* resources) const {
auto prev = Slot<VariantData>();
auto currentId = head_;
while (currentId != NULL_SLOT) {
auto currentSlot = resources->getSlot(currentId);
auto currentSlot = resources->getVariant(currentId);
if (currentSlot == target)
return prev;
prev = SlotWithId(currentSlot, currentId);
break;
prev = Slot<VariantData>(currentSlot, currentId);
currentId = currentSlot->next();
}
return SlotWithId();
return prev;
}
inline void CollectionData::remove(iterator it, ResourceManager* resources) {
inline void CollectionData::removeOne(iterator it, ResourceManager* resources) {
if (it.done())
return;
auto curr = it.slot_;
@ -114,7 +96,25 @@ inline void CollectionData::remove(iterator it, ResourceManager* resources) {
head_ = next;
if (next == NULL_SLOT)
tail_ = prev.id();
resources->freeSlot({it.slot_, it.currentId_});
resources->freeVariant({it.slot_, it.currentId_});
}
inline void CollectionData::removePair(ObjectData::iterator it,
ResourceManager* resources) {
if (it.done())
return;
auto keySlot = it.slot_;
auto valueId = it.nextId_;
auto valueSlot = resources->getVariant(valueId);
// remove value slot
keySlot->setNext(valueSlot->next());
resources->freeVariant({valueSlot, valueId});
// remove key slot
removeOne(it, resources);
}
inline size_t CollectionData::nesting(const ResourceManager* resources) const {

View File

@ -56,12 +56,6 @@
# endif
#endif
// Store floating-point values with float (0) or double (1)
// https://arduinojson.org/v7/config/use_double/
#ifndef ARDUINOJSON_USE_DOUBLE
# define ARDUINOJSON_USE_DOUBLE 1
#endif
// Pointer size: a heuristic to set sensible defaults
#ifndef ARDUINOJSON_SIZEOF_POINTER
# if defined(__SIZEOF_POINTER__)
@ -73,6 +67,16 @@
# endif
#endif
// Store floating-point values with float (0) or double (1)
// https://arduinojson.org/v7/config/use_double/
#ifndef ARDUINOJSON_USE_DOUBLE
# if ARDUINOJSON_SIZEOF_POINTER >= 4 // 32 & 64 bits systems
# define ARDUINOJSON_USE_DOUBLE 1
# else
# define ARDUINOJSON_USE_DOUBLE 0
# endif
#endif
// Store integral values with long (0) or long long (1)
// https://arduinojson.org/v7/config/use_long_long/
#ifndef ARDUINOJSON_USE_LONG_LONG
@ -106,12 +110,12 @@
// Capacity of each variant pool (in slots)
#ifndef ARDUINOJSON_POOL_CAPACITY
# if ARDUINOJSON_SIZEOF_POINTER <= 2
# define ARDUINOJSON_POOL_CAPACITY 16 // 128 bytes
# elif ARDUINOJSON_SIZEOF_POINTER == 4
# define ARDUINOJSON_POOL_CAPACITY 64 // 1024 bytes
# if ARDUINOJSON_SLOT_ID_SIZE == 1
# define ARDUINOJSON_POOL_CAPACITY 16 // 96 bytes
# elif ARDUINOJSON_SLOT_ID_SIZE == 2
# define ARDUINOJSON_POOL_CAPACITY 128 // 1024 bytes
# else
# define ARDUINOJSON_POOL_CAPACITY 128 // 3072 bytes
# define ARDUINOJSON_POOL_CAPACITY 256 // 4096 bytes
# endif
#endif
@ -269,6 +273,12 @@
# endif
#endif
#if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_DOUBLE
# define ARDUINOJSON_USE_EXTENSIONS 1
#else
# define ARDUINOJSON_USE_EXTENSIONS 0
#endif
#if defined(nullptr)
# error nullptr is defined as a macro. Remove the faulty #define or #undef nullptr
// See https://github.com/bblanchon/ArduinoJson/issues/1355

View File

@ -24,14 +24,10 @@ struct first_or_void<T, Rest...> {
// A meta-function that returns true if T is a valid destination type for
// deserialize()
template <class T, class = void>
struct is_deserialize_destination : false_type {};
template <class T>
struct is_deserialize_destination<
T, enable_if_t<is_same<decltype(VariantAttorney::getResourceManager(
detail::declval<T&>())),
ResourceManager*>::value>> : true_type {};
using is_deserialize_destination =
bool_constant<is_base_of<JsonDocument, remove_cv_t<T>>::value ||
IsVariant<T>::value>;
template <typename TDestination>
inline void shrinkJsonDocument(TDestination&) {

View File

@ -142,6 +142,13 @@ class JsonDocument : public detail::VariantOperators<const JsonDocument&> {
return to<JsonVariant>().set(src);
}
// Replaces the root with the specified value.
// https://arduinojson.org/v7/api/jsondocument/set/
template <typename TChar>
bool set(TChar* src) {
return to<JsonVariant>().set(src);
}
// Clears the document and converts it to the specified type.
// https://arduinojson.org/v7/api/jsondocument/to/
template <typename T>
@ -150,24 +157,27 @@ class JsonDocument : public detail::VariantOperators<const JsonDocument&> {
return getVariant().template to<T>();
}
// Returns true if the root object contains the specified key.
// DEPRECATED: use obj["key"].is<T>() instead
// https://arduinojson.org/v7/api/jsondocument/containskey/
template <typename TChar>
ARDUINOJSON_DEPRECATED("use doc[\"key\"].is<T>() instead")
bool containsKey(TChar* key) const {
return data_.getMember(detail::adaptString(key), &resources_) != 0;
}
// Returns true if the root object contains the specified key.
// DEPRECATED: use obj[key].is<T>() instead
// https://arduinojson.org/v7/api/jsondocument/containskey/
template <typename TString>
ARDUINOJSON_DEPRECATED("use doc[key].is<T>() instead")
detail::enable_if_t<detail::IsString<TString>::value, bool> containsKey(
const TString& key) const {
return data_.getMember(detail::adaptString(key), &resources_) != 0;
}
// Returns true if the root object contains the specified key.
// DEPRECATED: use obj[key].is<T>() instead
// https://arduinojson.org/v7/api/jsondocument/containskey/
template <typename TVariant>
ARDUINOJSON_DEPRECATED("use doc[key].is<T>() instead")
detail::enable_if_t<detail::IsVariant<TVariant>::value, bool> containsKey(
const TVariant& key) const {
return containsKey(key.template as<const char*>());
@ -229,8 +239,8 @@ class JsonDocument : public detail::VariantOperators<const JsonDocument&> {
template <typename TVariant>
detail::enable_if_t<detail::IsVariant<TVariant>::value, JsonVariantConst>
operator[](const TVariant& key) const {
if (key.template is<const char*>())
return operator[](key.template as<const char*>());
if (key.template is<JsonString>())
return operator[](key.template as<JsonString>());
if (key.template is<size_t>())
return operator[](key.template as<size_t>());
return {};

View File

@ -32,8 +32,8 @@ class EscapeSequence {
}
private:
static const char* escapeTable(bool excludeSolidus) {
return &"//\"\"\\\\b\bf\fn\nr\rt\t"[excludeSolidus ? 2 : 0];
static const char* escapeTable(bool isSerializing) {
return &"//''\"\"\\\\b\bf\fn\nr\rt\t"[isSerializing ? 4 : 0];
}
};

View File

@ -283,7 +283,7 @@ class JsonDeserializer {
if (!member)
return DeserializationError::NoMemory;
} else {
member->setNull(resources_);
member->clear(resources_);
}
// Parse value
@ -517,10 +517,37 @@ class JsonDeserializer {
}
buffer_[n] = 0;
if (!parseNumber(buffer_, result))
return DeserializationError::InvalidInput;
auto number = parseNumber(buffer_);
switch (number.type()) {
case NumberType::UnsignedInteger:
if (result.setInteger(number.asUnsignedInteger(), resources_))
return DeserializationError::Ok;
else
return DeserializationError::NoMemory;
return DeserializationError::Ok;
case NumberType::SignedInteger:
if (result.setInteger(number.asSignedInteger(), resources_))
return DeserializationError::Ok;
else
return DeserializationError::NoMemory;
case NumberType::Float:
if (result.setFloat(number.asFloat(), resources_))
return DeserializationError::Ok;
else
return DeserializationError::NoMemory;
#if ARDUINOJSON_USE_DOUBLE
case NumberType::Double:
if (result.setFloat(number.asDouble(), resources_))
return DeserializationError::Ok;
else
return DeserializationError::NoMemory;
#endif
default:
return DeserializationError::InvalidInput;
}
}
DeserializationError::Code skipNumericValue() {

View File

@ -25,9 +25,9 @@ class JsonSerializer : public VariantDataVisitor<size_t> {
auto slotId = array.head();
while (slotId != NULL_SLOT) {
auto slot = resources_->getSlot(slotId);
auto slot = resources_->getVariant(slotId);
slot->data()->accept(*this);
slot->accept(*this, resources_);
slotId = slot->next();
@ -44,24 +44,26 @@ class JsonSerializer : public VariantDataVisitor<size_t> {
auto slotId = object.head();
while (slotId != NULL_SLOT) {
auto slot = resources_->getSlot(slotId);
bool isKey = true;
formatter_.writeString(slot->key());
write(':');
slot->data()->accept(*this);
while (slotId != NULL_SLOT) {
auto slot = resources_->getVariant(slotId);
slot->accept(*this, resources_);
slotId = slot->next();
if (slotId != NULL_SLOT)
write(',');
write(isKey ? ':' : ',');
isKey = !isKey;
}
write('}');
return bytesWritten();
}
size_t visit(JsonFloat value) {
template <typename T>
enable_if_t<is_floating_point<T>::value, size_t> visit(T value) {
formatter_.writeFloat(value);
return bytesWritten();
}
@ -128,7 +130,8 @@ ARDUINOJSON_BEGIN_PUBLIC_NAMESPACE
// Produces a minified JSON document.
// https://arduinojson.org/v7/api/json/serializejson/
template <typename TDestination>
size_t serializeJson(JsonVariantConst source, TDestination& destination) {
detail::enable_if_t<!detail::is_pointer<TDestination>::value, size_t>
serializeJson(JsonVariantConst source, TDestination& destination) {
using namespace detail;
return serialize<JsonSerializer>(source, destination);
}

View File

@ -13,7 +13,7 @@ ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
template <typename TWriter>
class PrettyJsonSerializer : public JsonSerializer<TWriter> {
typedef JsonSerializer<TWriter> base;
using base = JsonSerializer<TWriter>;
public:
PrettyJsonSerializer(TWriter writer, const ResourceManager* resources)
@ -26,7 +26,7 @@ class PrettyJsonSerializer : public JsonSerializer<TWriter> {
nesting_++;
while (!it.done()) {
indent();
it->accept(*this);
it->accept(*this, base::resources_);
it.next(base::resources_);
base::write(it.done() ? "\r\n" : ",\r\n");
@ -45,14 +45,17 @@ class PrettyJsonSerializer : public JsonSerializer<TWriter> {
if (!it.done()) {
base::write("{\r\n");
nesting_++;
bool isKey = true;
while (!it.done()) {
indent();
base::visit(it.key());
base::write(": ");
it->accept(*this);
if (isKey)
indent();
it->accept(*this, base::resources_);
it.next(base::resources_);
base::write(it.done() ? "\r\n" : ",\r\n");
if (isKey)
base::write(": ");
else
base::write(it.done() ? "\r\n" : ",\r\n");
isKey = !isKey;
}
nesting_--;
indent();
@ -81,7 +84,8 @@ ARDUINOJSON_BEGIN_PUBLIC_NAMESPACE
// Produces JsonDocument to create a prettified JSON document.
// https://arduinojson.org/v7/api/json/serializejsonpretty/
template <typename TDestination>
size_t serializeJsonPretty(JsonVariantConst source, TDestination& destination) {
detail::enable_if_t<!detail::is_pointer<TDestination>::value, size_t>
serializeJsonPretty(JsonVariantConst source, TDestination& destination) {
using namespace ArduinoJson::detail;
return serialize<PrettyJsonSerializer>(source, destination);
}

View File

@ -66,6 +66,10 @@ class TextFormatter {
template <typename T>
void writeFloat(T value) {
writeFloat(JsonFloat(value), sizeof(T) >= 8 ? 9 : 6);
}
void writeFloat(JsonFloat value, int8_t decimalPlaces) {
if (isnan(value))
return writeRaw(ARDUINOJSON_ENABLE_NAN ? "NaN" : "null");
@ -87,7 +91,7 @@ class TextFormatter {
}
#endif
FloatParts<T> parts(value);
auto parts = decomposeFloat(value, decimalPlaces);
writeInteger(parts.integral);
if (parts.decimalPlaces)
@ -101,7 +105,7 @@ class TextFormatter {
template <typename T>
enable_if_t<is_signed<T>::value> writeInteger(T value) {
typedef make_unsigned_t<T> unsigned_type;
using unsigned_type = make_unsigned_t<T>;
unsigned_type unsigned_value;
if (value < 0) {
writeRaw('-');

View File

@ -0,0 +1,110 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2024, Benoit BLANCHON
// MIT License
#pragma once
#include <ArduinoJson/Memory/Allocator.hpp>
#include <ArduinoJson/Polyfills/assert.hpp>
#include <ArduinoJson/Polyfills/integer.hpp>
ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
using SlotId = uint_t<ARDUINOJSON_SLOT_ID_SIZE * 8>;
using SlotCount = SlotId;
const SlotId NULL_SLOT = SlotId(-1);
template <typename T>
class Slot {
public:
Slot() : ptr_(nullptr), id_(NULL_SLOT) {}
Slot(T* p, SlotId id) : ptr_(p), id_(id) {
ARDUINOJSON_ASSERT((p == nullptr) == (id == NULL_SLOT));
}
explicit operator bool() const {
return ptr_ != nullptr;
}
SlotId id() const {
return id_;
}
T* ptr() const {
return ptr_;
}
T* operator->() const {
ARDUINOJSON_ASSERT(ptr_ != nullptr);
return ptr_;
}
private:
T* ptr_;
SlotId id_;
};
template <typename T>
class MemoryPool {
public:
void create(SlotCount cap, Allocator* allocator) {
ARDUINOJSON_ASSERT(cap > 0);
slots_ = reinterpret_cast<T*>(allocator->allocate(slotsToBytes(cap)));
capacity_ = slots_ ? cap : 0;
usage_ = 0;
}
void destroy(Allocator* allocator) {
if (slots_)
allocator->deallocate(slots_);
slots_ = nullptr;
capacity_ = 0;
usage_ = 0;
}
Slot<T> allocSlot() {
if (!slots_)
return {};
if (usage_ >= capacity_)
return {};
auto index = usage_++;
return {slots_ + index, SlotId(index)};
}
T* getSlot(SlotId id) const {
ARDUINOJSON_ASSERT(id < usage_);
return slots_ + id;
}
void clear() {
usage_ = 0;
}
void shrinkToFit(Allocator* allocator) {
auto newSlots = reinterpret_cast<T*>(
allocator->reallocate(slots_, slotsToBytes(usage_)));
if (newSlots) {
slots_ = newSlots;
capacity_ = usage_;
}
}
SlotCount usage() const {
return usage_;
}
static SlotCount bytesToSlots(size_t n) {
return static_cast<SlotCount>(n / sizeof(T));
}
static size_t slotsToBytes(SlotCount n) {
return n * sizeof(T);
}
private:
SlotCount capacity_;
SlotCount usage_;
T* slots_;
};
ARDUINOJSON_END_PRIVATE_NAMESPACE

View File

@ -4,22 +4,34 @@
#pragma once
#include <ArduinoJson/Memory/VariantPool.hpp>
#include <ArduinoJson/Memory/MemoryPool.hpp>
#include <ArduinoJson/Polyfills/assert.hpp>
#include <ArduinoJson/Polyfills/utility.hpp>
#include <string.h> // memcpy
ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
using PoolCount = SlotId;
class VariantPoolList {
public:
VariantPoolList() = default;
template <typename T>
class MemoryPoolList {
struct FreeSlot {
SlotId next;
};
~VariantPoolList() {
static_assert(sizeof(FreeSlot) <= sizeof(T), "T is too small");
public:
using Pool = MemoryPool<T>;
MemoryPoolList() = default;
~MemoryPoolList() {
ARDUINOJSON_ASSERT(count_ == 0);
}
friend void swap(VariantPoolList& a, VariantPoolList& b) {
friend void swap(MemoryPoolList& a, MemoryPoolList& b) {
bool aUsedPreallocated = a.pools_ == a.preallocatedPools_;
bool bUsedPreallocated = b.pools_ == b.preallocatedPools_;
@ -50,7 +62,7 @@ class VariantPoolList {
swap_(a.freeList_, b.freeList_);
}
VariantPoolList& operator=(VariantPoolList&& src) {
MemoryPoolList& operator=(MemoryPoolList&& src) {
ARDUINOJSON_ASSERT(count_ == 0);
if (src.pools_ == src.preallocatedPools_) {
memcpy(preallocatedPools_, src.preallocatedPools_,
@ -67,7 +79,7 @@ class VariantPoolList {
return *this;
}
SlotWithId allocSlot(Allocator* allocator) {
Slot<T> allocSlot(Allocator* allocator) {
// try to allocate from free list
if (freeList_ != NULL_SLOT) {
return allocFromFreeList();
@ -88,9 +100,12 @@ class VariantPoolList {
return allocFromLastPool();
}
void freeSlot(SlotWithId slot);
void freeSlot(Slot<T> slot) {
reinterpret_cast<FreeSlot*>(slot.ptr())->next = freeList_;
freeList_ = slot.id();
}
VariantSlot* getSlot(SlotId id) const {
T* getSlot(SlotId id) const {
if (id == NULL_SLOT)
return nullptr;
auto poolIndex = SlotId(id / ARDUINOJSON_POOL_CAPACITY);
@ -118,30 +133,41 @@ class VariantPoolList {
return total;
}
size_t size() const {
return Pool::slotsToBytes(usage());
}
void shrinkToFit(Allocator* allocator) {
if (count_ > 0)
pools_[count_ - 1].shrinkToFit(allocator);
if (pools_ != preallocatedPools_ && count_ != capacity_) {
pools_ = static_cast<VariantPool*>(
allocator->reallocate(pools_, count_ * sizeof(VariantPool)));
pools_ = static_cast<Pool*>(
allocator->reallocate(pools_, count_ * sizeof(Pool)));
ARDUINOJSON_ASSERT(pools_ != nullptr); // realloc to smaller can't fail
capacity_ = count_;
}
}
private:
SlotWithId allocFromFreeList();
Slot<T> allocFromFreeList() {
ARDUINOJSON_ASSERT(freeList_ != NULL_SLOT);
auto id = freeList_;
auto slot = getSlot(freeList_);
freeList_ = reinterpret_cast<FreeSlot*>(slot)->next;
return {slot, id};
}
SlotWithId allocFromLastPool() {
Slot<T> allocFromLastPool() {
ARDUINOJSON_ASSERT(count_ > 0);
auto poolIndex = SlotId(count_ - 1);
auto slot = pools_[poolIndex].allocSlot();
if (!slot)
return {};
return {slot, SlotId(poolIndex * ARDUINOJSON_POOL_CAPACITY + slot.id())};
return {slot.ptr(),
SlotId(poolIndex * ARDUINOJSON_POOL_CAPACITY + slot.id())};
}
VariantPool* addPool(Allocator* allocator) {
Pool* addPool(Allocator* allocator) {
if (count_ == capacity_ && !increaseCapacity(allocator))
return nullptr;
auto pool = &pools_[count_++];
@ -159,24 +185,23 @@ class VariantPoolList {
auto newCapacity = PoolCount(capacity_ * 2);
if (pools_ == preallocatedPools_) {
newPools = allocator->allocate(newCapacity * sizeof(VariantPool));
newPools = allocator->allocate(newCapacity * sizeof(Pool));
if (!newPools)
return false;
memcpy(newPools, preallocatedPools_, sizeof(preallocatedPools_));
} else {
newPools =
allocator->reallocate(pools_, newCapacity * sizeof(VariantPool));
newPools = allocator->reallocate(pools_, newCapacity * sizeof(Pool));
if (!newPools)
return false;
}
pools_ = static_cast<VariantPool*>(newPools);
pools_ = static_cast<Pool*>(newPools);
capacity_ = newCapacity;
return true;
}
VariantPool preallocatedPools_[ARDUINOJSON_INITIAL_POOL_COUNT];
VariantPool* pools_ = preallocatedPools_;
Pool preallocatedPools_[ARDUINOJSON_INITIAL_POOL_COUNT];
Pool* pools_ = preallocatedPools_;
PoolCount count_ = 0;
PoolCount capacity_ = ARDUINOJSON_INITIAL_POOL_COUNT;
SlotId freeList_ = NULL_SLOT;

View File

@ -5,19 +5,29 @@
#pragma once
#include <ArduinoJson/Memory/Allocator.hpp>
#include <ArduinoJson/Memory/MemoryPoolList.hpp>
#include <ArduinoJson/Memory/StringPool.hpp>
#include <ArduinoJson/Memory/VariantPoolList.hpp>
#include <ArduinoJson/Polyfills/assert.hpp>
#include <ArduinoJson/Polyfills/utility.hpp>
#include <ArduinoJson/Strings/StringAdapters.hpp>
#include <ArduinoJson/Variant/VariantData.hpp>
ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
class VariantSlot;
class VariantPool;
class VariantData;
class VariantWithId;
class ResourceManager {
union SlotData {
VariantData variant;
#if ARDUINOJSON_USE_EXTENSIONS
VariantExtension extension;
#endif
};
public:
constexpr static size_t slotSize = sizeof(SlotData);
ResourceManager(Allocator* allocator = DefaultAllocator::instance())
: allocator_(allocator), overflowed_(false) {}
@ -41,26 +51,22 @@ class ResourceManager {
}
size_t size() const {
return VariantPool::slotsToBytes(variantPools_.usage()) +
stringPool_.size();
return variantPools_.size() + stringPool_.size();
}
bool overflowed() const {
return overflowed_;
}
SlotWithId allocSlot() {
auto p = variantPools_.allocSlot(allocator_);
if (!p)
overflowed_ = true;
return p;
}
Slot<VariantData> allocVariant();
void freeVariant(Slot<VariantData> slot);
VariantData* getVariant(SlotId id) const;
void freeSlot(SlotWithId slot);
VariantSlot* getSlot(SlotId id) const {
return variantPools_.getSlot(id);
}
#if ARDUINOJSON_USE_EXTENSIONS
Slot<VariantExtension> allocExtension();
void freeExtension(SlotId slot);
VariantExtension* getExtension(SlotId id) const;
#endif
template <typename TAdaptedString>
StringNode* saveString(TAdaptedString str) {
@ -119,7 +125,7 @@ class ResourceManager {
Allocator* allocator_;
bool overflowed_;
StringPool stringPool_;
VariantPoolList variantPools_;
MemoryPoolList<SlotData> variantPools_;
};
ARDUINOJSON_END_PRIVATE_NAMESPACE

View File

@ -6,15 +6,47 @@
#include <ArduinoJson/Collection/CollectionData.hpp>
#include <ArduinoJson/Memory/ResourceManager.hpp>
#include <ArduinoJson/Polyfills/alias_cast.hpp>
#include <ArduinoJson/Variant/VariantData.hpp>
ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
inline void ResourceManager::freeSlot(SlotWithId slot) {
if (slot->ownsKey())
dereferenceString(slot->key());
slot->data()->setNull(this);
variantPools_.freeSlot(slot);
inline Slot<VariantData> ResourceManager::allocVariant() {
auto p = variantPools_.allocSlot(allocator_);
if (!p) {
overflowed_ = true;
return {};
}
return {new (&p->variant) VariantData, p.id()};
}
inline void ResourceManager::freeVariant(Slot<VariantData> variant) {
variant->clear(this);
variantPools_.freeSlot({alias_cast<SlotData*>(variant.ptr()), variant.id()});
}
inline VariantData* ResourceManager::getVariant(SlotId id) const {
return reinterpret_cast<VariantData*>(variantPools_.getSlot(id));
}
#if ARDUINOJSON_USE_EXTENSIONS
inline Slot<VariantExtension> ResourceManager::allocExtension() {
auto p = variantPools_.allocSlot(allocator_);
if (!p) {
overflowed_ = true;
return {};
}
return {&p->extension, p.id()};
}
inline void ResourceManager::freeExtension(SlotId id) {
auto p = getExtension(id);
variantPools_.freeSlot({reinterpret_cast<SlotData*>(p), id});
}
inline VariantExtension* ResourceManager::getExtension(SlotId id) const {
return &variantPools_.getSlot(id)->extension;
}
#endif
ARDUINOJSON_END_PRIVATE_NAMESPACE

View File

@ -12,9 +12,6 @@
ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
class VariantSlot;
class VariantPool;
class StringPool {
public:
StringPool() = default;

View File

@ -1,63 +0,0 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2024, Benoit BLANCHON
// MIT License
#pragma once
#include <ArduinoJson/Memory/ResourceManager.hpp>
#include <ArduinoJson/Polyfills/assert.hpp>
#include <ArduinoJson/Polyfills/integer.hpp>
ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
class VariantSlot;
using SlotId = uint_t<ARDUINOJSON_SLOT_ID_SIZE * 8>;
using SlotCount = SlotId;
const SlotId NULL_SLOT = SlotId(-1);
class SlotWithId {
public:
SlotWithId() : slot_(nullptr), id_(NULL_SLOT) {}
SlotWithId(VariantSlot* slot, SlotId id) : slot_(slot), id_(id) {
ARDUINOJSON_ASSERT((slot == nullptr) == (id == NULL_SLOT));
}
SlotId id() const {
return id_;
}
operator VariantSlot*() {
return slot_;
}
VariantSlot* operator->() {
ARDUINOJSON_ASSERT(slot_ != nullptr);
return slot_;
}
private:
VariantSlot* slot_;
SlotId id_;
};
class VariantPool {
public:
void create(SlotCount cap, Allocator* allocator);
void destroy(Allocator* allocator);
SlotWithId allocSlot();
VariantSlot* getSlot(SlotId id) const;
void clear();
void shrinkToFit(Allocator*);
SlotCount usage() const;
static SlotCount bytesToSlots(size_t);
static size_t slotsToBytes(SlotCount);
private:
SlotCount capacity_;
SlotCount usage_;
VariantSlot* slots_;
};
ARDUINOJSON_END_PRIVATE_NAMESPACE

View File

@ -1,81 +0,0 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2024, Benoit BLANCHON
// MIT License
#pragma once
#include <ArduinoJson/Memory/VariantPool.hpp>
#include <ArduinoJson/Variant/VariantSlot.hpp>
ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
inline void VariantPool::create(SlotCount cap, Allocator* allocator) {
ARDUINOJSON_ASSERT(cap > 0);
slots_ =
reinterpret_cast<VariantSlot*>(allocator->allocate(slotsToBytes(cap)));
capacity_ = slots_ ? cap : 0;
usage_ = 0;
}
inline void VariantPool::destroy(Allocator* allocator) {
if (slots_)
allocator->deallocate(slots_);
slots_ = nullptr;
capacity_ = 0;
usage_ = 0;
}
inline void VariantPool::shrinkToFit(Allocator* allocator) {
auto newSlots = reinterpret_cast<VariantSlot*>(
allocator->reallocate(slots_, slotsToBytes(usage_)));
if (newSlots) {
slots_ = newSlots;
capacity_ = usage_;
}
}
inline SlotWithId VariantPool::allocSlot() {
if (!slots_)
return {};
if (usage_ >= capacity_)
return {};
auto index = usage_++;
auto slot = &slots_[index];
return {new (slot) VariantSlot, SlotId(index)};
}
inline VariantSlot* VariantPool::getSlot(SlotId id) const {
ARDUINOJSON_ASSERT(id < usage_);
return &slots_[id];
}
inline SlotCount VariantPool::usage() const {
return usage_;
}
inline void VariantPool::clear() {
usage_ = 0;
}
inline SlotCount VariantPool::bytesToSlots(size_t n) {
return static_cast<SlotCount>(n / sizeof(VariantSlot));
}
inline size_t VariantPool::slotsToBytes(SlotCount n) {
return n * sizeof(VariantSlot);
}
inline SlotWithId VariantPoolList::allocFromFreeList() {
ARDUINOJSON_ASSERT(freeList_ != NULL_SLOT);
auto id = freeList_;
auto slot = getSlot(freeList_);
freeList_ = slot->next();
return {new (slot) VariantSlot, id};
}
inline void VariantPoolList::freeSlot(SlotWithId slot) {
slot->setNext(freeList_);
freeList_ = slot.id();
}
ARDUINOJSON_END_PRIVATE_NAMESPACE

View File

@ -29,6 +29,7 @@ struct Converter<MsgPackBinary> : private detail::VariantAttorney {
if (!data)
return;
auto resources = getResourceManager(dst);
data->clear(resources);
if (src.data()) {
size_t headerSize = src.size() >= 0x10000 ? 5
: src.size() >= 0x100 ? 3
@ -62,7 +63,6 @@ struct Converter<MsgPackBinary> : private detail::VariantAttorney {
return;
}
}
data->setNull();
}
static MsgPackBinary fromJson(JsonVariantConst src) {

View File

@ -91,7 +91,7 @@ class MsgPackDeserializer {
if (code <= 0x7f || code >= 0xe0) { // fixint
if (allowValue)
variant->setInteger(static_cast<int8_t>(code));
variant->setInteger(static_cast<int8_t>(code), resources_);
return DeserializationError::Ok;
}
@ -230,13 +230,16 @@ class MsgPackDeserializer {
if (isSigned) {
auto truncatedValue = static_cast<JsonInteger>(signedValue);
if (truncatedValue == signedValue)
variant->setInteger(truncatedValue);
if (truncatedValue == signedValue) {
if (!variant->setInteger(truncatedValue, resources_))
return DeserializationError::NoMemory;
}
// else set null on overflow
} else {
auto truncatedValue = static_cast<JsonUInt>(unsignedValue);
if (truncatedValue == unsignedValue)
variant->setInteger(truncatedValue);
if (!variant->setInteger(truncatedValue, resources_))
return DeserializationError::NoMemory;
// else set null on overflow
}
@ -254,7 +257,7 @@ class MsgPackDeserializer {
return err;
fixEndianness(value);
variant->setFloat(value);
variant->setFloat(value, resources_);
return DeserializationError::Ok;
}
@ -270,9 +273,10 @@ class MsgPackDeserializer {
return err;
fixEndianness(value);
variant->setFloat(value);
return DeserializationError::Ok;
if (variant->setFloat(value, resources_))
return DeserializationError::Ok;
else
return DeserializationError::NoMemory;
}
template <typename T>
@ -289,7 +293,7 @@ class MsgPackDeserializer {
doubleToFloat(i, o);
fixEndianness(value);
variant->setFloat(value);
variant->setFloat(value, resources_);
return DeserializationError::Ok;
}

View File

@ -35,6 +35,7 @@ struct Converter<MsgPackExtension> : private detail::VariantAttorney {
if (!data)
return;
auto resources = getResourceManager(dst);
data->clear(resources);
if (src.data()) {
uint8_t format, sizeBytes;
if (src.size() >= 0x10000) {
@ -76,7 +77,6 @@ struct Converter<MsgPackExtension> : private detail::VariantAttorney {
return;
}
}
data->setNull();
}
static MsgPackExtension fromJson(JsonVariantConst src) {

View File

@ -61,8 +61,8 @@ class MsgPackSerializer : public VariantDataVisitor<size_t> {
auto slotId = array.head();
while (slotId != NULL_SLOT) {
auto slot = resources_->getSlot(slotId);
slot->data()->accept(*this);
auto slot = resources_->getVariant(slotId);
slot->accept(*this, resources_);
slotId = slot->next();
}
@ -83,9 +83,8 @@ class MsgPackSerializer : public VariantDataVisitor<size_t> {
auto slotId = object.head();
while (slotId != NULL_SLOT) {
auto slot = resources_->getSlot(slotId);
visit(slot->key());
slot->data()->accept(*this);
auto slot = resources_->getVariant(slotId);
slot->accept(*this, resources_);
slotId = slot->next();
}
@ -220,7 +219,8 @@ ARDUINOJSON_BEGIN_PUBLIC_NAMESPACE
// Produces a MessagePack document.
// https://arduinojson.org/v7/api/msgpack/serializemsgpack/
template <typename TDestination>
inline size_t serializeMsgPack(JsonVariantConst source, TDestination& output) {
detail::enable_if_t<!detail::is_pointer<TDestination>::value, size_t>
serializeMsgPack(JsonVariantConst source, TDestination& output) {
using namespace ArduinoJson::detail;
return serialize<MsgPackSerializer>(source, output);
}

View File

@ -6,83 +6,90 @@
#include <ArduinoJson/Configuration.hpp>
#include <ArduinoJson/Numbers/FloatTraits.hpp>
#include <ArduinoJson/Numbers/JsonFloat.hpp>
#include <ArduinoJson/Polyfills/math.hpp>
ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
template <typename TFloat>
struct FloatParts {
uint32_t integral;
uint32_t decimal;
int16_t exponent;
int8_t decimalPlaces;
FloatParts(TFloat value) {
uint32_t maxDecimalPart = sizeof(TFloat) >= 8 ? 1000000000 : 1000000;
decimalPlaces = sizeof(TFloat) >= 8 ? 9 : 6;
exponent = normalize(value);
integral = uint32_t(value);
// reduce number of decimal places by the number of integral places
for (uint32_t tmp = integral; tmp >= 10; tmp /= 10) {
maxDecimalPart /= 10;
decimalPlaces--;
}
TFloat remainder = (value - TFloat(integral)) * TFloat(maxDecimalPart);
decimal = uint32_t(remainder);
remainder = remainder - TFloat(decimal);
// rounding:
// increment by 1 if remainder >= 0.5
decimal += uint32_t(remainder * 2);
if (decimal >= maxDecimalPart) {
decimal = 0;
integral++;
if (exponent && integral >= 10) {
exponent++;
integral = 1;
}
}
// remove trailing zeros
while (decimal % 10 == 0 && decimalPlaces > 0) {
decimal /= 10;
decimalPlaces--;
}
}
static int16_t normalize(TFloat& value) {
typedef FloatTraits<TFloat> traits;
int16_t powersOf10 = 0;
int8_t index = sizeof(TFloat) == 8 ? 8 : 5;
int bit = 1 << index;
if (value >= ARDUINOJSON_POSITIVE_EXPONENTIATION_THRESHOLD) {
for (; index >= 0; index--) {
if (value >= traits::positiveBinaryPowersOfTen()[index]) {
value *= traits::negativeBinaryPowersOfTen()[index];
powersOf10 = int16_t(powersOf10 + bit);
}
bit >>= 1;
}
}
if (value > 0 && value <= ARDUINOJSON_NEGATIVE_EXPONENTIATION_THRESHOLD) {
for (; index >= 0; index--) {
if (value < traits::negativeBinaryPowersOfTen()[index] * 10) {
value *= traits::positiveBinaryPowersOfTen()[index];
powersOf10 = int16_t(powersOf10 - bit);
}
bit >>= 1;
}
}
return powersOf10;
}
};
template <typename TFloat>
inline int16_t normalize(TFloat& value) {
using traits = FloatTraits<TFloat>;
int16_t powersOf10 = 0;
int8_t index = sizeof(TFloat) == 8 ? 8 : 5;
int bit = 1 << index;
if (value >= ARDUINOJSON_POSITIVE_EXPONENTIATION_THRESHOLD) {
for (; index >= 0; index--) {
if (value >= traits::positiveBinaryPowersOfTen()[index]) {
value *= traits::negativeBinaryPowersOfTen()[index];
powersOf10 = int16_t(powersOf10 + bit);
}
bit >>= 1;
}
}
if (value > 0 && value <= ARDUINOJSON_NEGATIVE_EXPONENTIATION_THRESHOLD) {
for (; index >= 0; index--) {
if (value < traits::negativeBinaryPowersOfTen()[index] * 10) {
value *= traits::positiveBinaryPowersOfTen()[index];
powersOf10 = int16_t(powersOf10 - bit);
}
bit >>= 1;
}
}
return powersOf10;
}
constexpr uint32_t pow10(int exponent) {
return (exponent == 0) ? 1 : 10 * pow10(exponent - 1);
}
inline FloatParts decomposeFloat(JsonFloat value, int8_t decimalPlaces) {
uint32_t maxDecimalPart = pow10(decimalPlaces);
int16_t exponent = normalize(value);
uint32_t integral = uint32_t(value);
// reduce number of decimal places by the number of integral places
for (uint32_t tmp = integral; tmp >= 10; tmp /= 10) {
maxDecimalPart /= 10;
decimalPlaces--;
}
JsonFloat remainder =
(value - JsonFloat(integral)) * JsonFloat(maxDecimalPart);
uint32_t decimal = uint32_t(remainder);
remainder = remainder - JsonFloat(decimal);
// rounding:
// increment by 1 if remainder >= 0.5
decimal += uint32_t(remainder * 2);
if (decimal >= maxDecimalPart) {
decimal = 0;
integral++;
if (exponent && integral >= 10) {
exponent++;
integral = 1;
}
}
// remove trailing zeros
while (decimal % 10 == 0 && decimalPlaces > 0) {
decimal /= 10;
decimalPlaces--;
}
return {integral, decimal, exponent, decimalPlaces};
}
ARDUINOJSON_END_PRIVATE_NAMESPACE

Some files were not shown because too many files have changed in this diff Show More