On Wed, Jul 31, 2013 at 3:46 AM, Julius Pfrommer <[email protected]> wrote: > Thanks a lot. > > I believe to have a reasonable solution now. > > trait BinaryStorage { > fn to_binary(&self) -> ~[u8] { > let size = std::sys::size_of_val(self); > unsafe { > let src = std::ptr::to_unsafe_ptr(self) as *u8; > std::vec::from_buf(src,size) > > } > } > fn from_binary(bin: ~[u8], index: uint) -> Option<Self> { > let size = std::sys::size_of::<Self>(); > if bin.len() >= index+size { > unsafe { > let ptr = std::ptr::offset(std::vec::raw::to_ptr(bin), > index); > Some(std::ptr::read_ptr(ptr as *mut Self)) > } > } else { None } > } > } >
This should take a &[u8], it doesn't need to own the vector. > The trait is generic for all non-vector types. > > impl BinaryStorage for bool; > impl BinaryStorage for i32; > impl BinaryStorage for f64; > > If there still is a more "proper" way, feel free to tell me about the > rust-idiomatic approach. > This seems reasonable to me (and you could have a `impl<T: Freeze> BinaryStorage for T` I think), but see also http://static.rust-lang.org/doc/extra/serialize.html. Encodable and Decodable can be derived (with a #[deriving(Encodable)] attribute). _______________________________________________ Rust-dev mailing list [email protected] https://mail.mozilla.org/listinfo/rust-dev
