summaryrefslogtreecommitdiff
path: root/sys/src/libmp/port/mpmodop.c
blob: 331f1cc766f5e583e4e23ea3c83aa6e2c72f9002 (plain)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "os.h"
#include <mp.h>

/* operands need to have m->top+1 digits of space and satisfy 0 ≤ a ≤ m-1 */
static mpint*
modarg(mpint *a, mpint *m)
{
	if(a->size <= m->top || a->sign < 0 || mpmagcmp(a, m) >= 0){
		a = mpcopy(a);
		mpmod(a, m, a);
		mpbits(a, Dbits*(m->top+1));
		a->top = m->top;
	} else if(a->top < m->top){
		memset(&a->p[a->top], 0, (m->top - a->top)*Dbytes);
	}
	return a;
}

void
mpmodadd(mpint *b1, mpint *b2, mpint *m, mpint *sum)
{
	mpint *a, *b;
	mpdigit d;
	int i, j;

	a = modarg(b1, m);
	b = modarg(b2, m);

	sum->flags |= (a->flags | b->flags) & MPtimesafe;
	mpbits(sum, Dbits*2*(m->top+1));

	mpvecadd(a->p, m->top, b->p, m->top, sum->p);
	mpvecsub(sum->p, m->top+1, m->p, m->top, sum->p+m->top+1);

	d = sum->p[2*m->top+1];
	for(i = 0, j = m->top+1; i < m->top; i++, j++)
		sum->p[i] = (sum->p[i] & d) | (sum->p[j] & ~d);

	sum->top = m->top;
	sum->sign = 1;
	mpnorm(sum);

	if(a != b1)
		mpfree(a);
	if(b != b2)
		mpfree(b);
}

void
mpmodsub(mpint *b1, mpint *b2, mpint *m, mpint *diff)
{
	mpint *a, *b;
	mpdigit d;
	int i, j;

	a = modarg(b1, m);
	b = modarg(b2, m);

	diff->flags |= (a->flags | b->flags) & MPtimesafe;
	mpbits(diff, Dbits*2*(m->top+1));

	a->p[m->top] = 0;
	mpvecsub(a->p, m->top+1, b->p, m->top, diff->p);
	mpvecadd(diff->p, m->top, m->p, m->top, diff->p+m->top+1);

	d = ~diff->p[m->top];
	for(i = 0, j = m->top+1; i < m->top; i++, j++)
		diff->p[i] = (diff->p[i] & d) | (diff->p[j] & ~d);

	diff->top = m->top;
	diff->sign = 1;
	mpnorm(diff);

	if(a != b1)
		mpfree(a);
	if(b != b2)
		mpfree(b);
}

void
mpmodmul(mpint *b1, mpint *b2, mpint *m, mpint *prod)
{
	mpint *a, *b;

	a = modarg(b1, m);
	b = modarg(b2, m);

	mpmul(a, b, prod);
	mpmod(prod, m, prod);

	if(a != b1)
		mpfree(a);
	if(b != b2)
		mpfree(b);
}