6 releases
0.3.0 | Apr 12, 2019 |
---|---|
0.2.3 | Feb 24, 2019 |
0.2.1 | Jan 5, 2019 |
0.2.0 | Aug 16, 2018 |
0.1.0 | Aug 4, 2018 |
#2118 in Data structures
32 downloads per month
35KB
701 lines
sized-vec
Rust vectors with type level size.
Documentation
Examples
#[macro_use]
use sized_vec::Vec;
use typenum::{U2, U8};
fn main() {
let vec = svec![1, 2, 3, 4, 5];
// Use typenums for type safe index access:
assert_eq!(3, vec[U2::new()]);
// Out of bounds access won't even compile:
assert_eq!(0, vec[U8::new()]); // <- type error!
}
Licence
Copyright 2018 Bodil Stokke
This software is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
Code of Conduct
Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.
lib.rs
:
Type Level Sized Vectors
This crate provides a Vec<N, A>
type, which wraps the standard Vec<A>
and tracks its size N
at the type level.
Because the size is embedded in the type, we can do things like verifying at compile time that index lookups are within bounds.
let vec = svec![1, 2, 3];
// This index lookup won't compile, because index `U8` is outside
// the vector's length of `U3`:
assert_eq!(5, vec[U8::new()]);
let vec = svec![1, 2, 3];
// On the other hand, this lookup can be verified to be correct
// by the type system:
assert_eq!(3, vec[U2::new()]);
Limitations
If this looks too good to be true, it's because it comes with a number of
limitations: you won't be able to perform operations on the vector which
could leave it with a length that can't be known at compile time. This
includes Extend::extend()
and filtering operations like Vec::retain()
.
FromIterator::from_iter
is, notably, also not available, but you can use
Vec::try_from
as a replacement. Note that try_from
needs to be able to
infer the size of the resulting vector at compile time; there's no way to
construct a vector of arbitrary length.
let vec = svec![1, 2, 3, 4, 5];
let new_vec = Vec::try_from_iter(vec.into_iter().map(|i| i + 10));
assert_eq!(Some(svec![11, 12, 13, 14, 15]), new_vec);
Dependencies
~0.1–0.9MB
~16K SLoC