Skip to content

Commit 2725202

Browse files
authored
Use Lemire's fast check whether to escape a JSON string (#6923)
1 parent 42fafdc commit 2725202

File tree

1 file changed

+22
-17
lines changed

1 file changed

+22
-17
lines changed

include/util/string_util.hpp

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,40 @@
11
#ifndef STRING_UTIL_HPP
22
#define STRING_UTIL_HPP
33

4+
#include <array>
45
#include <cctype>
5-
6+
#include <cstddef>
67
#include <random>
78
#include <string>
89
#include <vector>
910

1011
namespace osrm::util
1112
{
1213

14+
// implements Lemire's table-based escape needs check
15+
// cf. https://lemire.me/blog/2024/05/31/quickly-checking-whether-a-string-needs-escaping/
16+
inline static constexpr std::array<uint8_t, 256> json_quotable_character = []() constexpr
17+
{
18+
std::array<uint8_t, 256> result{};
19+
for (auto i = 0; i < 32; i++)
20+
{
21+
result[i] = 1;
22+
}
23+
for (auto i : {'"', '\\'})
24+
{
25+
result[i] = 1;
26+
}
27+
return result;
28+
}();
29+
1330
inline bool RequiresJSONStringEscaping(const std::string &string)
1431
{
15-
for (const char letter : string)
32+
uint8_t needs = 0;
33+
for (uint8_t c : string)
1634
{
17-
switch (letter)
18-
{
19-
case '\\':
20-
case '"':
21-
case '/':
22-
case '\b':
23-
case '\f':
24-
case '\n':
25-
case '\r':
26-
case '\t':
27-
return true;
28-
default:
29-
continue;
30-
}
35+
needs |= json_quotable_character[c];
3136
}
32-
return false;
37+
return needs;
3338
}
3439

3540
inline void EscapeJSONString(const std::string &input, std::string &output)

0 commit comments

Comments
 (0)