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
//! Value for GraphQL. Used in the [`async-graphql`](https://crates.io/crates/async-graphql) crate.

#![warn(missing_docs)]
#![forbid(unsafe_code)]

mod deserializer;
mod macros;
mod serializer;
mod value_serde;
mod variables;

use std::borrow::{Borrow, Cow};
use std::collections::BTreeMap;
use std::convert::{TryFrom, TryInto};
use std::fmt::{self, Display, Formatter, Write};
use std::iter::FromIterator;
use std::ops::Deref;
use std::sync::Arc;

use bytes::Bytes;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

pub use deserializer::{from_value, DeserializerError};
pub use serde_json::Number;
pub use serializer::{to_value, SerializerError};

pub use variables::Variables;

/// A GraphQL name.
///
/// [Reference](https://spec.graphql.org/June2018/#Name).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Name(Arc<str>);

impl Serialize for Name {
    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

impl Name {
    /// Create a new name.
    pub fn new(name: impl AsRef<str>) -> Self {
        Self(name.as_ref().into())
    }

    /// Get the name as a string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for Name {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Borrow<str> for Name {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl Deref for Name {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Display for Name {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl PartialEq<String> for Name {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other
    }
}
impl PartialEq<str> for Name {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}
impl PartialEq<Name> for String {
    fn eq(&self, other: &Name) -> bool {
        self == other.as_str()
    }
}
impl PartialEq<Name> for str {
    fn eq(&self, other: &Name) -> bool {
        other == self
    }
}
impl<'a> PartialEq<&'a str> for Name {
    fn eq(&self, other: &&'a str) -> bool {
        self == *other
    }
}
impl<'a> PartialEq<Name> for &'a str {
    fn eq(&self, other: &Name) -> bool {
        other == self
    }
}

impl<'de> Deserialize<'de> for Name {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(Self(
            String::deserialize(deserializer)?.into_boxed_str().into(),
        ))
    }
}

/// A resolved GraphQL value, for example `1` or `"Hello World!"`.
///
/// It can be serialized and deserialized. Enums will be converted to strings. Attempting to
/// serialize `Upload` will fail, and `Enum` and `Upload` cannot be deserialized.
///
/// [Reference](https://spec.graphql.org/June2018/#Value).
#[derive(Clone, Debug, Eq)]
pub enum ConstValue {
    /// `null`.
    Null,
    /// A number.
    Number(Number),
    /// A string.
    String(String),
    /// A boolean.
    Boolean(bool),
    /// A binary.
    Binary(Bytes),
    /// An enum. These are typically in `SCREAMING_SNAKE_CASE`.
    Enum(Name),
    /// A list of values.
    List(Vec<ConstValue>),
    /// An object. This is a map of keys to values.
    Object(BTreeMap<Name, ConstValue>),
}

impl PartialEq for ConstValue {
    fn eq(&self, other: &ConstValue) -> bool {
        match (self, other) {
            (ConstValue::Null, ConstValue::Null) => true,
            (ConstValue::Number(a), ConstValue::Number(b)) => a == b,
            (ConstValue::Boolean(a), ConstValue::Boolean(b)) => a == b,
            (ConstValue::String(a), ConstValue::String(b)) => a == b,
            (ConstValue::Enum(a), ConstValue::String(b)) => a == b,
            (ConstValue::String(a), ConstValue::Enum(b)) => a == b,
            (ConstValue::Enum(a), ConstValue::Enum(b)) => a == b,
            (ConstValue::Binary(a), ConstValue::Binary(b)) => a == b,
            (ConstValue::List(a), ConstValue::List(b)) => {
                if a.len() != b.len() {
                    return false;
                }
                a.iter().zip(b.iter()).all(|(a, b)| a == b)
            }
            (ConstValue::Object(a), ConstValue::Object(b)) => {
                if a.len() != b.len() {
                    return false;
                }
                for (a_key, a_value) in a.iter() {
                    if let Some(b_value) = b.get(a_key.as_str()) {
                        if b_value != a_value {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }

                true
            }
            _ => false,
        }
    }
}

impl From<()> for ConstValue {
    fn from((): ()) -> Self {
        ConstValue::Null
    }
}

macro_rules! from_integer {
    ($($ty:ident),*) => {
        $(
            impl From<$ty> for ConstValue {
                fn from(n: $ty) -> Self {
                    ConstValue::Number(n.into())
                }
            }
        )*
    };
}

from_integer!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);

impl From<f32> for ConstValue {
    fn from(f: f32) -> Self {
        From::from(f as f64)
    }
}

impl From<f64> for ConstValue {
    fn from(f: f64) -> Self {
        Number::from_f64(f).map_or(ConstValue::Null, ConstValue::Number)
    }
}

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

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

impl<'a> From<&'a str> for ConstValue {
    fn from(value: &'a str) -> Self {
        ConstValue::String(value.into())
    }
}

impl<'a> From<Cow<'a, str>> for ConstValue {
    fn from(f: Cow<'a, str>) -> Self {
        ConstValue::String(f.into_owned())
    }
}

impl<T: Into<ConstValue>> FromIterator<T> for ConstValue {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        ConstValue::List(iter.into_iter().map(Into::into).collect())
    }
}

