nim-lang / bigints

BigInts for Nim
MIT License
124 stars 32 forks source link

Empty limbs when uninitialized #26

Closed auxym closed 4 years ago

auxym commented 4 years ago

Consider the following:

var
    a: BigInt
    b: BigInt = 12.initBigInt

echo a*b

This results in the following stack trace:

[...]/scratch.nim(7) scratch
[...].nimble/pkgs/bigints-0.4.3/bigints.nim(484) *
[...].nimble/pkgs/bigints-0.4.3/bigints.nim(394) multiplication
[...].choosenim/toolchains/nim-#devel/lib/system/fatal.nim(39) sysFatal
Error: unhandled exception: index out of bounds, the container is empty [IndexError]

This is because a.limbs is @[]. Would it be possible for an uninitialized BigInt to default to limbs = @[0], to be consistent with nim integers? Otherwise, maybe there could be a flag initialized that is checked before trying to operate on a BigInt, so we get slightly more readable errors. I'm not super proud about it, but tbh this took me a while to debug. To be fair, my actual code was slightly more complex and resulted in a zero BigInt not being initialized in a corner case.

def- commented 4 years ago

Sounds good but would require https://github.com/nim-lang/RFCs/issues/126

Alternatively we could handle @[] as the same as @[0]. I'd accept a PR that adds this.

auxym commented 4 years ago

Yeah, I wasn't sure if/how it could be implemented in Nim. Good to know there's an RFC about it!