POLY: add build_polynom() method

We can build a polynom via an array of integers or just an empty
one, so that it is initialized and properly allocated.
This commit is contained in:
hasufell 2014-04-15 18:49:17 +02:00
parent b7b4ffbbea
commit e60d9c9bac
No known key found for this signature in database
GPG Key ID: 220CD1C5BDEED020
2 changed files with 57 additions and 0 deletions

View File

@ -19,8 +19,10 @@
* MA 02110-1301 USA
*/
#include "context.h"
#include "err.h"
#include <stdbool.h>
#include <stdio.h>
#include <tompoly.h>
#include <tommath.h>
@ -75,6 +77,55 @@ void init_polynom_size(pb_poly *new_poly, mp_int *chara, size_t size)
}
}
/**
* Initializes and builds a polynomial with the
* coefficient values of c[] of size len within NTRU
* context ctx and returns a newly allocated polynomial
* pointer.
*
* @param c array of polynomial coefficients, can be NULL
* @param len size of the coefficient array, can be 0
* @param ctx NTRU context
* @return newly allocated polynomial pointer, must be freed
* with delete_polynom()
*/
pb_poly *build_polynom(int const * const c,
const size_t len,
ntru_context *ctx)
{
pb_poly *new_poly;
mp_int chara;
new_poly = malloc(sizeof(*new_poly));
init_integer(&chara);
init_polynom_size(new_poly, &chara, len);
mp_clear(&chara);
/* fill the polynom if c is not NULL */
if (c) {
for (unsigned int i = 0; i < len; i++) {
bool sign = false;
unsigned long unsigned_c;
if (c[i] < 0) {
unsigned_c = 0 - c[i];
sign = true;
} else {
unsigned_c = c[i];
}
mp_set_int(&(new_poly->terms[i]), unsigned_c);
if (sign == true)
new_poly->terms[i].sign = 1;
}
new_poly->used = len;
pb_clamp(new_poly);
}
return new_poly;
}
/**
* This deletes the internal structure of a polynomial,
* and frees the pointer. Don't call this on stack variables,

View File

@ -23,6 +23,8 @@
#ifndef NTRU_POLY_H
#define NTRU_POLY_H
#include "context.h"
#include <tompoly.h>
#include <tommath.h>
@ -33,6 +35,10 @@ void init_polynom(pb_poly *new_poly, mp_int *chara);
void init_polynom_size(pb_poly *new_poly, mp_int *chara, size_t size);
pb_poly *build_polynom(int const * const c,
const size_t len,
ntru_context *ctx);
void delete_polynom(pb_poly *new_poly);
void draw_polynom(pb_poly * const poly);