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 }
    }
}

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.

Best, Julius

On 30.07.2013 14:58, Corey Richardson wrote:
On Tue, Jul 30, 2013 at 8:56 AM, Julius Pfrommer <[email protected]> wrote:
The compiler aborts with the following message:
datatypes.rs:10:37: 10:41 error: unresolved name `Self`. Did you mean `bin`?
datatypes.rs:10         let size = std::sys::size_of<Self>()/8;

Is it currently possible to access the size (in bits/bytes) of the
"Self"-type?
std::sys::size_of::<Self>()

(there might be a better way to do what you'r achieving but I don't
have time for a "proper" email)

_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to