1 var BufferUtil = require('../utils/buffer')
2 var Polynomial = require('./polynomial')
3 var Buffer = require('buffer').Buffer
5 function ReedSolomonEncoder (degree) {
6 this.genPoly = undefined
9 if (this.degree) this.initialize(this.degree)
13 * Initialize the encoder.
14 * The input param should correspond to the number of error correction codewords.
16 * @param {Number} degree
18 ReedSolomonEncoder.prototype.initialize = function initialize (degree) {
19 // create an irreducible generator polynomial
21 this.genPoly = Polynomial.generateECPolynomial(this.degree)
25 * Encodes a chunk of data
27 * @param {Buffer} data Buffer containing input data
28 * @return {Buffer} Buffer containing encoded data
30 ReedSolomonEncoder.prototype.encode = function encode (data) {
32 throw new Error('Encoder not initialized')
35 // Calculate EC for this data block
36 // extends data size to data+genPoly size
37 var pad = BufferUtil.alloc(this.degree)
38 var paddedData = Buffer.concat([data, pad], data.length + this.degree)
40 // The error correction codewords are the remainder after dividing the data codewords
41 // by a generator polynomial
42 var remainder = Polynomial.mod(paddedData, this.genPoly)
44 // return EC data blocks (last n byte, where n is the degree of genPoly)
45 // If coefficients number in remainder are less than genPoly degree,
46 // pad with 0s to the left to reach the needed number of coefficients
47 var start = this.degree - remainder.length
49 var buff = BufferUtil.alloc(this.degree)
50 remainder.copy(buff, start)
58 module.exports = ReedSolomonEncoder