impl<'a, T: Clone + Into<ConstValue>> From<&'a [T]> for ConstValue {
    fn from(f: &'a [T]) -> Self {
        ConstValue::List(f.iter().cloned().map(Into::into).collect())
    }
}

impl<T: Into<ConstValue>> From<Vec<T>> for ConstValue {
    fn from(f: Vec<T>) -> Self {
        ConstValue::List(f.into_iter().map(Into::into).collect())
    }
}

impl From<BTreeMap<Name, ConstValue>> for ConstValue {
    fn from(f: BTreeMap<Name, ConstValue>) -> Self {
        ConstValue::Object(f)
    }
}

impl ConstValue {
    /// Convert this `ConstValue` into a `Value`.
    #[must_use]
    pub fn into_value(self) -> Value {
        match self {
            Self::Null => Value::Null,
            Self::Number(num) => Value::Number(num),
            Self::String(s) => Value::String(s),
            Self::Boolean(b) => Value::Boolean(b),
            Self::Binary(bytes) => Value::Binary(bytes),
            Self::Enum(v) => Value::Enum(v),
            Self::List(items) => {
                Value::List(items.into_iter().map(ConstValue::into_value).collect())
            }
            Self::Object(map) => Value::Object(
                map.into_iter()
                    .map(|(key, value)| (key, value.into_value()))
                    .collect(),
            ),
        }
    }

    /// Attempt to convert the value into JSON. This is equivalent to the `TryFrom` implementation.
    ///
    /// # Errors
    ///
    /// Fails if serialization fails (see enum docs for more info).
    pub fn into_json(self) -> serde_json::Result<serde_json::Value> {
        self.try_into()
    }

    /// Attempt to convert JSON into a value. This is equivalent to the `TryFrom` implementation.
    ///
    /// # Errors
    ///
    /// Fails if deserialization fails (see enum docs for more info).
    pub fn from_json(json: serde_json::Value) -> serde_json::Result<Self> {
        json.try_into()
    }
}

impl Default for ConstValue {
    fn default() -> Self {
        Self::Null
    }
}

impl Display for ConstValue {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Number(num) => write!(f, "{}", *num),
            Self::String(val) => write_quoted(val, f),
            Self::Boolean(true) => f.write_str("true"),
            Self::Boolean(false) => f.write_str("false"),
            Self::Binary(bytes) => write_binary(bytes, f),
            Self::Null => f.write_str("null"),
            Self::Enum(name) => f.write_str(name),
            Self::List(items) => write_list(items, f),
            Self::Object(map) => write_object(map, f),
        }
    }
}

impl TryFrom<serde_json::Value> for ConstValue {
    type Error = serde_json::Error;
    fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
        Self::deserialize(value)
    }
}

impl TryFrom<ConstValue> for serde_json::Value {
    type Error = serde_json::Error;
    fn try_from(value: ConstValue) -> Result<Self, Self::Error> {
        serde_json::to_value(value)
    }
}

/// A GraphQL value, for example `1`, `$name` or `"Hello World!"`. This is
/// [`ConstValue`](enum.ConstValue.html) with variables.
///
/// It can be serialized and deserialized. Enums will be converted to strings. Attempting to
/// serialize `Upload` or `Variable` will fail, and `Enum`, `Upload` and `Variable` cannot be
/// deserialized.
///
/// [Reference](https://spec.graphql.org/June2018/#Value).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Value {
    /// A variable, without the `$`.
    Variable(Name),
    /// `null`.
    Null,
    /// A number.
    Number(Number),
    /// A string.
    String(String),
    /// A boolean.
    Boolean(bool),
    /// A binary.
    Binary(Bytes),
    /// An enum. These are typically in `SCREAMING_SNAKE_CASE`.
    Enum(Name),
    /// A list of values.
    List(Vec<Value>),
    /// An object. This is a map of keys to values.
    Object(BTreeMap<Name, Value>),
}

impl Value {
    /// Attempt to convert the value into a const value by using a function to get a variable.
    pub fn into_const_with<E>(
        self,
        mut f: impl FnMut(Name) -> Result<ConstValue, E>,
    ) -> Result<ConstValue, E> {
        self.into_const_with_mut(&mut f)
    }

