1use indexmap::IndexMap;
2use std::{
3 borrow::Cow,
4 path::Path,
5 string::{String, ToString},
6};
7use std::{ffi::OsString, path::PathBuf};
8
9use crate::{Function, Number, SerdeValue};
10
11macro_rules! from_integer {
12 ($($ty:ident)*) => {
13 $(
14 impl From<$ty> for SerdeValue {
15 fn from(n: $ty) -> Self {
16 SerdeValue::Number(n.into())
17 }
18 }
19 )*
20 };
21}
22
23from_integer! {
24 i8 i16 i32 i64 isize
25 u8 u16 u32 u64 usize
26 f32 f64
27}
28
29impl From<bool> for SerdeValue {
30 fn from(f: bool) -> Self {
31 SerdeValue::Boolean(f)
32 }
33}
34
35impl From<String> for SerdeValue {
36 fn from(f: String) -> Self {
37 SerdeValue::String(f)
38 }
39}
40
41impl<'a> From<&'a str> for SerdeValue {
42 fn from(f: &str) -> Self {
43 SerdeValue::String(f.to_string())
44 }
45}
46
47impl<'a> From<Cow<'a, str>> for SerdeValue {
48 fn from(f: Cow<'a, str>) -> Self {
49 SerdeValue::String(f.into_owned())
50 }
51}
52
53impl From<OsString> for SerdeValue {
54 fn from(from: OsString) -> Self {
55 SerdeValue::String(from.to_str().unwrap_or("unknown").to_string())
56 }
57}
58
59impl From<PathBuf> for SerdeValue {
60 fn from(from: PathBuf) -> Self {
61 SerdeValue::String(from.display().to_string())
62 }
63}
64
65impl From<&Path> for SerdeValue {
66 fn from(from: &Path) -> Self {
67 SerdeValue::String(from.display().to_string())
68 }
69}
70
71impl From<Number> for SerdeValue {
72 fn from(f: Number) -> Self {
73 SerdeValue::Number(f)
74 }
75}
76
77impl From<IndexMap<String, SerdeValue>> for SerdeValue {
78 fn from(f: IndexMap<String, SerdeValue>) -> Self {
79 SerdeValue::Object(f)
80 }
81}
82
83impl<T: Into<SerdeValue>> From<Vec<T>> for SerdeValue {
84 fn from(f: Vec<T>) -> Self {
85 SerdeValue::List(f.into_iter().map(Into::into).collect())
86 }
87}
88
89impl<'a, T: Clone + Into<SerdeValue>> From<&'a [T]> for SerdeValue {
90 fn from(f: &'a [T]) -> Self {
91 SerdeValue::List(f.iter().cloned().map(Into::into).collect())
92 }
93}
94
95impl<T: Into<SerdeValue>> FromIterator<T> for SerdeValue {
96 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
97 SerdeValue::List(iter.into_iter().map(Into::into).collect())
98 }
99}
100
101impl<K: Into<String>, V: Into<SerdeValue>> FromIterator<(K, V)> for SerdeValue {
102 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
103 SerdeValue::Object(
104 iter.into_iter()
105 .map(|(k, v)| (k.into(), v.into()))
106 .collect(),
107 )
108 }
109}
110
111impl From<Function> for SerdeValue {
112 fn from(function: Function) -> Self {
113 SerdeValue::Function(function)
114 }
115}
116
117impl From<()> for SerdeValue {
118 fn from((): ()) -> Self {
119 SerdeValue::Null
120 }
121}
122
123impl<T> From<Option<T>> for SerdeValue
124where
125 T: Into<SerdeValue>,
126{
127 fn from(opt: Option<T>) -> Self {
128 match opt {
129 None => SerdeValue::Null,
130 Some(value) => Into::into(value),
131 }
132 }
133}