Stream.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { end_of_stream } from "../encoding/terminology";
  2. /**
  3. * A stream represents an ordered sequence of tokens.
  4. */
  5. export class Stream {
  6. /**
  7. *
  8. * @constructor
  9. * @param {!(Array.<number>|Uint8Array)} tokens Array of tokens that provide
  10. * the stream.
  11. */
  12. constructor(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. endOfStream() {
  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. read() {
  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. prepend(token) {
  46. if (Array.isArray(token)) {
  47. const 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. push(token) {
  64. if (Array.isArray(token)) {
  65. const tokens = (token);
  66. while (tokens.length)
  67. this.tokens.unshift(tokens.shift());
  68. }
  69. else {
  70. this.tokens.unshift(token);
  71. }
  72. }
  73. }
  74. //# sourceMappingURL=Stream.js.map