Minh Nguyen / ArduinoJson
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers ArduinoStringWriter.hpp Source File

ArduinoStringWriter.hpp

00001 // ArduinoJson - arduinojson.org
00002 // Copyright Benoit Blanchon 2014-2021
00003 // MIT License
00004 
00005 #pragma once
00006 
00007 #include <Arduino.h>
00008 
00009 namespace ARDUINOJSON_NAMESPACE {
00010 
00011 template <>
00012 class Writer< ::String, void> {
00013   static const size_t bufferCapacity = ARDUINOJSON_STRING_BUFFER_SIZE;
00014 
00015  public:
00016   explicit Writer(::String &str) : _destination(&str) {
00017     _size = 0;
00018   }
00019 
00020   ~Writer() {
00021     flush();
00022   }
00023 
00024   size_t write(uint8_t c) {
00025     ARDUINOJSON_ASSERT(_size < bufferCapacity);
00026     _buffer[_size++] = static_cast<char>(c);
00027     if (_size + 1 >= bufferCapacity)
00028       flush();
00029     return 1;
00030   }
00031 
00032   size_t write(const uint8_t *s, size_t n) {
00033     for (size_t i = 0; i < n; i++) {
00034       write(s[i]);
00035     }
00036     return n;
00037   }
00038 
00039  private:
00040   void flush() {
00041     ARDUINOJSON_ASSERT(_size < bufferCapacity);
00042     _buffer[_size] = 0;
00043     *_destination += _buffer;
00044     _size = 0;
00045   }
00046 
00047   ::String *_destination;
00048   char _buffer[bufferCapacity];
00049   size_t _size;
00050 };
00051 
00052 }  // namespace ARDUINOJSON_NAMESPACE