1
0
mirror of https://github.com/esphome/esphome.git synced 2026-02-08 08:41:59 +00:00

make sure new stringref functions work

This commit is contained in:
J. Nick Koston
2026-01-17 08:42:56 -10:00
parent 83d164c213
commit f3226b108f
2 changed files with 9 additions and 10 deletions

View File

@@ -81,26 +81,25 @@ class StringRef {
operator std::string() const { return str(); }
/// Find first occurrence of substring, returns NPOS if not found
static constexpr size_type NPOS = static_cast<size_type>(-1);
/// Find first occurrence of substring, returns std::string::npos if not found
size_type find(const char *s, size_type pos = 0) const {
if (pos >= len_)
return NPOS;
return std::string::npos;
const char *result = std::strstr(base_ + pos, s);
return result ? static_cast<size_type>(result - base_) : NPOS;
return result ? static_cast<size_type>(result - base_) : std::string::npos;
}
size_type find(char c, size_type pos = 0) const {
if (pos >= len_)
return NPOS;
return std::string::npos;
const char *result = std::strchr(base_ + pos, c);
return (result && result < base_ + len_) ? static_cast<size_type>(result - base_) : NPOS;
return (result && result < base_ + len_) ? static_cast<size_type>(result - base_) : std::string::npos;
}
/// Return substring as std::string
std::string substr(size_type pos = 0, size_type count = NPOS) const {
std::string substr(size_type pos = 0, size_type count = std::string::npos) const {
if (pos >= len_)
return std::string();
size_type actual_count = (count == NPOS || pos + count > len_) ? len_ - pos : count;
size_type actual_count = (count == std::string::npos || pos + count > len_) ? len_ - pos : count;
return std::string(base_ + pos, actual_count);
}

View File

@@ -42,13 +42,13 @@ select:
ESP_LOGI("test", "Length: %d", (int)x.length());
# Test 6: StringRef.find() method with substring
- lambda: |-
if (x.find("Option") != StringRef::NPOS) {
if (x.find("Option") != std::string::npos) {
ESP_LOGI("test", "Found 'Option' in value");
}
# Test 7: StringRef.find() method with character
- lambda: |-
size_t space_pos = x.find(' ');
if (space_pos != StringRef::NPOS) {
if (space_pos != std::string::npos) {
ESP_LOGI("test", "Space at position: %d", (int)space_pos);
}
# Test 8: StringRef.substr() method