aleaxit / gmpy

General Multi-Precision arithmetic for Python 2.6+/3+ (GMP, MPIR, MPFR, MPC)
https://gmpy2.readthedocs.io/en/latest/
GNU Lesser General Public License v3.0
518 stars 86 forks source link

Add mpz.to_bytes()/from_bytes() #394

Closed skirpichev closed 1 year ago

skirpichev commented 1 year ago

Closes #357

Some benchmarks:

$ python -m timeit -s 'from math import factorial' -s 'a = factorial(57)' 'a.to_bytes(32)'
500000 loops, best of 5: 285 nsec per loop
$ python -m timeit -s 'from gmpy2 import fac' -s 'a = fac(57)' 'a.to_bytes(32)'
500000 loops, best of 5: 486 nsec per loop
$ python -m timeit -s 'from gmpy2 import fac' -s 'a = fac(57)' 'int(a).to_bytes(32)'
500000 loops, best of 5: 823 nsec per loop

It seems, int.to_bytes() is slightly better than the mpz_export.

I don't know which formatting should be used for the C code, so PEP 7 is used. Let me know if I shouldn't use braces for single-line if/for statements or something else.

BTW, this PR adds an optional dependency on pytest and hypothesis, so added bulk tests check that mpz.to_bytes/from_bytes output match int's functions output for same integers. To always keep some fixed set of tested values (e.g. for code coverage) - the "example" decorator is used.

codecov-commenter commented 1 year ago

Codecov Report

Merging #394 (e22279e) into master (dd12e9a) will increase coverage by 0.24%. The diff coverage is 100.00%.

:mega: This organization is not using Codecov’s GitHub App Integration. We recommend you install it so Codecov can continue to function properly for your repositories. Learn more

@@            Coverage Diff             @@
##           master     #394      +/-   ##
==========================================
+ Coverage   82.34%   82.58%   +0.24%     
==========================================
  Files          49       49              
  Lines       11553    11714     +161     
  Branches     2151     2197      +46     
==========================================
+ Hits         9513     9674     +161     
  Misses       2040     2040              
Impacted Files Coverage Δ
src/gmpy2_mpz_misc.c 100.00% <100.00%> (ø)

:mega: We’re building smart automated test selection to slash your CI/CD build times. Learn more

casevh commented 1 year ago

Thanks.

The C formatting style is correct.

I just noticed this after I merged. Instead of using TEMP_ALLOC(buffer,length), can we use PyBytes_FromStringAndSize(NULL, length) to create the buffer of the correct length and then manipulate the internal data directly. See also PyBytes_AS_STRING.

Case