Lines
97.5 %
Functions
100 %
Branches
//! Account order of the pickers, from the shared `rpc::account_order` rules.
use std::cmp::Ordering;
use std::collections::HashMap;
use nomiscript::Value;
use rpc::account_order::{path_label, path_then_id};
use uuid::Uuid;
use super::row_id;
use crate::eval::plist_field_raw;
struct Node {
name: Option<String>,
parent: Option<Uuid>,
}
fn uuid_field(element: &Value, key: &str) -> Option<Uuid> {
match plist_field_raw(element, key) {
Some(Value::String(text)) => Uuid::parse_str(&text).ok(),
_ => None,
fn account_id(element: &Value) -> Option<Uuid> {
row_id(element).and_then(|id| Uuid::parse_str(&id).ok())
fn nodes(elements: &[Value]) -> HashMap<Uuid, Node> {
elements
.iter()
.filter_map(|element| {
let name = match plist_field_raw(element, ":name") {
Some(Value::String(text)) => Some(text),
};
let parent = uuid_field(element, ":parent");
Some((account_id(element)?, Node { name, parent }))
})
.collect()
type Keyed = (Option<(String, Uuid)>, String, Value);
/// Records whose id is not a UUID go last, by their id text.
fn compare(a: &Keyed, b: &Keyed) -> Ordering {
match (&a.0, &b.0) {
(Some((la, ia)), Some((lb, ib))) => path_then_id((la, *ia), (lb, *ib)),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => a.1.cmp(&b.1),
/// Sort account records by path, then id, as `form-options` does.
pub fn sort_by_path(elements: &mut [Value]) {
let nodes = nodes(elements);
let name_of = |id| nodes.get(&id).and_then(|node| node.name.as_deref());
let parent_of = |id| nodes.get(&id).and_then(|node| node.parent);
let mut keyed: Vec<Keyed> = elements
.map(|element| {
let key = account_id(element).map(|id| (path_label(id, name_of, parent_of), id));
(key, row_id(element).unwrap_or_default(), element.clone())
.collect();
keyed.sort_by(compare);
for (slot, (_, _, element)) in elements.iter_mut().zip(keyed) {
*slot = element;
#[cfg(test)]
mod tests;