Merge pull request #4 from thesamesam/develop
[libtompoly.git] / pb_readraw.c
blob8e4b70a77ddae49c6dfd1a3835ed1042d9794c54
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_readraw(pb_poly *a, unsigned char *buf, int len)
16 int terms, x, y, z, err;
18 /* zero poly */
19 pb_zero(a);
21 /* must be at least four bytes */
22 if (len < 4) {
23 return MP_VAL;
26 /* number of terms */
27 terms = ((unsigned)buf[0]) | ((unsigned)buf[1]<<8);
28 y = 2;
30 /* grow to the right size */
31 if (a->alloc < terms) {
32 if ((err = pb_grow(a, terms)) != MP_OKAY) {
33 return err;
37 /* read characteristic */
38 z = ((unsigned)buf[y]) | ((unsigned)buf[y+1]<<8); y += 2;
39 if (z + y > len) { return MP_VAL; }
40 if ((err = mp_read_signed_bin(&(a->characteristic), buf+y, z)) != MP_OKAY) { return err; }
41 y += z;
44 /* read terms */
45 for (x = 0; x < terms; x++) {
46 z = ((unsigned)buf[y]) | ((unsigned)buf[y+1]<<8); y += 2;
47 if (z + y > len) { return MP_VAL; }
48 if ((err = mp_read_signed_bin(&(a->characteristic), buf+y, z)) != MP_OKAY) { return err; }
49 y += z;
52 return MP_OKAY;