1use crate::core::{EString, ParseFragment, ToEString};
2use crate::error::{Error, Reason};
3
4#[doc(hidden)]
5macro_rules! from_env_string_numbers_impl {
6 ($($ty:ty),+$(,)?) => {
7 $(
8 impl ParseFragment for $ty {
9 #[inline]
10 fn parse_frag(s: EString) -> crate::Result<Self> {
11 s.0.parse::<Self>().map_err(|_| Error(s, Reason::Parse))
12 }
13 }
14
15 impl ToEString for $ty {
16 #[inline]
17 fn to_estring(&self) -> EString {
18 EString(self.to_string())
19 }
20 }
21
22 #[cfg(feature = "aggs")]
23 impl crate::core::Aggregatable for $ty {
24 type Item = Self;
25
26 #[inline]
27 fn items(self) -> Vec<Self::Item> {
28 vec![self]
29 }
30 }
31 )+
32 };
33}
34
35#[rustfmt::skip]
36from_env_string_numbers_impl![
37 i8, i16, i32, i64, i128, isize,
38 u8, u16, u32, u64, u128, usize,
39 f32, f64
40];
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45
46 #[test]
47 fn should_parse_number() {
48 let estr = EString::from("-10");
49 match estr.parse::<i32>() {
50 Ok(res) => assert_eq!(res, -10),
51 _ => unreachable!(),
52 };
53 }
54
55 #[test]
56 fn should_parse_float_number() {
57 let estr = EString::from("-0.15");
58 match estr.parse::<f32>() {
59 #[allow(clippy::float_cmp)]
60 Ok(res) => assert_eq!(res, -0.15),
61 _ => unreachable!(),
62 };
63 }
64
65 #[test]
66 fn should_throw_parse_error() {
67 let estr = EString::from("-10");
68 match estr.parse::<u32>() {
69 Err(Error(orig, reason)) => {
70 assert_eq!(orig, EString::from("-10"));
71 assert_eq!(reason, Reason::Parse);
72 }
73 _ => unreachable!(),
74 };
75 }
76
77 #[test]
78 fn should_format_number() {
79 assert_eq!((-1).to_estring(), EString(String::from("-1")));
80 assert_eq!(10.to_estring(), EString(String::from("10")));
81 assert_eq!(1.1.to_estring(), EString(String::from("1.1")));
82 }
83}