0

I have a mmapped file from which I read (and write) Messages. I have a byte slice (&[u8]) of the mmap's contents. My current struct definition of a Message is:

struct Message<'a> {
    bytes: &'a [u8]
    id: &'a MessageId(u64),
    // ... some fields omitted ...
}

What I'd like is to map the byte slice to the message's fields, but I can't seem to get this right.

I've been looking into mem::transmute but I keep doing something wrong here:

error: transmute called with differently sized types: *const [u8] (128 bits) to u64 (64 bits) [E0512]
let offset: u64 = unsafe { mem::transmute(self.bytes) };

From my understanding transmute "reinterprets" the buffer as another type. How should I go about fixing this? How about mapping subsequent fields (as e.g. u32, &'a str, etc.)?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Melle
  • 7,639
  • 1
  • 30
  • 31
  • 1
    Note that it doesn't make any sense to (de)serialize a struct with a reference. There's no way to guarantee that the pointed-at value will be in the same location, or even that it exists! – Shepmaster Aug 13 '16 at 14:21
  • 1
    Also, a `&[u8]` is a [*fat pointer*](http://stackoverflow.com/a/31953048/155423), explaining why it's 128 bits and why it would be a Bad Idea to `transmute` it. – Shepmaster Aug 13 '16 at 14:40

0 Answers0