ESPHome 2026.7.3
Loading...
Searching...
No Matches
json_escape.h
Go to the documentation of this file.
1#pragma once
2#include <cstddef>
3#include <cstdint>
4#include <span>
5
8
10
12static constexpr size_t JSON_ESCAPE_MAX_EXPANSION = 6;
13
23inline const char *json_escape_into_buffer(std::span<char> buf, StringRef value) {
24 if (buf.empty())
25 return "";
26 // Reserve one byte for the null terminator.
27 const size_t limit = buf.size() - 1;
28 size_t pos = 0;
29 for (char ch : value) {
30 auto c = static_cast<unsigned char>(ch);
31 // Every short form is a backslash followed by a single character, so only that character is needed here. Keeping
32 // it a char rather than a string avoids putting the sequences in read only data, which is RAM on the ESP8266.
33 char escape = '\0';
34 switch (c) {
35 case '"':
36 escape = '"';
37 break;
38 case '\\':
39 escape = '\\';
40 break;
41 case '\n':
42 escape = 'n';
43 break;
44 case '\r':
45 escape = 'r';
46 break;
47 case '\t':
48 escape = 't';
49 break;
50 case '\b':
51 escape = 'b';
52 break;
53 case '\f':
54 escape = 'f';
55 break;
56 default:
57 break;
58 }
59 if (escape != '\0') {
60 if (pos + 2 > limit)
61 break;
62 buf[pos++] = '\\';
63 buf[pos++] = escape;
64 } else if (c < 0x20) {
65 // Remaining control characters have no short form and must be written as \u00XX. The value is below 0x20, so
66 // the two high hex digits are always zero.
67 if (pos + JSON_ESCAPE_MAX_EXPANSION > limit)
68 break;
69 buf[pos++] = '\\';
70 buf[pos++] = 'u';
71 buf[pos++] = '0';
72 buf[pos++] = '0';
73 buf[pos++] = format_hex_char(static_cast<uint8_t>(c >> 4));
74 buf[pos++] = format_hex_char(static_cast<uint8_t>(c & 0x0F));
75 } else {
76 if (pos + 1 > limit)
77 break;
78 buf[pos++] = static_cast<char>(c);
79 }
80 }
81 buf[pos] = '\0';
82 return buf.data();
83}
84
85} // namespace esphome::captive_portal
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
const char * json_escape_into_buffer(std::span< char > buf, StringRef value)
Copy value into buf, escaping the characters that cannot appear raw inside a JSON string literal.
Definition json_escape.h:23
ESPHOME_ALWAYS_INLINE char format_hex_char(uint8_t v, char base)
Convert a nibble (0-15) to hex char with specified base ('a' for lowercase, 'A' for uppercase)
Definition helpers.h:1263
size_t size_t pos
Definition helpers.h:1052