some fetching modules fixes and ItemData::sort_keys()

This commit is contained in:
Sebastian Moser
2024-10-06 11:14:54 +02:00
parent 5607dcaad2
commit d98585e026
3 changed files with 91 additions and 11 deletions

View File

@@ -5,6 +5,40 @@ use crate::item::IntoItemData;
use super::*;
#[test]
fn test_sort_keys() -> MizeResult<()> {
let mut data = ItemData::from_toml(r#"
[hi]
test = 4
[config]
zzz = "hiiii"
hi = "hello from config/hi"
[config.test]
inner = "inner"
"#)?;
let data_sorted = ItemData::from_toml(r#"
[config]
hi = "hello from config/hi"
test = { inner = "inner" }
zzz = "hiiii"
[hi]
test = 4
"#)?;
data.sort_keys()?;
assert_eq!(data.to_json()?, data_sorted.to_json()?);
Ok(())
}
#[test]
fn test_get_module_hash() -> MizeResult<()> {
let mut instance = Instance::empty()?;
@@ -18,9 +52,10 @@ fn test_get_module_hash() -> MizeResult<()> {
instance.set_blocking("0/config/selector", ItemData::from_toml(&selector_toml)?)?;
let hash = get_module_hash(&mut instance, "String", ItemData::new())?;
let (hash, selector) = get_module_hash(&mut instance, "String", ItemData::new())?;
test_println!("hash: {}", hash);
test_println!("selector: {}", selector);
assert_eq!(hash, "e96edf60216688314efc263c1aa8d6ce".to_owned());

View File

@@ -189,6 +189,10 @@ impl ItemData {
ItemData (cbor)
}
pub fn sort_keys(&mut self) -> MizeResult<()> {
item_data_sort_keys(&mut self.0)
}
pub fn null() -> CborValue {
CborValue::Null
}
@@ -254,6 +258,38 @@ pub fn item_data_get_path(data: &CborValue, path: Vec<String>) -> MizeResult<&Cb
item_data_get_path(sub_data, path_iter.collect())
}
pub fn item_data_sort_keys(data: &mut CborValue) -> MizeResult<()> {
// for a list, sort each item of the list
if data.is_array() {
for el in data.as_array_mut().unwrap().iter_mut() {
item_data_sort_keys(el)?
}
}
// sort the keys of a map
if data.is_map() {
let map: &mut Vec<(CborValue, CborValue)> = data.as_map_mut().unwrap();
//map.sort_by_key(|el| el.0);
map.sort_by(|a,b| {
match a.0.partial_cmp(&b.0) {
Some(val) => val,
None => {
// just say the two values are equal, if they can't be ordered
std::cmp::Ordering::Equal
}
}
});
// also sort every sub value
for (key, val) in map {
item_data_sort_keys(val)?
}
}
Ok(())
}
pub fn item_data_set_path(data: &mut CborValue, path: Vec<String>, data_to_set: &CborValue) -> MizeResult<()> {
//trace!("[ {} ] item_data_set_path()", "CALL".yellow());
//trace!("[ {} ] data: {}", "ARG".yellow(), data.clone().into_item_data());