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:
- 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();
- The capacity can’t be converted to units of the output type.
ⓘ
let input: Vec<u8> = Vec::with_capacity(3);
let output: Vec<u16, _> = transmute_vec(input).unwrap();
- The alignment of the vec is wrong.
Alignment, then length, then capacity will always be returned.
ZSTs
- Anything -> ZST
- Keeps length, deallocates data.
- ZST -> Non ZST
- New Vec from previous allocator.
- Just don’t do this.
See also
transmute_vec_may_copy
– Infailabletransmute_vec_basic
– Returns a Vec without a specical allocator and works on stable, but only works with types with the same alignment.