UTF16Encoder.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { finished } from "../../encoding/finished";
  2. import { end_of_stream } from "../../encoding/terminology";
  3. import { inRange } from "../../encoding/utilities";
  4. import { convertCodeUnitToBytes } from "./converCodeUnitToBytes";
  5. /**
  6. * @constructor
  7. * @implements {Encoder}
  8. * @param {boolean} utf16_be True if big-endian, false if little-endian.
  9. * @param {{fatal: boolean}} options
  10. */
  11. export class UTF16Encoder {
  12. constructor(utf16_be, options) {
  13. this.utf16_be = utf16_be;
  14. this.fatal = options.fatal;
  15. }
  16. /**
  17. * @param {Stream} stream Input stream.
  18. * @param {number} code_point Next code point read from the stream.
  19. * @return {(number|!Array.<number>)} Byte(s) to emit.
  20. */
  21. handler(stream, code_point) {
  22. // 1. If code point is end-of-stream, return finished.
  23. if (code_point === end_of_stream)
  24. return finished;
  25. // 2. If code point is in the range U+0000 to U+FFFF, inclusive,
  26. // return the sequence resulting of converting code point to
  27. // bytes using utf-16be encoder flag.
  28. if (inRange(code_point, 0x0000, 0xFFFF))
  29. return convertCodeUnitToBytes(code_point, this.utf16_be);
  30. // 3. Let lead be ((code point − 0x10000) >> 10) + 0xD800,
  31. // converted to bytes using utf-16be encoder flag.
  32. const lead = convertCodeUnitToBytes(((code_point - 0x10000) >> 10) + 0xD800, this.utf16_be);
  33. // 4. Let trail be ((code point − 0x10000) & 0x3FF) + 0xDC00,
  34. // converted to bytes using utf-16be encoder flag.
  35. const trail = convertCodeUnitToBytes(((code_point - 0x10000) & 0x3FF) + 0xDC00, this.utf16_be);
  36. // 5. Return a byte sequence of lead followed by trail.
  37. return lead.concat(trail);
  38. }
  39. }
  40. //# sourceMappingURL=UTF16Encoder.js.map