• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef CORE__LOADER__JSON_UTIL_H
17 #define CORE__LOADER__JSON_UTIL_H
18 
19 #include <cstdlib>
20 
21 #include <base/containers/string.h>
22 #include <base/containers/string_view.h>
23 #include <core/json/json.h>
24 #include <core/log.h>
25 #include <core/namespace.h>
26 
27 #include "util/string_util.h"
28 
CORE3D_BEGIN_NAMESPACE()29 CORE3D_BEGIN_NAMESPACE()
30 template<class T, BASE_NS::enable_if_t<BASE_NS::is_arithmetic_v<T>, bool> = true>
31 inline bool SafeGetJsonValue(
32     const CORE_NS::json::value& jsonData, const BASE_NS::string_view element, BASE_NS::string& error, T& output)
33 {
34     if (auto const pos = jsonData.find(element); pos) {
35         if (pos->is_number()) {
36             output = pos->as_number<T>();
37             return true;
38         } else {
39             error += element + ": expected number.\n";
40         }
41     }
42     return false;
43 }
44 
45 template<class T, BASE_NS::enable_if_t<BASE_NS::is_convertible_v<T, BASE_NS::string_view>, bool> = true>
SafeGetJsonValue(const CORE_NS::json::value & jsonData,const BASE_NS::string_view element,BASE_NS::string & error,T & output)46 inline bool SafeGetJsonValue(
47     const CORE_NS::json::value& jsonData, const BASE_NS::string_view element, BASE_NS::string& error, T& output)
48 {
49     if (auto const pos = jsonData.find(element); pos) {
50         if (pos->is_string()) {
51             output = T(pos->string_.data(), pos->string_.size());
52             return true;
53         } else {
54             error += element + ": expected string.\n";
55         }
56     }
57     return false;
58 }
59 CORE3D_END_NAMESPACE()
60 
61 #endif