Parses the string representation of a Python dict The keys need to be known and may not appear anywhere else in the data. */
| 219 | The keys need to be known and may not appear anywhere else in the data. |
| 220 | */ |
| 221 | inline std::unordered_map <std::string, std::string> parse_dict(std::string in, const std::vector <std::string> &keys) { |
| 222 | std::unordered_map <std::string, std::string> map; |
| 223 | |
| 224 | if (keys.size() == 0) |
| 225 | return map; |
| 226 | |
| 227 | in = trim(in); |
| 228 | |
| 229 | // unwrap dictionary |
| 230 | if ((in.front() == '{') && (in.back() == '}')) |
| 231 | in = in.substr(1, in.length() - 2); |
| 232 | else |
| 233 | throw std::runtime_error("Not a Python dictionary."); |
| 234 | |
| 235 | std::vector <std::pair<size_t, std::string>> positions; |
| 236 | |
| 237 | for (auto const &value : keys) { |
| 238 | size_t pos = in.find("'" + value + "'"); |
| 239 | |
| 240 | if (pos == std::string::npos) |
| 241 | throw std::runtime_error("Missing '" + value + "' key."); |
| 242 | |
| 243 | std::pair <size_t, std::string> position_pair{pos, value}; |
| 244 | positions.push_back(position_pair); |
| 245 | } |
| 246 | |
| 247 | // sort by position in dict |
| 248 | std::sort(positions.begin(), positions.end()); |
| 249 | |
| 250 | for (size_t i = 0; i < positions.size(); ++i) { |
| 251 | std::string raw_value; |
| 252 | size_t begin{positions[i].first}; |
| 253 | size_t end{std::string::npos}; |
| 254 | |
| 255 | std::string key = positions[i].second; |
| 256 | |
| 257 | if (i + 1 < positions.size()) |
| 258 | end = positions[i + 1].first; |
| 259 | |
| 260 | raw_value = in.substr(begin, end - begin); |
| 261 | |
| 262 | raw_value = trim(raw_value); |
| 263 | |
| 264 | if (raw_value.back() == ',') |
| 265 | raw_value.pop_back(); |
| 266 | |
| 267 | map[key] = get_value_from_map(raw_value); |
| 268 | } |
| 269 | |
| 270 | return map; |
| 271 | } |
| 272 | |
| 273 | /** |
| 274 | Parses the string representation of a Python boolean |
no test coverage detected