Implement builtin function str-length

This commit is contained in:
ConnorSkees 2020-02-08 20:38:37 -05:00
parent 07845beee9
commit 22670a7e4b
3 changed files with 32 additions and 6 deletions

View File

@ -1,7 +1,8 @@
use std::collections::BTreeMap;
use super::Builtin;
use crate::value::Value;
use crate::units::Unit;
use crate::value::{Number, Value};
pub(crate) fn register(f: &mut BTreeMap<String, Builtin>) {
decl!(f "to-upper-case", |args, _| {
@ -18,4 +19,11 @@ pub(crate) fn register(f: &mut BTreeMap<String, Builtin>) {
_ => todo!("")
}
});
decl!(f "str-length", |args, _| {
let s: &Value = arg!(args, 0, "string");
match s.eval() {
Value::Ident(i, _) => Some(Value::Dimension(Number::from(i.len()), Unit::None)),
_ => todo!("")
}
});
}

View File

@ -30,14 +30,22 @@ impl From<BigInt> for Number {
}
}
impl From<u16> for Number {
fn from(b: u16) -> Self {
Number {
val: BigRational::from_integer(BigInt::from(b)),
macro_rules! from_integer {
($ty:ty) => {
impl From<$ty> for Number {
fn from(b: $ty) -> Self {
Number {
val: BigRational::from_integer(BigInt::from(b)),
}
}
}
}
};
}
from_integer!(u16);
from_integer!(usize);
from_integer!(i32);
impl Display for Number {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.val.to_integer())?;

View File

@ -23,3 +23,13 @@ test!(
"a {\n color: to-lower-case($string: AbC123);\n}\n",
"a {\n color: abc123;\n}\n"
);
test!(
length_ident,
"a {\n color: str-length(AbC123);\n}\n",
"a {\n color: 6;\n}\n"
);
test!(
length_named_arg,
"a {\n color: str-length($string: aBc123);\n}\n",
"a {\n color: 6;\n}\n"
);