Crate univec

Source
Expand description

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

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 and IndexMut traits are not implemented for UniVec because the result type is only known at runtime. Instead use the at() and at_mut() methods from the At 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.

Macros§

univec
A macro to create a UniVec with elements. This macro wraps the vec! macro creating an UniVec instead.

Structs§

TypeError
Error that happens on a query when the requested type is not stored in the UniVec.
TypeErrorIntoInner
When UniVec::into_inner() fails because of a type error, one gets the failed UniVec back.
TypeErrorValue
When pushing/setting an element fails because of a type error, one gets the failed element back.
UniVec
A dynamic vector that can store elements of any single type.

Traits§

At
Trait to get a reference to an element at a given index.
AtMut
Trait to get a mutable reference to an element at a given index.
IntoIndex
Trait to convert a types into an usize index.