--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs +++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs @@ -121,6 +121,7 @@ ("reverse".into(), builtin_reverse), ("id".into(), builtin_id), ("strReplace".into(), builtin_str_replace), + ("splitLimit".into(), builtin_splitlimit), ("parseJson".into(), builtin_parse_json), ].iter().cloned().collect() }; @@ -751,6 +752,29 @@ }) } +fn builtin_splitlimit( + context: Context, + _loc: Option<&ExprLocation>, + args: &ArgsDesc, +) -> Result { + parse_args!(context, "splitLimit", args, 3, [ + 0, str: ty!(string) => Val::Str; + 1, c: ty!(char) => Val::Str; + 2, maxsplits: ty!(number) => Val::Num; + ], { + let maxsplits = maxsplits as isize; + let c = c.chars().next().unwrap(); + + let out: Vec = if maxsplits == -1 { + str.split(c).map(|s| Val::Str(s.into())).collect() + } else { + str.splitn(maxsplits as usize + 1, c).map(|s| Val::Str(s.into())).collect() + }; + + Ok(Val::Arr(out.into())) + }) +} + pub fn call_builtin( context: Context, loc: Option<&ExprLocation>, --- a/crates/jrsonnet-stdlib/src/std.jsonnet +++ b/crates/jrsonnet-stdlib/src/std.jsonnet @@ -123,21 +123,7 @@ assert std.length(c) == 1 : 'std.split second parameter should have length 1, got ' + std.length(c); std.splitLimit(str, c, -1), - splitLimit(str, c, maxsplits):: - assert std.isString(str) : 'std.splitLimit first parameter should be a string, got ' + std.type(str); - assert std.isString(c) : 'std.splitLimit second parameter should be a string, got ' + std.type(c); - assert std.length(c) == 1 : 'std.splitLimit second parameter should have length 1, got ' + std.length(c); - assert std.isNumber(maxsplits) : 'std.splitLimit third parameter should be a number, got ' + std.type(maxsplits); - local aux(str, delim, i, arr, v) = - local c = str[i]; - local i2 = i + 1; - if i >= std.length(str) then - arr + [v] - else if c == delim && (maxsplits == -1 || std.length(arr) < maxsplits) then - aux(str, delim, i2, arr + [v], '') tailstrict - else - aux(str, delim, i2, arr, v + c) tailstrict; - aux(str, c, 0, [], ''), + splitLimit:: $intrinsic(splitLimit), strReplace:: $intrinsic(strReplace),