Stream.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { end_of_stream } from "../encoding/terminology";
  2. /**
  3. * A stream represents an ordered sequence of tokens.
  4. */
  5. var Stream = /** @class */ (function () {
  6. /**
  7. *
  8. * @constructor
  9. * @param {!(Array.<number>|Uint8Array)} tokens Array of tokens that provide
  10. * the stream.
  11. */
  12. function Stream(tokens) {
  13. /** @type {!Array.<number>} */
  14. this.tokens = Array.from(tokens);
  15. // Reversed as push/pop is more efficient than shift/unshift.
  16. this.tokens.reverse();
  17. }
  18. /**
  19. * @return {boolean} True if end-of-stream has been hit.
  20. */
  21. Stream.prototype.endOfStream = function () {
  22. return !this.tokens.length;
  23. };
  24. /**
  25. * When a token is read from a stream, the first token in the
  26. * stream must be returned and subsequently removed, and
  27. * end-of-stream must be returned otherwise.
  28. *
  29. * @return {number} Get the next token from the stream, or
  30. * end_of_stream.
  31. */
  32. Stream.prototype.read = function () {
  33. if (!this.tokens.length)
  34. return end_of_stream;
  35. return this.tokens.pop();
  36. };
  37. /**
  38. * When one or more tokens are prepended to a stream, those tokens
  39. * must be inserted, in given order, before the first token in the
  40. * stream.
  41. *
  42. * @param {(number|!Array.<number>)} token The token(s) to prepend to the
  43. * stream.
  44. */
  45. Stream.prototype.prepend = function (token) {
  46. if (Array.isArray(token)) {
  47. var tokens = (token);
  48. while (tokens.length)
  49. this.tokens.push(tokens.pop());
  50. }
  51. else {
  52. this.tokens.push(token);
  53. }
  54. };
  55. /**
  56. * When one or more tokens are pushed to a stream, those tokens
  57. * must be inserted, in given order, after the last token in the
  58. * stream.
  59. *
  60. * @param {(number|!Array.<number>)} token The tokens(s) to push to the
  61. * stream.
  62. */
  63. Stream.prototype.push = function (token) {
  64. if (Array.isArray(token)) {
  65. var tokens = (token);
  66. while (tokens.length)
  67. this.tokens.unshift(tokens.shift());
  68. }
  69. else {
  70. this.tokens.unshift(token);
  71. }
  72. };
  73. return Stream;
  74. }());
  75. export { Stream };
  76. //# sourceMappingURL=Stream.js.map