1use jrsonnet_evaluator::{2 error::Result,3 function::{builtin, FuncVal},4 throw_runtime,5 typed::Any,6 val::ArrValue,7 State, 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_runtime!("sort elements should have the same types")45 }46 _ => throw_runtime!("sort key should either be a string or a number"),47 }48 }49 Ok(sort_type)50}515253pub fn sort(s: State, 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_simple(s.clone(), &(Any(value.clone()),))?,80 ));81 }82 let sort_type = get_sort_type(&mut vk, |v| &mut v.1)?;83 match sort_type {84 SortKeyType::Number => vk.sort_by_key(|v| match v.1 {85 Val::Num(n) => NonNaNf64(n),86 _ => unreachable!(),87 }),88 SortKeyType::String => vk.sort_by_key(|v| match &v.1 {89 Val::Str(s) => s.clone(),90 _ => unreachable!(),91 }),92 SortKeyType::Unknown => unreachable!(),93 };94 Ok(Cc::new(vk.into_iter().map(|v| v.0).collect()))95 }96}9798#[builtin]99#[allow(non_snake_case)]100pub fn builtin_sort(s: State, arr: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {101 if arr.len() <= 1 {102 return Ok(arr);103 }104 Ok(ArrValue::Eager(super::sort::sort(105 s.clone(),106 arr.evaluated(s)?,107 keyF.unwrap_or_else(FuncVal::identity),108 )?))109}