git.delta.rocks / jrsonnet / refs/commits / ff10378ddbc9

difftreelog

perf faster std.map

Yaroslav Bolyukin2021-02-20parent: #643b007.patch.diff
in: master

3 files changed

modifiedcrates/jrsonnet-evaluator/build.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/build.rs
+++ b/crates/jrsonnet-evaluator/build.rs
@@ -40,7 +40,7 @@
 								name == "base64" || name == "foldl" || name == "foldr" ||
 								name == "sortImpl" || name == "format" || name == "range" ||
 								name == "reverse" || name == "slice" || name == "mod" ||
-								name == "strReplace"
+								name == "strReplace" || name == "map"
 							)
 						})
 						.collect(),
modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -57,6 +57,7 @@
 			("extVar".into(), builtin_ext_var),
 			("native".into(), builtin_native),
 			("filter".into(), builtin_filter),
+			("map".into(), builtin_map),
 			("foldl".into(), builtin_foldl),
 			("foldr".into(), builtin_foldr),
 			("sortImpl".into(), builtin_sort_impl),
@@ -294,16 +295,19 @@
 		0, func: ty!(function) => Val::Func;
 		1, arr: ty!(array) => Val::Arr;
 	], {
-		let mut out = Vec::new();
-		for item in arr.iter() {
-			let item = item?;
-			if func
-						.evaluate_values(context.clone(), &[item.clone()])?
-						.try_cast_bool("filter predicate")? {
-							out.push(item);
-						}
-		}
-		Ok(Val::Arr(out.into()))
+		Ok(Val::Arr(arr.filter(|val| func
+			.evaluate_values(context.clone(), &[val.clone()])?
+			.try_cast_bool("filter predicate"))?))
+	})
+}
+
+fn builtin_map(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+	parse_args!(context, "map", args, 2, [
+		0, func: ty!(function) => Val::Func;
+		1, arr: ty!(array) => Val::Arr;
+	], {
+		Ok(Val::Arr(arr.map(|val| func
+			.evaluate_values(context.clone(), &[val]))?))
 	})
 }
 
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
283 }283 }
284 }284 }
285
286 pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {
287 let mut out = Vec::with_capacity(self.len());
288
289 for value in self.iter() {
290 out.push(mapper(value?)?);
291 }
292
293 Ok(Self::Eager(Rc::new(out)))
294 }
295
296 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {
297 let mut out = Vec::with_capacity(self.len());
298
299 for value in self.iter() {
300 let value = value?;
301 if filter(&value)? {
302 out.push(value);
303 }
304 }
305
306 Ok(Self::Eager(Rc::new(out)))
307 }
285308
286 pub fn ptr_eq(a: &Self, b: &Self) -> bool {309 pub fn ptr_eq(a: &Self, b: &Self) -> bool {
287 match (a, b) {310 match (a, b) {