1use crate::error::{Error, Result};
40use crate::value::Value;
41
42const I64_UPPER_EXCLUSIVE: f64 = 9_223_372_036_854_775_808.0; const I64_LOWER_INCLUSIVE: f64 = -9_223_372_036_854_775_808.0; pub(crate) fn integer_from(value: &Value, type_name: &'static str) -> Result<i64> {
48 match value {
49 Value::Integer(i) => Ok(*i),
50 Value::Float(f)
51 if f.is_finite()
52 && f.fract() == 0.0
53 && *f >= I64_LOWER_INCLUSIVE
54 && *f < I64_UPPER_EXCLUSIVE =>
55 {
56 Ok(*f as i64)
57 }
58 Value::Float(_) => Err(Error::type_error(
59 "float with a fractional part or out of range",
60 type_name,
61 value.type_name(),
62 )),
63 _ => Err(Error::type_error(
64 format!("Cannot convert to {type_name}"),
65 type_name,
66 value.type_name(),
67 )),
68 }
69}
70
71macro_rules! impl_try_from_integer {
72 ($($ty:ty),* $(,)?) => {
73 $(
74 impl TryFrom<&Value> for $ty {
75 type Error = Error;
76
77 fn try_from(value: &Value) -> Result<Self> {
78 let name = stringify!($ty);
79 if let Value::String(s) = value {
80 return s.parse::<$ty>().map_err(|_| {
81 Error::type_error(
82 format!("string is not a valid {name}"),
83 name,
84 value.type_name(),
85 )
86 });
87 }
88 let wide = integer_from(value, name)?;
89 <$ty>::try_from(wide).map_err(|_| {
90 Error::type_error(
91 format!("{wide} is out of range for {name}"),
92 name,
93 value.type_name(),
94 )
95 })
96 }
97 }
98
99 impl TryFrom<Value> for $ty {
100 type Error = Error;
101
102 fn try_from(value: Value) -> Result<Self> {
103 <$ty>::try_from(&value)
104 }
105 }
106 )*
107 };
108}
109
110impl_try_from_integer!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
111
112impl TryFrom<&Value> for bool {
113 type Error = Error;
114
115 fn try_from(value: &Value) -> Result<Self> {
116 value.as_bool()
117 }
118}
119
120impl TryFrom<Value> for bool {
121 type Error = Error;
122
123 fn try_from(value: Value) -> Result<Self> {
124 value.as_bool()
125 }
126}
127
128impl TryFrom<&Value> for f64 {
129 type Error = Error;
130
131 fn try_from(value: &Value) -> Result<Self> {
132 value.as_float()
133 }
134}
135
136impl TryFrom<Value> for f64 {
137 type Error = Error;
138
139 fn try_from(value: Value) -> Result<Self> {
140 value.as_float()
141 }
142}
143
144impl TryFrom<&Value> for String {
145 type Error = Error;
146
147 fn try_from(value: &Value) -> Result<Self> {
148 value.as_string().map(str::to_owned)
149 }
150}
151
152impl TryFrom<Value> for String {
153 type Error = Error;
154
155 fn try_from(value: Value) -> Result<Self> {
156 match value {
157 Value::String(s) => Ok(s),
158 other => other.as_string().map(str::to_owned),
159 }
160 }
161}
162
163#[cfg(test)]
164mod tests {
165 use super::*;
166
167 #[test]
168 fn integers_are_range_checked() {
169 assert_eq!(u16::try_from(Value::Integer(8080)).unwrap(), 8080);
170 assert!(u16::try_from(Value::Integer(70_000)).is_err());
171 assert!(u8::try_from(Value::Integer(-1)).is_err());
172 assert_eq!(i8::try_from(Value::Integer(-128)).unwrap(), -128);
173 assert!(i8::try_from(Value::Integer(-129)).is_err());
174 assert_eq!(usize::try_from(Value::Integer(4)).unwrap(), 4);
175 }
176
177 #[test]
178 fn integers_from_floats_must_be_whole() {
179 assert_eq!(i64::try_from(Value::Float(8080.0)).unwrap(), 8080);
180 assert!(i64::try_from(Value::Float(8080.5)).is_err());
181 assert!(i64::try_from(Value::Float(f64::NAN)).is_err());
182 assert!(i64::try_from(Value::Float(f64::INFINITY)).is_err());
183 assert!(i64::try_from(Value::Float(1e19)).is_err());
184 assert_eq!(
185 i64::try_from(Value::Float(-9_223_372_036_854_775_808.0)).unwrap(),
186 i64::MIN
187 );
188 }
189
190 #[test]
191 fn integers_from_strings_parse_into_the_target_type() {
192 assert_eq!(u16::try_from(Value::from("443")).unwrap(), 443);
193 assert!(u16::try_from(Value::from("65536")).is_err());
194 assert!(u16::try_from(Value::from("port")).is_err());
195 assert_eq!(
196 u64::try_from(Value::from("18446744073709551615")).unwrap(),
197 u64::MAX
198 );
199 }
200
201 #[test]
202 fn integers_refuse_other_types() {
203 assert!(i64::try_from(Value::Bool(true)).is_err());
204 assert!(i64::try_from(Value::Null).is_err());
205 assert!(i64::try_from(Value::Array(vec![])).is_err());
206 }
207
208 #[test]
209 fn bool_float_and_string() {
210 assert!(bool::try_from(Value::Bool(true)).unwrap());
211 assert!(!bool::try_from(Value::from("off")).unwrap());
212 assert!(bool::try_from(Value::Integer(1)).unwrap());
215 assert!(!bool::try_from(Value::Integer(0)).unwrap());
216 assert!(bool::try_from(Value::Integer(2)).is_err());
217
218 assert_eq!(f64::try_from(Value::Float(1.5)).unwrap(), 1.5);
219 assert_eq!(f64::try_from(Value::Integer(2)).unwrap(), 2.0);
220 assert!(f64::try_from(Value::Bool(false)).is_err());
221
222 assert_eq!(String::try_from(Value::from("app")).unwrap(), "app");
223 assert_eq!(String::try_from(&Value::from("app")).unwrap(), "app");
224 assert!(String::try_from(Value::Integer(1)).is_err());
225 }
226
227 #[test]
228 fn errors_are_type_errors() {
229 let err = u16::try_from(Value::Integer(70_000)).unwrap_err();
230 assert!(matches!(err, Error::Type { .. }), "{err:?}");
231 }
232}