Skip to content

Commit 24b76cb

Browse files
authored
Add string constructor and concat routines taking explicit length args (#5586)
## Summary Applies the upstream changes here: arduino/ArduinoCore-API@3b88acac8^...0d83f1a ## 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.
1 parent 4a55ff9 commit 24b76cb

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

Diff for: cores/esp32/WString.cpp

+7-4
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,12 @@ String::String(const char *cstr) {
3535
copy(cstr, strlen(cstr));
3636
}
3737

38+
String::String(const char *cstr, unsigned int length) {
39+
init();
40+
if (cstr)
41+
copy(cstr, length);
42+
}
43+
3844
String::String(const String &value) {
3945
init();
4046
*this = value;
@@ -705,10 +711,7 @@ String String::substring(unsigned int left, unsigned int right) const {
705711
return out;
706712
if(right > len())
707713
right = len();
708-
char temp = buffer()[right]; // save the replaced character
709-
wbuffer()[right] = '\0';
710-
out = wbuffer() + left; // pointer arithmetic
711-
wbuffer()[right] = temp; //restore character
714+
out.copy(buffer() + left, right - left);
712715
return out;
713716
}
714717

Diff for: cores/esp32/WString.h

+6-1
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,10 @@ class String {
5555
// fails, the string will be marked as invalid (i.e. "if (s)" will
5656
// be false).
5757
String(const char *cstr = "");
58+
String(const char *cstr, unsigned int length);
59+
#ifdef __GXX_EXPERIMENTAL_CXX0X__
60+
String(const uint8_t *cstr, unsigned int length) : String((const char*)cstr, length) {}
61+
#endif
5862
String(const String &str);
5963
String(const __FlashStringHelper *str);
6064
#ifdef __GXX_EXPERIMENTAL_CXX0X__
@@ -108,6 +112,8 @@ class String {
108112
// concatenation is considered unsuccessful.
109113
unsigned char concat(const String &str);
110114
unsigned char concat(const char *cstr);
115+
unsigned char concat(const char *cstr, unsigned int length);
116+
unsigned char concat(const uint8_t *cstr, unsigned int length) {return concat((const char*)cstr, length);}
111117
unsigned char concat(char c);
112118
unsigned char concat(unsigned char c);
113119
unsigned char concat(int num);
@@ -326,7 +332,6 @@ class String {
326332
void init(void);
327333
void invalidate(void);
328334
unsigned char changeBuffer(unsigned int maxStrLen);
329-
unsigned char concat(const char *cstr, unsigned int length);
330335

331336
// copy and move
332337
String & copy(const char *cstr, unsigned int length);

0 commit comments

Comments
 (0)