add dynamic casting abilities to BufferSlice
This commit is contained in:
parent
e91533440e
commit
5991420aa8
|
@ -1,3 +1,5 @@
|
||||||
|
use core::mem;
|
||||||
|
use core::slice;
|
||||||
use core::ops::{Deref, DerefMut, Range};
|
use core::ops::{Deref, DerefMut, Range};
|
||||||
|
|
||||||
use alloc::Vec;
|
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>
|
impl<'a, T> BufferSlice<'a, T>
|
||||||
where
|
where
|
||||||
[T]: ToOwned<Owned = Vec<T>>,
|
[T]: ToOwned<Owned = Vec<T>>,
|
||||||
|
|
Reference in a new issue