diff options
author | Jack Lloyd <[email protected]> | 2018-09-09 12:47:21 -0400 |
---|---|---|
committer | Jack Lloyd <[email protected]> | 2018-09-09 12:47:21 -0400 |
commit | e79eec4e92e05b42d70acf578256adcfb0a0c22d (patch) | |
tree | 07d3ab12911f214a852715d2d3d8c7d9cf2bcb2a /src/lib/utils/read_kv.cpp | |
parent | 4d75da1814c44aa891feaffa3d118acf8329e499 (diff) | |
parent | fb656ae863fd5b755e4bc0e779b95d34e1106219 (diff) |
Merge GH #1678 Add read_kv utility function
Diffstat (limited to 'src/lib/utils/read_kv.cpp')
-rw-r--r-- | src/lib/utils/read_kv.cpp | 85 |
1 files changed, 85 insertions, 0 deletions
diff --git a/src/lib/utils/read_kv.cpp b/src/lib/utils/read_kv.cpp new file mode 100644 index 000000000..cdc84c622 --- /dev/null +++ b/src/lib/utils/read_kv.cpp @@ -0,0 +1,85 @@ +/* +* (C) 2018 Ribose Inc +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include <botan/parsing.h> +#include <botan/exceptn.h> + +namespace Botan { + +std::map<std::string, std::string> read_kv(const std::string& kv) + { + std::map<std::string, std::string> m; + if(kv == "") + return m; + + std::vector<std::string> parts; + + try + { + parts = split_on(kv, ','); + } + catch(std::exception&) + { + throw Invalid_Argument("Bad KV spec"); + } + + bool escaped = false; + bool reading_key = true; + std::string cur_key; + std::string cur_val; + + for(char c : kv) + { + if(c == '\\' && !escaped) + { + escaped = true; + } + else if(c == ',' && !escaped) + { + if(cur_key.empty()) + throw Invalid_Argument("Bad KV spec empty key"); + + if(m.find(cur_key) != m.end()) + throw Invalid_Argument("Bad KV spec duplicated key"); + m[cur_key] = cur_val; + cur_key = ""; + cur_val = ""; + reading_key = true; + } + else if(c == '=' && !escaped) + { + if(reading_key == false) + throw Invalid_Argument("Bad KV spec unexpected equals sign"); + reading_key = false; + } + else + { + if(reading_key) + cur_key += c; + else + cur_val += c; + + if(escaped) + escaped = false; + } + } + + if(!cur_key.empty()) + { + if(reading_key == false) + { + if(m.find(cur_key) != m.end()) + throw Invalid_Argument("Bad KV spec duplicated key"); + m[cur_key] = cur_val; + } + else + throw Invalid_Argument("Bad KV spec incomplete string"); + } + + return m; + } + +} |