aboutsummaryrefslogtreecommitdiffstats
path: root/libquanta_bigint_divmod_small__.c
blob: a2c345f6c18abad070478f14f4c286564633b465 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* See LICENSE file for copyright and license details. */
#include "common.h"


uintmax_t
libquanta_bigint_divmod_small__(struct bigint *big, uintmax_t small)
{
	uintmax_t q = 0, hi, lo;
	int e = 8 * (int)sizeof(small);

#if 0 /* this would overflow (undefined behaviour) and not fit in the result */
	q = big->high / small;
	q <<= 8 * (int)sizeof(small);
#endif
	big->high %= small;

	while (big->high && --e) {
		hi = small >> (8 * (int)sizeof(small) - e);
		lo = small << e;

		if (hi > big->high)
			continue;
		if (hi == big->high && lo > big->low)
			continue;

		q |= (uintmax_t)1 << e;
		bigint_sub_small(big, lo);
		big->high -= hi;
	}

	q += big->low / small;
	big->low %= small;
	return q;
}