userver: userver/utils/encoding/tskv.hpp Source File
Loading...
Searching...
No Matches
tskv.hpp
Go to the documentation of this file.
1#pragma once
2
6
7#include <array>
8#include <cstddef>
9#include <cstdint>
10#include <cstring>
11#include <limits>
12#include <string_view>
13#include <type_traits>
14
15#ifdef __AVX2__
16#include <immintrin.h>
17#elif defined(__SSSE3__)
18#include <tmmintrin.h>
19#elif defined(__SSE2__)
20#include <emmintrin.h>
21#endif
22
24
25// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
26#define USERVER_IMPL_FORCE_INLINE __attribute__((always_inline)) inline
27
28#ifdef __clang__
29// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
30#define USERVER_IMPL_DISABLE_ASAN __attribute__((no_sanitize_address, no_sanitize_memory, no_sanitize_thread))
31#else
32// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
33#define USERVER_IMPL_DISABLE_ASAN __attribute__((no_sanitize_address))
34#endif
35
36USERVER_NAMESPACE_BEGIN
37
38namespace utils::encoding {
39
40constexpr inline char kTskvKeyValueSeparator = '=';
41constexpr inline char kTskvPairsSeparator = '\t';
42
43// kKeyReplacePeriod is for logging. Elastic has a long history of problems with
44// periods in TSKV keys. For more info see:
45// www.elastic.co/guide/en/elasticsearch/reference/2.4/dots-in-names.html
46enum class EncodeTskvMode { kKey, kValue, kKeyReplacePeriod };
47
51template <typename OutIter>
52OutIter EncodeTskv(OutIter destination, char ch, EncodeTskvMode mode);
53
60template <typename Container>
61void EncodeTskv(Container& container, std::string_view str, EncodeTskvMode mode);
62
63// ==================== Implementation follows ====================
64
65// always_inline to eliminate 'mode' checks
66template <typename OutIter>
67USERVER_IMPL_FORCE_INLINE OutIter EncodeTskv(OutIter destination, char ch, EncodeTskvMode mode) {
68 const bool is_key_encoding = (mode == EncodeTskvMode::kKey || mode == EncodeTskvMode::kKeyReplacePeriod);
69 const auto append = [&destination](char ch) { *(destination++) = ch; };
70
71 switch (ch) {
72 case '\t':
73 append('\\');
74 append('t');
75 break;
76 case '\r':
77 append('\\');
78 append('r');
79 break;
80 case '\n':
81 append('\\');
82 append('n');
83 break;
84 case '\0':
85 append('\\');
86 append('0');
87 break;
88 case '\\':
89 append('\\');
90 append(ch);
91 break;
92 case '.':
93 if (mode == EncodeTskvMode::kKeyReplacePeriod) {
94 append('_');
95 break;
96 }
97 [[fallthrough]];
98 case 'A':
99 case 'B':
100 case 'C':
101 case 'D':
102 case 'E':
103 case 'F':
104 case 'G':
105 case 'H':
106 case 'I':
107 case 'J':
108 case 'K':
109 case 'L':
110 case 'M':
111 case 'N':
112 case 'O':
113 case 'P':
114 case 'Q':
115 case 'R':
116 case 'S':
117 case 'T':
118 case 'U':
119 case 'V':
120 case 'W':
121 case 'X':
122 case 'Y':
123 case 'Z':
124 if (is_key_encoding) {
125 append(ch | 0x20); // ch - 'A' + 'a'
126 break;
127 }
128 [[fallthrough]];
129 case '=':
130 if (is_key_encoding) {
131 append('\\');
132 append(ch);
133 break;
134 }
135 [[fallthrough]];
136 default:
137 append(ch);
138 break;
139 }
140 return destination;
141}
142
143namespace impl::tskv {
144
145template <std::size_t Alignment, typename T>
146USERVER_IMPL_FORCE_INLINE T* AlignDown(T* ptr) noexcept {
147 static_assert(Alignment % sizeof(T) == 0);
148 return reinterpret_cast<T*>(reinterpret_cast<std::uintptr_t>(ptr) / Alignment * Alignment);
149}
150
151template <std::size_t Alignment>
152USERVER_IMPL_FORCE_INLINE const char* AssumeAligned(const char* block) noexcept {
153 UASSERT(reinterpret_cast<std::uintptr_t>(block) % Alignment == 0);
154 return static_cast<const char*>(__builtin_assume_aligned(block, Alignment));
155}
156
157constexpr auto MakeShuffleIndicesForRightShift() noexcept {
158 constexpr std::size_t kShuffleWidth = 16;
159 std::array<std::uint8_t, kShuffleWidth * 2> result{};
160 for (auto& item : result) {
161 item = 0xf0;
162 }
163 for (std::size_t i = 0; i < kShuffleWidth; ++i) {
164 result[i] = i;
165 }
166 return result;
167}
168
169struct EncoderStd final {
170 using Block = std::uint64_t;
171 static constexpr std::size_t kBlockSize = sizeof(Block);
172
173 // Sanitizers are disabled within the function, because the SIMD loads
174 // may intentionally wander to uninitialized memory. The loads never touch
175 // memory outside "our" cache lines, though.
176 USERVER_IMPL_DISABLE_ASAN inline static auto LoadBlock(const char* block) noexcept {
177 block = impl::tskv::AssumeAligned<kBlockSize>(block);
178 return *reinterpret_cast<const Block*>(block);
179 }
180
181 USERVER_IMPL_FORCE_INLINE static void CopyBlock(Block block, std::size_t offset, char* destination) noexcept {
182 const auto cut_block = block >> (offset * 8);
183 std::memcpy(destination, &cut_block, sizeof(cut_block));
184 }
185
186 USERVER_IMPL_FORCE_INLINE static bool MayNeedValueEscaping(Block block, std::size_t offset, std::size_t count)
187 noexcept {
188 char buffer[kBlockSize]{};
189 std::memcpy(&buffer, &block, sizeof(block));
190 for (const unsigned char c : std::string_view(buffer + offset, count)) {
191 // c must be unsigned so bytes 0x80..0xff stay above '\r'
192 // and do not trigger unnecessary per-byte encoding.
193 if (c <= '\r' || c == '\\') {
194 return true;
195 }
196 }
197 return false;
198 }
199};
200
201#ifdef __SSE2__
202struct EncoderSse2 {
203 using Block = __m128i;
204 static constexpr std::size_t kBlockSize = sizeof(Block);
205
206 // Sanitizers are disabled within the function, because the SIMD loads
207 // may intentionally wander to uninitialized memory. The loads never touch
208 // memory outside "our" cache lines, though.
209 USERVER_IMPL_DISABLE_ASAN inline static Block LoadBlock(const char* block) noexcept {
210 block = impl::tskv::AssumeAligned<kBlockSize>(block);
211 return _mm_load_si128(reinterpret_cast<const Block*>(block));
212 }
213
214 USERVER_IMPL_FORCE_INLINE static void CopyBlock(Block block_contents, std::size_t offset, char* destination)
215 noexcept {
216 alignas(kBlockSize * 2) char storage[kBlockSize * 2]{};
217 _mm_store_si128(reinterpret_cast<Block*>(&storage), block_contents);
218 const auto cut_block = _mm_loadu_si128(reinterpret_cast<__m128i_u*>(&storage[offset]));
219 _mm_storeu_si128(reinterpret_cast<__m128i_u*>(destination), cut_block);
220 }
221
222 USERVER_IMPL_FORCE_INLINE static bool MayNeedValueEscaping(Block block, std::size_t offset, std::size_t count)
223 noexcept {
224 // Unsigned c <= '\r' <=> max(c, '\r') == '\r', as in RapidJSON's ScanWriteUnescapedString:
225 // https://github.com/Tencent/rapidjson/blob/24b5e7a8b27f42fa16b96fc70aade9106cf7102f/include/rapidjson/writer.h#L620
226 // 16 lower bits of the mask contain may-need-escaping flag per block's char
227 const auto max_control_char = _mm_set1_epi8('\r');
228 const auto may_need_escaping_mask = _mm_movemask_epi8(_mm_or_si128(
229 _mm_cmpeq_epi8(_mm_max_epu8(block, max_control_char), max_control_char),
230 _mm_cmpeq_epi8(block, _mm_set1_epi8('\\'))
231 ));
232 return static_cast<
233 std::uint32_t>(static_cast<std::uint32_t>(may_need_escaping_mask) >> offset << (32 - count)) != 0;
234 }
235};
236#endif
237
238#ifdef __SSSE3__
239struct EncoderSsse3 final : public EncoderSse2 {
240 USERVER_IMPL_FORCE_INLINE static void CopyBlock(Block block, std::size_t offset, char* destination) noexcept {
241 static constexpr auto kShuffleIdx = MakeShuffleIndicesForRightShift();
242 const auto pos = _mm_loadu_si128(reinterpret_cast<const __m128i_u*>(&kShuffleIdx[offset]));
243 const auto cut_block = _mm_shuffle_epi8(block, pos);
244 _mm_storeu_si128(reinterpret_cast<__m128i_u*>(destination), cut_block);
245 }
246};
247#endif
248
249#ifdef __AVX2__
250struct EncoderAvx2 final {
251 using Block = __m256i;
252 static constexpr std::size_t kBlockSize = sizeof(Block);
253
254 // Sanitizers are disabled within the function, because the SIMD loads
255 // may intentionally wander to uninitialized memory. The loads never touch
256 // memory outside "our" cache lines, though.
257 USERVER_IMPL_DISABLE_ASAN inline static Block LoadBlock(const char* block) noexcept {
258 block = impl::tskv::AssumeAligned<kBlockSize>(block);
259 return _mm256_load_si256(reinterpret_cast<const Block*>(block));
260 }
261
262 USERVER_IMPL_FORCE_INLINE static void CopyBlock(Block block, std::size_t offset, char* destination) noexcept {
263 alignas(kBlockSize * 2) char storage[kBlockSize * 2]{};
264 _mm256_store_si256(reinterpret_cast<Block*>(&storage), block);
265 const auto cut_block = _mm256_loadu_si256(reinterpret_cast<__m256i_u*>(&storage[offset]));
266 _mm256_storeu_si256(reinterpret_cast<__m256i_u*>(destination), cut_block);
267 }
268
269 USERVER_IMPL_FORCE_INLINE static bool MayNeedValueEscaping(Block block, std::size_t offset, std::size_t count)
270 noexcept {
271 // Unsigned c <= '\r' <=> max(c, '\r') == '\r', as in RapidJSON's ScanWriteUnescapedString:
272 // https://github.com/Tencent/rapidjson/blob/24b5e7a8b27f42fa16b96fc70aade9106cf7102f/include/rapidjson/writer.h#L620
273 // 32 lower bits of the mask contain may-need-escaping flag per block's char
274 const auto max_control_char = _mm256_set1_epi8('\r');
275 const auto may_need_escaping_mask = _mm256_movemask_epi8(_mm256_or_si256(
276 _mm256_cmpeq_epi8(_mm256_max_epu8(block, max_control_char), max_control_char),
277 _mm256_cmpeq_epi8(block, _mm256_set1_epi8('\\'))
278 ));
279 return static_cast<
280 std::uint32_t>(static_cast<std::uint32_t>(may_need_escaping_mask) >> offset << (32 - count)) != 0;
281 }
282};
283#endif
284
285#if defined(__AVX2__)
286using SystemEncoder = EncoderAvx2;
287#elif defined(__SSSE3__)
288using SystemEncoder = EncoderSsse3;
289#elif defined(__SSE2__)
290using SystemEncoder = EncoderSse2;
291#else
292using SystemEncoder = EncoderStd;
293#endif
294
295// It is assumed that starting with the current output position, there is enough
296// free space to fit the converted data, plus `PaddingSize` extra bytes of free
297// space, which the encoder is free to fill with garbage.
298template <typename Encoder>
299constexpr std::size_t PaddingSize() {
300 return Encoder::kBlockSize;
301}
302
303template <typename Encoder>
304struct BufferPtr final {
305 char* current{nullptr};
306};
307
308template <typename Encoder>
309USERVER_IMPL_FORCE_INLINE BufferPtr<Encoder> AppendBlock(
310 BufferPtr<Encoder> destination,
311 typename Encoder::Block block,
312 std::size_t offset,
313 std::size_t count
314) noexcept {
315 char* const old_current = destination.current;
316 destination.current += count;
317 Encoder::CopyBlock(block, offset, old_current);
318 return destination;
319}
320
321// noinline to avoid code duplication for a cold path
322template <typename Encoder>
323[[nodiscard]] __attribute__((noinline)) BufferPtr<Encoder> EncodeValueEach(
324 BufferPtr<Encoder> destination,
325 std::string_view str
326) {
327 for (const char c : str) {
328 destination.current = utils::encoding::EncodeTskv(destination.current, c, EncodeTskvMode::kValue);
329 }
330 return destination;
331}
332
333template <typename Encoder>
334[[nodiscard]] USERVER_IMPL_FORCE_INLINE BufferPtr<Encoder> EncodeValueBlock(
335 BufferPtr<Encoder> destination,
336 const char* block,
337 std::size_t offset,
338 std::size_t count
339) {
340 UASSERT(offset < Encoder::kBlockSize);
341 UASSERT(offset + count <= Encoder::kBlockSize);
342 block = impl::tskv::AssumeAligned<Encoder::kBlockSize>(block);
343 const auto block_contents = Encoder::LoadBlock(block);
344
345 if (__builtin_expect(Encoder::MayNeedValueEscaping(block_contents, offset, count), false)) {
346 destination = impl::tskv::EncodeValueEach(destination, std::string_view(block + offset, count));
347 } else {
348 // happy path: the whole block does not need escaping
349 destination = impl::tskv::AppendBlock(destination, block_contents, offset, count);
350 }
351
352 return destination;
353}
354
355// BufferPtr must be passed around by value to avoid aliasing issues.
356// Alignment reduces layout-sensitive loop-branch mispredictions.
357template <typename Encoder>
358[[nodiscard]] __attribute__((noinline, aligned(64))) BufferPtr<Encoder> EncodeValue(
359 BufferPtr<Encoder> destination,
360 std::string_view str
361) {
362 if (str.empty()) {
363 return destination;
364 }
365
366 const char* const first_block = impl::tskv::AlignDown<Encoder::kBlockSize>(str.data());
367 const auto first_block_offset = static_cast<std::size_t>(str.data() - first_block);
368 const auto first_block_count = std::min(Encoder::kBlockSize - first_block_offset, str.size());
369
370 destination = impl::tskv::EncodeValueBlock(destination, first_block, first_block_offset, first_block_count);
371
372 const char* const last_block = impl::tskv::AlignDown<Encoder::kBlockSize>(str.data() + str.size());
373
374 if (last_block != first_block) {
375 for (const char* current_block = first_block + Encoder::kBlockSize; current_block < last_block;
376 current_block += Encoder::kBlockSize)
377 {
378 destination = impl::tskv::EncodeValueBlock(destination, current_block, 0, Encoder::kBlockSize);
379 }
380
381 const auto last_block_count = static_cast<std::size_t>(str.data() + str.size() - last_block);
382 if (last_block_count != 0) {
383 destination = impl::tskv::EncodeValueBlock(destination, last_block, 0, last_block_count);
384 }
385 }
386
387 return destination;
388}
389
390template <typename Encoder>
391[[nodiscard]] BufferPtr<Encoder> DoEncode(BufferPtr<Encoder> destination, std::string_view str, EncodeTskvMode mode) {
392 if (mode == EncodeTskvMode::kValue) {
393 return impl::tskv::EncodeValue(destination, str);
394 } else {
395 for (const char c : str) {
396 destination.current = utils::encoding::EncodeTskv(destination.current, c, mode);
397 }
398 return destination;
399 }
400}
401
402inline std::size_t MaxEncodedSize(std::size_t source_size) noexcept { return source_size * 2; }
403
404template <typename Encoder, typename Container>
405void EncodeFullyBuffered(Container& container, std::string_view str, EncodeTskvMode mode) {
406 const auto old_size = container.size();
407 const auto max_size = old_size + impl::tskv::MaxEncodedSize(str.size()) + impl::tskv::PaddingSize<Encoder>();
408 const auto encode = [&](char* data, std::size_t) {
409 BufferPtr<Encoder> buffer_ptr{data + old_size};
410 buffer_ptr = impl::tskv::DoEncode(buffer_ptr, str, mode);
411 return static_cast<std::size_t>(buffer_ptr.current - data);
412 };
413 if constexpr (requires { container.resize_and_overwrite(max_size, encode); }) {
414 container.resize_and_overwrite(max_size, encode);
415 } else {
416 // Preserve the resize-only contract of the generic container API.
417 container.resize(max_size);
418 container.resize(encode(container.data(), max_size));
419 }
420}
421
422} // namespace impl::tskv
423
424template <typename Container>
425void EncodeTskv(Container& container, std::string_view str, EncodeTskvMode mode) {
426 impl::tskv::EncodeFullyBuffered<impl::tskv::SystemEncoder>(container, str, mode);
427}
428
430USERVER_IMPL_FORCE_INLINE bool ShouldKeyBeEscaped(std::string_view key, EncodeTskvMode mode) noexcept {
431 UASSERT(mode == EncodeTskvMode::kKey || mode == EncodeTskvMode::kKeyReplacePeriod);
432 for (const char ch : key) {
433 switch (ch) {
434 case '\t':
435 case '\r':
436 case '\n':
437 case '\0':
438 case '\\':
439 case '=':
440 return true;
441 case '.':
442 if (mode == EncodeTskvMode::kKeyReplacePeriod) {
443 return true;
444 }
445 break;
446 default:
447 if ('A' <= ch && ch <= 'Z') {
448 return true;
449 }
450 break;
451 }
452 }
453 return false;
454}
455
456inline bool ShouldKeyBeEscaped(std::string_view key) noexcept {
457 return ShouldKeyBeEscaped(key, EncodeTskvMode::kKeyReplacePeriod);
458}
459
460inline bool ShouldValueBeEscaped(std::string_view key) noexcept {
461 using Encoder = impl::tskv::SystemEncoder;
462 const auto block_contents = Encoder::LoadBlock(key.data());
463 return Encoder::MayNeedValueEscaping(block_contents, 0, key.size());
464}
466
467} // namespace utils::encoding
468
469USERVER_NAMESPACE_END
470
471#undef USERVER_IMPL_FORCE_INLINE
472#undef USERVER_IMPL_DONT_SANITIZE