Potential overflowing expression not checked by rustc?

I have the following function:

pub(crate) fn add_constant(chunk: &mut Chunk, value: Value) -> u8 {
    chunk.constants.push(value);
    (chunk.constants.len() - 1) as u8
}

where chunk.constants is a Vec.

I'm curious as to why rustc does not warn of a possible overflow should the expression (chunk.constants.len() - 1) be greater than 255, since it is of type usize. Is there a check that exists that can be manually enabled? Alternatively, I could write validation code myself.

You might want to use u8::try_from:

u8::try_from(chunk.constants.len() - 1)
3 Likes

Using as is a coercion, which forces the cast and does truncation in this case. To check explicitly you can use try_into, which uses the TryFrom trait, which is implemented for all the primitive conversions such as usize to u8. You can unwrap the error if you want to generate a panic rather than handle the error:

(chunk.constants.len() - 1).try_into().unwrap()
3 Likes

This was exactly what I was looking for, thanks for your help.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.