From c0ed9338506c118c0b3ad423af529957beb85835 Mon Sep 17 00:00:00 2001 From: ConnorSkees <39542938+ConnorSkees@users.noreply.github.com> Date: Sun, 22 Mar 2020 15:58:32 -0400 Subject: [PATCH] implement builtin function str-index --- src/builtin/string.rs | 20 ++++++++++++++++++++ tests/strings.rs | 11 +++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/builtin/string.rs b/src/builtin/string.rs index 8c13882..b77efcf 100644 --- a/src/builtin/string.rs +++ b/src/builtin/string.rs @@ -126,4 +126,24 @@ pub(crate) fn register(f: &mut HashMap) { } }), ); + f.insert( + "str-index".to_owned(), + Box::new(|args, _| { + max_args!(args, 2); + let s1 = match arg!(args, 0, "string") { + Value::Ident(i, _) => i, + v => return Err(format!("$string: {} is not a string.", v).into()), + }; + + let substr = match arg!(args, 1, "substring") { + Value::Ident(i, _) => i, + v => return Err(format!("$substring: {} is not a string.", v).into()), + }; + + Ok(match s1.find(&substr) { + Some(v) => Value::Dimension(Number::from(v + 1), Unit::None), + None => Value::Null, + }) + }), + ); } diff --git a/tests/strings.rs b/tests/strings.rs index 8c6523e..7f81ee4 100644 --- a/tests/strings.rs +++ b/tests/strings.rs @@ -103,3 +103,14 @@ test!( "a {\n color: str-length(\"foo bar\");\n}\n", "a {\n color: 7;\n}\n" ); +test!( + str_index_char, + "a {\n color: str-index(abcd, a);\n}\n", + "a {\n color: 1;\n}\n" +); +test!( + str_index_str, + "a {\n color: str-index(abcd, ab);\n}\n", + "a {\n color: 1;\n}\n" +); +test!(str_index_null, "a {\n color: str-index(abcd, X);\n}\n", "");