ppap4lmp  0.7.2
add_map.cpp
Go to the documentation of this file.
1 
9 #include "add_map.h"
10 #include "../utils/runtime_error.h"
11 
12 namespace ut = utils;
13 
14 /* ------------------------------------------------------------------ */
15 
17  const Str &key_ref_,
18  const Str &key_new_,
19  const Map<Json,Json> &mapping_)
20 {
21  key_ref = key_ref_;
22  key_new = key_new_;
23  mapping = mapping_;
24 }
25 
26 /* ------------------------------------------------------------------ */
27 
29  Json &data,
30  JsonToVoidFunc check_required_keys,
31  JsonToBoolFunc check_optional_keys)
32 {
33  check_required_keys(key_ref);
34 
35  if (check_optional_keys(key_new) && !do_overwrite)
36  {
37  ut::runtime_error("Key '" + key_new + "' already exists");
38  }
39 
40  if (data.is_array())
41  {
42  for (auto &d : data)
43  {
44  /* NOTE:
45  Use at(), not operator [], to throw an error
46  if the reference value does not exit as a key of the mapping.
47  */
48  d[key_new] = mapping.at(d[key_ref]);
49  }
50  }
51  else
52  {
53  data[key_new] = mapping.at(data[key_ref]);
54  }
55 }
56 
57 /* ------------------------------------------------------------------ */
58 
60  bool do_overwrite_)
61 {
62  do_overwrite = do_overwrite_;
63 
64  return std::dynamic_pointer_cast<AddMap>(shared_from_this());
65 }
ShPtr< AddMap > overwrite(bool do_overwrite_=true)
Allow overwriting an existing property by a new property with the same name.
Definition: add_map.cpp:59
Str key_ref
Definition: add_map.h:36
std::function< bool(const Json &)> JsonToBoolFunc
An alias for a function accepts a Json object and returns a bool.
Definition: updater.h:20
Str key_new
Definition: add_map.h:40
Map< Json, Json > mapping
Definition: add_map.h:49
std::string Str
Str is an alias for string.
Definition: std.h:21
bool do_overwrite
Definition: add_map.h:32
nlohmann::json Json
Json is an alias for nlohmann::json.
Definition: json.h:22
This file has a definition of AddMap class, which is a subclass of Adder class.
virtual void compute_impl(Json &data, JsonToVoidFunc check_required_keys, JsonToBoolFunc check_optional_keys) override
This method overrides Updater::compute_impl.
Definition: add_map.cpp:28
AddMap(const Str &key_ref_, const Str &key_new_, const Map< Json, Json > &mapping_)
Constructor of AddMap class.
Definition: add_map.cpp:16
void runtime_error(const Str &msg)
Raise (for Python) and throw (for C++) a runtime error.
Namespace for utility functions.
Definition: join.h:14
AddMap adds a new property by mapping from an existing property.
Definition: add_map.h:27
std::function< void(const Json &)> JsonToVoidFunc
An alias for a function accepts a Json object.
Definition: updater.h:18
std::shared_ptr< T > ShPtr
ShPtr is an alias for shared pointer.
Definition: std.h:16
std::unordered_map< T, U > Map
Map is an alias for unordered map (same as dict in Python).
Definition: std.h:38