glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Values as `.glacier` reads them: `a || b`, Ruby's "a, or else b", and
//! Ruby's conversions, `to_s`, `to_i` and `to_f`.
//!
//! ```
//! let name: Option<String> = None;
//! assert_eq!(glacier::or_else!(name, "Anonymous"), "Anonymous");
//! let nickname = Some("Ada".to_owned());
//! assert_eq!(glacier::or_else!(nickname, "Anonymous"), "Ada");
//! assert!(glacier::or_else!(false, true));
//! let per_page: i64 = glacier::or_else!("x".parse::<i64>(), 25);
//! assert_eq!(per_page, 25);
//! ```
//!
//! In `.glacier`, `name || "Anonymous"` compiles to [`or_else!`](crate::or_else).
//!
//! ```
//! use glacier::prelude::*;
//! assert_eq!(42.to_s(), "42");
//! assert_eq!("12 books".to_i(), 12);
//! assert_eq!("none".to_i(), 0);
//! assert_eq!(" -3.5kg".to_f(), -3.5);
//! assert_eq!(7.to_f(), 7.0);
//! assert_eq!(7.9.to_i(), 7);
//! ```

/// A list of values, as Ruby's and Elixir's: `Array<String>`,
/// `Array.new()`. It's Rust's `Vec`, by the name Ruby uses; `Vec` works
/// too, and the two are the same type.
pub type Array<T> = Vec<T>;

/// What `||` falls through: `false`, `None` and an `Err`.
pub trait Truthy {
    /// What a value that isn't `false` or `None` gives: `true`, or the
    /// `Option`'s value.
    type Value;
    /// `None` for `false` and `None`.
    fn truthy(self) -> Option<Self::Value>;
}

impl Truthy for bool {
    type Value = bool;
    fn truthy(self) -> Option<bool> {
        self.then_some(true)
    }
}

impl<T> Truthy for Option<T> {
    type Value = T;
    fn truthy(self) -> Option<T> {
        self
    }
}

/// An error falls through as `None` does, so `text.parse() || 10` is the
/// number, or 10 when it isn't one. The error is dropped: use `!` or
/// `case` where it matters.
impl<T, E> Truthy for Result<T, E> {
    type Value = T;
    fn truthy(self) -> Option<T> {
        self.ok()
    }
}

/// `a || b` in `.glacier`: `a` unless it's `false` or `None` (an
/// `Option`'s value when it has one), else `b`, which runs only then and
/// is converted to `a`'s type (`Option<String> || "x"` is a `String`).
#[macro_export]
macro_rules! or_else {
    // A literal fallback, which takes the value's type as it is.
    ($a:expr, @value $b:expr) => {
        match $crate::values::Truthy::truthy($a) {
            ::core::option::Option::Some(__value) => __value,
            ::core::option::Option::None => $b,
        }
    };
    ($a:expr, $b:expr) => {
        match $crate::values::Truthy::truthy($a) {
            ::core::option::Option::Some(__value) => __value,
            #[allow(clippy::useless_conversion)]
            ::core::option::Option::None => ::core::convert::Into::into($b),
        }
    };
}

/// `x.to_s()`: anything that displays, as text (Ruby's `to_s`).
pub trait ToS {
    fn to_s(&self) -> String;
}

impl<T: std::fmt::Display + ?Sized> ToS for T {
    fn to_s(&self) -> String {
        self.to_string()
    }
}

/// `x.to_i()`: a whole number, as Ruby's `to_i`. Text gives the number it
/// starts with (`"12 books"` is 12, `"-3"` is -3) and 0 when it doesn't
/// start with one, never an error; a float drops its fraction.
pub trait ToI {
    fn to_i(&self) -> i64;
}

/// `x.to_f()`: a float, as Ruby's `to_f`. Text gives the number it starts
/// with (`"3.5kg"` is 3.5) and 0.0 when it doesn't start with one.
pub trait ToF {
    fn to_f(&self) -> f64;
}

/// The number `text` starts with, after any whitespace: its sign and
/// digits, and with `fraction`, a `.` and more digits.
fn leading_number(text: &str, fraction: bool) -> &str {
    let text = text.trim_start();
    let bytes = text.as_bytes();
    let mut end = usize::from(matches!(bytes.first(), Some(b'-' | b'+')));
    let digits = |from: usize| {
        bytes[from..]
            .iter()
            .take_while(|b| b.is_ascii_digit())
            .count()
    };
    let whole = digits(end);
    end += whole;
    if fraction && bytes.get(end) == Some(&b'.') {
        let after = digits(end + 1);
        if after > 0 {
            end += 1 + after;
        }
    }
    if whole == 0 && !text[..end].contains('.') {
        return "";
    }
    &text[..end]
}

impl ToI for str {
    fn to_i(&self) -> i64 {
        leading_number(self, false).parse().unwrap_or(0)
    }
}

impl ToF for str {
    fn to_f(&self) -> f64 {
        leading_number(self, true).parse().unwrap_or(0.0)
    }
}

impl ToI for String {
    fn to_i(&self) -> i64 {
        self.as_str().to_i()
    }
}

impl ToF for String {
    fn to_f(&self) -> f64 {
        self.as_str().to_f()
    }
}

macro_rules! numbers {
    ($($t:ty),*) => {$(
        impl ToI for $t {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_lossless)]
            fn to_i(&self) -> i64 {
                *self as i64
            }
        }
        impl ToF for $t {
            #[allow(clippy::cast_precision_loss, clippy::cast_lossless)]
            fn to_f(&self) -> f64 {
                *self as f64
            }
        }
    )*};
}

numbers!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64);

impl<T: ToI + ?Sized> ToI for &T {
    fn to_i(&self) -> i64 {
        (**self).to_i()
    }
}

impl<T: ToF + ?Sized> ToF for &T {
    fn to_f(&self) -> f64 {
        (**self).to_f()
    }
}

/// `nil.to_i` is 0 in Ruby, and `nil.to_s` is `""`; so a missing value
/// converts to its zero.
impl<T: ToI> ToI for Option<T> {
    fn to_i(&self) -> i64 {
        self.as_ref().map_or(0, ToI::to_i)
    }
}

impl<T: ToF> ToF for Option<T> {
    fn to_f(&self) -> f64 {
        self.as_ref().map_or(0.0, ToF::to_f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn text_gives_the_number_it_starts_with() {
        assert_eq!("42".to_i(), 42);
        assert_eq!("  +7 days".to_i(), 7);
        assert_eq!("-12.9".to_i(), -12);
        assert_eq!("abc".to_i(), 0);
        assert_eq!("".to_i(), 0);
        assert_eq!("-".to_i(), 0);
        assert_eq!("3.25 kg".to_f(), 3.25);
        assert_eq!("3.".to_f(), 3.0);
        assert_eq!(".5".to_f(), 0.5);
        assert_eq!(".".to_f(), 0.0);
        assert_eq!("x".to_f(), 0.0);
        assert_eq!(Some("8").to_i(), 8);
        assert_eq!(None::<&str>.to_i(), 0);
        assert_eq!(String::from("9").to_i(), 9);
    }
}