DynamicJsonBuffer.hpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. DynamicJsonBuffer() : _next(NULL), _size(0) {}
  15. ~DynamicJsonBuffer() { delete _next; }
  16. size_t size() const { return _size + (_next ? _next->size() : 0); }
  17. size_t blockCount() const { return 1 + (_next ? _next->blockCount() : 0); }
  18. static const size_t BLOCK_CAPACITY = 32;
  19. protected:
  20. virtual void* alloc(size_t bytes) {
  21. if (canAllocInThisBlock(bytes))
  22. return allocInThisBlock(bytes);
  23. else if (canAllocInOtherBlocks(bytes))
  24. return allocInOtherBlocks(bytes);
  25. else
  26. return NULL;
  27. }
  28. private:
  29. bool canAllocInThisBlock(size_t bytes) const {
  30. return _size + bytes <= BLOCK_CAPACITY;
  31. }
  32. void* allocInThisBlock(size_t bytes) {
  33. void* p = _buffer + _size;
  34. _size += bytes;
  35. return p;
  36. }
  37. bool canAllocInOtherBlocks(size_t bytes) const {
  38. // by design a DynamicJsonBuffer can't alloc a block bigger than
  39. // BLOCK_CAPACITY
  40. return bytes <= BLOCK_CAPACITY;
  41. }
  42. void* allocInOtherBlocks(size_t bytes) {
  43. if (!_next) {
  44. _next = new DynamicJsonBuffer();
  45. if (!_next) return NULL;
  46. }
  47. return _next->alloc(bytes);
  48. }
  49. size_t _size;
  50. uint8_t _buffer[BLOCK_CAPACITY];
  51. DynamicJsonBuffer* _next;
  52. };
  53. }