| Crates.io | sorted-groups |
| lib.rs | sorted-groups |
| version | 0.2.0 |
| created_at | 2024-12-18 08:52:06.066463+00 |
| updated_at | 2024-12-18 21:49:17.84362+00 |
| description | Implement a data structure to store elements in sorted groups while maintaining the order of elements in each group |
| homepage | https://github.com/dax/sorted-groups |
| repository | https://github.com/dax/sorted-groups |
| max_upload_size | |
| id | 1487320 |
| size | 23,410 |
sorted-groups implement a data structure to store elements in sorted groups while maintaining the order of elements in each group.
First, add the sorted_groups crate as a dependency:
cargo add sorted_groups
use sorted_groups::SortedGroups;
#[derive(PartialEq, Eq, Ord, Debug)]
struct Element {
group: i32,
value: i32,
}
impl PartialOrd for Element {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
// Elements will be grouped by the `group` field
let sorted_groups = SortedGroups::<i32, Element>::new(vec![
Element { group: 1, value: 1 },
Element { group: 1, value: 2 },
Element { group: 2, value: 1 },
], |e| e.group);
// `len` returns the total number of elements
assert_eq!(sorted_groups.len(), 3);
// `groups_len` returns the number of groups
assert_eq!(sorted_groups.groups_len(), 2);
// `iter` returns an iterator over groups and elements
let mut iter = sorted_groups.iter();
assert_eq!(iter.next(), Some((&1, &Element { group: 1, value: 1 })));
assert_eq!(iter.next(), Some((&1, &Element { group: 1, value: 2 })));
assert_eq!(iter.next(), Some((&2, &Element { group: 2, value: 1 })));
assert_eq!(iter.next(), None);
This project is distributed under the terms of the Apache License (Version 2.0).
See LICENSE