载入中...
搜索中...
未找到
Value.cpp
浏览该文件的文档.
1#include "common/Value.h"
2#include "common/Assert.h"
3#include "common/ValueRead.h"
4
5#include "common/Json.h"
6
7#include <cmath>
8#include <cstdint>
9#include <cstdio>
10#include <limits>
11#include <string>
12#include <string_view>
13#include <utility>
14
15#if defined(_WIN32)
16template class EVENGINE_API_FOUNDATION std::vector<eve::Value>;
17template class EVENGINE_API_FOUNDATION std::map<std::string, eve::Value>;
18#else
19template class std::vector<eve::Value>;
20template class std::map<std::string, eve::Value>;
21#endif
22
23namespace eve {
24
25Result<std::string> readStringMember(const Value::Object& object, std::string_view name) {
26 const auto found = object.find(std::string(name));
27 const auto* text = found == object.end() ? nullptr : found->second.getIf<std::string>();
28 if (!text)
29 return Result<std::string>::failure(Diagnostic::error(DiagnosticCode::ParseError, "expected a string field"));
31}
32
34 auto text = readStringMember(object, name);
35 if (!text || text.value().empty())
37 Diagnostic::error(DiagnosticCode::ParseError, "expected a nonempty string field"));
38 return text;
39}
40
42 const auto* integer = value.getIf<std::int64_t>();
43 if (!integer)
44 return Result<int>::failure(Diagnostic::error(DiagnosticCode::TypeMismatch, "expected an Int64 value"));
45 if (*integer < std::numeric_limits<int>::min() || *integer > std::numeric_limits<int>::max())
46 return Result<int>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "integer exceeds int range"));
47 return Result<int>::success(static_cast<int>(*integer));
48}
49
51 const auto* boolean = value.getIf<bool>();
52 if (!boolean)
53 return Result<bool>::failure(Diagnostic::error(DiagnosticCode::TypeMismatch, "expected a Bool value"));
54 return Result<bool>::success(*boolean);
55}
56
58 const auto* integer = value.getIf<std::int64_t>();
59 if (!integer)
61 Diagnostic::error(DiagnosticCode::TypeMismatch, "expected an Int64 value"));
62 return Result<std::int64_t>::success(*integer);
63}
64
66 auto integer = readInt64Value(value);
67 if (!integer) return Result<std::uint32_t>::failure(integer.status());
68 if (integer.value() < 0 || static_cast<std::uint64_t>(integer.value()) > std::numeric_limits<std::uint32_t>::max())
70 Diagnostic::error(DiagnosticCode::InvalidArgument, "integer exceeds UInt32 range"));
71 return Result<std::uint32_t>::success(static_cast<std::uint32_t>(integer.value()));
72}
73
75 if (const auto* integer = value.getIf<std::int64_t>())
76 return Result<double>::success(static_cast<double>(*integer));
77 if (const auto* number = value.getIf<double>()) return Result<double>::success(*number);
78 return Result<double>::failure(Diagnostic::error(DiagnosticCode::TypeMismatch, "expected Int64 or Double"));
79}
80
82 double number = 0.0;
83 if (const auto* integer = value.getIf<std::int64_t>())
84 number = static_cast<double>(*integer);
85 else if (const auto* real = value.getIf<double>())
86 number = *real;
87 else
88 return Result<float>::failure(Diagnostic::error(DiagnosticCode::TypeMismatch, "expected Integer or Double"));
89 const double maximum = static_cast<double>(std::numeric_limits<float>::max());
90 if (!std::isfinite(number) || number < -maximum || number > maximum)
92 Diagnostic::error(DiagnosticCode::InvalidArgument, "number exceeds finite Float range"));
93 return Result<float>::success(static_cast<float>(number));
94}
95
97 const auto* text = value.getIf<std::string>();
98 if (!text || text->empty())
100 Diagnostic::error(DiagnosticCode::ParseError, "expected a nonempty unsigned decimal string"));
101 return json::scanUnsignedInteger(*text, json::UnsignedIntegerSyntax::Decimal);
102}
103
105 auto text = readNonEmptyStringMember(object, name);
107 return json::scanUnsignedInteger(text.value(), json::UnsignedIntegerSyntax::Decimal);
108}
109
110Value::Value() noexcept = default;
111Value::Value(std::nullptr_t) {}
112Value::Value(bool value) : storage_(value) {}
113Value::Value(std::int64_t value) : storage_(value) {}
114Value::Value(int value) : storage_(static_cast<std::int64_t>(value)) {}
115Value::Value(double value) : storage_(value) {}
116Value::Value(float value) : storage_(static_cast<double>(value)) {}
117Value::Value(const char* value) : storage_(std::string(value ? value : "")) {}
118Value::Value(std::string value) : storage_(std::move(value)) {}
119Value::Value(Array value) : storage_(std::move(value)) {}
120Value::Value(Object value) : storage_(std::move(value)) {}
121Value::~Value() = default;
122Value::Value(const Value& other) = default;
123Value::Value(Value&& other) noexcept = default;
124Value& Value::operator=(const Value& other) = default;
125Value& Value::operator=(Value&& other) noexcept = default;
126bool Value::operator==(const Value& other) const { return storage_ == other.storage_; }
127
128Value Value::array(Array value) { return Value(std::move(value)); }
129Value Value::object(Object value) { return Value(std::move(value)); }
130Value Value::array(std::initializer_list<Value> values) { return Value(Array(values)); }
131Value Value::object(std::initializer_list<Object::value_type> members) { return Value(Object(members)); }
132
133namespace {
134
135Result<Value> copyJsonValue(const json::Value& source) {
136 if (source.isNull()) return Result<Value>::success(Value());
137 if (source.isBool()) return Result<Value>::success(Value(source.asBool()));
138 if (source.isString()) return Result<Value>::success(Value(source.asString()));
139
140 if (source.isNumber()) {
141 if (source.isIntegerLiteral()) {
142 if (!source.isInt64()) {
144 Diagnostic::error(DiagnosticCode::ParseError, "JSON integer is outside the canonical Int64 range"));
145 }
146 return Result<Value>::success(Value(source.asInt64()));
147 }
148 return Result<Value>::success(Value(source.asDouble()));
149 }
150
151 if (source.isArray()) {
153 result.reserve(source.size());
154 for (std::size_t index = 0; index < source.size(); ++index) {
155 auto element = copyJsonValue(source.at(index));
156 if (!element.ok()) return Result<Value>::failure(element.status());
157 result.push_back(std::move(element).takeValue());
158 }
159 return Result<Value>::success(Value(std::move(result)));
160 }
161
162 if (source.isObject()) {
164 for (const std::string& key : source.keys()) {
165 auto member = copyJsonValue(source.get(key.c_str()));
166 if (!member.ok()) return Result<Value>::failure(member.status());
167 result.emplace(key, std::move(member).takeValue());
168 }
169 return Result<Value>::success(Value(std::move(result)));
170 }
171
172 return Result<Value>::failure(Diagnostic::error(DiagnosticCode::ParseError, "unsupported JSON value kind"));
173}
174
175} // namespace
176
177Result<Value> Value::fromJson(std::string_view jsonText) {
178 const std::string input(jsonText);
179 std::string error;
181 if (!document.valid()) {
183 }
184 return copyJsonValue(document.root());
185}
186
188
189std::int64_t Value::asInt() const {
190 const auto* value = getIf<std::int64_t>();
191 EV_ASSERT(value != nullptr, "Value::asInt requires an Int64 value");
192 return value ? *value : 0;
193}
194
195double Value::asDouble() const {
196 const auto* value = getIf<double>();
197 EV_ASSERT(value != nullptr, "Value::asDouble requires a Double value");
198 return value ? *value : 0.0;
199}
200
201bool Value::asBool() const {
202 const auto* value = getIf<bool>();
203 EV_ASSERT(value != nullptr, "Value::asBool requires a Bool value");
204 return value ? *value : false;
205}
206
207const std::string& Value::asString() const {
208 const auto* value = getIf<std::string>();
209 EV_ASSERT(value != nullptr, "Value::asString requires a String value");
210 static const std::string empty;
211 return value ? *value : empty;
212}
213
215 auto* array = getIf<Array>();
216 EV_ASSERT(array != nullptr, "Value::pushBack requires an Array value");
217 if (array) array->push_back(std::move(value));
218}
219
220std::size_t Value::arraySize() const {
221 const auto* array = getIf<Array>();
222 EV_ASSERT(array != nullptr, "Value::arraySize requires an Array value");
223 return array ? array->size() : 0;
224}
225
226Value& Value::at(std::size_t index) {
227 auto* array = getIf<Array>();
228 EV_ASSERT(array != nullptr, "Value::at requires an Array value");
229 return array->at(index);
230}
231
232const Value& Value::at(std::size_t index) const {
233 const auto* array = getIf<Array>();
234 EV_ASSERT(array != nullptr, "Value::at requires an Array value");
235 return array->at(index);
236}
237
238void Value::set(const std::string& key, Value value) {
239 auto* object = getIf<Object>();
240 EV_ASSERT(object != nullptr, "Value::set requires an Object value");
241 if (object) (*object)[key] = std::move(value);
242}
243
244Value* Value::find(const std::string& key) noexcept {
245 auto* object = getIf<Object>();
246 if (!object) return nullptr;
247 const auto it = object->find(key);
248 return it == object->end() ? nullptr : &it->second;
249}
250
251const Value* Value::find(const std::string& key) const noexcept {
252 const auto* object = getIf<Object>();
253 if (!object) return nullptr;
254 const auto it = object->find(key);
255 return it == object->end() ? nullptr : &it->second;
256}
257
258std::vector<std::string> Value::keys() const {
259 const auto* object = getIf<Object>();
260 if (!object) return {};
261 std::vector<std::string> result;
262 result.reserve(object->size());
263 for (const auto& [key, value] : *object) {
264 (void)value;
265 result.push_back(key);
266 }
267 return result;
268}
269
270std::string Value::typeName() const {
271 switch (type()) {
272 case Type::Null: return "null";
273 case Type::Bool: return "bool";
274 case Type::Int64: return "int";
275 case Type::Double: return "float";
276 case Type::String: return "string";
277 case Type::Array: return "array";
278 case Type::Object: return "object";
279 }
280 return "null";
281}
282
283std::string Value::toString() const {
284 if (isString()) return asString();
285 if (isInt64()) return std::to_string(asInt());
286 if (isDouble()) {
287 char buffer[64];
288 std::snprintf(buffer, sizeof(buffer), "%g", asDouble());
289 return buffer;
290 }
291 if (isBool()) return asBool() ? "true" : "false";
292 return {};
293}
294
295} // namespace eve
296
297#if defined(_WIN32) && defined(EVENGINE_MODULE_DLL)
298template __declspec(dllexport) std::monostate* eve::Value::getIf<std::monostate>() noexcept;
299template __declspec(dllexport) const std::monostate* eve::Value::getIf<std::monostate>() const noexcept;
300template __declspec(dllexport) bool* eve::Value::getIf<bool>() noexcept;
301template __declspec(dllexport) const bool* eve::Value::getIf<bool>() const noexcept;
302template __declspec(dllexport) std::int64_t* eve::Value::getIf<std::int64_t>() noexcept;
303template __declspec(dllexport) const std::int64_t* eve::Value::getIf<std::int64_t>() const noexcept;
304template __declspec(dllexport) double* eve::Value::getIf<double>() noexcept;
305template __declspec(dllexport) const double* eve::Value::getIf<double>() const noexcept;
306template __declspec(dllexport) std::string* eve::Value::getIf<std::string>() noexcept;
307template __declspec(dllexport) const std::string* eve::Value::getIf<std::string>() const noexcept;
308template __declspec(dllexport) eve::Value::Array* eve::Value::getIf<eve::Value::Array>() noexcept;
309template __declspec(dllexport) const eve::Value::Array* eve::Value::getIf<eve::Value::Array>() const noexcept;
310template __declspec(dllexport) eve::Value::Object* eve::Value::getIf<eve::Value::Object>() noexcept;
311template __declspec(dllexport) const eve::Value::Object* eve::Value::getIf<eve::Value::Object>() const noexcept;
312#endif
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
Definition Assert.h:37
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
#define EVENGINE_API_FOUNDATION
每个链接组(link group)各自的导出宏。
Definition Export.h:106
float maximum[3]
Poco::JSON::Object::Ptr result
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::string error
Definition Package.cpp:174
std::set< std::string > values
Object::Ptr value
double number
bool found
std::string text
std::string_view source
std::string string
std::string element
Json object
float(ui::Theme::* member)[4]
std::map< std::string, std::span< const std::uint8_t > > members
uint32_t index
Owning, renderer-independent dynamic values.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
Result< std::string > toJson() const
Serialize this value as deterministic compact JSON.
Definition Value.cpp:187
const std::string & asString() const
Return the string payload; the caller must have checked the kind.
Definition Value.cpp:207
bool isInt64() const noexcept
Return true when this value is an Int64.
Definition Value.h:102
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::string typeName() const
Return the compatibility type name used by dialogue scripts.
Definition Value.cpp:270
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< std::string > keys() const
Return object member names in deterministic order.
Definition Value.cpp:258
double asDouble() const
Return the Double payload; the caller must have checked the kind.
Definition Value.cpp:195
~Value() noexcept
Destroy the recursively owned payload.
void set(const std::string &key, Value value)
Insert or replace an object member.
Definition Value.cpp:238
Value & operator=(const Value &other)
Replace this payload with a recursive copy.
bool isString() const noexcept
Return true when this value is a string.
Definition Value.h:106
std::int64_t asInt() const
Return the Int64 payload; the caller must have checked the kind.
Definition Value.cpp:189
Value() noexcept
Construct a null value.
std::vector< Value > Array
Definition Value.h:33
static Value array(Array value)
Compatibility factory for an array value.
Definition Value.cpp:128
std::string toString() const
Render a scalar using the former dialogue formatting rules.
Definition Value.cpp:283
bool operator==(const Value &) const
Compare two values recursively, including their numeric kinds.
Definition Value.cpp:126
void pushBack(Value value)
Append an element to an array value.
Definition Value.cpp:214
std::size_t arraySize() const
Return the number of array elements.
Definition Value.cpp:220
bool asBool() const
Return the boolean payload; the caller must have checked the kind.
Definition Value.cpp:201
bool isBool() const noexcept
Return true when this value is a boolean.
Definition Value.h:100
Value & at(std::size_t index)
Return a bounds-checked array element.
Definition Value.cpp:226
static Value object(Object value)
Compatibility factory for an object value.
Definition Value.cpp:129
bool isDouble() const noexcept
Return true when this value is a Double.
Definition Value.h:104
Type type() const noexcept
Return the active value kind.
Definition Value.h:94
Value * find(const std::string &key) noexcept
Return an object member, or nullptr when absent.
Definition Value.cpp:244
EVENGINE_API_FOUNDATION public API.
Definition Json.h:137
bool valid() const
Valid.
Definition Json.h:158
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
Value root() const
Root.
Definition Json.h:160
EVENGINE_API_FOUNDATION public API.
Definition Json.h:39
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
void keys(const Value &value, std::initializer_list< const char * > names)
Result< std::string > stringify(const eve::Value &value)
Serialize the canonical owning Value as deterministic compact JSON.
Definition Json.cpp:605
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
Result< float > readFiniteFloatValue(const Value &value)
Convert an Integer or Double to a finite Float after validating its source range.
Definition Value.cpp:81
Result< bool > readBoolValue(const Value &value)
Read a Bool without coercing integers, strings or other kinds.
Definition Value.cpp:50
Result< int > readIntValue(const Value &value)
Read an Int64 value as a range-checked native int without numeric coercion.
Definition Value.cpp:41
Result< json::UnsignedIntegerScan > scanUnsignedStringMember(const Value::Object &object, std::string_view name)
Scan a required nonempty decimal-string field using from_chars semantics.
Definition Value.cpp:104
Result< std::string > readStringMember(const Value::Object &object, std::string_view name)
Read a required string field, including an empty string, as an owning value.
Definition Value.cpp:25
Result< json::UnsignedIntegerScan > scanUnsignedStringValue(const Value &value)
Scan an unsigned decimal prefix from a required nonempty String value.
Definition Value.cpp:96
Result< std::string > readNonEmptyStringMember(const Value::Object &object, std::string_view name)
Read a required nonempty string field as an independent owning value.
Definition Value.cpp:33
Result< std::int64_t > readInt64Value(const Value &value)
Read an Int64 without narrowing or numeric coercion.
Definition Value.cpp:57
Result< std::uint32_t > readUInt32Value(const Value &value)
Read an Int64 as a range-checked UInt32 without numeric coercion.
Definition Value.cpp:65
Result< double > readNumericDoubleValue(const Value &value)
Read an Int64 or Double as a double without imposing a finite-value policy.
Definition Value.cpp:74
enum EVENGINE_API_FOUNDATION Array
OT_ARRAY (editable via Runtime array APIs / ReflectedPropertyModel).
Definition Runtime.h:120