diff --git a/libraries/AP_Common/ExpandingString.cpp b/libraries/AP_Common/ExpandingString.cpp index 33a18daf6b..84101c3f0f 100644 --- a/libraries/AP_Common/ExpandingString.cpp +++ b/libraries/AP_Common/ExpandingString.cpp @@ -27,6 +27,10 @@ extern const AP_HAL::HAL& hal; */ bool ExpandingString::expand(uint32_t min_extra_space_needed) { + if (external_buffer) { + // we can't expand an external buffer + return false; + } // expand a reasonable amount uint32_t newsize = (5*buflen/4) + EXPAND_INCREMENT; if (newsize - used < min_extra_space_needed) { @@ -102,5 +106,22 @@ bool ExpandingString::append(const char *s, uint32_t len) ExpandingString::~ExpandingString() { - free(buf); + if (!external_buffer) { + free(buf); + } +} + + +void ExpandingString::set_buffer(char *s, uint32_t total_len, uint32_t used_len) +{ + if (buf != nullptr) { + // we need to free previously used buffer + free(buf); + } + + buf = s; + buflen = total_len; + used = used_len; + allocation_failed = false; + external_buffer = true; } diff --git a/libraries/AP_Common/ExpandingString.h b/libraries/AP_Common/ExpandingString.h index 7f4f23629c..3c5deecf25 100644 --- a/libraries/AP_Common/ExpandingString.h +++ b/libraries/AP_Common/ExpandingString.h @@ -39,6 +39,9 @@ public: // append data to the string. s can be null for zero fill bool append(const char *s, uint32_t len); + // set address to custom external buffer + void set_buffer(char *s, uint32_t total_len, uint32_t used_len); + // destructor ~ExpandingString(); @@ -51,6 +54,7 @@ private: uint32_t buflen; uint32_t used; bool allocation_failed; + bool external_buffer; // try to expand the buffer bool expand(uint32_t min_needed) WARN_IF_UNUSED;