Bounds checking macro for builtin functions

This commit is contained in:
ConnorSkees 2020-02-16 15:14:14 -05:00
parent fcb5069f82
commit 5f59c71752
3 changed files with 16 additions and 2 deletions

View File

@ -88,7 +88,7 @@ pub(crate) fn register(f: &mut BTreeMap<String, Builtin>) {
v => return Err(format!("$color: {} is not a color.", v).into()), v => return Err(format!("$color: {} is not a color.", v).into()),
}; };
let amount = match arg!(args, 1, "amount").eval() { let amount = match arg!(args, 1, "amount").eval() {
Value::Dimension(n, _) => n / Number::from(100), Value::Dimension(n, u) => bound!(n, u, 0, 100) / Number::from(100),
v => return Err(format!("$amount: {} is not a number.", v).into()) v => return Err(format!("$amount: {} is not a number.", v).into())
}; };
Ok(Value::Color(color.lighten(amount))) Ok(Value::Color(color.lighten(amount)))

View File

@ -46,3 +46,17 @@ macro_rules! max_args {
} }
}; };
} }
macro_rules! bound {
($arg:ident, $unit:ident, $low:literal, $high:literal) => {
if $arg > Number::from($high) || $arg < Number::from($low) {
return Err(format!(
"Expected {}{} to be within {}{} and {}{}.",
$arg, $unit, $low, $unit, $high, $unit,
)
.into());
} else {
$arg
}
};
}