Skip to main content

gql/
value.rs

1//! GraphQL values.
2//!
3//! There are two value models in GraphQL: the *input* value model used by variables and
4//! arguments, and the *result* value model embedded in a response. Rust's type system does not
5//! need to distinguish them at runtime because both are JSON-shaped, so a single [`Value`] type
6//! serves both sides. Scalars are represented by the closest JSON primitive; [`Value::Enum`]
7//! exists so enum names stay distinguishable without allocating a second string, and
8//! [`Value::BigInt`] keeps integers that do not fit GraphQL's 32-bit `Int` exact.
9
10use core::fmt;
11use std::{any::Any, borrow::Cow, sync::Arc};
12
13use smallvec::SmallVec;
14
15use crate::types::names_eq;
16
17/// A GraphQL input or result value.
18#[derive(Clone, Debug, PartialEq)]
19pub enum Value {
20    /// The explicit `null` value.
21    Null,
22    /// A boolean.
23    Boolean(bool),
24    /// A 32-bit signed integer. GraphQL's built-in `Int` is 32-bit.
25    Int(i32),
26    /// An integer that does not fit in GraphQL's built-in 32-bit `Int`.
27    ///
28    /// Document literals can carry integers up to `i128` and JSON transports preserve 64-bit
29    /// integers. Keeping them as an exact integer lets a custom scalar receive them unchanged,
30    /// lets `Float` widen them to a double, and lets `ID` render them as a decimal string.
31    /// The built-in `Int` scalar rejects a `BigInt` outside its 32-bit range at coercion time.
32    ///
33    /// The value is boxed so this variant does not widen [`Value`] on every other value and
34    /// stack frame; use [`Value::integer`] to construct one and [`Value::as_i128`] to read it.
35    BigInt(Box<i128>),
36    /// A 64-bit IEEE-754 floating point number.
37    Float(f64),
38    /// A string.
39    String(Arc<str>),
40    /// The name of an enum value.
41    Enum(Arc<str>),
42    /// An ordered list.
43    List(Vec<Value>),
44    /// An object: an ordered sequence of distinct field names and values.
45    Object(Arc<Object>),
46    /// An opaque Rust value produced by a higher-level API.
47    ///
48    /// Executors never serialize this variant directly. It exists so a type-safe schema builder
49    /// can pass its own model types (for example a `User` struct) between resolvers while the
50    /// engine stays completely generic. An object type with a resolver accepts it as the parent
51    /// value; the high-level layer downcasts it with [`External::downcast_ref`].
52    External(External),
53}
54
55/// An opaque, thread-safe value used to carry model types through the executor.
56#[derive(Clone)]
57pub struct External(Arc<dyn Any + Send + Sync>);
58
59impl External {
60    /// Wrap a model value.
61    #[must_use]
62    pub fn new<T: Any + Send + Sync>(value: T) -> Self {
63        Self(Arc::new(value))
64    }
65
66    /// Borrow the model value as a concrete type.
67    #[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    /// Construct a string value from anything string-like.
87    #[must_use]
88    pub fn string(value: impl Into<Arc<str>>) -> Self {
89        Self::String(value.into())
90    }
91
92    /// Construct an enum value from an enum variant name.
93    #[must_use]
94    pub fn enumeration(value: impl Into<Arc<str>>) -> Self {
95        Self::Enum(value.into())
96    }
97
98    /// Construct an object value.
99    #[must_use]
100    pub fn object(object: impl Into<Object>) -> Self {
101        Self::Object(Arc::new(object.into()))
102    }
103
104    /// Construct an integer value, narrowing to [`Value::Int`] when it fits.
105    #[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    /// Whether the value is explicit `null`.
111    #[must_use]
112    pub const fn is_null(&self) -> bool {
113        matches!(self, Self::Null)
114    }
115
116    /// The name of the value's GraphQL-ish kind, used in error messages.
117    #[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    /// Borrow the value as a string.
132    #[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    /// Borrow the value as a bool.
142    #[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    /// Borrow the value as an `i32`.
151    ///
152    /// A [`Value::BigInt`] also converts when it fits, so callers that accept the built-in `Int`
153    /// range do not have to spell out both variants.
154    #[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    /// Borrow the value as an `i64`.
170    #[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    /// Borrow the value as an exact `i128`.
186    #[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    /// Borrow the value as an `f64`.
196    ///
197    /// Integers widen exactly as the `Float` scalar does. Values outside `i128` are not
198    /// representable by this type at all.
199    #[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    /// Borrow the value as an object.
210    #[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    /// Mutably borrow the value as an object.
219    #[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    /// Borrow the value as a list.
228    #[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    /// Wrap a model value for a type-safe high-level API.
237    #[must_use]
238    pub fn external<T: Any + Send + Sync>(value: T) -> Self {
239        Self::External(External::new(value))
240    }
241
242    /// Whether this is an opaque model value.
243    #[must_use]
244    pub const fn is_external(&self) -> bool {
245        matches!(self, Self::External(_))
246    }
247
248    /// Borrow an opaque model value as a concrete type.
249    #[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    /// Turn the value into a list, if it is one.
258    #[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    /// Turn the value into a string, if it is one.
267    #[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/// An ordered GraphQL object.
392///
393/// Objects in GraphQL are small: most have fewer than a dozen fields. A linear scan over an
394/// inline `SmallVec` beats hashing for those shapes, and it keeps field order stable in responses
395/// without an extra `IndexMap` allocation. Larger objects still behave correctly, just with a
396/// linear lookup.
397#[derive(Clone, Debug, Default, PartialEq)]
398pub struct Object {
399    fields: SmallVec<[(Arc<str>, Value); 8]>,
400}
401
402impl Object {
403    /// Create an empty object.
404    #[must_use]
405    pub fn new() -> Self {
406        Self {
407            fields: SmallVec::new(),
408        }
409    }
410
411    /// Create an empty object with capacity for `capacity` fields.
412    #[must_use]
413    pub fn with_capacity(capacity: usize) -> Self {
414        Self {
415            fields: SmallVec::with_capacity(capacity),
416        }
417    }
418
419    /// Create an object from field pairs. Later duplicates replace earlier ones.
420    #[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    /// The number of fields.
430    #[must_use]
431    pub fn len(&self) -> usize {
432        self.fields.len()
433    }
434
435    /// Whether the object has no fields.
436    #[must_use]
437    pub fn is_empty(&self) -> bool {
438        self.fields.is_empty()
439    }
440
441    /// Look up a field by name.
442    #[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    /// Mutably look up a field by name.
451    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    /// Whether a field is present.
459    #[must_use]
460    pub fn contains_key(&self, key: &str) -> bool {
461        self.get(key).is_some()
462    }
463
464    /// Insert a field, replacing an existing value while preserving its position.
465    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    /// Append a field without checking for an existing key.
480    ///
481    /// This is for callers that already guarantee uniqueness, such as a JSON object converted into
482    /// a variable map or the executor building a response. Skipping the linear duplicate scan
483    /// keeps large objects linear instead of quadratic.
484    #[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    /// Remove a field by name.
490    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    /// Iterate over the fields in insertion order.
499    pub fn iter(&self) -> impl ExactSizeIterator<Item = (&Arc<str>, &Value)> {
500        self.fields.iter().map(|(key, value)| (key, value))
501    }
502
503    /// Iterate over the field names in insertion order.
504    pub fn keys(&self) -> impl ExactSizeIterator<Item = &Arc<str>> {
505        self.fields.iter().map(|(key, _)| key)
506    }
507
508    /// Iterate over the field values in insertion order.
509    pub fn values(&self) -> impl ExactSizeIterator<Item = &Value> {
510        self.fields.iter().map(|(_, value)| value)
511    }
512
513    /// Consume the object into its fields.
514    pub fn into_fields(self) -> impl Iterator<Item = (Arc<str>, Value)> {
515        self.fields.into_iter()
516    }
517
518    /// Reserve capacity for additional fields.
519    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}