Skip to content

Commit

Permalink
add Stream::readStringUntil function that uses string terminator (esp…
Browse files Browse the repository at this point in the history
…8266#9011)

* add readStringUntil function with string terminator
* rename count parameter to untilTotalNumberOfOccurrences
  • Loading branch information
Arian8j2 authored and hasenradball committed Nov 18, 2024
1 parent 48e0686 commit cc84a4b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
26 changes: 26 additions & 0 deletions cores/esp8266/Stream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,32 @@ String Stream::readStringUntil(char terminator) {
return ret;
}

String Stream::readStringUntil(const char* terminator, uint32_t untilTotalNumberOfOccurrences) {
String ret;
int c;
uint32_t occurrences = 0;
size_t termLen = strlen(terminator);
size_t termIndex = 0;
size_t index = 0;

while ((c = timedRead()) > 0) {
ret += (char) c;
index++;

if (terminator[termIndex] == c) {
if (++termIndex == termLen && ++occurrences == untilTotalNumberOfOccurrences) {
// don't include terminator in returned string
ret.remove(index - termIndex, termLen);
break;
}
} else {
termIndex = 0;
}
}

return ret;
}

// read what can be read, immediate exit on unavailable data
// prototype similar to Arduino's `int Client::read(buf, len)`
int Stream::read (uint8_t* buffer, size_t maxLen)
Expand Down
1 change: 1 addition & 0 deletions cores/esp8266/Stream.h
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ class Stream: public Print {
// Arduino String functions to be added here
virtual String readString();
String readStringUntil(char terminator);
String readStringUntil(const char* terminator, uint32_t untilTotalNumberOfOccurrences = 1);

virtual int read (uint8_t* buffer, size_t len);
int read (char* buffer, size_t len) { return read((uint8_t*)buffer, len); }
Expand Down

0 comments on commit cc84a4b

Please sign in to comment.