$darkmode
json.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2020 Robert Bosch GmbH
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * SPDX-License-Identifier: Apache-2.0
17  */
24 #pragma once
25 #ifndef FABLE_SCHEMA_JSON_HPP_
26 #define FABLE_SCHEMA_JSON_HPP_
27 
28 #include <string> // for string
29 #include <utility> // for move
30 
31 #include <fable/schema/interface.hpp> // for Base<>
32 
33 namespace fable {
34 namespace schema {
35 
48 template <typename T>
49 class FromJson : public Base<FromJson<T>> {
50  public: // Types and Constructors
51  using Type = T;
52 
53  FromJson(Type* ptr, JsonType t, std::string&& desc)
54  : Base<FromJson<T>>(t, std::move(desc)), ptr_(ptr) {}
55 
56  public: // Overrides
57  Json json_schema() const override {
58  Json j{
59  {"type", this->type_string()},
60  };
61  this->augment_schema(j);
62  return j;
63  }
64 
65  void validate(const Conf& c) const override { this->validate_type(c); }
66 
67  using Interface::to_json;
68  void to_json(Json& j) const override {
69  assert(ptr_ != nullptr);
70  j = static_cast<const Type&>(*ptr_);
71  }
72 
73  void from_conf(const Conf& c) override {
74  assert(ptr_ != nullptr);
75  *ptr_ = c.get<Type>();
76  }
77 
78  void reset_ptr() override { ptr_ = nullptr; }
79 
80  private:
81  Type* ptr_{nullptr};
82 };
83 
84 template <typename T>
85 inline FromJson<T> make_schema(T* ptr, JsonType t, std::string&& desc) {
86  return FromJson<T>(ptr, t, std::move(desc));
87 }
88 
89 } // namespace schema
90 } // namespace fable
91 
92 #endif // FABLE_SCHEMA_JSON_HPP_
Definition: conf.hpp:74
void to_json(Json &j) const override
Definition: json.hpp:68
void reset_ptr() override
Definition: json.hpp:78
T get() const
Definition: conf.hpp:164
Definition: json.hpp:49
nlohmann::json Json
Definition: json.hpp:62
Json::value_t JsonType
Definition: json.hpp:78
Definition: conf.hpp:70
virtual Json to_json() const
Definition: interface.hpp:220
Json json_schema() const override
Definition: json.hpp:57
void from_conf(const Conf &c) override
Definition: json.hpp:73
Definition: interface.hpp:354
std::string type_string() const override
Definition: interface.hpp:366
void validate(const Conf &c) const override
Definition: json.hpp:65