Merge pull request #578 from PX4/fix_mp_prime_strong_lucas_lefridge_compilation
[libtommath.git] / mp_pack.c
blob447f1fdf940843a885ea8f2178c1efe4ff065008
1 #include "tommath_private.h"
2 #ifdef MP_PACK_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 /* based on gmp's mpz_export.
7 * see http://gmplib.org/manual/Integer-Import-and-Export.html
8 */
9 mp_err mp_pack(void *rop, size_t maxcount, size_t *written, mp_order order, size_t size,
10 mp_endian endian, size_t nails, const mp_int *op)
12 mp_err err;
13 size_t odd_nails, nail_bytes, i, j, count;
14 uint8_t odd_nail_mask;
16 mp_int t;
18 count = mp_pack_count(op, nails, size);
20 if (count > maxcount) {
21 return MP_BUF;
24 if ((err = mp_init_copy(&t, op)) != MP_OKAY) {
25 return err;
28 if (endian == MP_NATIVE_ENDIAN) {
29 MP_GET_ENDIANNESS(endian);
32 odd_nails = (nails % 8u);
33 odd_nail_mask = 0xff;
34 for (i = 0u; i < odd_nails; ++i) {
35 odd_nail_mask ^= (uint8_t)(1u << (7u - i));
37 nail_bytes = nails / 8u;
39 for (i = 0u; i < count; ++i) {
40 for (j = 0u; j < size; ++j) {
41 uint8_t *byte = (uint8_t *)rop +
42 (((order == MP_LSB_FIRST) ? i : ((count - 1u) - i)) * size) +
43 ((endian == MP_LITTLE_ENDIAN) ? j : ((size - 1u) - j));
45 if (j >= (size - nail_bytes)) {
46 *byte = 0;
47 continue;
50 *byte = (uint8_t)((j == ((size - nail_bytes) - 1u)) ? (t.dp[0] & odd_nail_mask) : (t.dp[0] & 0xFFuL));
52 if ((err = mp_div_2d(&t, (j == ((size - nail_bytes) - 1u)) ? (int)(8u - odd_nails) : 8, &t, NULL)) != MP_OKAY) {
53 goto LBL_ERR;
59 if (written != NULL) {
60 *written = count;
62 err = MP_OKAY;
64 LBL_ERR:
65 mp_clear(&t);
66 return err;
69 #endif