Skip to content

Commit

Permalink
added hamdist to the LibTomMath backend
Browse files Browse the repository at this point in the history
  • Loading branch information
antoinemine committed Aug 20, 2024
1 parent 9f9f146 commit f3e70f9
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
37 changes: 35 additions & 2 deletions caml_z_tommath.c
Original file line number Diff line number Diff line change
Expand Up @@ -1825,9 +1825,42 @@ CAMLprim value ml_z_popcount(value arg)
}
}

CAMLprim value ml_z_hamdist(UNUSED_PARAM value arg1, UNUSED_PARAM value arg2)
CAMLprim value ml_z_hamdist(value arg1, value arg2)
{
caml_failwith("Z.hamdist: not implemented in LibTomMath backend");
if (Z_ISNEG(arg1) != Z_ISNEG(arg2))
ml_z_raise_overflow();
/* XXX TODO: case where arg1 & arg2 are both negative */
if (Z_ISNEG(arg1) || Z_ISNEG(arg2))
caml_invalid_argument("Z.hamdist: negative arguments");
if (Is_long(arg1) && Is_long(arg2)) {
return Val_long(ml_z_count(Long_val(arg1) ^ Long_val(arg2)));
}
else {
Z_DECL(arg1);
Z_DECL(arg2);
intnat r = 0;
mp_digit *a1, *a2;
size_t len1, len2;
Z_ARG(arg1);
Z_ARG(arg2);
/* a1 is the shortest one */
if (mp_arg1->used <= mp_arg2->used) {
a1 = mp_arg1->dp; len1 = mp_arg1->used;
a2 = mp_arg2->dp; len2 = mp_arg2->used;
}
else {
a1 = mp_arg2->dp; len1 = mp_arg2->used;
a2 = mp_arg1->dp; len2 = mp_arg1->used;
}
for (size_t i = 0; i < len1; i++)
r += ml_z_count(a1[i] ^ a2[i]);
for (size_t i = len1; i < len2; i++)
r += ml_z_count(a2[i]);
Z_END_ARG(arg1);
Z_END_ARG(arg2);
if (r < 0 || !Z_FITS_INT(r)) ml_z_raise_overflow();
return Val_long(r);
}
}

CAMLprim value ml_z_testbit(value arg, value index)
Expand Down
26 changes: 25 additions & 1 deletion tests/zq.output-LibTomMath-64-60
Original file line number Diff line number Diff line change
Expand Up @@ -889,7 +889,31 @@ popcount 2^120
= 1
popcount (2^120-1)
= 120
Failure: Z.hamdist: not implemented in LibTomMath backend
hamdist 0 0
= 0
hamdist 0 1
= 1
hamdist 0 2^300
= 1
hamdist 2^120 2^120
= 0
hamdist 2^120 (2^120-1)
= 121
hamdist 2^120 2^300
= 2
hamdist (2^120-1) (2^300-1)
= 180
divisible 42 7
= true
divisible 43 7
= false
divisible 0 0
= true
divisible 0 2^120
= true
divisible 2 2^120
= false
Failure: Z.divisible: not implemented in LibTomMath backend
hash(2^120)
= 900619431
hash(2^121)
Expand Down

0 comments on commit f3e70f9

Please sign in to comment.