num-bigint icon indicating copy to clipboard operation
num-bigint copied to clipboard

Saturating conversion to primitives

Open carbotaniuman opened this issue 4 years ago • 2 comments

I would like to request a way to convert a bigint into a smaller primitive, saturating at MAX_VALUE or MIN_VALUE if needed.

carbotaniuman avatar Nov 15 '20 02:11 carbotaniuman

This seems like an unusual thing to want -- can you describe the use case where a saturating conversion would be helpful?

You can do this manually, if a little cumbersome, something like:

let small_int = bigint.to_i32().unwrap_or_else(|| {
    if bigint.sign() == Sign::Plus { i32::MAX } else { i32::MIN }
});

cuviper avatar Nov 16 '20 19:11 cuviper

Sorry, I was mistaken when I created this issue. I'm looking for a masking conversion to u64 where you discard the high bits.

carbotaniuman avatar Nov 19 '20 13:11 carbotaniuman