Crates.io | purse |
lib.rs | purse |
version | 0.1.4 |
source | src |
created_at | 2023-12-26 16:13:27.16178 |
updated_at | 2023-12-30 04:39:56.928584 |
description | Bag data structure implementation in Rust |
homepage | https://github.com/rauljordan/purse |
repository | https://github.com/rauljordan/purse |
max_upload_size | |
id | 1081039 |
size | 31,983 |
Purse implements a bag in Rust, also known as a multi set, but that's a much more boring name. Bags are quite versatile structures, allowing storage of heterogeneous and non-unique collections of items, supporting different types and allowing duplicates.
cargo add purse
use std::any::TypeId;
use purse::Purse;
let mut purse = purse::new();
purse.insert("hello");
purse.insert(42);
assert!(purse.contains("hello"));
assert!(purse.contains(42));
assert_eq!(purse.count::<&str>(), 1);
// Get all of type.
let strings: Vec<&&str> = purse.get_all_of_type();
assert_eq!(strings.len(), 4);
purse.insert("foo");
purse.insert("bar");
purse.insert("baz");
assert!(strings.contains(&&"foo"));
assert!(strings.contains(&&"bar"));
assert!(strings.contains(&&"baz"));
// Check the most common type.
assert_eq!(purse.most_common_type(), Some(TypeId::of::<&str>()));
// Clearing the bag.
purse.clear();
assert!(purse.is_empty());
// Add a few items again.
purse.insert(5);
purse.insert("foo");
// Iteration over all elements in the bag
let mut nums: Vec<i32> = vec![];
let mut strs: Vec<&str> = vec![];
purse.iter().for_each(|item| {
if let Some(&t) = item.downcast_ref::<i32>() {
nums.push(t);
} else if let Some(&t) = item.downcast_ref::<&str>() {
strs.push(t);
} else {
panic!("unexpected type found in bag");
}
});
assert_eq!(nums.first(), Some(&5));
assert_eq!(strs.first(), Some(&"foo"));
Contributions are welcome! Please follow the standard Rust conventions for pull requests.
This project is licensed under either of
at your option.
The SPDX license identifier for this project is MIT OR Apache-2.0.