Crate purse

Source
Expand description

Purse implements a bag data structure, also known as a multiset. A bag can contain anything, with possible duplicates of each item, and items of different types - it’s a free for all!

Purse is helpful in a wide range of applications where a heterogeneous and non-unique collection of items is required.

§Examples

Basic usage:

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);

purse.insert("foo");
purse.insert("bar");
purse.insert("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"));

Structs§

Purse