1 var BufferUtil = require('../utils/buffer')
2 var GF = require('./galois-field')
5 * Multiplies two polynomials inside Galois Field
7 * @param {Buffer} p1 Polynomial
8 * @param {Buffer} p2 Polynomial
9 * @return {Buffer} Product of p1 and p2
11 exports.mul = function mul (p1, p2) {
12 var coeff = BufferUtil.alloc(p1.length + p2.length - 1)
14 for (var i = 0; i < p1.length; i++) {
15 for (var j = 0; j < p2.length; j++) {
16 coeff[i + j] ^= GF.mul(p1[i], p2[j])
24 * Calculate the remainder of polynomials division
26 * @param {Buffer} divident Polynomial
27 * @param {Buffer} divisor Polynomial
28 * @return {Buffer} Remainder
30 exports.mod = function mod (divident, divisor) {
31 var result = BufferUtil.from(divident)
33 while ((result.length - divisor.length) >= 0) {
36 for (var i = 0; i < divisor.length; i++) {
37 result[i] ^= GF.mul(divisor[i], coeff)
40 // remove all zeros from buffer head
42 while (offset < result.length && result[offset] === 0) offset++
43 result = result.slice(offset)
50 * Generate an irreducible generator polynomial of specified degree
51 * (used by Reed-Solomon encoder)
53 * @param {Number} degree Degree of the generator polynomial
54 * @return {Buffer} Buffer containing polynomial coefficients
56 exports.generateECPolynomial = function generateECPolynomial (degree) {
57 var poly = BufferUtil.from([1])
58 for (var i = 0; i < degree; i++) {
59 poly = exports.mul(poly, [1, GF.exp(i)])