From 0ca2f56b7118a89f5557f393d269156d6c8af23e Mon Sep 17 00:00:00 2001 From: Siddharth Purohit Date: Fri, 31 Jul 2020 19:07:52 +0530 Subject: [PATCH] AP_HAL: add support for external buffer to be used in ByteBuffer --- libraries/AP_HAL/utility/RingBuffer.cpp | 9 ++++++++- libraries/AP_HAL/utility/RingBuffer.h | 18 +++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/libraries/AP_HAL/utility/RingBuffer.cpp b/libraries/AP_HAL/utility/RingBuffer.cpp index b297ee3083..4116cfc7b9 100644 --- a/libraries/AP_HAL/utility/RingBuffer.cpp +++ b/libraries/AP_HAL/utility/RingBuffer.cpp @@ -7,11 +7,14 @@ ByteBuffer::ByteBuffer(uint32_t _size) { buf = (uint8_t*)calloc(1, _size); size = buf ? _size : 0; + external_buf = false; } ByteBuffer::~ByteBuffer(void) { - free(buf); + if (!external_buf) { + free(buf); + } } /* @@ -19,6 +22,10 @@ ByteBuffer::~ByteBuffer(void) */ bool ByteBuffer::set_size(uint32_t _size) { + if (external_buf) { + // resize not supported with external buffer + return false; + } head = tail = 0; if (_size != size) { free(buf); diff --git a/libraries/AP_HAL/utility/RingBuffer.h b/libraries/AP_HAL/utility/RingBuffer.h index b766efe105..0d014b5dd6 100644 --- a/libraries/AP_HAL/utility/RingBuffer.h +++ b/libraries/AP_HAL/utility/RingBuffer.h @@ -12,6 +12,11 @@ class ByteBuffer { public: ByteBuffer(uint32_t size); + ByteBuffer(uint8_t* _buf, uint32_t _size) : + buf(_buf), + size(_size), + external_buf(true) + {} ~ByteBuffer(void); // number of bytes available to be read @@ -92,6 +97,8 @@ private: std::atomic head{0}; // where to read data std::atomic tail{0}; // where to write data + + bool external_buf; }; /* @@ -107,9 +114,17 @@ public: // multiple of the object size so that we always get aligned // elements, which makes the readptr() method possible buffer = new ByteBuffer(((_size+1) * sizeof(T))); + external_buf = false; } + + ObjectBuffer(ByteBuffer *_buffer) : + buffer(_buffer), + external_buf(true) + {} + ~ObjectBuffer(void) { - delete buffer; + if (!external_buf) + delete buffer; } // return size of ringbuffer @@ -246,6 +261,7 @@ public: private: ByteBuffer *buffer = nullptr; + bool external_buf = true; }; /*