2 stable releases

Uses old Rust 2015

1.1.0 May 2, 2016
1.0.0 Mar 13, 2016

#2684 in Algorithms

Download history 42/week @ 2024-07-22 81/week @ 2024-07-29 62/week @ 2024-08-05 105/week @ 2024-08-12 79/week @ 2024-08-19 89/week @ 2024-08-26 80/week @ 2024-09-02 117/week @ 2024-09-09 140/week @ 2024-09-16 131/week @ 2024-09-23 122/week @ 2024-09-30 137/week @ 2024-10-07 198/week @ 2024-10-14 101/week @ 2024-10-21 188/week @ 2024-10-28 149/week @ 2024-11-04

653 downloads per month
Used in 10 crates (3 directly)

MIT/Apache

9KB
141 lines

This is a Rust crate to convert slices (which have run-time lengths) to arrays (which have compile-time lengths).

Documentation


lib.rs:

This crate provides macros to convert from slices, which have lengths that are stored and checked at runtime, into arrays, which have lengths known at compile time. This can make types more expressive (e.g. &[u8; 32] instead of &[u8]) and helps the compiler omit bounds checks.

slice_as_array!(xs, [u32; 4]) returns Some(&[u32; 4]) if xs was a slice of length 4, or None otherwise.

slice_as_array_mut!(ys, [String; 7]) returns Some(&mut [String; 7]) if ys was a slice of length 7, or None otherwise.

slice_to_array_clone!(zs, [String; 4] returns Some([String; 4]) if zs was a slice of length 4, or `None otherwise. The passed-in slice remains intact and its elements are cloned.

For most users, stating a dependency on this is simply:

[dependencies]
slice_as_array "1.1.0"

To support being called from a #![no_std] crate, this crate has a feature named with_std that is on by default. A #![no_std] crate should use:

[dependencies]
slice_as_array = { version = "1.1.0", default-features = false }

Example usage:

#[macro_use] extern crate slice_as_array;

fn slice_as_hash(xs: &[u8]) -> &[u8; 32] {
    slice_as_array!(xs, [u8; 32]).expect("bad hash length")
}

fn mutate_chunk(xs: &mut [u32; 10]) {
    // ...
}

fn mutate_chunks(xs: &mut [u32; 100]) {
    for chunk in xs.chunks_mut(10).map(|c| slice_as_array_mut!(c, [u32; 10]).unwrap() ) {
        mutate_chunk(chunk)
    }
}

Dependencies

~66KB