From 970fbe703e95430fd861d170e4f3146a46c066b0 Mon Sep 17 00:00:00 2001 From: Yaroslav Bolyukin Date: Tue, 12 Jan 2021 03:55:27 +0000 Subject: [PATCH] perf: faster strReplace --- --- a/crates/jrsonnet-evaluator/build.rs +++ b/crates/jrsonnet-evaluator/build.rs @@ -39,7 +39,8 @@ name == "escapeStringJson" || name == "equals" || name == "base64" || name == "foldl" || name == "foldr" || name == "sortImpl" || name == "format" || name == "range" || - name == "reverse" || name == "slice" || name == "mod" + name == "reverse" || name == "slice" || name == "mod" || + name == "strReplace" ) }) .collect(), --- a/crates/jrsonnet-evaluator/src/builtin/mod.rs +++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs @@ -73,6 +73,7 @@ ("manifestJsonEx".into(), builtin_manifest_json_ex), ("reverse".into(), builtin_reverse), ("id".into(), builtin_id), + ("strReplace".into(), builtin_str_replace), ].iter().cloned().collect() }; } @@ -131,7 +132,7 @@ parse_args!(context, "codepoint", args, 1, [ 0, str: ty!(char) => Val::Str; ], { - Ok(Val::Num(str.chars().take(1).next().unwrap() as u32 as f64)) + Ok(Val::Num(str.chars().next().unwrap() as u32 as f64)) }) } @@ -557,6 +558,28 @@ }) } +// faster +fn builtin_str_replace(context: Context, _loc: &Option, args: &ArgsDesc) -> Result { + parse_args!(context, "strReplace", args, 3, [ + 0, str: ty!(string) => Val::Str; + 1, from: ty!(string) => Val::Str; + 2, to: ty!(string) => Val::Str; + ], { + let mut out = String::new(); + let mut last_idx = 0; + while let Some(idx) = (&str[last_idx..]).find(&from as &str) { + out.push_str(&str[last_idx..last_idx+idx]); + out.push_str(&to); + last_idx += idx + from.len(); + } + if last_idx == 0 { + return Ok(Val::Str(str)) + } + out.push_str(&str[last_idx..]); + Ok(Val::Str(out.into())) + }) +} + #[allow(clippy::cognitive_complexity)] pub fn call_builtin( context: Context, -- gitstuff