AP_Common: add support for setting custom external buffer

This commit is contained in:
bugobliterator 2021-11-09 16:12:22 +05:30 committed by Andrew Tridgell
parent 09096cb355
commit 60e0bec628
2 changed files with 26 additions and 1 deletions

View File

@ -27,6 +27,10 @@ extern const AP_HAL::HAL& hal;
*/ */
bool ExpandingString::expand(uint32_t min_extra_space_needed) 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 // expand a reasonable amount
uint32_t newsize = (5*buflen/4) + EXPAND_INCREMENT; uint32_t newsize = (5*buflen/4) + EXPAND_INCREMENT;
if (newsize - used < min_extra_space_needed) { if (newsize - used < min_extra_space_needed) {
@ -102,5 +106,22 @@ bool ExpandingString::append(const char *s, uint32_t len)
ExpandingString::~ExpandingString() 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;
} }

View File

@ -39,6 +39,9 @@ public:
// append data to the string. s can be null for zero fill // append data to the string. s can be null for zero fill
bool append(const char *s, uint32_t len); 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 // destructor
~ExpandingString(); ~ExpandingString();
@ -51,6 +54,7 @@ private:
uint32_t buflen; uint32_t buflen;
uint32_t used; uint32_t used;
bool allocation_failed; bool allocation_failed;
bool external_buffer;
// try to expand the buffer // try to expand the buffer
bool expand(uint32_t min_needed) WARN_IF_UNUSED; bool expand(uint32_t min_needed) WARN_IF_UNUSED;