1
#pragma once
2

            
3
#include <string>
4

            
5
#include "absl/container/flat_hash_map.h"
6
#include "absl/strings/string_view.h"
7

            
8
namespace Envoy {
9
namespace Json {
10

            
11
/**
12
 * Sanitizes a string so it is suitable for JSON. The buffer is
13
 * used if any of the characters in str need to be escaped. Performance
14
 * is good if there are no characters requiring escaping or utf-8 decode.
15
 *
16
 * --------------------------------------------------------------------
17
 * Benchmark                          Time             CPU   Iterations
18
 * --------------------------------------------------------------------
19
 * BM_ProtoEncoderNoEscape         1445 ns         1444 ns       455727
20
 * BM_NlohmannNoEscape             9.79 ns         9.79 ns     71449511
21
 * BM_ProtoEncoderWithEscape       1521 ns         1521 ns       462697
22
 * BM_NlohmannWithEscape            215 ns          215 ns      3264218
23
 *
24
 * The returned string is suitable for including in a double-quoted JSON
25
 * context, but does not include the surrounding double-quotes. The primary
26
 * reason is performance: most of the time this function can return the
27
 * passed-in str without needing to perform memory operations, and the main
28
 * expected usage is in a context where unconditionally adding the double-quotes
29
 * is fast and easy.
30
 *
31
 * @param buffer a string in which an escaped string can be written, if needed.
32
 *   It is not necessary for callers to clear the buffer first; it be cleared
33
 *   by this method if needed.
34
 * @param str the string to be translated
35
 * @return the translated string_view, valid as long as both buffer and str are
36
 *   valid.
37
 */
38
absl::string_view sanitize(std::string& buffer, absl::string_view str);
39

            
40
/**
41
 * Strips double-quotes on first and last characters of str. It's a
42
 * precondition to call this on a string that is surrounded by double-quotes.
43
 *
44
 * @param str The string to strip double-quotes from.
45
 * @return The string without its surrounding double-quotes.
46
 */
47
absl::string_view stripDoubleQuotes(absl::string_view str);
48

            
49
} // namespace Json
50
} // namespace Envoy