From 31c1592ad6e1153dfaa9957f5b64e0f1920d4d5a Mon Sep 17 00:00:00 2001 From: AriaN Date: Tue, 7 Nov 2023 16:49:31 +0330 Subject: [PATCH] add Stream::readStringUntil function that uses string terminator (#9011) * add readStringUntil function with string terminator * rename count parameter to untilTotalNumberOfOccurrences --- cores/esp8266/Stream.cpp | 26 ++++++++++++++++++++++++++ cores/esp8266/Stream.h | 1 + 2 files changed, 27 insertions(+) diff --git a/cores/esp8266/Stream.cpp b/cores/esp8266/Stream.cpp index a901c8d437..b9b5b95f65 100644 --- a/cores/esp8266/Stream.cpp +++ b/cores/esp8266/Stream.cpp @@ -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) diff --git a/cores/esp8266/Stream.h b/cores/esp8266/Stream.h index f39bb423f2..21f319ee6b 100644 --- a/cores/esp8266/Stream.h +++ b/cores/esp8266/Stream.h @@ -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); }