use crate::base::hash::Hash256;
use crate::record::kind::RefType;
use serde::{Deserialize, Serialize};
pub type RecordId = Hash256;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Ref {
#[serde(rename = "type")]
pub type_: RefType,
pub target: RecordId,
}
pub fn sort_and_dedup_refs(refs: &mut Vec<Ref>) {
refs.sort_by(|a, b| {
let ord_a = a.type_ as u8;
let ord_b = b.type_ as u8;
ord_a.cmp(&ord_b).then_with(|| a.target.cmp(&b.target))
});
refs.dedup();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sort_and_dedup() {
let target_a = [0u8; 32];
let target_b = [1u8; 32];
let mut refs = vec![
Ref {
type_: RefType::Replace,
target: target_a,
},
Ref {
type_: RefType::Cause,
target: target_b,
},
Ref {
type_: RefType::Cause,
target: target_a,
},
Ref {
type_: RefType::Cause,
target: target_a,
}, ];
sort_and_dedup_refs(&mut refs);
assert_eq!(refs.len(), 3);
assert_eq!(refs[0].type_, RefType::Cause);
assert_eq!(refs[0].target, target_a);
assert_eq!(refs[1].type_, RefType::Cause);
assert_eq!(refs[1].target, target_b);
assert_eq!(refs[2].type_, RefType::Replace);
}
}