From 24b76cbb14d0ec36086133d4cb31594fb54e0f6a Mon Sep 17 00:00:00 2001 From: rcombs Date: Tue, 31 Aug 2021 01:12:27 -0500 Subject: [PATCH] Add string constructor and concat routines taking explicit length args (#5586) ## Summary Applies the upstream changes here: https://github.com/arduino/ArduinoCore-API/compare/3b88acac8%5E...0d83f1afc3367037dbde5323c2abd0ae1bd2c583 ## Impact Adds new String convenience methods that are now available in the mainline Arduino implementation, simplifying interoperability with C code that uses pointer+length strings rather than 0-termination. Also includes a change to avoid mutating the source string when taking a substring. --- cores/esp32/WString.cpp | 11 +++++++---- cores/esp32/WString.h | 7 ++++++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/cores/esp32/WString.cpp b/cores/esp32/WString.cpp index 23b1af20..b78cf2ee 100644 --- a/cores/esp32/WString.cpp +++ b/cores/esp32/WString.cpp @@ -35,6 +35,12 @@ String::String(const char *cstr) { copy(cstr, strlen(cstr)); } +String::String(const char *cstr, unsigned int length) { + init(); + if (cstr) + copy(cstr, length); +} + String::String(const String &value) { init(); *this = value; @@ -705,10 +711,7 @@ String String::substring(unsigned int left, unsigned int right) const { return out; if(right > len()) right = len(); - char temp = buffer()[right]; // save the replaced character - wbuffer()[right] = '\0'; - out = wbuffer() + left; // pointer arithmetic - wbuffer()[right] = temp; //restore character + out.copy(buffer() + left, right - left); return out; } diff --git a/cores/esp32/WString.h b/cores/esp32/WString.h index 9440b38b..958b0179 100644 --- a/cores/esp32/WString.h +++ b/cores/esp32/WString.h @@ -55,6 +55,10 @@ class String { // fails, the string will be marked as invalid (i.e. "if (s)" will // be false). String(const char *cstr = ""); + String(const char *cstr, unsigned int length); +#ifdef __GXX_EXPERIMENTAL_CXX0X__ + String(const uint8_t *cstr, unsigned int length) : String((const char*)cstr, length) {} +#endif String(const String &str); String(const __FlashStringHelper *str); #ifdef __GXX_EXPERIMENTAL_CXX0X__ @@ -108,6 +112,8 @@ class String { // concatenation is considered unsuccessful. unsigned char concat(const String &str); unsigned char concat(const char *cstr); + unsigned char concat(const char *cstr, unsigned int length); + unsigned char concat(const uint8_t *cstr, unsigned int length) {return concat((const char*)cstr, length);} unsigned char concat(char c); unsigned char concat(unsigned char c); unsigned char concat(int num); @@ -326,7 +332,6 @@ class String { void init(void); void invalidate(void); unsigned char changeBuffer(unsigned int maxStrLen); - unsigned char concat(const char *cstr, unsigned int length); // copy and move String & copy(const char *cstr, unsigned int length);