userver: userver/utils/encoding/tskv_parser_read.hpp Source File
Loading...
Searching...
No Matches
tskv_parser_read.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/encoding/tskv_parser_read.hpp
4/// @brief @copybrief utils::encoding::TskvReadKeysValues
5
6#include <utility>
7
8#include <userver/compiler/thread_local.hpp>
9#include <userver/utils/encoding/tskv_parser.hpp>
10
11USERVER_NAMESPACE_BEGIN
12
13namespace utils::encoding {
14
15namespace impl {
16
17struct TskvParserKvStorage {
18 std::string key{};
19 std::string value{};
20};
21
22inline compiler::ThreadLocal tskv_parser_kv_storage = [] {
23 return TskvParserKvStorage{};
24};
25
26} // namespace impl
27
28/// @brief Read all keys-values for 1 TSKV record.
29///
30/// @param parser parser that should have already found the start of the TSKV
31/// record using TskvParser::SkipToRecordBegin
32/// @param consumer a lambda with the signature
33/// `(const std::string&, const std::string&) -> bool`;
34/// the strings are temporaries, references to them should not be stored;
35/// can return `false` to skip the record and return immediately
36///
37/// Usage example:
38/// @snippet utils/encoding/tskv_parser_test.cpp sample
39template <typename TagConsumer>
40TskvParser::RecordStatus TskvReadRecord(TskvParser& parser,
41 TagConsumer consumer) {
42 using RecordStatus = TskvParser::RecordStatus;
43
44 auto kv_storage = impl::tskv_parser_kv_storage.Use();
45
46 while (true) {
47 if (const auto key_status = parser.ReadKey(kv_storage->key)) {
48 return *key_status;
49 }
50
51 const auto value_status = parser.ReadValue(kv_storage->value);
52 if (value_status == RecordStatus::kIncomplete) {
53 return RecordStatus::kIncomplete;
54 }
55
56 const bool record_ok = consumer(std::as_const(kv_storage->key),
57 std::as_const(kv_storage->value));
58 if (value_status == RecordStatus::kReachedEnd) {
59 return RecordStatus::kReachedEnd;
60 }
61 if (!record_ok) {
62 return parser.SkipToRecordEnd();
63 }
64 }
65}
66
67} // namespace utils::encoding
68
69USERVER_NAMESPACE_END