From 5991420aa8f064e18977a2fcd23264ba587a807f Mon Sep 17 00:00:00 2001 From: Szymon Walter Date: Mon, 19 Mar 2018 08:25:14 +0100 Subject: [PATCH] add dynamic casting abilities to BufferSlice --- src/buffer/mod.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/buffer/mod.rs b/src/buffer/mod.rs index 994c540..54ca4ba 100644 --- a/src/buffer/mod.rs +++ b/src/buffer/mod.rs @@ -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(&self) -> (T, usize) { + assert!(self.inner.len() >= mem::size_of::()); + let index = self.index; + let cast = unsafe { + mem::transmute_copy(self.inner.as_ptr().as_ref().unwrap()) + }; + (cast, index) + } + + pub fn from_cast(cast: &T, index: usize) -> BufferSlice<'a, u8> { + let len = mem::size_of::(); + 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>,