    fn into_const_with_mut<E>(
        self,
        f: &mut impl FnMut(Name) -> Result<ConstValue, E>,
    ) -> Result<ConstValue, E> {
        Ok(match self {
            Self::Variable(name) => f(name)?,
            Self::Null => ConstValue::Null,
            Self::Number(num) => ConstValue::Number(num),
            Self::String(s) => ConstValue::String(s),
            Self::Boolean(b) => ConstValue::Boolean(b),
            Self::Binary(v) => ConstValue::Binary(v),
            Self::Enum(v) => ConstValue::Enum(v),
            Self::List(items) => ConstValue::List(
                items
                    .into_iter()
                    .map(|value| value.into_const_with_mut(f))
                    .collect::<Result<_, _>>()?,
            ),
            Self::Object(map) => ConstValue::Object(
                map.into_iter()
                    .map(|(key, value)| Ok((key, value.into_const_with_mut(f)?)))
                    .collect::<Result<_, _>>()?,
            ),
        })
    }

    /// Attempt to convert the value into a const value.
    ///
    /// Will fail if the value contains variables.
    #[must_use]
    pub fn into_const(self) -> Option<ConstValue> {
        self.into_const_with(|_| Err(())).ok()
    }

    /// Attempt to convert the value into JSON. This is equivalent to the `TryFrom` implementation.
    ///
    /// # Errors
    ///
    /// Fails if serialization fails (see enum docs for more info).
    pub fn into_json(self) -> serde_json::Result<serde_json::Value> {
        self.try_into()
    }

    /// Attempt to convert JSON into a value. This is equivalent to the `TryFrom` implementation.
    ///
    /// # Errors
    ///
    /// Fails if deserialization fails (see enum docs for more info).
    pub fn from_json(json: serde_json::Value) -> serde_json::Result<Self> {
        json.try_into()
    }
}

impl Default for Value {
    fn default() -> Self {
        Self::Null
    }
}

impl Display for Value {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Variable(name) => write!(f, "${}", name),
            Self::Number(num) => write!(f, "{}", *num),
            Self::String(val) => write_quoted(val, f),
            Self::Boolean(true) => f.write_str("true"),
            Self::Boolean(false) => f.write_str("false"),
            Self::Binary(bytes) => write_binary(bytes, f),
            Self::Null => f.write_str("null"),
            Self::Enum(name) => f.write_str(name),
            Self::List(items) => write_list(items, f),
            Self::Object(map) => write_object(map, f),
        }
    }
}

impl From<ConstValue> for Value {
    fn from(value: ConstValue) -> Self {
        value.into_value()
    }
}

impl TryFrom<serde_json::Value> for Value {
    type Error = serde_json::Error;
    fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
        Self::deserialize(value)
    }
}
impl TryFrom<Value> for serde_json::Value {
    type Error = serde_json::Error;
    fn try_from(value: Value) -> Result<Self, Self::Error> {
        serde_json::to_value(value)
    }
}

fn write_quoted(s: &str, f: &mut Formatter<'_>) -> fmt::Result {
    f.write_char('"')?;
    for c in s.chars() {
        match c {
            '\r' => f.write_str("\\r"),
            '\n' => f.write_str("\\n"),
            '\t' => f.write_str("\\t"),
            '"' => f.write_str("\\\""),
            '\\' => f.write_str("\\\\"),
            c if c.is_control() => write!(f, "\\u{:04}", c as u32),
            c => f.write_char(c),
        }?
    }
    f.write_char('"')
}

fn write_binary(bytes: &[u8], f: &mut Formatter<'_>) -> fmt::Result {
    f.write_char('[')?;
    let mut iter = bytes.iter().copied();
    if let Some(value) = iter.next() {
        value.fmt(f)?;
    }
    for value in iter {
        f.write_char(',')?;
        value.fmt(f)?;
    }
    f.write_char(']')
}

fn write_list<T: Display>(list: impl IntoIterator<Item = T>, f: &mut Formatter<'_>) -> fmt::Result {
    f.write_char('[')?;
    let mut iter = list.into_iter();
    if let Some(item) = iter.next() {
        item.fmt(f)?;
    }
    for item in iter {
        f.write_char(',')?;
        item.fmt(f)?;
    }
    f.write_char(']')
}

fn write_object<K: Display, V: Display>(
    object: impl IntoIterator<Item = (K, V)>,
    f: &mut Formatter<'_>,
) -> fmt::Result {
    f.write_char('{')?;
    let mut iter = object.into_iter();
    if let Some((name, value)) = iter.next() {
        write!(f, "{}: {}", name, value)?;
    }
    for (name, value) in iter {
        f.write_char(',')?;
        write!(f, "{}: {}", name, value)?;
    }
    f.write_char('}')
}