I want to send Vec<u8>
via some protocol.
There is restriction for 3 bytes for length of packet, so:
fn create_packet(data: &[u8]) -> Result<Vec<u8>, PacketSizeOverflow> {
const MAX_PACKET_SIZE: u32 = (1u32 << 24) - 1;
if data.len() > MAX_PACKET_SIZE {
return Err(PacketSizeOverflow);
}
...
}
But how exactly should I compare usize and u32?
I can imagine only something like this:
// in case size_of usize <= size_of u32
if let Ok(len) = u32::try_from(data.len()) {
if len > MAX_PACKET_SIZE { ... }
} else {
//so size_of usize > size_of u32
let mps = usize::try_from(MAX_PACKET_SIZE).unwrap();
if len > mps { ... }
}
But I don't like this unwrap
. Any other safe way to compare usize
and u32
?