-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathobject_macro.rs
More file actions
102 lines (90 loc) · 2.43 KB
/
object_macro.rs
File metadata and controls
102 lines (90 loc) · 2.43 KB
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
use crate::data::value::Object;
use crate::prelude::q;
use crate::prelude::r;
use std::iter::FromIterator;
/// Creates a `graphql_parser::query::Value::Object` from key/value pairs.
/// If you don't need to determine which keys are included dynamically at runtime
/// consider using the `object! {}` macro instead.
pub fn object_value(data: Vec<(&str, r::Value)>) -> r::Value {
r::Value::Object(Object::from_iter(
data.into_iter().map(|(k, v)| (k.to_string(), v)),
))
}
pub trait IntoValue {
fn into_value(self) -> r::Value;
}
impl IntoValue for r::Value {
#[inline]
fn into_value(self) -> r::Value {
self
}
}
impl IntoValue for &'_ str {
#[inline]
fn into_value(self) -> r::Value {
self.to_owned().into_value()
}
}
impl IntoValue for i32 {
#[inline]
fn into_value(self) -> r::Value {
r::Value::Int(self as i64)
}
}
impl IntoValue for q::Number {
#[inline]
fn into_value(self) -> r::Value {
r::Value::Int(self.as_i64().unwrap())
}
}
impl IntoValue for u64 {
#[inline]
fn into_value(self) -> r::Value {
r::Value::String(self.to_string())
}
}
impl<T: IntoValue> IntoValue for Option<T> {
#[inline]
fn into_value(self) -> r::Value {
match self {
Some(v) => v.into_value(),
None => r::Value::Null,
}
}
}
impl<T: IntoValue> IntoValue for Vec<T> {
#[inline]
fn into_value(self) -> r::Value {
r::Value::List(self.into_iter().map(|e| e.into_value()).collect::<Vec<_>>())
}
}
macro_rules! impl_into_values {
($(($T:ty, $V:ident)),*) => {
$(
impl IntoValue for $T {
#[inline]
fn into_value(self) -> r::Value {
r::Value::$V(self)
}
}
)+
};
}
impl_into_values![(String, String), (f64, Float), (bool, Boolean)];
/// Creates a `data::value::Value::Object` from key/value pairs.
#[macro_export]
macro_rules! object {
($($name:ident: $value:expr,)*) => {
{
let mut result = $crate::data::value::Object::new();
$(
let value = $crate::data::graphql::object_macro::IntoValue::into_value($value);
result.insert(stringify!($name).to_string(), value);
)*
$crate::prelude::r::Value::Object(result)
}
};
($($name:ident: $value:expr),*) => {
object! {$($name: $value,)*}
};
}