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, the integers `1` and
33//!   `0`, or one of the strings `true`/`false`, `yes`/`no`, `on`/`off`,
34//!   `1`/`0` (any case).
35//! - `String` accepts a string value only.
36//!
37//! A failed conversion returns [`Error::Type`](crate::Error::Type).
38
39use crate::error::{Error, Result};
40use crate::value::Value;
41
42/// The `i64` range as floats (`-2^63` inclusive, `2^63` exclusive), checked
43/// before a float is cast to `i64`. Both bounds are exact in `f64`.
44const I64_UPPER_EXCLUSIVE: f64 = 9_223_372_036_854_775_808.0; // 2^63
45const I64_LOWER_INCLUSIVE: f64 = -9_223_372_036_854_775_808.0; // -2^63
46
47pub(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        // 1 and 0 read as booleans (INI and environment values are
213        // integers since v1.4.0); other integers do not
214        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}