aboutsummaryrefslogtreecommitdiffstats
path: root/src/zlsh.c
blob: 42894e024f90959d4a78cbdd615e522436f876e6 (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
35
36
37
38
39
40
41
42
43
44
45
46
/* See LICENSE file for copyright and license details. */
#include "internals.h"


void
zlsh(z_t a, z_t b, size_t bits)
{
	size_t i, chars, cbits;
	zahl_char_t carry[] = {0, 0};

	if (unlikely(zzero(b))) {
		SET_SIGNUM(a, 0);
		return;
	}
	if (unlikely(!bits)) {
		SET(a, b);
		return;
	}

	chars = FLOOR_BITS_TO_CHARS(bits);
	bits = BITS_IN_LAST_CHAR(bits);
	cbits = BITS_PER_CHAR - bits;

	ENSURE_SIZE(a, b->used + chars);
	if (likely(a == b))
		zmemmove(a->chars + chars, b->chars, b->used);
	else
		zmemcpy(a->chars + chars, b->chars, b->used);
	zmemset(a->chars, 0, chars);
	a->used = b->used + chars;

	if (likely(bits)) { /* This if statement is very important in C. */
		for (i = chars; i < a->used; i++) {
			carry[~i & 1] = a->chars[i] >> cbits;
			a->chars[i] <<= bits;
			a->chars[i] |= carry[i & 1];
		}
		if (carry[i & 1]) {
			ENSURE_SIZE(a, a->used + 1);
			a->chars[i] = carry[i & 1];
			a->used++;
		}
	}

	SET_SIGNUM(a, zsignum(b));
}