Merge pull request #4 from thesamesam/develop
[libtompoly.git] / pb_add.c
blob6709e7d0ff40144bbe33e2f59305244bfd74d8b8
1 /* LibTomPoly, Polynomial Basis Math -- Tom St Denis
2 *
3 * LibTomPoly is a public domain library that provides
4 * polynomial basis arithmetic support. It relies on
5 * LibTomMath for large integer support.
7 * This library is free for all purposes without any
8 * express guarantee that it works.
10 * Tom St Denis, tomstdenis@iahu.ca, http://poly.libtomcrypt.org
12 #include <tompoly.h>
14 int pb_add(pb_poly *a, pb_poly *b, pb_poly *c)
16 int err, x, y, z, characteristic;
17 pb_poly *tmp;
19 /* grow c to be the max size */
20 y = PB_MAX(a->used, b->used);
21 if (c->alloc < y) {
22 if ((err = pb_grow(c, y)) != MP_OKAY) {
23 return err;
27 /* do we need to concern char */
28 characteristic = mp_iszero(&(c->characteristic));
30 /* add the terms */
31 z = PB_MIN(a->used, b->used);
32 for (x = 0; x < z; x++) {
33 if ((err = mp_add(&(a->terms[x]), &(b->terms[x]), &(c->terms[x]))) != MP_OKAY) {
34 return err;
36 if (characteristic == MP_NO) {
37 if ((err = mp_mod(&(c->terms[x]), &(c->characteristic), &(c->terms[x]))) != MP_OKAY) {
38 return err;
43 /* excess digits? */
44 if (y != z) {
45 if (a->used == y) {
46 tmp = a;
47 } else {
48 tmp = b;
50 for (x = z; x < y; x++) {
51 if (characteristic == MP_NO) {
52 if ((err = mp_mod(&(tmp->terms[x]), &(c->characteristic), &(c->terms[x]))) != MP_OKAY) {
53 return err;
55 } else {
56 if ((err = mp_copy(&(tmp->terms[x]), &(c->terms[x]))) != MP_OKAY) {
57 return err;
63 /* zero excess */
64 for (x = y; x < c->used; x++) {
65 mp_zero(&(c->terms[x]));
67 c->used = y;
68 pb_clamp(c);
70 return MP_OKAY;