gql 0.2.0

A GraphQL reference implementation for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! GraphQL values.
//!
//! There are two value models in GraphQL: the *input* value model used by variables and
//! arguments, and the *result* value model embedded in a response. Rust's type system does not
//! need to distinguish them at runtime because both are JSON-shaped, so a single [`Value`] type
//! serves both sides. Scalars are represented by the closest JSON primitive; [`Value::Enum`]
//! exists so enum names stay distinguishable without allocating a second string, and
//! [`Value::BigInt`] keeps integers that do not fit GraphQL's 32-bit `Int` exact.

use core::fmt;
use std::{any::Any, borrow::Cow, sync::Arc};

use smallvec::SmallVec;

use crate::types::names_eq;

/// A GraphQL input or result value.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    /// The explicit `null` value.
    Null,
    /// A boolean.
    Boolean(bool),
    /// A 32-bit signed integer. GraphQL's built-in `Int` is 32-bit.
    Int(i32),
    /// An integer that does not fit in GraphQL's built-in 32-bit `Int`.
    ///
    /// Document literals can carry integers up to `i128` and JSON transports preserve 64-bit
    /// integers. Keeping them as an exact integer lets a custom scalar receive them unchanged,
    /// lets `Float` widen them to a double, and lets `ID` render them as a decimal string.
    /// The built-in `Int` scalar rejects a `BigInt` outside its 32-bit range at coercion time.
    ///
    /// The value is boxed so this variant does not widen [`Value`] on every other value and
    /// stack frame; use [`Value::integer`] to construct one and [`Value::as_i128`] to read it.
    BigInt(Box<i128>),
    /// A 64-bit IEEE-754 floating point number.
    Float(f64),
    /// A string.
    String(Arc<str>),
    /// The name of an enum value.
    Enum(Arc<str>),
    /// An ordered list.
    List(Vec<Value>),
    /// An object: an ordered sequence of distinct field names and values.
    Object(Arc<Object>),
    /// An opaque Rust value produced by a higher-level API.
    ///
    /// Executors never serialize this variant directly. It exists so a type-safe schema builder
    /// can pass its own model types (for example a `User` struct) between resolvers while the
    /// engine stays completely generic. An object type with a resolver accepts it as the parent
    /// value; the high-level layer downcasts it with [`External::downcast_ref`].
    External(External),
}

/// An opaque, thread-safe value used to carry model types through the executor.
#[derive(Clone)]
pub struct External(Arc<dyn Any + Send + Sync>);

impl External {
    /// Wrap a model value.
    #[must_use]
    pub fn new<T: Any + Send + Sync>(value: T) -> Self {
        Self(Arc::new(value))
    }

    /// Borrow the model value as a concrete type.
    #[must_use]
    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
        self.0.downcast_ref()
    }
}

impl fmt::Debug for External {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("External(<model>)")
    }
}

impl PartialEq for External {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl Value {
    /// Construct a string value from anything string-like.
    #[must_use]
    pub fn string(value: impl Into<Arc<str>>) -> Self {
        Self::String(value.into())
    }

    /// Construct an enum value from an enum variant name.
    #[must_use]
    pub fn enumeration(value: impl Into<Arc<str>>) -> Self {
        Self::Enum(value.into())
    }

    /// Construct an object value.
    #[must_use]
    pub fn object(object: impl Into<Object>) -> Self {
        Self::Object(Arc::new(object.into()))
    }

    /// Construct an integer value, narrowing to [`Value::Int`] when it fits.
    #[must_use]
    pub fn integer(value: i128) -> Self {
        i32::try_from(value).map_or_else(|_| Self::BigInt(Box::new(value)), Self::Int)
    }

    /// Whether the value is explicit `null`.
    #[must_use]
    pub const fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }

