754a466036f5ab8013d9a1f2c74ff52a4c62f98219f86350b7ffd739df289cf6b47cdddf49427e99187efa48dd5efb6101058b26315e32496a054a9804f272 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const bufLength = 1024 * 16;
  2. // Provide a fallback for older environments.
  3. const td =
  4. typeof TextDecoder !== 'undefined'
  5. ? /* #__PURE__ */ new TextDecoder()
  6. : typeof Buffer !== 'undefined'
  7. ? {
  8. decode(buf: Uint8Array): string {
  9. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  10. return out.toString();
  11. },
  12. }
  13. : {
  14. decode(buf: Uint8Array): string {
  15. let out = '';
  16. for (let i = 0; i < buf.length; i++) {
  17. out += String.fromCharCode(buf[i]);
  18. }
  19. return out;
  20. },
  21. };
  22. export class StringWriter {
  23. pos = 0;
  24. private out = '';
  25. private buffer = new Uint8Array(bufLength);
  26. write(v: number): void {
  27. const { buffer } = this;
  28. buffer[this.pos++] = v;
  29. if (this.pos === bufLength) {
  30. this.out += td.decode(buffer);
  31. this.pos = 0;
  32. }
  33. }
  34. flush(): string {
  35. const { buffer, out, pos } = this;
  36. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  37. }
  38. }
  39. export class StringReader {
  40. pos = 0;
  41. declare private buffer: string;
  42. constructor(buffer: string) {
  43. this.buffer = buffer;
  44. }
  45. next(): number {
  46. return this.buffer.charCodeAt(this.pos++);
  47. }
  48. peek(): number {
  49. return this.buffer.charCodeAt(this.pos);
  50. }
  51. indexOf(char: string): number {
  52. const { buffer, pos } = this;
  53. const idx = buffer.indexOf(char, pos);
  54. return idx === -1 ? buffer.length : idx;
  55. }
  56. }