Self way to compare integers (usize, u32)?

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?

1 Like

How about?

let len: usize = ...;
let mps: u32 = ...;
let is_len_largest = usize::try_from(mps)
    .map(|mps| len > mps)
    .unwrap_or(false); // mps > usize::max_value() >= len
4 Likes

That's great, I for some reason thought that try_from based on size of type, and missed that it also check value.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.