    /// The name of the value's GraphQL-ish kind, used in error messages.
    #[must_use]
    pub const fn kind(&self) -> &'static str {
        match self {
            Self::Null => "null",
            Self::Boolean(_) => "boolean",
            Self::Int(_) | Self::BigInt(_) | Self::Float(_) => "number",
            Self::String(_) => "string",
            Self::Enum(_) => "enum",
            Self::List(_) => "list",
            Self::Object(_) => "object",
            Self::External(_) => "model",
        }
    }

    /// Borrow the value as a string.
    #[must_use]
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(value) => Some(value),
            Self::Enum(value) => Some(value),
            _ => None,
        }
    }

    /// Borrow the value as a bool.
    #[must_use]
    pub const fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Boolean(value) => Some(*value),
            _ => None,
        }
    }

    /// Borrow the value as an `i32`.
    ///
    /// A [`Value::BigInt`] also converts when it fits, so callers that accept the built-in `Int`
    /// range do not have to spell out both variants.
    #[must_use]
    pub const fn as_i32(&self) -> Option<i32> {
        match self {
            Self::Int(value) => Some(*value),
            Self::BigInt(value) => {
                if **value >= i32::MIN as i128 && **value <= i32::MAX as i128 {
                    Some(**value as i32)
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    /// Borrow the value as an `i64`.
    #[must_use]
    pub const fn as_i64(&self) -> Option<i64> {
        match self {
            Self::Int(value) => Some(*value as i64),
            Self::BigInt(value) => {
                if **value >= i64::MIN as i128 && **value <= i64::MAX as i128 {
                    Some(**value as i64)
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    /// Borrow the value as an exact `i128`.
    #[must_use]
    pub const fn as_i128(&self) -> Option<i128> {
        match self {
            Self::Int(value) => Some(*value as i128),
            Self::BigInt(value) => Some(**value),
            _ => None,
        }
    }

    /// Borrow the value as an `f64`.
    ///
    /// Integers widen exactly as the `Float` scalar does. Values outside `i128` are not
    /// representable by this type at all.
    #[must_use]
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Self::Float(value) => Some(*value),
            Self::Int(value) => Some(f64::from(*value)),
            Self::BigInt(value) => Some(**value as f64),
            _ => None,
        }
    }

    /// Borrow the value as an object.
    #[must_use]
    pub fn as_object(&self) -> Option<&Object> {
        match self {
            Self::Object(object) => Some(object),
            _ => None,
        }
    }

    /// Mutably borrow the value as an object.
    #[must_use]
    pub fn as_object_mut(&mut self) -> Option<&mut Object> {
        match self {
            Self::Object(object) => Some(Arc::make_mut(object)),
            _ => None,
        }
    }

    /// Borrow the value as a list.
    #[must_use]
    pub fn as_list(&self) -> Option<&[Value]> {
        match self {
            Self::List(list) => Some(list),
            _ => None,
        }
    }

    /// Wrap a model value for a type-safe high-level API.
    #[must_use]
    pub fn external<T: Any + Send + Sync>(value: T) -> Self {
        Self::External(External::new(value))
    }

    /// Whether this is an opaque model value.
    #[must_use]
    pub const fn is_external(&self) -> bool {
        matches!(self, Self::External(_))
    }

    /// Borrow an opaque model value as a concrete type.
    #[must_use]
    pub fn as_external<T: Any>(&self) -> Option<&T> {
        match self {
            Self::External(value) => value.downcast_ref(),
            _ => None,
        }
    }

    /// Turn the value into a list, if it is one.
    #[must_use]
    pub fn into_list(self) -> Option<Vec<Value>> {
        match self {
            Self::List(list) => Some(list),
            _ => None,
        }
    }

    /// Turn the value into a string, if it is one.
    #[must_use]
    pub fn into_string(self) -> Option<Arc<str>> {
        match self {
            Self::String(value) | Self::Enum(value) => Some(value),
            _ => None,
        }
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Null => f.write_str("null"),
            Self::Boolean(value) => write!(f, "{value}"),
            Self::Int(value) => write!(f, "{value}"),
            Self::BigInt(value) => write!(f, "{value}"),
            Self::Float(value) => write!(f, "{value}"),
            Self::String(value) => write!(f, "{value}"),
            Self::Enum(value) => f.write_str(value),
            Self::List(_) => f.write_str("[list]"),
            Self::Object(_) => f.write_str("{object}"),
            Self::External(_) => f.write_str("<model>"),
        }
    }
}

impl From<bool> for Value {
    fn from(value: bool) -> Self {
        Self::Boolean(value)
    }
}

macro_rules! impl_from_int {
    ($($ty:ty),* $(,)?) => {
        $(
            impl From<$ty> for Value {
                fn from(value: $ty) -> Self {
                    Self::Int(value as i32)
                }
            }
        )*
    };
}

impl_from_int!(i8, i16, i32, u8, u16);

impl From<i64> for Value {
    fn from(value: i64) -> Self {
        Self::integer(i128::from(value))
    }
}

impl From<i128> for Value {
    fn from(value: i128) -> Self {
        Self::integer(value)
    }
}

impl From<u32> for Value {
    fn from(value: u32) -> Self {
        Self::integer(i128::from(value))
    }
}

impl From<u64> for Value {
    fn from(value: u64) -> Self {
        Self::integer(i128::from(value))
    }
}

impl From<f32> for Value {
    fn from(value: f32) -> Self {
        Self::Float(f64::from(value))
    }
}

impl From<f64> for Value {
    fn from(value: f64) -> Self {
        Self::Float(value)
    }
}

impl From<&str> for Value {
    fn from(value: &str) -> Self {
        Self::String(Arc::from(value))
    }
}

impl From<String> for Value {
    fn from(value: String) -> Self {
        Self::String(Arc::from(value))
    }
}

impl From<Arc<str>> for Value {
    fn from(value: Arc<str>) -> Self {
        Self::String(value)
    }
}

impl From<Cow<'_, str>> for Value {
    fn from(value: Cow<'_, str>) -> Self {
        Self::String(Arc::from(value.as_ref()))
    }
}

impl From<Vec<Value>> for Value {
    fn from(value: Vec<Value>) -> Self {
        Self::List(value)
    }
}

impl From<Object> for Value {
    fn from(value: Object) -> Self {
        Self::Object(Arc::new(value))
    }
}

impl<T: Into<Value>> From<Option<T>> for Value {
    fn from(value: Option<T>) -> Self {
        value.map_or(Self::Null, Into::into)
    }
}

/// An ordered GraphQL object.
///
/// Objects in GraphQL are small: most have fewer than a dozen fields. A linear scan over an
/// inline `SmallVec` beats hashing for those shapes, and it keeps field order stable in responses
/// without an extra `IndexMap` allocation. Larger objects still behave correctly, just with a
/// linear lookup.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Object {
    fields: SmallVec<[(Arc<str>, Value); 8]>,
}

impl Object {
    /// Create an empty object.
    #[must_use]
    pub fn new() -> Self {
        Self {
            fields: SmallVec::new(),
        }
    }

    /// Create an empty object with capacity for `capacity` fields.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            fields: SmallVec::with_capacity(capacity),
        }
    }

    /// Create an object from field pairs. Later duplicates replace earlier ones.
    #[must_use]
    pub fn from_fields(fields: impl IntoIterator<Item = (impl Into<Arc<str>>, Value)>) -> Self {
        let mut object = Self::new();
        for (key, value) in fields {
            object.insert(key, value);
        }
        object
    }

    /// The number of fields.
    #[must_use]
    pub fn len(&self) -> usize {
        self.fields.len()
    }

    /// Whether the object has no fields.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }

    /// Look up a field by name.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&Value> {
        self.fields
            .iter()
            .find(|(name, _)| names_eq(name, key))
            .map(|(_, value)| value)
    }

    /// Mutably look up a field by name.
    pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
        self.fields
            .iter_mut()
            .find(|(name, _)| names_eq(name, key))
            .map(|(_, value)| value)
    }

    /// Whether a field is present.
    #[must_use]
    pub fn contains_key(&self, key: &str) -> bool {
        self.get(key).is_some()
    }

    /// Insert a field, replacing an existing value while preserving its position.
    pub fn insert(&mut self, key: impl Into<Arc<str>>, value: impl Into<Value>) -> Option<Value> {
        let key = key.into();
        let value = value.into();
        if let Some((_, existing)) = self
            .fields
            .iter_mut()
            .find(|(name, _)| names_eq(name, &key))
        {
            return Some(core::mem::replace(existing, value));
        }
        self.fields.push((key, value));
        None
    }

    /// Append a field without checking for an existing key.
    ///
    /// This is for callers that already guarantee uniqueness, such as a JSON object converted into
    /// a variable map or the executor building a response. Skipping the linear duplicate scan
    /// keeps large objects linear instead of quadratic.
    #[doc(hidden)]
    pub fn push_unchecked(&mut self, key: impl Into<Arc<str>>, value: Value) {
        self.fields.push((key.into(), value));
    }

    /// Remove a field by name.
    pub fn remove(&mut self, key: &str) -> Option<Value> {
        let index = self
            .fields
            .iter()
            .position(|(name, _)| names_eq(name, key))?;
        Some(self.fields.remove(index).1)
    }

    /// Iterate over the fields in insertion order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = (&Arc<str>, &Value)> {
        self.fields.iter().map(|(key, value)| (key, value))
    }

    /// Iterate over the field names in insertion order.
    pub fn keys(&self) -> impl ExactSizeIterator<Item = &Arc<str>> {
        self.fields.iter().map(|(key, _)| key)
    }

    /// Iterate over the field values in insertion order.
    pub fn values(&self) -> impl ExactSizeIterator<Item = &Value> {
        self.fields.iter().map(|(_, value)| value)
    }

    /// Consume the object into its fields.
    pub fn into_fields(self) -> impl Iterator<Item = (Arc<str>, Value)> {
        self.fields.into_iter()
    }

    /// Reserve capacity for additional fields.
    pub fn reserve(&mut self, additional: usize) {
        self.fields.reserve(additional);
    }
}

