reed-solomon-encoder.js 1.7 KB

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