oxblade 0.2.0

Laravel Blade templates for Rust: Blade's markup and directives with Rust expressions, rendering the same HTML as Laravel. Community package, not affiliated with Laravel.
Documentation
use crate::{
    error::Result,
    library::{fault, integer},
    value::{Arg, Object, Value, expansion_error},
};

#[derive(Clone, Copy, Debug)]
pub(super) struct Range {
    first: i128,
    stride: i128,
    count: i128,
}

impl Range {
    pub(super) fn new(start: Option<i64>, end: Option<i64>, inclusive: bool) -> Result<Self> {
        let start =
            i128::from(start.ok_or_else(|| fault("iterable range requires a lower endpoint"))?);
        let end =
            i128::from(end.ok_or_else(|| fault("iterable range requires an upper endpoint"))?);
        Ok(Self {
            first: start,
            stride: 1,
            count: (end - start + i128::from(inclusive)).max(0),
        })
    }

    fn step(self, step: i64) -> Result<Self> {
        let step = i128::from(step);
        if step <= 0 {
            return Err(fault("step_by requires a positive step"));
        }
        let count = (self.count + step - 1) / step;
        let stride = if count > 1 {
            self.stride * step
        } else {
            self.stride
        };
        Ok(Self {
            stride,
            count,
            ..self
        })
    }

    fn reverse(self) -> Self {
        Self {
            first: self.first + self.stride * (self.count - 1).max(0),
            stride: -self.stride,
            ..self
        }
    }
}

impl<'a> Object<'a> for Range {
    fn type_name(&self) -> &'static str {
        "range"
    }

    fn method(&self, name: &str, args: Vec<Arg<'a, '_>>) -> Option<Result<Value<'a>>> {
        Some(match (name, args.as_slice()) {
            ("step_by", [Arg::Value(step)]) => integer(step)
                .and_then(|step| self.step(step))
                .map(Value::object),
            ("rev", []) => Ok(Value::object(self.reverse())),
            _ => return None,
        })
    }

    fn entries(&self, limit: usize) -> Result<Vec<(Value<'a>, Value<'a>)>> {
        if self.count > limit as i128 {
            return Err(expansion_error());
        }
        Ok((0..self.count)
            .map(|offset| {
                (
                    Value::Int(offset as i64),
                    Value::Int((self.first + self.stride * offset) as i64),
                )
            })
            .collect())
    }
}