Skip to main content

config_lib/
convert.rs

1//! `TryFrom<Value>` and `TryFrom<&Value>` for plain Rust types.
2//!
3//! These impls are what make [`Config::get_or`](crate::Config::get_or)
4//! work with ordinary types:
5//!
6//! ```rust
7//! use config_lib::Config;
8//!
9//! # fn main() -> Result<(), config_lib::Error> {
10//! let config = Config::from_string("port = 8080\ndebug = true", None)?;
11//!
12//! let port: u16 = config.get_or("port", 3000);
13//! let debug = config.get_or("debug", false);
14//! let workers: usize = config.get_or("workers", 4); // missing, so the default
15//!
16//! assert_eq!(port, 8080);
17//! assert!(debug);
18//! assert_eq!(workers, 4);
19//! # Ok(())
20//! # }
21//! ```
22//!
23//! Conversion rules:
24//!
25//! - Integer types (`i8` to `i64`, `isize`, `u8` to `u64`, `usize`)
26//!   accept an integer value, a float with no fractional part, or a string
27//!   that parses as the target type. The result is range-checked: `70000`
28//!   does not convert to `u16`, and `8080.5` does not convert to any
29//!   integer type.
30//! - `f64` follows [`Value::as_float`]: a float, an integer, or a string
31//!   that parses as a float.
32//! - `bool` follows [`Value::as_bool`]: a boolean, or one of the strings
33//!   `true`/`false`, `yes`/`no`, `on`/`off`, `1`/`0` (any case).
34//! - `String` accepts a string value only.
35//!
36//! A failed conversion returns [`Error::Type`](crate::Error::Type).
37
38use crate::error::{Error, Result};
39use crate::value::Value;
40
41/// The `i64` range as floats (`-2^63` inclusive, `2^63` exclusive), checked
42/// before a float is cast to `i64`. Both bounds are exact in `f64`.
43const I64_UPPER_EXCLUSIVE: f64 = 9_223_372_036_854_775_808.0; // 2^63
44const I64_LOWER_INCLUSIVE: f64 = -9_223_372_036_854_775_808.0; // -2^63
45
46fn integer_from(value: &Value, type_name: &'static str) -> Result<i64> {
47    match value {
48        Value::Integer(i) => Ok(*i),
49        Value::Float(f)
50            if f.is_finite()
51                && f.fract() == 0.0
52                && *f >= I64_LOWER_INCLUSIVE
53                && *f < I64_UPPER_EXCLUSIVE =>
54        {
55            Ok(*f as i64)
56        }
57        Value::Float(_) => Err(Error::type_error(
58            "float with a fractional part or out of range",
59            type_name,
60            value.type_name(),
61        )),
62        _ => Err(Error::type_error(
63            format!("Cannot convert to {type_name}"),
64            type_name,
65            value.type_name(),
66        )),
67    }
68}
69
70macro_rules! impl_try_from_integer {
71    ($($ty:ty),* $(,)?) => {
72        $(
73            impl TryFrom<&Value> for $ty {
74                type Error = Error;
75
76                fn try_from(value: &Value) -> Result<Self> {
77                    let name = stringify!($ty);
78                    if let Value::String(s) = value {
79                        return s.parse::<$ty>().map_err(|_| {
80                            Error::type_error(
81                                format!("string is not a valid {name}"),
82                                name,
83                                value.type_name(),
84                            )
85                        });
86                    }
87                    let wide = integer_from(value, name)?;
88                    <$ty>::try_from(wide).map_err(|_| {
89                        Error::type_error(
90                            format!("{wide} is out of range for {name}"),
91                            name,
92                            value.type_name(),
93                        )
94                    })
95                }
96            }
97
98            impl TryFrom<Value> for $ty {
99                type Error = Error;
100
101                fn try_from(value: Value) -> Result<Self> {
102                    <$ty>::try_from(&value)
103                }
104            }
105        )*
106    };
107}
108
109impl_try_from_integer!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
110
111impl TryFrom<&Value> for bool {
112    type Error = Error;
113
114    fn try_from(value: &Value) -> Result<Self> {
115        value.as_bool()
116    }
117}
118
119impl TryFrom<Value> for bool {
120    type Error = Error;
121
122    fn try_from(value: Value) -> Result<Self> {
123        value.as_bool()
124    }
125}
126
127impl TryFrom<&Value> for f64 {
128    type Error = Error;
129
130    fn try_from(value: &Value) -> Result<Self> {
131        value.as_float()
132    }
133}
134
135impl TryFrom<Value> for f64 {
136    type Error = Error;
137
138    fn try_from(value: Value) -> Result<Self> {
139        value.as_float()
140    }
141}
142
143impl TryFrom<&Value> for String {
144    type Error = Error;
145
146    fn try_from(value: &Value) -> Result<Self> {
147        value.as_string().map(str::to_owned)
148    }
149}
150
151impl TryFrom<Value> for String {
152    type Error = Error;
153
154    fn try_from(value: Value) -> Result<Self> {
155        match value {
156            Value::String(s) => Ok(s),
157            other => other.as_string().map(str::to_owned),
158        }
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn integers_are_range_checked() {
168        assert_eq!(u16::try_from(Value::Integer(8080)).unwrap(), 8080);
169        assert!(u16::try_from(Value::Integer(70_000)).is_err());
170        assert!(u8::try_from(Value::Integer(-1)).is_err());
171        assert_eq!(i8::try_from(Value::Integer(-128)).unwrap(), -128);
172        assert!(i8::try_from(Value::Integer(-129)).is_err());
173        assert_eq!(usize::try_from(Value::Integer(4)).unwrap(), 4);
174    }
175
176    #[test]
177    fn integers_from_floats_must_be_whole() {
178        assert_eq!(i64::try_from(Value::Float(8080.0)).unwrap(), 8080);
179        assert!(i64::try_from(Value::Float(8080.5)).is_err());
180        assert!(i64::try_from(Value::Float(f64::NAN)).is_err());
181        assert!(i64::try_from(Value::Float(f64::INFINITY)).is_err());
182        assert!(i64::try_from(Value::Float(1e19)).is_err());
183        assert_eq!(
184            i64::try_from(Value::Float(-9_223_372_036_854_775_808.0)).unwrap(),
185            i64::MIN
186        );
187    }
188
189    #[test]
190    fn integers_from_strings_parse_into_the_target_type() {
191        assert_eq!(u16::try_from(Value::from("443")).unwrap(), 443);
192        assert!(u16::try_from(Value::from("65536")).is_err());
193        assert!(u16::try_from(Value::from("port")).is_err());
194        assert_eq!(
195            u64::try_from(Value::from("18446744073709551615")).unwrap(),
196            u64::MAX
197        );
198    }
199
200    #[test]
201    fn integers_refuse_other_types() {
202        assert!(i64::try_from(Value::Bool(true)).is_err());
203        assert!(i64::try_from(Value::Null).is_err());
204        assert!(i64::try_from(Value::Array(vec![])).is_err());
205    }
206
207    #[test]
208    fn bool_float_and_string() {
209        assert!(bool::try_from(Value::Bool(true)).unwrap());
210        assert!(!bool::try_from(Value::from("off")).unwrap());
211        assert!(bool::try_from(Value::Integer(1)).is_err());
212
213        assert_eq!(f64::try_from(Value::Float(1.5)).unwrap(), 1.5);
214        assert_eq!(f64::try_from(Value::Integer(2)).unwrap(), 2.0);
215        assert!(f64::try_from(Value::Bool(false)).is_err());
216
217        assert_eq!(String::try_from(Value::from("app")).unwrap(), "app");
218        assert_eq!(String::try_from(&Value::from("app")).unwrap(), "app");
219        assert!(String::try_from(Value::Integer(1)).is_err());
220    }
221
222    #[test]
223    fn errors_are_type_errors() {
224        let err = u16::try_from(Value::Integer(70_000)).unwrap_err();
225        assert!(matches!(err, Error::Type { .. }), "{err:?}");
226    }
227}