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, values: Cc<Vec<Val>>, key_getter: FuncVal) -> Result<Cc<Vec<Val>>> {54 if values.len() <= 1 {55 return Ok(values);56 }57 if key_getter.is_identity() {58 59 let mut values = (*values).clone();60 let sort_type = get_sort_type(&mut values, |k| k)?;61 match sort_type {62 SortKeyType::Number => values.sort_unstable_by_key(|v| match v {63 Val::Num(n) => NonNaNf64(*n),64 _ => unreachable!(),65 }),66 SortKeyType::String => values.sort_unstable_by_key(|v| match v {67 Val::Str(s) => s.clone(),68 _ => unreachable!(),69 }),70 SortKeyType::Unknown => unreachable!(),71 };72 Ok(Cc::new(values))73 } else {74 75 let mut vk = Vec::with_capacity(values.len());76 for value in values.iter() {77 vk.push((78 value.clone(),79 key_getter.evaluate(80 ctx.clone(),81 CallLocation::native(),82 &(Any(value.clone()),),83 true,84 )?,85 ));86 }87 let sort_type = get_sort_type(&mut vk, |v| &mut v.1)?;88 match sort_type {89 SortKeyType::Number => vk.sort_by_key(|v| match v.1 {90 Val::Num(n) => NonNaNf64(n),91 _ => unreachable!(),92 }),93 SortKeyType::String => vk.sort_by_key(|v| match &v.1 {94 Val::Str(s) => s.clone(),95 _ => unreachable!(),96 }),97 SortKeyType::Unknown => unreachable!(),98 };99 Ok(Cc::new(vk.into_iter().map(|v| v.0).collect()))100 }101}102103#[builtin]104#[allow(non_snake_case)]105pub fn builtin_sort(ctx: Context, arr: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {106 if arr.len() <= 1 {107 return Ok(arr);108 }109 Ok(ArrValue::Eager(super::sort::sort(110 ctx,111 arr.evaluated()?,112 keyF.unwrap_or_else(FuncVal::identity),113 )?))114}