reed-solomon-encoder.js 1.6 KB

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