uint8ArrayWriter.js 961 B

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. var utils = require('./utils');
  3. /**
  4. * An object to write any content to an Uint8Array.
  5. * @constructor
  6. * @param {number} length The length of the array.
  7. */
  8. var Uint8ArrayWriter = function(length) {
  9. this.data = new Uint8Array(length);
  10. this.index = 0;
  11. };
  12. Uint8ArrayWriter.prototype = {
  13. /**
  14. * Append any content to the current array.
  15. * @param {Object} input the content to add.
  16. */
  17. append: function(input) {
  18. if (input.length !== 0) {
  19. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  20. input = utils.transformTo("uint8array", input);
  21. this.data.set(input, this.index);
  22. this.index += input.length;
  23. }
  24. },
  25. /**
  26. * Finalize the construction an return the result.
  27. * @return {Uint8Array} the generated array.
  28. */
  29. finalize: function() {
  30. return this.data;
  31. }
  32. };
  33. module.exports = Uint8ArrayWriter;