kokke / tiny-bignum-c

Small portable multiple-precision unsigned integer arithmetic in C
The Unlicense
419 stars 86 forks source link

For ease of use there should be a function telling the size of string for bignum_to_string() #30

Open yurivict opened 2 years ago

yurivict commented 2 years ago

Otherwise the user of bignum_to_string() should guess how many characters might be needed?

kokke commented 2 years ago

Hi @yurivict and thanks for your interest in the project :)

You raise a good question!

Otherwise the user of bignum_to_string() should guess how many characters might be needed?

No guessing is needed, but I completely understand if it's not immediately obvious.

You use two bytes to represent each byte of the bignum (always -> because of hex-string representation).

If you are using e.g. 1024-bit bignums, you need 2048 bits of space + a null-termination byte. The bignum_to_string function also null-terminates the string for you, so if you pass it "too much memory" it will still work.

From the README (emphasis mine)

No dynamic memory management is utilized, and stdio.h is only used for testing functions parsing to and from hex-strings.

So I consider bignum_to_string and bignum_from_string to be used only for testing and I am not sure I agree that a new function needs to be added.

A quick idea instead would be to make a macro like #define BN_STR_FMT_BUF_SIZE ((2 * BN_ARRAY_SIZE) + 1) or something along that way.

I think that should do the trick, but I haven't tested it - it's just off the top of my head :)