1use core::fmt;
11use std::{any::Any, borrow::Cow, sync::Arc};
12
13use smallvec::SmallVec;
14
15use crate::types::names_eq;
16
17#[derive(Clone, Debug, PartialEq)]
19pub enum Value {
20 Null,
22 Boolean(bool),
24 Int(i32),
26 BigInt(Box<i128>),
36 Float(f64),
38 String(Arc<str>),
40 Enum(Arc<str>),
42 List(Vec<Value>),
44 Object(Arc<Object>),
46 External(External),
53}
54
55#[derive(Clone)]
57pub struct External(Arc<dyn Any + Send + Sync>);
58
59impl External {
60 #[must_use]
62 pub fn new<T: Any + Send + Sync>(value: T) -> Self {
63 Self(Arc::new(value))
64 }
65
66 #[must_use]
68 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
69 self.0.downcast_ref()
70 }
71}
72
73impl fmt::Debug for External {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 f.write_str("External(<model>)")
76 }
77}
78
79impl PartialEq for External {
80 fn eq(&self, other: &Self) -> bool {
81 Arc::ptr_eq(&self.0, &other.0)
82 }
83}
84
85impl Value {
86 #[must_use]
88 pub fn string(value: impl Into<Arc<str>>) -> Self {
89 Self::String(value.into())
90 }
91
92 #[must_use]
94 pub fn enumeration(value: impl Into<Arc<str>>) -> Self {
95 Self::Enum(value.into())
96 }
97
98 #[must_use]
100 pub fn object(object: impl Into<Object>) -> Self {
101 Self::Object(Arc::new(object.into()))
102 }
103
104 #[must_use]
106 pub fn integer(value: i128) -> Self {
107 i32::try_from(value).map_or_else(|_| Self::BigInt(Box::new(value)), Self::Int)
108 }
109
110 #[must_use]
112 pub const fn is_null(&self) -> bool {
113 matches!(self, Self::Null)
114 }
115
116 #[must_use]
118 pub const fn kind(&self) -> &'static str {
119 match self {
120 Self::Null => "null",
121 Self::Boolean(_) => "boolean",
122 Self::Int(_) | Self::BigInt(_) | Self::Float(_) => "number",
123 Self::String(_) => "string",
124 Self::Enum(_) => "enum",
125 Self::List(_) => "list",
126 Self::Object(_) => "object",
127 Self::External(_) => "model",
128 }
129 }
130
131 #[must_use]
133 pub fn as_str(&self) -> Option<&str> {
134 match self {
135 Self::String(value) => Some(value),
136 Self::Enum(value) => Some(value),
137 _ => None,
138 }
139 }
140
141 #[must_use]
143 pub const fn as_bool(&self) -> Option<bool> {
144 match self {
145 Self::Boolean(value) => Some(*value),
146 _ => None,
147 }
148 }
149
150 #[must_use]
155 pub const fn as_i32(&self) -> Option<i32> {
156 match self {
157 Self::Int(value) => Some(*value),
158 Self::BigInt(value) => {
159 if **value >= i32::MIN as i128 && **value <= i32::MAX as i128 {
160 Some(**value as i32)
161 } else {
162 None
163 }
164 }
165 _ => None,
166 }
167 }
168
169 #[must_use]
171 pub const fn as_i64(&self) -> Option<i64> {
172 match self {
173 Self::Int(value) => Some(*value as i64),
174 Self::BigInt(value) => {
175 if **value >= i64::MIN as i128 && **value <= i64::MAX as i128 {
176 Some(**value as i64)
177 } else {
178 None
179 }
180 }
181 _ => None,
182 }
183 }
184
185 #[must_use]
187 pub const fn as_i128(&self) -> Option<i128> {
188 match self {
189 Self::Int(value) => Some(*value as i128),
190 Self::BigInt(value) => Some(**value),
191 _ => None,
192 }
193 }
194
195 #[must_use]
200 pub fn as_f64(&self) -> Option<f64> {
201 match self {
202 Self::Float(value) => Some(*value),
203 Self::Int(value) => Some(f64::from(*value)),
204 Self::BigInt(value) => Some(**value as f64),
205 _ => None,
206 }
207 }
208
209 #[must_use]
211 pub fn as_object(&self) -> Option<&Object> {
212 match self {
213 Self::Object(object) => Some(object),
214 _ => None,
215 }
216 }
217
218 #[must_use]
220 pub fn as_object_mut(&mut self) -> Option<&mut Object> {
221 match self {
222 Self::Object(object) => Some(Arc::make_mut(object)),
223 _ => None,
224 }
225 }
226
227 #[must_use]
229 pub fn as_list(&self) -> Option<&[Value]> {
230 match self {
231 Self::List(list) => Some(list),
232 _ => None,
233 }
234 }
235
236 #[must_use]
238 pub fn external<T: Any + Send + Sync>(value: T) -> Self {
239 Self::External(External::new(value))
240 }
241
242 #[must_use]
244 pub const fn is_external(&self) -> bool {
245 matches!(self, Self::External(_))
246 }
247
248 #[must_use]
250 pub fn as_external<T: Any>(&self) -> Option<&T> {
251 match self {
252 Self::External(value) => value.downcast_ref(),
253 _ => None,
254 }
255 }
256
257 #[must_use]
259 pub fn into_list(self) -> Option<Vec<Value>> {
260 match self {
261 Self::List(list) => Some(list),
262 _ => None,
263 }
264 }
265
266 #[must_use]
268 pub fn into_string(self) -> Option<Arc<str>> {
269 match self {
270 Self::String(value) | Self::Enum(value) => Some(value),
271 _ => None,
272 }
273 }
274}
275
276impl fmt::Display for Value {
277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278 match self {
279 Self::Null => f.write_str("null"),
280 Self::Boolean(value) => write!(f, "{value}"),
281 Self::Int(value) => write!(f, "{value}"),
282 Self::BigInt(value) => write!(f, "{value}"),
283 Self::Float(value) => write!(f, "{value}"),
284 Self::String(value) => write!(f, "{value}"),
285 Self::Enum(value) => f.write_str(value),
286 Self::List(_) => f.write_str("[list]"),
287 Self::Object(_) => f.write_str("{object}"),
288 Self::External(_) => f.write_str("<model>"),
289 }
290 }
291}
292
293impl From<bool> for Value {
294 fn from(value: bool) -> Self {
295 Self::Boolean(value)
296 }
297}
298
299macro_rules! impl_from_int {
300 ($($ty:ty),* $(,)?) => {
301 $(
302 impl From<$ty> for Value {
303 fn from(value: $ty) -> Self {
304 Self::Int(value as i32)
305 }
306 }
307 )*
308 };
309}
310
311impl_from_int!(i8, i16, i32, u8, u16);
312
313impl From<i64> for Value {
314 fn from(value: i64) -> Self {
315 Self::integer(i128::from(value))
316 }
317}
318
319impl From<i128> for Value {
320 fn from(value: i128) -> Self {
321 Self::integer(value)
322 }
323}
324
325impl From<u32> for Value {
326 fn from(value: u32) -> Self {
327 Self::integer(i128::from(value))
328 }
329}
330
331impl From<u64> for Value {
332 fn from(value: u64) -> Self {
333 Self::integer(i128::from(value))
334 }
335}
336
337impl From<f32> for Value {
338 fn from(value: f32) -> Self {
339 Self::Float(f64::from(value))
340 }
341}
342
343impl From<f64> for Value {
344 fn from(value: f64) -> Self {
345 Self::Float(value)
346 }
347}
348
349impl From<&str> for Value {
350 fn from(value: &str) -> Self {
351 Self::String(Arc::from(value))
352 }
353}
354
355impl From<String> for Value {
356 fn from(value: String) -> Self {
357 Self::String(Arc::from(value))
358 }
359}
360
361impl From<Arc<str>> for Value {
362 fn from(value: Arc<str>) -> Self {
363 Self::String(value)
364 }
365}
366
367impl From<Cow<'_, str>> for Value {
368 fn from(value: Cow<'_, str>) -> Self {
369 Self::String(Arc::from(value.as_ref()))
370 }
371}
372
373impl From<Vec<Value>> for Value {
374 fn from(value: Vec<Value>) -> Self {
375 Self::List(value)
376 }
377}
378
379impl From<Object> for Value {
380 fn from(value: Object) -> Self {
381 Self::Object(Arc::new(value))
382 }
383}
384
385impl<T: Into<Value>> From<Option<T>> for Value {
386 fn from(value: Option<T>) -> Self {
387 value.map_or(Self::Null, Into::into)
388 }
389}
390
391#[derive(Clone, Debug, Default, PartialEq)]
398pub struct Object {
399 fields: SmallVec<[(Arc<str>, Value); 8]>,
400}
401
402impl Object {
403 #[must_use]
405 pub fn new() -> Self {
406 Self {
407 fields: SmallVec::new(),
408 }
409 }
410
411 #[must_use]
413 pub fn with_capacity(capacity: usize) -> Self {
414 Self {
415 fields: SmallVec::with_capacity(capacity),
416 }
417 }
418
419 #[must_use]
421 pub fn from_fields(fields: impl IntoIterator<Item = (impl Into<Arc<str>>, Value)>) -> Self {
422 let mut object = Self::new();
423 for (key, value) in fields {
424 object.insert(key, value);
425 }
426 object
427 }
428
429 #[must_use]
431 pub fn len(&self) -> usize {
432 self.fields.len()
433 }
434
435 #[must_use]
437 pub fn is_empty(&self) -> bool {
438 self.fields.is_empty()
439 }
440
441 #[must_use]
443 pub fn get(&self, key: &str) -> Option<&Value> {
444 self.fields
445 .iter()
446 .find(|(name, _)| names_eq(name, key))
447 .map(|(_, value)| value)
448 }
449
450 pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
452 self.fields
453 .iter_mut()
454 .find(|(name, _)| names_eq(name, key))
455 .map(|(_, value)| value)
456 }
457
458 #[must_use]
460 pub fn contains_key(&self, key: &str) -> bool {
461 self.get(key).is_some()
462 }
463
464 pub fn insert(&mut self, key: impl Into<Arc<str>>, value: impl Into<Value>) -> Option<Value> {
466 let key = key.into();
467 let value = value.into();
468 if let Some((_, existing)) = self
469 .fields
470 .iter_mut()
471 .find(|(name, _)| names_eq(name, &key))
472 {
473 return Some(core::mem::replace(existing, value));
474 }
475 self.fields.push((key, value));
476 None
477 }
478
479 #[doc(hidden)]
485 pub fn push_unchecked(&mut self, key: impl Into<Arc<str>>, value: Value) {
486 self.fields.push((key.into(), value));
487 }
488
489 pub fn remove(&mut self, key: &str) -> Option<Value> {
491 let index = self
492 .fields
493 .iter()
494 .position(|(name, _)| names_eq(name, key))?;
495 Some(self.fields.remove(index).1)
496 }
497
498 pub fn iter(&self) -> impl ExactSizeIterator<Item = (&Arc<str>, &Value)> {
500 self.fields.iter().map(|(key, value)| (key, value))
501 }
502
503 pub fn keys(&self) -> impl ExactSizeIterator<Item = &Arc<str>> {
505 self.fields.iter().map(|(key, _)| key)
506 }
507
508 pub fn values(&self) -> impl ExactSizeIterator<Item = &Value> {
510 self.fields.iter().map(|(_, value)| value)
511 }
512
513 pub fn into_fields(self) -> impl Iterator<Item = (Arc<str>, Value)> {
515 self.fields.into_iter()
516 }
517
518 pub fn reserve(&mut self, additional: usize) {
520 self.fields.reserve(additional);
521 }
522}
523
524impl FromIterator<(Arc<str>, Value)> for Object {
525 fn from_iter<T: IntoIterator<Item = (Arc<str>, Value)>>(iter: T) -> Self {
526 let mut object = Self::new();
527 for (key, value) in iter {
528 object.insert(key, value);
529 }
530 object
531 }
532}
533
534impl IntoIterator for Object {
535 type Item = (Arc<str>, Value);
536 type IntoIter = smallvec::IntoIter<[(Arc<str>, Value); 8]>;
537
538 fn into_iter(self) -> Self::IntoIter {
539 self.fields.into_iter()
540 }
541}
542
543#[cfg(feature = "serde")]
544impl serde::Serialize for Value {
545 fn serialize<S: serde::Serializer>(
546 &self,
547 serializer: S,
548 ) -> core::result::Result<S::Ok, S::Error> {
549 match self {
550 Self::Null => serializer.serialize_none(),
551 Self::Boolean(value) => serializer.serialize_bool(*value),
552 Self::Int(value) => serializer.serialize_i32(*value),
553 Self::BigInt(value) => serializer.serialize_i128(**value),
554 Self::Float(value) => serializer.serialize_f64(*value),
555 Self::String(value) | Self::Enum(value) => serializer.serialize_str(value),
556 Self::List(values) => {
557 use serde::ser::SerializeSeq as _;
558 let mut seq = serializer.serialize_seq(Some(values.len()))?;
559 for value in values {
560 seq.serialize_element(value)?;
561 }
562 seq.end()
563 }
564 Self::Object(object) => (**object).serialize(serializer),
565 Self::External(_) => Err(serde::ser::Error::custom(
566 "an opaque model value reached the serializer; was an object field resolved?",
567 )),
568 }
569 }
570}
571
572#[cfg(feature = "serde")]
573impl serde::Serialize for Object {
574 fn serialize<S: serde::Serializer>(
575 &self,
576 serializer: S,
577 ) -> core::result::Result<S::Ok, S::Error> {
578 use serde::ser::SerializeMap as _;
579
580 let mut map = serializer.serialize_map(Some(self.fields.len()))?;
581 for (key, value) in &self.fields {
582 map.serialize_entry(&**key, value)?;
583 }
584 map.end()
585 }
586}