utfSplitter.ts 896 B

1234567891011121314151617181920212223242526272829303132
  1. const partials = [
  2. [0b110, 5, 0],
  3. [0b1110, 4, 1],
  4. [0b11110, 3, 2],
  5. ]
  6. export class UTF8Splitter {
  7. private internal = Buffer.alloc(0)
  8. write (data: Buffer): Buffer {
  9. this.internal = Buffer.concat([this.internal, data])
  10. let keep = 0
  11. for (const [pattern, shift, maxOffset] of partials) {
  12. for (let offset = 0; offset < maxOffset + 1; offset++) {
  13. if (this.internal[this.internal.length - offset - 1] >> shift === pattern) {
  14. keep = Math.max(keep, offset + 1)
  15. }
  16. }
  17. }
  18. const result = this.internal.slice(0, this.internal.length - keep)
  19. this.internal = this.internal.slice(this.internal.length - keep)
  20. return result
  21. }
  22. flush (): Buffer {
  23. const result = this.internal
  24. this.internal = Buffer.alloc(0)
  25. return result
  26. }
  27. }