Skip to content

Commit 9f536e6

Browse files
authored
WString: avoid writing to const storage (#8463)
This avoids the null termination requirement of both String::substring and String::lastIndexOf by using APIs that don't require it. So we can stop writing to the buffer inside of const functions. I also changed wbuffer to make it non const.
1 parent 30b0450 commit 9f536e6

File tree

2 files changed

+6
-15
lines changed

2 files changed

+6
-15
lines changed

cores/esp8266/WString.cpp

+4-13
Original file line numberDiff line numberDiff line change
@@ -682,14 +682,9 @@ int String::lastIndexOf(char ch) const {
682682
int String::lastIndexOf(char ch, unsigned int fromIndex) const {
683683
if (fromIndex >= len())
684684
return -1;
685-
char *writeTo = wbuffer();
686-
char tempchar = writeTo[fromIndex + 1]; // save the replaced character
687-
writeTo[fromIndex + 1] = '\0';
688-
char *temp = strrchr(writeTo, ch);
689-
writeTo[fromIndex + 1] = tempchar; // restore character
690-
if (temp == NULL)
691-
return -1;
692-
return temp - writeTo;
685+
int index = fromIndex + 1;
686+
while (index-- > 0 && buffer()[index] != ch);
687+
return index;
693688
}
694689

695690
int String::lastIndexOf(const String &s2) const {
@@ -732,11 +727,7 @@ String String::substring(unsigned int left, unsigned int right) const {
732727
return out;
733728
if (right > len())
734729
right = len();
735-
char *writeTo = wbuffer();
736-
char tempchar = writeTo[right]; // save the replaced character
737-
writeTo[right] = '\0';
738-
out = writeTo + left; // pointer arithmetic
739-
writeTo[right] = tempchar; // restore character
730+
out.concat(buffer() + left, right - left);
740731
return out;
741732
}
742733

cores/esp8266/WString.h

+2-2
Original file line numberDiff line numberDiff line change
@@ -263,8 +263,8 @@ class String {
263263
void setCapacity(int cap) { if (!isSSO()) ptr.cap = cap; }
264264
void setBuffer(char *buff) { if (!isSSO()) ptr.buff = buff; }
265265
// Buffer accessor functions
266-
const char *buffer() const { return wbuffer(); }
267-
char *wbuffer() const { return isSSO() ? const_cast<char *>(sso.buff) : ptr.buff; } // Writable version of buffer
266+
const char *buffer() const { return isSSO() ? sso.buff : ptr.buff; }
267+
char *wbuffer() { return const_cast<char *>(buffer()); } // Writable version of buffer
268268

269269
// concatenation is done via non-member functions
270270
// make sure we still have access to internal methods, since we optimize based on capacity of both sides and want to manipulate internal buffers directly

0 commit comments

Comments
 (0)