impl FromIterator<(Arc<str>, Value)> for Object {
    fn from_iter<T: IntoIterator<Item = (Arc<str>, Value)>>(iter: T) -> Self {
        let mut object = Self::new();
        for (key, value) in iter {
            object.insert(key, value);
        }
        object
    }
}

impl IntoIterator for Object {
    type Item = (Arc<str>, Value);
    type IntoIter = smallvec::IntoIter<[(Arc<str>, Value); 8]>;

    fn into_iter(self) -> Self::IntoIter {
        self.fields.into_iter()
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Value {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> core::result::Result<S::Ok, S::Error> {
        match self {
            Self::Null => serializer.serialize_none(),
            Self::Boolean(value) => serializer.serialize_bool(*value),
            Self::Int(value) => serializer.serialize_i32(*value),
            Self::BigInt(value) => serializer.serialize_i128(**value),
            Self::Float(value) => serializer.serialize_f64(*value),
            Self::String(value) | Self::Enum(value) => serializer.serialize_str(value),
            Self::List(values) => {
                use serde::ser::SerializeSeq as _;
                let mut seq = serializer.serialize_seq(Some(values.len()))?;
                for value in values {
                    seq.serialize_element(value)?;
                }
                seq.end()
            }
            Self::Object(object) => (**object).serialize(serializer),
            Self::External(_) => Err(serde::ser::Error::custom(
                "an opaque model value reached the serializer; was an object field resolved?",
            )),
        }
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Object {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> core::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap as _;

        let mut map = serializer.serialize_map(Some(self.fields.len()))?;
        for (key, value) in &self.fields {
            map.serialize_entry(&**key, value)?;
        }
        map.end()
    }
}