newbie question - how to overlay a struct onto the packet bytes #309
Replies: 2 comments 2 replies
-
you could use an union but it's hard to advice with no MCVE. |
Beta Was this translation helpful? Give feedback.
-
The decoding of buffers is an extremely common task. The buffers come in an array of bytes, in this case above, the next_packet function is going to return a data buffer of some slice, which is an array of bytes. As my code traverses across this buffer, i will need to view the next 10 or 20 bytes as some kind of record, maybe an ethernet record, maybe a TCP/IP header, etc., then there will be payload. In C, i can take the address of buf[10], and cast that as a pointer to a struct, and then reference the fields of the struct. zero overhead, and the only risk is going off the end of the array which i can check for externally. Why is Rust fighting me so hard in trying to cast a raw pointer to a pointer to a struct? This is such a basic task. In most languages you can tell the compiler, this is a pointer, convert it to a raw address and treat it as if it points to this kind of struct... there is a function in std::mem:: called transmute, but i can't seem to get it to work. The Unsafe blocks don't seem to relax the compiler's fanaticism. |
Beta Was this translation helpful? Give feedback.
-
when you get a packet, it is of type &[u8], an array of bytes.
I define a structure, like the ethernet header, and i want to then take a pointer to a structure, set to an offset in the packet bytes, and then access the fields of the struct. Rust doesn't let me do this because it is a violation of type matching. So i tried to use an unsafe{} block, but it still complains. I am sure there is a simple way to do this without copying the bytes in Rust, but it sure isn't obvious. When you are decoding packets this will be very common.
The above code doesn't compile, because apparently you can't put a record at a certain offset in a byte array, which in C is a trivial task. I will also need to convert to big endian the ether_type field, but i am sure there are std library functions in rust that convert a u16 to big endian. Where i am stuck is how to force Rust to allow me to point the struct into an array of bytes.
Beta Was this translation helpful? Give feedback.
All reactions