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

#2104 in Data structures

Download history 24/week @ 2024-08-26 6/week @ 2024-09-02 7/week @ 2024-09-09 3/week @ 2024-09-16 15/week @ 2024-09-23 26/week @ 2024-09-30 2/week @ 2024-10-07 9/week @ 2024-10-14 7/week @ 2024-10-21 5/week @ 2024-10-28 10/week @ 2024-11-04 4/week @ 2024-11-18 16/week @ 2024-11-25 14/week @ 2024-12-02 55/week @ 2024-12-09

89 downloads per month

MPL-2.0+

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