Botan 3.14.1
Crypto and TLS for C&
read_kv.cpp
Go to the documentation of this file.
1/*
2* (C) 2018 Ribose Inc
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#include <botan/internal/parsing.h>
8
9#include <botan/exceptn.h>
10
11namespace Botan {
12
13std::map<std::string, std::string> read_kv(std::string_view kv) {
14 std::map<std::string, std::string> m;
15 if(kv.empty()) {
16 return m;
17 }
18
19 try {
20 // Validate input format before manual parsing
21 [[maybe_unused]] const auto _ = split_on(kv, ',');
22 } catch(std::exception&) {
23 throw Invalid_Argument("Bad KV spec");
24 }
25
26 bool escaped = false;
27 bool reading_key = true;
28 std::string cur_key;
29 std::string cur_val;
30
31 for(const char c : kv) {
32 if(c == '\\' && !escaped) {
33 escaped = true;
34 } else if(c == ',' && !escaped) {
35 if(cur_key.empty()) {
36 throw Invalid_Argument("Bad KV spec empty key");
37 }
38
39 if(m.contains(cur_key)) {
40 throw Invalid_Argument("Bad KV spec duplicated key");
41 }
42 m[cur_key] = cur_val;
43 cur_key = "";
44 cur_val = "";
45 reading_key = true;
46 } else if(c == '=' && !escaped) {
47 if(!reading_key) {
48 throw Invalid_Argument("Bad KV spec unexpected equals sign");
49 }
50 reading_key = false;
51 } else {
52 if(reading_key) {
53 cur_key += c;
54 } else {
55 cur_val += c;
56 }
57 escaped = false;
58 }
59 }
60
61 if(!cur_key.empty()) {
62 if(!reading_key) {
63 if(m.contains(cur_key)) {
64 throw Invalid_Argument("Bad KV spec duplicated key");
65 }
66 m[cur_key] = cur_val;
67 } else {
68 throw Invalid_Argument("Bad KV spec incomplete string");
69 }
70 }
71
72 return m;
73}
74
75} // namespace Botan
BOTAN_TEST_API std::map< std::string, std::string > read_kv(std::string_view kv)
Definition read_kv.cpp:13
std::vector< std::string > split_on(std::string_view str, char delim)
Definition parsing.cpp:83