DynamicJsonBuffer.hpp 978 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright Benoit Blanchon 2014
  2. // MIT License
  3. //
  4. // Arduino JSON library
  5. // https://github.com/bblanchon/ArduinoJson
  6. #pragma once
  7. #include "JsonBuffer.hpp"
  8. namespace ArduinoJson {
  9. // Implements a JsonBuffer with dynamic memory allocation.
  10. // You are strongly encouraged to consider using StaticJsonBuffer which is much
  11. // more suitable for embedded systems.
  12. class DynamicJsonBuffer : public JsonBuffer {
  13. public:
  14. explicit DynamicJsonBuffer() : _size(0) {}
  15. size_t size() const { return _size; }
  16. size_t blockCount() const { return 1; }
  17. static const size_t BLOCK_CAPACITY = 32;
  18. protected:
  19. virtual void* alloc(size_t bytes) {
  20. if (bytes > BLOCK_CAPACITY) return NULL;
  21. void* p = _buffer + _size;
  22. _size += bytes;
  23. return p;
  24. }
  25. bool canStore(size_t bytes) {
  26. // by design a DynamicJsonBuffer can't alloc a block bigger than
  27. // BLOCK_CAPACITY
  28. return bytes < BLOCK_CAPACITY;
  29. }
  30. size_t _size;
  31. uint8_t _buffer[BLOCK_CAPACITY];
  32. };
  33. }