node-qrcode-lite/lib/core/reed-solomon-encoder.js
Vincenzo Greco 77064f5e5e Refactor/core ()
* Split core lib into multiple files

* Refactor data encoding methods

* Refactor data masking process

* Improve qr code generation process

* Increase minimum required node version to 0.10

* Add linter

* Add tests and tests coverage

* Update travis config to fix compilation issues

* Add examples folder

* Add missing license tag in package.json

* Update build script and add sourcemap support

* Publish only strictly needed files on npm

* Update readme
2016-12-16 23:45:08 +01:00

59 lines
1.7 KiB
JavaScript

var Buffer = require('../utils/buffer')
var Polynomial = require('./polynomial')
function ReedSolomonEncoder (degree) {
this.genPoly = undefined
this.degree = degree
if (this.degree) this.initialize(this.degree)
}
/**
* Initialize the encoder.
* The input param should correspond to the number of error correction codewords.
*
* @param {Number} degree
*/
ReedSolomonEncoder.prototype.initialize = function initialize (degree) {
// create an irreducible generator polynomial
this.degree = degree
this.genPoly = Polynomial.generateECPolynomial(this.degree)
}
/**
* Encodes a chunk of data
*
* @param {Buffer} data Buffer containing input data
* @return {Buffer} Buffer containing encoded data
*/
ReedSolomonEncoder.prototype.encode = function encode (data) {
if (!this.genPoly) {
throw new Error('Encoder not initialized')
}
// Calculate EC for this data block
// extends data size to data+genPoly size
var pad = new Buffer(this.degree)
pad.fill(0)
var paddedData = Buffer.concat([data, pad], data.length + this.degree)
// The error correction codewords are the remainder after dividing the data codewords
// by a generator polynomial
var remainder = Polynomial.mod(paddedData, this.genPoly)
// return EC data blocks (last n byte, where n is the degree of genPoly)
// If coefficients number in remainder are less than genPoly degree,
// pad with 0s to the left to reach the needed number of coefficients
var start = this.degree - remainder.length
if (start > 0) {
var buff = new Buffer(this.degree)
buff.fill(0)
remainder.copy(buff, start)
return buff
}
return remainder
}
module.exports = ReedSolomonEncoder