UTF8Encoder.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. var finished_1 = require("../../encoding/finished");
  4. var terminology_1 = require("../../encoding/terminology");
  5. var utilities_1 = require("../../encoding/utilities");
  6. /**
  7. * @constructor
  8. * @implements {Encoder}
  9. * @param {{fatal: boolean}} options
  10. */
  11. var UTF8Encoder = /** @class */ (function () {
  12. function UTF8Encoder(options) {
  13. this.fatal = options.fatal;
  14. }
  15. /**
  16. * @param {Stream} stream Input stream.
  17. * @param {number} code_point Next code point read from the stream.
  18. * @return {(number|!Array.<number>)} Byte(s) to emit.
  19. */
  20. UTF8Encoder.prototype.handler = function (stream, code_point) {
  21. // 1. If code point is end-of-stream, return finished.
  22. if (code_point === terminology_1.end_of_stream)
  23. return finished_1.finished;
  24. // 2. If code point is an ASCII code point, return a byte whose
  25. // value is code point.
  26. if (terminology_1.isASCIICodePoint(code_point))
  27. return code_point;
  28. // 3. Set count and offset based on the range code point is in:
  29. var count, offset;
  30. // U+0080 to U+07FF, inclusive:
  31. if (utilities_1.inRange(code_point, 0x0080, 0x07FF)) {
  32. // 1 and 0xC0
  33. count = 1;
  34. offset = 0xC0;
  35. }
  36. // U+0800 to U+FFFF, inclusive:
  37. else if (utilities_1.inRange(code_point, 0x0800, 0xFFFF)) {
  38. // 2 and 0xE0
  39. count = 2;
  40. offset = 0xE0;
  41. }
  42. // U+10000 to U+10FFFF, inclusive:
  43. else if (utilities_1.inRange(code_point, 0x10000, 0x10FFFF)) {
  44. // 3 and 0xF0
  45. count = 3;
  46. offset = 0xF0;
  47. }
  48. // 4. Let bytes be a byte sequence whose first byte is (code
  49. // point >> (6 × count)) + offset.
  50. var bytes = [(code_point >> (6 * count)) + offset];
  51. // 5. Run these substeps while count is greater than 0:
  52. while (count > 0) {
  53. // 1. Set temp to code point >> (6 × (count − 1)).
  54. var temp = code_point >> (6 * (count - 1));
  55. // 2. Append to bytes 0x80 | (temp & 0x3F).
  56. bytes.push(0x80 | (temp & 0x3F));
  57. // 3. Decrease count by one.
  58. count -= 1;
  59. }
  60. // 6. Return bytes bytes, in order.
  61. return bytes;
  62. };
  63. return UTF8Encoder;
  64. }());
  65. exports.UTF8Encoder = UTF8Encoder;
  66. //# sourceMappingURL=UTF8Encoder.js.map