Merge pull request #4 from thesamesam/develop
[libtompoly.git] / pb_sub.c
blobc11cd88b59d7bdb6b9d1167bb928307bda4eb66a
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_sub(pb_poly *a, pb_poly *b, pb_poly *c)
16 int neg, 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 /* sub the terms */
31 z = PB_MIN(a->used, b->used);
32 for (x = 0; x < z; x++) {
33 if ((err = mp_sub(&(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 neg = 0;
48 } else {
49 tmp = b;
50 neg = 1;
52 for (x = z; x < y; x++) {
53 if (characteristic == MP_NO) {
54 if ((err = mp_mod(&(tmp->terms[x]), &(c->characteristic), &(c->terms[x]))) != MP_OKAY) {
55 return err;
57 if (neg) {
58 if ((err = mp_sub(&(c->characteristic), &(c->terms[x]), &(c->terms[x]))) != MP_OKAY) {
59 return err;
62 } else {
63 if (neg) {
64 if ((err = mp_neg(&(tmp->terms[x]), &(c->terms[x]))) != MP_OKAY) {
65 return err;
67 } else {
68 if ((err = mp_copy(&(tmp->terms[x]), &(c->terms[x]))) != MP_OKAY) {
69 return err;
76 /* zero excess */
77 for (x = y; x < c->used; x++) {
78 mp_zero(&(c->terms[x]));
80 c->used = y;
81 pb_clamp(c);
83 return MP_OKAY;