A Rust library providing strongly typed indices for collections and everything else needed for working with them in an ergonomic manner.
What are typed indices?
In standard Rust, collections use usize for indexing. This works well but provides no compile-time
protection against using an index from one collection with another. Typed indices solve this by
creating custom index types that are statically associated with specific collections.
In standard Rust, a raw usize can index any collection. This allows subtle bugs:
let nodes: = vec!; // 10 nodes
let edges: = vec!; // 5 edges
let node_index = 3;
nodes;
edges; // compiles just fine!
With typed indices, cross-contamination becomes a compile error:
;
;
let nodes: = typed_vec!;
let edges: = typed_vec!;
let node_id = NodeId;
nodes; // OK
// edges[node_id]; // COMPILE ERROR: expected EdgeId, found NodeId
Features
- Type Safety: Prevents accidental misuse of indices between different collections at compile time
no_stdSupport: Works in embedded systems and otherno_stdenvironments- Memory Efficiency: Use smaller integer types (
u8,u16) for indices when collections are bounded - Niche Optimization: Supports
NonZerotypes soOption<Index>has the same size asIndex - Rich Collections: Provides
TypedSlice,TypedVec,TypedArray, andTypedArrayVec - Derive Macros: Easy to define custom index types with
#[derive(IndexType)] - Range Iterators: Iterate over ranges using custom index types
Quick Start
use ;
;
let mut vec: = new;
let idx = vec.push;
assert_eq!;
// vec[0usize]; // This won't compile - requires MyIndex type
Defining Index Types
Use the #[derive(IndexType)] macro on a newtype struct:
use IndexType;
;
The macro automatically implements the IndexType trait for your custom type. By default,
it generates an error type MyIndexTooBigError. You can specify a custom error type:
;
;
Typed Collections
TypedVec
A growable vector with typed indexing. See TypedVec for the full API.
;
let mut nodes: = new;
let id0 = nodes.push;
let id1 = nodes.push;
println!;
Operations that can fail due to index overflow have both panicking and fallible variants:
let mut vec: = new;
// This will panic on index overflow (e.g. if the vector already contains (2^32 - 1) elements before calling `push`)
let idx = vec.push;
// This will gracefully return an error in case of index overflow
let result: = vec.try_push;
TypedSlice
A slice wrapper with typed indexing.
TypedSlice<I, T> is the same as [T] but with index type I.
So, to represent &[u8] for example, use &TypedSlice<I, u8>, where I is your custom index type.
See TypedSlice for the full API.
;
let vec: = typed_vec!;
let slice: & = vec.as_slice;
// Safe indexing with custom type
let first = slice;
TypedArray
A fixed-size array with typed indexing. The array length N is checked at compile time
to ensure it fits within the index type’s range. See TypedArray for the full API.
;
;
// An index-typed version of `[Value; 3]`, with index type `ValueIdx`
let mut values: = from_array;
values = Value;
values = Value;
assert_eq!;
assert_eq!;
assert_eq!;
TypedArrayVec
A fixed-capacity vector backed by an array, similar to the ArrayVec type provided by the arrayvec crate but with typed indexing.
See TypedArrayVec for the full API.
;
let mut buffer: = new;
buffer.push;
assert_eq!;
A TypedArrayVec<u8, u8, 3> is only 4 bytes (3 bytes for data + 1 byte for length).
Complex Indexing
This crate also supports complex forms of indexing when using custom index types, for example, slicing a collection with a range of a custom index type:
;
;
let values: = typed_vec!;
let some_values: & = &values;
assert_eq!;
// Can even perform more complex types of slicing
let other_values: & = &values;
assert_eq!;
let other_values_2: & = &values;
assert_eq!;
Memory-Efficient Indices
Using smaller integer types reduces memory when storing many indices. This is useful when you know that the size of the collection is bounded.
For example, if you are implementing a graph using an adjacency list, and you know that the graph will be reasonably small, you can use
32-bit integers as indices instead of usize, which on 64-bit machines is half the size:
// We know that the graph will never have more than `2^32 - 1` nodes, so we can use `u32` as the index type.
;
NonZero Indices and Niche Optimization
Using NonZero types enables niche optimization, where Option<Index>
has the same size as Index:
;
// Option<SafeId> takes only 4 bytes, not 8!
assert_eq!;
assert_eq!;
And indexing into a collection with non-zero indices is of course as seamless as using any other integer type as the index type:
;
let arr: = typed_array!;
assert_eq!;
Range Iterators
Currently, in stable Rust, you cannot iterate over a range of values of a custom type:
;
// There is nothing you can do to make this code work in stable Rust
for i in MyIdx..MyIdx
The reason for this is that the built-in range types only implement the Iterator trait if the value type T implements the
unstable Step trait, which you cannot implement for your own types in stable Rust.
Being able to iterate over ranges of custom index types is important for making the experience of working with typed indices feel seamless and as smooth as using regular index types.
This crate provides TypedRangeIterExt for iterating over ranges with custom index types:
use TypedRangeIterExt;
;
for idx in .iter
Typed Enumerate
Use TypedIteratorExt to enumerate any iterator with typed indices:
use TypedIteratorExt;
;
let pairs: =
.into_iter
.
.collect;
assert_eq!;
assert_eq!;
Macros
Convenience macros for creating typed collections:
;
// Create a TypedVec
let v: = typed_vec!;
// Create a TypedArray
let a: = typed_array!;
// Create a TypedArrayVec
let av: = typed_array_vec!;
// Create a TypedSlice reference, similar to a slice literal (`&[1, 2, 3]`)
let s: & = typed_slice!;
Error Handling
Operations that can fail due to index overflow return Result types.
Each index type has its own custom error type which is returned when operating on a collection which uses that index type.
// Note: the `#[derive(IndexType)]` macro automatically generates a type called `MyIndexTooBigError` which is the custom error
// type for this custom index type.
;
let mut vec: = new;
// Fill up to capacity
for i in 0..255
// At this point, pushing will cause the length of the vec to exceed the index type, so this fails gracefully.
let res: = vec.try_push;
assert!;
no_std Compatibility
This crate is no_std compatible. The alloc feature (enabled by default) enables
heap-allocated collections (TypedVec and related macros).
For pure no_std environments without heap allocation, disable the alloc feature:
[]
= { = "...", = false }
serde Support
This crate has a serde feature flag which implements Serialize and Deserialize for all of the relevant types exported by this
crate. This includes for example the main collection types (e.g. TypedVec).