1 #include "tommath_private.h"
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
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
)
13 size_t odd_nails
, nail_bytes
, i
, j
, count
;
14 uint8_t odd_nail_mask
;
18 count
= mp_pack_count(op
, nails
, size
);
20 if (count
> maxcount
) {
24 if ((err
= mp_init_copy(&t
, op
)) != MP_OKAY
) {
28 if (endian
== MP_NATIVE_ENDIAN
) {
29 MP_GET_ENDIANNESS(endian
);
32 odd_nails
= (nails
% 8u);
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
)) {
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
) {
59 if (written
!= NULL
) {