libtommath icon indicating copy to clipboard operation
libtommath copied to clipboard

Allow to define custom MP_MIN_DIGIT_COUNT.

Open J08nY opened this issue 1 year ago • 3 comments

Basically, some internal functions ignore MP_DEFAULT_DIGIT_COUNT and allocate much smaller, which then reads to reallocations quite a bit.

Allowing a custom MP_MIN_DIGIT_COUNT is nice when one wants to save reallocations, also related to constant-timeness a bit (#567).

J08nY avatar Nov 28 '23 14:11 J08nY

Hey there.

I went the way of allowing a custom MP_MIN_DIGIT_COUNT instead of modifying the uses in mp_init_size because I did not want to influence the default behavior of the library, but just allow me (and others that might find it useful) to modify it. The default behavior of the functions that use mp_init_size is likely right, they should know the appropriate size of the int they will need and so they allocate it. I guess even performance wise as it is now it may be better (depends on how you measure but it likely uses less memory as is).

My aim was to have libtommath with the least reallocations possible and with ints of a fixed size essentially. This is because I saw that the occasional mp_grow (and thus often a reallocation) caused significant timing differences that we do not want in our use of libtommath (and those timing differences also depended on the state of the allocator and the size of the alloc request).

With both the default and min digit count set to a sensible value (>= 2*field size for our ECC use case) we get way less reallocations and have more of fixed-size ints (though not really).

I am of course open to any change that gets this, I just don't want to be intrusive to other users of this library that might not want something like this.

J08nY avatar Nov 29 '23 08:11 J08nY

@czurnieden your opinion on this?

sjaeckel avatar Dec 05 '23 10:12 sjaeckel

@czurnieden your opinion on this?

A custom MP_MIN_DIGIT_COUNT by way of preprocessor allows for negative values and therefore quite large ones—still smaller than MP_MAX_DIGIT_COUNT—if the type of size changes to size_t . Either catch that (e.g. by moving check for size < 0down after thesize = MAX(...)` ) or put a warning note in the documentation.

Otherwise: yes, good idea, has my support.

czurnieden avatar Dec 05 '23 21:12 czurnieden