add dynamic casting abilities to BufferSlice

This commit is contained in:
Szymon Walter 2018-03-19 08:25:14 +01:00
parent e91533440e
commit 5991420aa8

View file

@ -1,3 +1,5 @@
use core::mem;
use core::slice;
use core::ops::{Deref, DerefMut, Range};
use alloc::Vec;
@ -89,6 +91,24 @@ where
}
}
impl<'a> BufferSlice<'a, u8> {
pub fn dynamic_cast<T: Copy>(&self) -> (T, usize) {
assert!(self.inner.len() >= mem::size_of::<T>());
let index = self.index;
let cast = unsafe {
mem::transmute_copy(self.inner.as_ptr().as_ref().unwrap())
};
(cast, index)
}
pub fn from_cast<T: Copy>(cast: &T, index: usize) -> BufferSlice<'a, u8> {
let len = mem::size_of::<T>();
let ptr = cast as *const T as *const u8;
let slice = unsafe { slice::from_raw_parts(ptr, len) };
BufferSlice::new(slice, index)
}
}
impl<'a, T> BufferSlice<'a, T>
where
[T]: ToOwned<Owned = Vec<T>>,