Procházet zdrojové kódy

Use only one byte for the string length on 8-bit platforms

Benoit Blanchon před 2 roky
rodič
revize
7e6b89d21f

+ 9 - 0
src/ArduinoJson/Configuration.hpp

@@ -122,6 +122,15 @@
 #  endif
 #  endif
 #endif
 #endif
 
 
+// Number of bytes to store the length of a string
+#ifndef ARDUINOJSON_STRING_LENGTH_SIZE
+#  if ARDUINOJSON_SIZEOF_POINTER <= 2
+#    define ARDUINOJSON_STRING_LENGTH_SIZE 1  // up to 255 characters
+#  else
+#    define ARDUINOJSON_STRING_LENGTH_SIZE 2  // up to 65535 characters
+#  endif
+#endif
+
 #ifdef ARDUINO
 #ifdef ARDUINO
 
 
 // Enable support for Arduino's String class
 // Enable support for Arduino's String class

+ 6 - 5
src/ArduinoJson/Memory/StringNode.hpp

@@ -11,7 +11,6 @@
 #include <ArduinoJson/Polyfills/limits.hpp>
 #include <ArduinoJson/Polyfills/limits.hpp>
 
 
 #include <stddef.h>  // offsetof
 #include <stddef.h>  // offsetof
-#include <stdint.h>  // uint16_t
 
 
 ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
 ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
 
 
@@ -20,12 +19,14 @@ struct StringNode {
   // (there can never be more references than slots)
   // (there can never be more references than slots)
   using references_type = uint_t<ARDUINOJSON_SLOT_ID_SIZE * 8>::type;
   using references_type = uint_t<ARDUINOJSON_SLOT_ID_SIZE * 8>::type;
 
 
+  using length_type = uint_t<ARDUINOJSON_STRING_LENGTH_SIZE * 8>::type;
+
   struct StringNode* next;
   struct StringNode* next;
-  uint16_t length;
+  length_type length;
   references_type references;
   references_type references;
   char data[1];
   char data[1];
 
 
-  static constexpr size_t maxLength = numeric_limits<uint16_t>::highest();
+  static constexpr size_t maxLength = numeric_limits<length_type>::highest();
 
 
   static constexpr size_t sizeForLength(size_t n) {
   static constexpr size_t sizeForLength(size_t n) {
     return n + 1 + offsetof(StringNode, data);
     return n + 1 + offsetof(StringNode, data);
@@ -37,7 +38,7 @@ struct StringNode {
     auto node = reinterpret_cast<StringNode*>(
     auto node = reinterpret_cast<StringNode*>(
         allocator->allocate(sizeForLength(length)));
         allocator->allocate(sizeForLength(length)));
     if (node) {
     if (node) {
-      node->length = uint16_t(length);
+      node->length = length_type(length);
       node->references = 1;
       node->references = 1;
     }
     }
     return node;
     return node;
@@ -53,7 +54,7 @@ struct StringNode {
     else
     else
       newNode = nullptr;
       newNode = nullptr;
     if (newNode)
     if (newNode)
-      newNode->length = uint16_t(length);
+      newNode->length = length_type(length);
     else
     else
       allocator->deallocate(node);
       allocator->deallocate(node);
     return newNode;
     return newNode;