11 releases (2 stable)
1.0.1 | May 2, 2024 |
---|---|
0.9.0 | Apr 22, 2024 |
0.4.0 | Oct 7, 2023 |
#491 in Rust patterns
803 downloads per month
39KB
342 lines
A dynamic vector that can store elements of any single type.
Usage
UniVec
is a dynamic vector that wraps any Vec<T>
to store elements of any single type
determined at runtime. Its primary use case is when one need to store elements of a single
type, but this type might vary by context.
The type T
becomes associated to an instance of UniVec
upon the first insertion of an
element of type T
. Once the type is set, all subsequent insertions must be of the same
type.
It comes with a push/pop API's to implement an efficient stack functionality.
Example
# use univec::{UniVec, univec};
# use std::collections::HashMap;
let mut things = HashMap::<String, UniVec>::new();
things.insert("integers".to_string(), univec![1, 2, 3]);
things.insert("names".to_string(), univec!["foo", "bar", "baz"]);
assert_eq!(things["integers"].get::<i32>(0), Some(&1));
assert_eq!(things["names"].get::<&str>(0), Some(&"foo"));
Convenience Features
This crate re-exports the IntoIndex
trait that can convert any integer type into usize
.
This in turn is used by the At
trait to provide a at()
and at_mut()
method that can be
used to access elements of a UniVec
and Vec
by any integer type.
Performance
UniVec
is a wrapper around dyn trait of a Vec<T>
. Most operations are just a single layer
of indirection into the underlying Vec
. Because of this, UniVec
should have performance
close to Vec
.
Limitations
- Since it is based on
std::any::Any
references contained in stored objects must be of'static
lifetime. - The
Index
andIndexMut
traits are not implemented forUniVec
because the result type is only known at runtime. Instead use theat()
andat_mut()
methods from theAt
trait.
Fun Fact
This crates was a testbed for code and documentation generation with ChatGPT and Codepilot. Nevertheless all code is manually audited and tested with miri and cargo mutants.
Contribution
Contributions are welcome! Feel free to open an issue or submit a pull request.
Credits
- FSMaxB -- Implementation Idea about the helper trait.
Dependencies
~245–700KB
~16K SLoC