Skip to main content

glacier/
values.rs

1//! Values as `.glacier` reads them: `a || b`, Ruby's "a, or else b", and
2//! Ruby's conversions, `to_s`, `to_i` and `to_f`.
3//!
4//! ```
5//! let name: Option<String> = None;
6//! assert_eq!(glacier::or_else!(name, "Anonymous"), "Anonymous");
7//! let nickname = Some("Ada".to_owned());
8//! assert_eq!(glacier::or_else!(nickname, "Anonymous"), "Ada");
9//! assert!(glacier::or_else!(false, true));
10//! let per_page: i64 = glacier::or_else!("x".parse::<i64>(), 25);
11//! assert_eq!(per_page, 25);
12//! ```
13//!
14//! In `.glacier`, `name || "Anonymous"` compiles to [`or_else!`](crate::or_else).
15//!
16//! ```
17//! use glacier::prelude::*;
18//! assert_eq!(42.to_s(), "42");
19//! assert_eq!("12 books".to_i(), 12);
20//! assert_eq!("none".to_i(), 0);
21//! assert_eq!(" -3.5kg".to_f(), -3.5);
22//! assert_eq!(7.to_f(), 7.0);
23//! assert_eq!(7.9.to_i(), 7);
24//! ```
25
26/// A list of values, as Ruby's and Elixir's: `Array<String>`,
27/// `Array.new()`. It's Rust's `Vec`, by the name Ruby uses; `Vec` works
28/// too, and the two are the same type.
29pub type Array<T> = Vec<T>;
30
31/// What `||` falls through: `false`, `None` and an `Err`.
32pub trait Truthy {
33    /// What a value that isn't `false` or `None` gives: `true`, or the
34    /// `Option`'s value.
35    type Value;
36    /// `None` for `false` and `None`.
37    fn truthy(self) -> Option<Self::Value>;
38}
39
40impl Truthy for bool {
41    type Value = bool;
42    fn truthy(self) -> Option<bool> {
43        self.then_some(true)
44    }
45}
46
47impl<T> Truthy for Option<T> {
48    type Value = T;
49    fn truthy(self) -> Option<T> {
50        self
51    }
52}
53
54/// An error falls through as `None` does, so `text.parse() || 10` is the
55/// number, or 10 when it isn't one. The error is dropped: use `!` or
56/// `case` where it matters.
57impl<T, E> Truthy for Result<T, E> {
58    type Value = T;
59    fn truthy(self) -> Option<T> {
60        self.ok()
61    }
62}
63
64/// `a || b` in `.glacier`: `a` unless it's `false` or `None` (an
65/// `Option`'s value when it has one), else `b`, which runs only then and
66/// is converted to `a`'s type (`Option<String> || "x"` is a `String`).
67#[macro_export]
68macro_rules! or_else {
69    // A literal fallback, which takes the value's type as it is.
70    ($a:expr, @value $b:expr) => {
71        match $crate::values::Truthy::truthy($a) {
72            ::core::option::Option::Some(__value) => __value,
73            ::core::option::Option::None => $b,
74        }
75    };
76    ($a:expr, $b:expr) => {
77        match $crate::values::Truthy::truthy($a) {
78            ::core::option::Option::Some(__value) => __value,
79            #[allow(clippy::useless_conversion)]
80            ::core::option::Option::None => ::core::convert::Into::into($b),
81        }
82    };
83}
84
85/// `x.to_s()`: anything that displays, as text (Ruby's `to_s`).
86pub trait ToS {
87    fn to_s(&self) -> String;
88}
89
90impl<T: std::fmt::Display + ?Sized> ToS for T {
91    fn to_s(&self) -> String {
92        self.to_string()
93    }
94}
95
96/// `x.to_i()`: a whole number, as Ruby's `to_i`. Text gives the number it
97/// starts with (`"12 books"` is 12, `"-3"` is -3) and 0 when it doesn't
98/// start with one, never an error; a float drops its fraction.
99pub trait ToI {
100    fn to_i(&self) -> i64;
101}
102
103/// `x.to_f()`: a float, as Ruby's `to_f`. Text gives the number it starts
104/// with (`"3.5kg"` is 3.5) and 0.0 when it doesn't start with one.
105pub trait ToF {
106    fn to_f(&self) -> f64;
107}
108
109/// The number `text` starts with, after any whitespace: its sign and
110/// digits, and with `fraction`, a `.` and more digits.
111fn leading_number(text: &str, fraction: bool) -> &str {
112    let text = text.trim_start();
113    let bytes = text.as_bytes();
114    let mut end = usize::from(matches!(bytes.first(), Some(b'-' | b'+')));
115    let digits = |from: usize| {
116        bytes[from..]
117            .iter()
118            .take_while(|b| b.is_ascii_digit())
119            .count()
120    };
121    let whole = digits(end);
122    end += whole;
123    if fraction && bytes.get(end) == Some(&b'.') {
124        let after = digits(end + 1);
125        if after > 0 {
126            end += 1 + after;
127        }
128    }
129    if whole == 0 && !text[..end].contains('.') {
130        return "";
131    }
132    &text[..end]
133}
134
135impl ToI for str {
136    fn to_i(&self) -> i64 {
137        leading_number(self, false).parse().unwrap_or(0)
138    }
139}
140
141impl ToF for str {
142    fn to_f(&self) -> f64 {
143        leading_number(self, true).parse().unwrap_or(0.0)
144    }
145}
146
147impl ToI for String {
148    fn to_i(&self) -> i64 {
149        self.as_str().to_i()
150    }
151}
152
153impl ToF for String {
154    fn to_f(&self) -> f64 {
155        self.as_str().to_f()
156    }
157}
158
159macro_rules! numbers {
160    ($($t:ty),*) => {$(
161        impl ToI for $t {
162            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_lossless)]
163            fn to_i(&self) -> i64 {
164                *self as i64
165            }
166        }
167        impl ToF for $t {
168            #[allow(clippy::cast_precision_loss, clippy::cast_lossless)]
169            fn to_f(&self) -> f64 {
170                *self as f64
171            }
172        }
173    )*};
174}
175
176numbers!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64);
177
178impl<T: ToI + ?Sized> ToI for &T {
179    fn to_i(&self) -> i64 {
180        (**self).to_i()
181    }
182}
183
184impl<T: ToF + ?Sized> ToF for &T {
185    fn to_f(&self) -> f64 {
186        (**self).to_f()
187    }
188}
189
190/// `nil.to_i` is 0 in Ruby, and `nil.to_s` is `""`; so a missing value
191/// converts to its zero.
192impl<T: ToI> ToI for Option<T> {
193    fn to_i(&self) -> i64 {
194        self.as_ref().map_or(0, ToI::to_i)
195    }
196}
197
198impl<T: ToF> ToF for Option<T> {
199    fn to_f(&self) -> f64 {
200        self.as_ref().map_or(0.0, ToF::to_f)
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn text_gives_the_number_it_starts_with() {
210        assert_eq!("42".to_i(), 42);
211        assert_eq!("  +7 days".to_i(), 7);
212        assert_eq!("-12.9".to_i(), -12);
213        assert_eq!("abc".to_i(), 0);
214        assert_eq!("".to_i(), 0);
215        assert_eq!("-".to_i(), 0);
216        assert_eq!("3.25 kg".to_f(), 3.25);
217        assert_eq!("3.".to_f(), 3.0);
218        assert_eq!(".5".to_f(), 0.5);
219        assert_eq!(".".to_f(), 0.0);
220        assert_eq!("x".to_f(), 0.0);
221        assert_eq!(Some("8").to_i(), 8);
222        assert_eq!(None::<&str>.to_i(), 0);
223        assert_eq!(String::from("9").to_i(), 9);
224    }
225}