[SignalingServer] Optimize dependent modules
[platform/framework/web/wrtjs.git] / device_home / node_modules / qrcode / lib / core / reed-solomon-encoder.js
1 var BufferUtil = require('../utils/buffer')
2 var Polynomial = require('./polynomial')
3 var Buffer = require('buffer').Buffer
4
5 function ReedSolomonEncoder (degree) {
6   this.genPoly = undefined
7   this.degree = degree
8
9   if (this.degree) this.initialize(this.degree)
10 }
11
12 /**
13  * Initialize the encoder.
14  * The input param should correspond to the number of error correction codewords.
15  *
16  * @param  {Number} degree
17  */
18 ReedSolomonEncoder.prototype.initialize = function initialize (degree) {
19   // create an irreducible generator polynomial
20   this.degree = degree
21   this.genPoly = Polynomial.generateECPolynomial(this.degree)
22 }
23
24 /**
25  * Encodes a chunk of data
26  *
27  * @param  {Buffer} data Buffer containing input data
28  * @return {Buffer}      Buffer containing encoded data
29  */
30 ReedSolomonEncoder.prototype.encode = function encode (data) {
31   if (!this.genPoly) {
32     throw new Error('Encoder not initialized')
33   }
34
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)
39
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)
43
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
48   if (start > 0) {
49     var buff = BufferUtil.alloc(this.degree)
50     remainder.copy(buff, start)
51
52     return buff
53   }
54
55   return remainder
56 }
57
58 module.exports = ReedSolomonEncoder