ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
string_ref.h
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <cstdint>
5#include <cstring>
6#include <iterator>
7#include <memory>
8#include <string>
10
11#ifdef USE_JSON
13#endif // USE_JSON
14
15#ifdef USE_ESP8266
16#include <pgmspace.h>
17#endif // USE_ESP8266
18
19namespace esphome {
20
31class StringRef {
32 public:
33 using traits_type = std::char_traits<char>;
34 using value_type = traits_type::char_type;
35 using allocator_type = std::allocator<char>;
36 using size_type = std::allocator_traits<allocator_type>::size_type;
37 using difference_type = std::allocator_traits<allocator_type>::difference_type;
38 using const_reference = const value_type &;
39 using const_pointer = const value_type *;
41 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
42
43 constexpr StringRef() : base_(""), len_(0) {}
44 explicit StringRef(const std::string &s) : base_(s.c_str()), len_(s.size()) {}
45 explicit StringRef(const char *s) : base_(s), len_(strlen(s)) {}
46 constexpr StringRef(const char *s, size_t n) : base_(s), len_(n) {}
47 template<typename CharT>
48 constexpr StringRef(const CharT *s, size_t n) : base_(reinterpret_cast<const char *>(s)), len_(n) {}
49 template<typename InputIt>
50 StringRef(InputIt first, InputIt last)
51 : base_(reinterpret_cast<const char *>(&*first)), len_(std::distance(first, last)) {}
52 template<typename InputIt>
53 StringRef(InputIt *first, InputIt *last)
54 : base_(reinterpret_cast<const char *>(first)), len_(std::distance(first, last)) {}
55 template<typename CharT, size_t N> constexpr static StringRef from_lit(const CharT (&s)[N]) {
56 return StringRef{s, N - 1};
57 }
58 static StringRef from_maybe_nullptr(const char *s) {
59 if (s == nullptr) {
60 return StringRef();
61 }
62
63 return StringRef(s);
64 }
65
66 constexpr const_iterator begin() const { return base_; };
67 constexpr const_iterator cbegin() const { return base_; };
68
69 constexpr const_iterator end() const { return base_ + len_; };
70 constexpr const_iterator cend() const { return base_ + len_; };
71
72 const_reverse_iterator rbegin() const { return const_reverse_iterator{base_ + len_}; }
73 const_reverse_iterator crbegin() const { return const_reverse_iterator{base_ + len_}; }
74
77
78 constexpr const char *c_str() const { return base_; }
79 constexpr size_type size() const { return len_; }
80 constexpr size_type length() const { return len_; }
81 constexpr bool empty() const { return len_ == 0; }
82 constexpr const_reference operator[](size_type pos) const { return *(base_ + pos); }
83
85 bool starts_with(const StringRef &prefix) const {
86 return len_ >= prefix.len_ && (prefix.len_ == 0 || std::memcmp(base_, prefix.base_, prefix.len_) == 0);
87 }
88 bool starts_with(const char *prefix) const { return this->starts_with(StringRef(prefix)); }
89 bool starts_with(const std::string &prefix) const { return this->starts_with(StringRef(prefix)); }
90
92 size_type copy(char *dest, size_type count, size_type pos = 0) const {
93 if (pos >= len_)
94 return 0;
95 size_type actual = (count > len_ - pos) ? len_ - pos : count;
96 std::memcpy(dest, base_ + pos, actual);
97 return actual;
98 }
99
100 std::string str() const { return std::string(base_, len_); } // fine for {nullptr, 0}: nothing is read
101 const uint8_t *byte() const { return reinterpret_cast<const uint8_t *>(base_); }
102
103 operator std::string() const { return str(); }
104
106 int compare(const StringRef &other) const {
107 size_type common = std::min(len_, other.len_);
108 int result = common == 0 ? 0 : std::memcmp(base_, other.base_, common);
109 if (result != 0)
110 return result;
111 if (len_ < other.len_)
112 return -1;
113 if (len_ > other.len_)
114 return 1;
115 return 0;
116 }
117 int compare(const char *s) const { return compare(StringRef(s)); }
118 int compare(const std::string &s) const { return compare(StringRef(s)); }
119
122 size_type find(const StringRef &s, size_type pos = 0) const {
123 if (pos > len_)
124 return std::string::npos;
125 if (s.len_ == 0)
126 return pos;
127 if (s.len_ > len_ - pos)
128 return std::string::npos;
129 for (size_type i = pos, last = len_ - s.len_; i <= last; i++) {
130 if (std::memcmp(base_ + i, s.base_, s.len_) == 0)
131 return i;
132 }
133 return std::string::npos;
134 }
135 size_type find(const char *s, size_type pos = 0) const { return this->find(StringRef(s), pos); }
136 size_type find(const std::string &s, size_type pos = 0) const { return this->find(StringRef(s), pos); }
137 size_type find(char c, size_type pos = 0) const {
138 if (pos >= len_)
139 return std::string::npos;
140 const void *result = std::memchr(base_ + pos, static_cast<unsigned char>(c), len_ - pos);
141 return result ? static_cast<size_type>(static_cast<const char *>(result) - base_) : std::string::npos;
142 }
143
145 std::string substr(size_type pos = 0, size_type count = std::string::npos) const {
146 if (pos >= len_)
147 return std::string();
148 size_type actual_count = (count == std::string::npos || pos + count > len_) ? len_ - pos : count;
149 return std::string(base_ + pos, actual_count);
150 }
151
152 private:
153 const char *base_;
154 size_type len_;
155};
156
157inline bool operator==(const StringRef &lhs, const StringRef &rhs) {
158 return lhs.size() == rhs.size() && std::equal(std::begin(lhs), std::end(lhs), std::begin(rhs));
159}
160
161inline bool operator==(const StringRef &lhs, const std::string &rhs) {
162 return lhs.size() == rhs.size() && std::equal(std::begin(lhs), std::end(lhs), std::begin(rhs));
163}
164
165inline bool operator==(const std::string &lhs, const StringRef &rhs) { return rhs == lhs; }
166
167inline bool operator==(const StringRef &lhs, const char *rhs) {
168 return lhs.size() == strlen(rhs) && std::equal(std::begin(lhs), std::end(lhs), rhs);
169}
170
171inline bool operator==(const char *lhs, const StringRef &rhs) { return rhs == lhs; }
172
173inline bool operator!=(const StringRef &lhs, const StringRef &rhs) { return !(lhs == rhs); }
174
175inline bool operator!=(const StringRef &lhs, const std::string &rhs) { return !(lhs == rhs); }
176
177inline bool operator!=(const std::string &lhs, const StringRef &rhs) { return !(rhs == lhs); }
178
179inline bool operator!=(const StringRef &lhs, const char *rhs) { return !(lhs == rhs); }
180
181inline bool operator!=(const char *lhs, const StringRef &rhs) { return !(rhs == lhs); }
182
183#ifdef USE_ESP8266
184inline bool operator==(const StringRef &lhs, const __FlashStringHelper *rhs) {
185 PGM_P p = reinterpret_cast<PGM_P>(rhs);
186 size_t rhs_len = strlen_P(p);
187 if (lhs.size() != rhs_len) {
188 return false;
189 }
190 return memcmp_P(lhs.c_str(), p, rhs_len) == 0;
191}
192
193inline bool operator==(const __FlashStringHelper *lhs, const StringRef &rhs) { return rhs == lhs; }
194
195inline bool operator!=(const StringRef &lhs, const __FlashStringHelper *rhs) { return !(lhs == rhs); }
196
197inline bool operator!=(const __FlashStringHelper *lhs, const StringRef &rhs) { return !(rhs == lhs); }
198
199#endif // USE_ESP8266
200
201inline bool operator<(const StringRef &lhs, const StringRef &rhs) {
202 return std::lexicographical_compare(std::begin(lhs), std::end(lhs), std::begin(rhs), std::end(rhs));
203}
204
205inline std::string &operator+=(std::string &lhs, const StringRef &rhs) {
206 lhs.append(rhs.c_str(), rhs.size());
207 return lhs;
208}
209
210inline std::string operator+(const char *lhs, const StringRef &rhs) {
211 auto str = std::string(lhs);
212 str.append(rhs.c_str(), rhs.size());
213 return str;
214}
215
216inline std::string operator+(const StringRef &lhs, const char *rhs) {
217 auto str = lhs.str();
218 str.append(rhs);
219 return str;
220}
221
222inline std::string operator+(const StringRef &lhs, const std::string &rhs) {
223 auto str = lhs.str();
224 str.append(rhs);
225 return str;
226}
227
228inline std::string operator+(const std::string &lhs, const StringRef &rhs) {
229 std::string str(lhs);
230 str.append(rhs.c_str(), rhs.size());
231 return str;
232}
233
237 public:
238 constexpr ProgmemStringRef() = default;
239 constexpr ProgmemStringRef(const char *s, size_t len) : ref_(s, len) {}
240 constexpr explicit ProgmemStringRef(const StringRef &s) : ref_(s) {}
242 template<size_t N> static constexpr ProgmemStringRef from_lit(const char (&s)[N]) { return {s, N - 1}; }
243
244 constexpr const char *progmem_ptr() const { return this->ref_.c_str(); }
245 constexpr size_t size() const { return this->ref_.size(); }
246 constexpr bool empty() const { return this->ref_.empty(); }
247
249 size_t write_to(char *buf, size_t buf_size) const {
250 if (buf_size == 0)
251 return 0;
252 size_t len = std::min(this->ref_.size(), buf_size - 1);
253#ifdef USE_ESP8266
254 memcpy_P(buf, this->ref_.c_str(), len);
255#else
256 std::memcpy(buf, this->ref_.c_str(), len);
257#endif
258 buf[len] = '\0';
259 return len;
260 }
261
262 bool equals(const StringRef &other) const {
263#ifdef USE_ESP8266
264 // A StringRef may be {nullptr, 0}, and memcmp_P with a null pointer is undefined even for 0 bytes
265 return other.size() == this->ref_.size() &&
266 (other.empty() || memcmp_P(other.c_str(), this->ref_.c_str(), other.size()) == 0);
267#else
268 return other == this->ref_;
269#endif
270 }
271
272#ifndef USE_ESP8266
274 constexpr const StringRef &ram_ref() const { return this->ref_; }
275#endif
276
277 // Remove before 2027.5.0
278 [[deprecated(
279 "May point to flash; use progmem_ptr() or the owner's accessors. Removed in 2027.5.0")]] constexpr const char *
280 c_str() const {
281 return this->ref_.c_str();
282 }
283
284 private:
285 StringRef ref_;
286};
287
288#ifdef USE_ESP8266
289inline bool operator==(const StringRef &lhs, const ProgmemStringRef &rhs) { return rhs.equals(lhs); }
290inline bool operator!=(const StringRef &lhs, const ProgmemStringRef &rhs) { return !rhs.equals(lhs); }
291inline bool operator==(const std::string &lhs, const ProgmemStringRef &rhs) { return rhs.equals(StringRef(lhs)); }
292inline bool operator!=(const std::string &lhs, const ProgmemStringRef &rhs) { return !rhs.equals(StringRef(lhs)); }
293#endif
294
295// String conversion functions for ADL compatibility (allows stoi(x) where x is StringRef)
296// Must be in esphome namespace for ADL to find them. Uses strtol/strtod directly to avoid heap allocation.
297namespace internal {
298// NOLINTBEGIN(google-runtime-int)
299template<typename R, typename F> inline R parse_number(const StringRef &str, size_t *pos, F conv) {
300 if (str.empty()) { // nothing to parse, and a null view must not reach the C library
301 if (pos)
302 *pos = 0;
303 return R{};
304 }
305 char *end;
306 R result = conv(str.c_str(), &end);
307 // Set pos to 0 on conversion failure (when no characters consumed), otherwise index after number
308 if (pos)
309 *pos = (end == str.c_str()) ? 0 : static_cast<size_t>(end - str.c_str());
310 return result;
311}
312template<typename R, typename F> inline R parse_number(const StringRef &str, size_t *pos, int base, F conv) {
313 if (str.empty()) { // nothing to parse, and a null view must not reach the C library
314 if (pos)
315 *pos = 0;
316 return R{};
317 }
318 char *end;
319 R result = conv(str.c_str(), &end, base);
320 // Set pos to 0 on conversion failure (when no characters consumed), otherwise index after number
321 if (pos)
322 *pos = (end == str.c_str()) ? 0 : static_cast<size_t>(end - str.c_str());
323 return result;
324}
325// NOLINTEND(google-runtime-int)
326} // namespace internal
327// readability-non-const-parameter: `pos` is written through by internal::parse_number, one call
328// frame away; the check only inspects these bodies, so it wrongly proposes `const size_t *`.
329// NOLINTBEGIN(readability-identifier-naming,google-runtime-int,readability-non-const-parameter)
330inline int stoi(const StringRef &str, size_t *pos = nullptr, int base = 10) {
331 return static_cast<int>(internal::parse_number<long>(str, pos, base, std::strtol));
332}
333inline long stol(const StringRef &str, size_t *pos = nullptr, int base = 10) {
334 return internal::parse_number<long>(str, pos, base, std::strtol);
335}
336inline float stof(const StringRef &str, size_t *pos = nullptr) {
337 return internal::parse_number<float>(str, pos, std::strtof);
338}
339inline double stod(const StringRef &str, size_t *pos = nullptr) {
340 return internal::parse_number<double>(str, pos, std::strtod);
341}
342// NOLINTEND(readability-identifier-naming,google-runtime-int,readability-non-const-parameter)
343
344#ifdef USE_JSON
345// A StringRef may view a scratch buffer (mqtt topics do), so the document copies it
346// NOLINTNEXTLINE(readability-identifier-naming)
347inline void convertToJson(const StringRef &src, JsonVariant dst) {
348 // Bounded by the view length; a null, empty view becomes "" rather than JSON null
349 if (src.empty()) {
350 dst.set("");
351 return;
352 }
353 // The explicit isStatic is load bearing: without it clang-tidy reads size() as the bool of the two argument
354 // constructor and asks for empty() instead
355 dst.set(JsonString(src.c_str(), src.size(), /* isStatic= */ false));
356}
357
358namespace json {
359// For a view that outlives the document, see json_util.h. ArduinoJson keeps a linked string as a bare
360// pointer and reads it to its terminator on every platform, so the view must be a whole string, as the
361// entity getters' views are. A null, empty view links "" too
362inline JsonString linked(const StringRef &s) { return JsonString(s.empty() ? "" : s.c_str(), s.size(), true); }
363#ifdef USE_ESP8266
364// ArduinoJson copies a flash string into the document
365inline ProgmemStr linked(const ProgmemStringRef &s) { return reinterpret_cast<ProgmemStr>(s.progmem_ptr()); }
366#else
367inline JsonString linked(const ProgmemStringRef &s) { return JsonString(s.progmem_ptr(), s.size(), true); }
368#endif
369} // namespace json
370#endif // USE_JSON
371
372} // namespace esphome
A string that may live in flash (on ESP8266): pointer and length, with no byte-reading operations.
Definition string_ref.h:236
constexpr const char * progmem_ptr() const
Definition string_ref.h:244
size_t write_to(char *buf, size_t buf_size) const
Copy into buf (null terminated, truncated to fit), returns the length copied.
Definition string_ref.h:249
static constexpr ProgmemStringRef from_lit(const char(&s)[N])
A PROGMEM char array, with its length known at compile time.
Definition string_ref.h:242
constexpr ProgmemStringRef()=default
constexpr ProgmemStringRef(const char *s, size_t len)
Definition string_ref.h:239
constexpr ProgmemStringRef(const StringRef &s)
Definition string_ref.h:240
constexpr const StringRef & ram_ref() const
The string is in RAM here, so it can be viewed directly.
Definition string_ref.h:274
bool equals(const StringRef &other) const
Definition string_ref.h:262
constexpr size_t size() const
Definition string_ref.h:245
constexpr const char * c_str() const
Definition string_ref.h:280
constexpr bool empty() const
Definition string_ref.h:246
StringRef is a reference to a string owned by something else.
Definition string_ref.h:31
bool starts_with(const char *prefix) const
Definition string_ref.h:88
StringRef(const std::string &s)
Definition string_ref.h:44
size_type find(const std::string &s, size_type pos=0) const
Definition string_ref.h:136
std::allocator< char > allocator_type
Definition string_ref.h:35
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition string_ref.h:41
size_type find(char c, size_type pos=0) const
Definition string_ref.h:137
const_reverse_iterator crend() const
Definition string_ref.h:76
constexpr const char * c_str() const
Definition string_ref.h:78
bool starts_with(const std::string &prefix) const
Definition string_ref.h:89
size_type find(const StringRef &s, size_type pos=0) const
Find first occurrence of a substring, returns std::string::npos if not found.
Definition string_ref.h:122
constexpr StringRef(const CharT *s, size_t n)
Definition string_ref.h:48
std::char_traits< char > traits_type
Definition string_ref.h:33
const value_type * const_pointer
Definition string_ref.h:39
constexpr size_type length() const
Definition string_ref.h:80
int compare(const StringRef &other) const
Compare (compatible with std::string::compare)
Definition string_ref.h:106
size_type find(const char *s, size_type pos=0) const
Definition string_ref.h:135
traits_type::char_type value_type
Definition string_ref.h:34
constexpr const_iterator cend() const
Definition string_ref.h:70
constexpr const_reference operator[](size_type pos) const
Definition string_ref.h:82
size_type copy(char *dest, size_type count, size_type pos=0) const
Copy characters to destination buffer (std::string::copy-like, but returns 0 instead of throwing on o...
Definition string_ref.h:92
constexpr const_iterator begin() const
Definition string_ref.h:66
int compare(const char *s) const
Definition string_ref.h:117
constexpr StringRef(const char *s, size_t n)
Definition string_ref.h:46
bool starts_with(const StringRef &prefix) const
True if the view begins with the given prefix (std::string::starts_with-like)
Definition string_ref.h:85
StringRef(const char *s)
Definition string_ref.h:45
constexpr bool empty() const
Definition string_ref.h:81
const_reverse_iterator rbegin() const
Definition string_ref.h:72
constexpr size_type size() const
Definition string_ref.h:79
static constexpr StringRef from_lit(const CharT(&s)[N])
Definition string_ref.h:55
constexpr const_iterator end() const
Definition string_ref.h:69
std::string str() const
Definition string_ref.h:100
std::allocator_traits< allocator_type >::size_type size_type
Definition string_ref.h:36
std::string substr(size_type pos=0, size_type count=std::string::npos) const
Return substring as std::string.
Definition string_ref.h:145
constexpr StringRef()
Definition string_ref.h:43
std::allocator_traits< allocator_type >::difference_type difference_type
Definition string_ref.h:37
StringRef(InputIt first, InputIt last)
Definition string_ref.h:50
static StringRef from_maybe_nullptr(const char *s)
Definition string_ref.h:58
int compare(const std::string &s) const
Definition string_ref.h:118
const value_type & const_reference
Definition string_ref.h:38
const_reverse_iterator rend() const
Definition string_ref.h:75
constexpr const_iterator cbegin() const
Definition string_ref.h:67
const_reverse_iterator crbegin() const
Definition string_ref.h:73
const_pointer const_iterator
Definition string_ref.h:40
const uint8_t * byte() const
Definition string_ref.h:101
StringRef(InputIt *first, InputIt *last)
Definition string_ref.h:53
unsigned count
Definition gif.cpp:51
R parse_number(const StringRef &str, size_t *pos, F conv)
Definition string_ref.h:299
JsonString linked(const char *s)
Definition json_util.h:24
std::string operator+(const char *lhs, const StringRef &rhs)
Definition string_ref.h:210
bool operator!=(const StringRef &lhs, const StringRef &rhs)
Definition string_ref.h:173
const void size_t len
Definition hal.h:68
double stod(const StringRef &str, size_t *pos=nullptr)
Definition string_ref.h:339
void convertToJson(const StringRef &src, JsonVariant dst)
Definition string_ref.h:347
bool operator<(const StringRef &lhs, const StringRef &rhs)
Definition string_ref.h:201
std::string & operator+=(std::string &lhs, const StringRef &rhs)
Definition string_ref.h:205
size_t size_t pos
Definition helpers.h:1333
float stof(const StringRef &str, size_t *pos=nullptr)
Definition string_ref.h:336
const void * src
Definition hal.h:68
bool operator==(const StringRef &lhs, const StringRef &rhs)
Definition string_ref.h:157
int stoi(const StringRef &str, size_t *pos=nullptr, int base=10)
Definition string_ref.h:330
long stol(const StringRef &str, size_t *pos=nullptr, int base=10)
Definition string_ref.h:333
STL namespace.
const __FlashStringHelper * ProgmemStr
Definition progmem.h:31
uint8_t end[39]
Definition sun_gtil2.cpp:17