Function transvec::transmute_vec[][src]

pub fn transmute_vec<I: Pod, O: Pod, A: Allocator>(
    input: Vec<I, A>
) -> Result<Vec<O, AlignmentCorrectorAllocator<I, O, A>>, (Vec<I, A>, TransmuteError)>
Expand description

Allows transmuting of a Vec to another vec of a different size, with 0 copies.

Example

#![feature(allocator_api)] // this requires the allocator api because the way that this
// handles deallocating hooks into the allocator api
use transvec::transmute_vec;
let input_vec: Vec<u16> = vec![1, 2, 3, 4, 5, 6, 7, 8];
let output: Vec<u8, _> = match transmute_vec(input_vec) {
    Ok(x) => x,
    // the "transmute" can fail, if the alignment/capacity/length is incorrect
    // consider using `transmute_vec_may_copy`
    Err((old_vec, err)) => return println!("Error: {:?}", err),
};
if cfg!(target_endian = "big") {
    assert_eq!(
        &output,
        &[0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8]
    );
} else {
    assert_eq!(
        &output,
        &[1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0]
    );
}

Errors

This errors when:

  1. The length of the vector wouldn’t fit the type.
let input: Vec<u8> = vec![1, 2, 3];
let output: Vec<u16, _> = transmute_vec(input).unwrap();
  1. The capacity can’t be converted to units of the output type.
  2. The alignment of the vec is wrong.

Alignment, then length, then capacity will always be returned.

See also