num icon indicating copy to clipboard operation
num copied to clipboard

As (truncating) conversion for BigInt?

Open digama0 opened this issue 4 years ago • 5 comments

I might be missing it, but I don't see a version of Wrapping<u32> or other such wrapping conversions for BigInt. Specifically, I would like to be able to convert n: BigInt to (n % 2^N): uN and (n + 2^(N-1)) % 2^N - 2^(N-1): iN, which is what you would get with as conversion, except that BigInt is not a primitive type so it doesn't have an AsPrimitive implementation. Should this be a new trait, or a function?

digama0 avatar Mar 02 '21 07:03 digama0

I understand the mathematical representation, but what would you actually use this for?

cuviper avatar Mar 10 '21 19:03 cuviper

Well, my case might not be particularly interesting to you since I'm implementing a programming language which has this as a primitive operation, but it also participates in some commuting diagrams like u64 multiplication being equal to bigint multiplication followed by a truncation (or more generally, any expression involving multiplication, addition, and subtraction on u64 with wrapping semantics is equal to the corresponding expression using entirely bigint types, followed by a truncation operation). It's useful to isolate the truncation part from the other operations.

digama0 avatar Mar 11 '21 05:03 digama0

By the way, GMP's mpz_get_ui is prior art, if it helps to justify the existence of such an operation in the library (although that appears to be what I would call n.magnitude().truncate::<u64>(), since it ignores the sign instead of taking the 2's complement as in my proposed implementation).

digama0 avatar Mar 11 '21 05:03 digama0

If you want to write this, I'm open. I think we can add this just in num-bigint for now. A method seems nicer, but I'm not sure what constraints would suffice -- might need a new trait regardless.

cuviper avatar Apr 09 '21 23:04 cuviper

By a method, do you mean BigInt::truncate_u64, BigInt::truncate_i8, etc. as inherent methods? I can prepare a PR doing that for {BigInt, BigUint}::truncate_{ui}{8, 16, 32, 64, 128} if you want.

digama0 avatar Apr 10 '21 09:04 digama0