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

difftreelog

source

crates/jrsonnet-stdlib/src/sort.rs2.8 KiBsourcehistory
1use jrsonnet_evaluator::{2	error::Result,3	function::{builtin, CallLocation, FuncVal},4	throw,5	val::ArrValue,6	Context, Val,7};89#[derive(Copy, Clone)]10enum SortKeyType {11	Number,12	String,13	Unknown,14}1516#[derive(PartialEq)]17struct NonNaNf64(f64);18impl PartialOrd for NonNaNf64 {19	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {20		self.0.partial_cmp(&other.0)21	}22}23impl Eq for NonNaNf64 {}24impl Ord for NonNaNf64 {25	fn cmp(&self, other: &Self) -> std::cmp::Ordering {26		self.partial_cmp(other).expect("non nan")27	}28}2930fn get_sort_type<T>(31	values: &mut [T],32	key_getter: impl Fn(&mut T) -> &mut Val,33) -> Result<SortKeyType> {34	let mut sort_type = SortKeyType::Unknown;35	for i in values.iter_mut() {36		let i = key_getter(i);37		match (i, sort_type) {38			(Val::Str(_), SortKeyType::Unknown) => sort_type = SortKeyType::String,39			(Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,40			(Val::Str(_), SortKeyType::String) | (Val::Num(_), SortKeyType::Number) => {}41			(Val::Str(_) | Val::Num(_), _) => {42				throw!("sort elements should have the same types")43			}44			_ => throw!("sort key should either be a string or a number"),45		}46	}47	Ok(sort_type)48}4950/// * `key_getter` - None, if identity sort required51pub fn sort(ctx: Context, mut values: Vec<Val>, key_getter: FuncVal) -> Result<Vec<Val>> {52	if values.len() <= 1 {53		return Ok(values);54	}55	if key_getter.is_identity() {56		// Fast path, identity key getter57		let sort_type = get_sort_type(&mut values, |k| k)?;58		match sort_type {59			SortKeyType::Number => values.sort_unstable_by_key(|v| match v {60				Val::Num(n) => NonNaNf64(*n),61				_ => unreachable!(),62			}),63			SortKeyType::String => values.sort_unstable_by_key(|v| match v {64				Val::Str(s) => s.clone(),65				_ => unreachable!(),66			}),67			SortKeyType::Unknown => unreachable!(),68		};69		Ok(values)70	} else {71		// Slow path, user provided key getter72		let mut vk = Vec::with_capacity(values.len());73		for value in values.iter() {74			vk.push((75				value.clone(),76				key_getter.evaluate(77					ctx.clone(),78					CallLocation::native(),79					&(value.clone(),),80					true,81				)?,82			));83		}84		let sort_type = get_sort_type(&mut vk, |v| &mut v.1)?;85		match sort_type {86			SortKeyType::Number => vk.sort_by_key(|v| match v.1 {87				Val::Num(n) => NonNaNf64(n),88				_ => unreachable!(),89			}),90			SortKeyType::String => vk.sort_by_key(|v| match &v.1 {91				Val::Str(s) => s.clone(),92				_ => unreachable!(),93			}),94			SortKeyType::Unknown => unreachable!(),95		};96		Ok(vk.into_iter().map(|v| v.0).collect())97	}98}99100#[builtin]101#[allow(non_snake_case)]102pub fn builtin_sort(ctx: Context, arr: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {103	if arr.len() <= 1 {104		return Ok(arr);105	}106	Ok(ArrValue::eager(super::sort::sort(107		ctx,108		arr.iter().collect::<Result<Vec<_>>>()?,109		keyF.unwrap_or_else(FuncVal::identity),110	)?))111}