1use super::{Map, Number, Value};
2use std::borrow::Cow;
3
4macro_rules! impl_from_integer {
5 ($($ty:ty),*) => {
6 $(
7 impl From<$ty> for Value {
8 fn from(n: $ty) -> Self {
9 Self::Number(n.into())
10 }
11 }
12 )*
13 };
14}
15
16impl_from_integer!(i8, i16, i32, i64, isize);
17impl_from_integer!(u8, u16, u32, u64, usize);
18
19impl From<f32> for Value {
20 fn from(f: f32) -> Self {
21 From::from(f as f64)
22 }
23}
24
25impl From<f64> for Value {
26 fn from(f: f64) -> Self {
27 Number::from_f64(f).map_or(Value::Null, Value::Number)
28 }
29}
30
31impl From<Number> for Value {
32 fn from(num: Number) -> Self {
33 Self::Number(num)
34 }
35}
36
37impl From<bool> for Value {
38 fn from(b: bool) -> Self {
39 Self::Bool(b)
40 }
41}
42
43impl From<String> for Value {
44 fn from(s: String) -> Self {
45 Self::String(s)
46 }
47}
48
49impl From<&str> for Value {
50 fn from(s: &str) -> Self {
51 Self::String(s.to_string())
52 }
53}
54
55impl<'a> From<Cow<'a, str>> for Value {
56 fn from(s: Cow<'a, str>) -> Self {
57 Self::String(s.into_owned())
58 }
59}
60
61impl From<Map<String, Value>> for Value {
62 fn from(f: Map<String, Value>) -> Self {
63 Self::Object(f)
64 }
65}
66
67impl<T: Into<Value>> From<Vec<T>> for Value {
68 fn from(f: Vec<T>) -> Self {
69 Self::Array(f.into_iter().map(Into::into).collect())
70 }
71}
72
73impl<'a, T: Clone + Into<Value>> From<&'a [T]> for Value {
74 fn from(f: &'a [T]) -> Self {
75 Self::Array(f.iter().cloned().map(Into::into).collect())
76 }
77}
78
79impl<T: Into<Value>> FromIterator<T> for Value {
80 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
81 Self::Array(iter.into_iter().map(Into::into).collect())
82 }
83}
84
85impl<K: Into<String>, V: Into<Value>> FromIterator<(K, V)> for Value {
86 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
87 Self::Object(
88 iter.into_iter()
89 .map(|(k, v)| (k.into(), v.into()))
90 .collect(),
91 )
92 }
93}
94
95impl From<()> for Value {
96 fn from((): ()) -> Self {
97 Self::Null
98 }
99}