From 6967c6c80a44186a9aa6ae695cf5caf61d3901fd Mon Sep 17 00:00:00 2001 From: Laurenz Date: Fri, 18 Jun 2021 10:50:08 +0200 Subject: [PATCH] Len function for strings, arrays and dictionaries --- src/library/basic.rs | 14 ++++++++++++++ src/library/mod.rs | 1 + tests/typ/utility/basics.typ | 16 ++++++++++++++++ tests/typ/utility/{calc.typ => math.typ} | 2 +- 4 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 tests/typ/utility/basics.typ rename tests/typ/utility/{calc.typ => math.typ} (88%) diff --git a/src/library/basic.rs b/src/library/basic.rs index a094f039d..333416b4d 100644 --- a/src/library/basic.rs +++ b/src/library/basic.rs @@ -31,6 +31,20 @@ pub fn repr(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value { } } +/// `len`: The length of a string, an array or a dictionary. +pub fn len(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value { + match args.eat_expect::>(ctx, "collection") { + Some(Spanned { v: Value::Str(v), .. }) => Value::Int(v.len() as i64), + Some(Spanned { v: Value::Array(v), .. }) => Value::Int(v.len() as i64), + Some(Spanned { v: Value::Dict(v), .. }) => Value::Int(v.len() as i64), + Some(other) if other.v != Value::Error => { + ctx.diag(error!(other.span, "expected string, array or dictionary")); + Value::Error + } + _ => Value::Error, + } +} + /// `rgb`: Create an RGB(A) color. /// /// # Positional parameters diff --git a/src/library/mod.rs b/src/library/mod.rs index 0536eaa19..6c7360813 100644 --- a/src/library/mod.rs +++ b/src/library/mod.rs @@ -56,6 +56,7 @@ pub fn new() -> Scope { std.def_func("h", h); std.def_func("image", image); std.def_func("lang", lang); + std.def_func("len", len); std.def_func("max", max); std.def_func("min", min); std.def_func("overline", overline); diff --git a/tests/typ/utility/basics.typ b/tests/typ/utility/basics.typ new file mode 100644 index 000000000..75e06413b --- /dev/null +++ b/tests/typ/utility/basics.typ @@ -0,0 +1,16 @@ +// Test basic functions. +// Ref: false + +--- +// Test the `len` function. + +#test(len(()), 0) +#test(len(("A", "B", "C")), 3) +#test(len("Hello World!"), 12) +#test(len((a: 1, b: 2)), 2) + +// Error: 6 missing argument: collection +#len() + +// Error: 6-10 expected string, array or dictionary +#len(12pt) diff --git a/tests/typ/utility/calc.typ b/tests/typ/utility/math.typ similarity index 88% rename from tests/typ/utility/calc.typ rename to tests/typ/utility/math.typ index 3bfc98024..db234d9c0 100644 --- a/tests/typ/utility/calc.typ +++ b/tests/typ/utility/math.typ @@ -1,4 +1,4 @@ -// Test basic calculation functions. +// Test math functions. // Ref: false ---