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 = [] { return TskvParserKvStorage{}; };
23
24} // namespace impl
25
26/// @brief Read all keys-values for 1 TSKV record.
27///
28/// @param parser parser that should have already found the start of the TSKV
29/// record using TskvParser::SkipToRecordBegin
30/// @param consumer a lambda with the signature
31/// `(const std::string&, const std::string&) -> bool`;
32/// the strings are temporaries, references to them should not be stored;
33/// can return `false` to skip the record and return immediately
34///
35/// Usage example:
36/// @snippet utils/encoding/tskv_parser_test.cpp sample
37template <typename TagConsumer>
38TskvParser::RecordStatus TskvReadRecord(TskvParser& parser, TagConsumer consumer) {
39 using RecordStatus = TskvParser::RecordStatus;
40
41 auto kv_storage = impl::tskv_parser_kv_storage.Use();
42
43 while (true) {
44 if (const auto key_status = parser.ReadKey(kv_storage->key)) {
45 return *key_status;
46 }
47
48 const auto value_status = parser.ReadValue(kv_storage->value);
49 if (value_status == RecordStatus::kIncomplete) {
50 return RecordStatus::kIncomplete;
51 }
52
53 const bool record_ok = consumer(std::as_const(kv_storage->key), std::as_const(kv_storage->value));
54 if (value_status == RecordStatus::kReachedEnd) {
55 return RecordStatus::kReachedEnd;
56 }
57 if (!record_ok) {
58 return parser.SkipToRecordEnd();
59 }
60 }
61}
62
63} // namespace utils::encoding
64
65USERVER_NAMESPACE_END