git.delta.rocks / jrsonnet / refs/commits / 364fdf96177a

difftreelog

source

crates/jrsonnet-stdlib/src/keyf.rs1.0 KiBsourcehistory
1use jrsonnet_evaluator::{2	Error, Result, Thunk, Val,3	function::{CallLocation, FuncVal, PreparedFuncVal},4	typed::{ComplexValType, FromUntyped, Typed, ValType},5};67#[derive(Default, Clone)]8pub enum KeyF {9	#[default]10	Identity,11	Prepared(PreparedFuncVal),12	PrepareFailure(Error),13}14impl KeyF {15	pub fn is_identity(&self) -> bool {16		matches!(self, Self::Identity)17	}18	fn new(val: FuncVal) -> Self {19		if val.is_identity() {20			Self::Identity21		} else {22			PreparedFuncVal::new(val, 1, &[]).map_or_else(Self::PrepareFailure, Self::Prepared)23		}24	}25	pub fn eval(&self, val: impl Into<Thunk<Val>>) -> Result<Val> {26		match self {27			KeyF::Identity => val.into().evaluate(),28			KeyF::Prepared(p) => p.call(CallLocation::native(), &[val.into()], &[]),29			KeyF::PrepareFailure(e) => Err(e.clone()),30		}31	}32}3334impl Typed for KeyF {35	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);36}37impl FromUntyped for KeyF {38	fn from_untyped(untyped: Val) -> Result<Self> {39		FuncVal::from_untyped(untyped).map(Self::new)40	}41}