So I am currently writing code to read and write the RTMP chunk protocol. One annoying part of that is that the protocol designates the timestamp as a 3 byte number (so essentially a u24). Of course, there’s no such thing as a u24 in Rust so the value I want to write into my byte array is a 4 byte u32.

Assuming I’ve already added checks to make sure the u32 value isn’t a value higher than the max that 3 bytes can hold, what is the best way to get the 3 bytes making up the number?

There are several things I thought of:

Using unsafe to convert the u32 into a byte array, then copy the last 3 values into my packet’s vector. The disadvantage of this is obviously I’m hesitant to utilize the unsafe flag if I don’t have to. I’m not totally sure if this is that much of a concern or not since the scope is easily manageable. Use the byteorder crate to write the u32 to a new vector, then drain bytes 1-3 off into my packet vector. Since this code will be called every time I need to send audio/video data packets off and I want it to be as low latency as possible the needless allocations don’t have me too happy. Create bitwise masks and use bitwise operations to get the values for each bit, then shift each of them over until they are all the way to the right of each value.

Are there any better ideas out there to keep things readable, safe (as possible), and quick?