Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Stream::readStringUntil function that uses string terminator #9011

Merged
merged 3 commits into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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