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

Add `truncate_*` operations on `BigInt` and `BigUint`

Open digama0 opened this issue 3 years ago • 3 comments

Implements https://github.com/rust-num/num/issues/404

digama0 avatar Apr 11 '21 09:04 digama0

Hi @cuviper, gentle reminder that this PR exists and could use review.

digama0 avatar May 20 '21 20:05 digama0

I wonder if there's a way we can do this generically, rather than so many new methods, something like:

impl BigUint {
    pub fn truncate<T>(&self) -> T
    where
        T: PrimInt,
        u128: AsPrimitive<T>,
    {
        todo!("truncate as u128").as_()
    }
}

impl BigInt {
    pub fn truncate<T>(&self) -> T
    where
        T: PrimInt,
        i128: AsPrimitive<T>,
    {
        todo!("truncate as i128").as_()
    }
}

The u128/i128 distinction here doesn't really matter, but it looks appropriate.

Or maybe T: PrimInt is sufficient to build T directly? Not sure -- I think signs may be tricky.

cuviper avatar May 22 '21 00:05 cuviper

Check out the latest commit for a version that puts all the functions under a trait. It's not PrimInt, but a TruncateFrom trait; the actual front-end functions are the inherent truncate methods on BigInt and BigUint (which allows for turbofishing and also avoids the need to import the trait at use sites). BigInt::truncate has the cumbersome bound TruncateFrom<BigUint> + Zero + WrappingNeg but users shouldn't have to deal with it directly.

It probably shouldn't be merged as is, but if this looks good then the trait should move to the num_traits crate.

digama0 avatar May 26 '21 06:05 digama0