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