ShiftJISEncoder.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { encoderError } from "../../encoding/encodings";
  2. import { finished } from "../../encoding/finished";
  3. import { indexShiftJISPointerFor } from "../../encoding/indexes";
  4. import { end_of_stream, isASCIICodePoint } from "../../encoding/terminology";
  5. import { inRange } from "../../encoding/utilities";
  6. /**
  7. * @constructor
  8. * @implements {Encoder}
  9. * @param {{fatal: boolean}} options
  10. */
  11. export class ShiftJISEncoder {
  12. constructor(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. handler(stream, code_point) {
  21. // 1. If code point is end-of-stream, return finished.
  22. if (code_point === end_of_stream)
  23. return finished;
  24. // 2. If code point is an ASCII code point or U+0080, return a
  25. // byte whose value is code point.
  26. if (isASCIICodePoint(code_point) || code_point === 0x0080)
  27. return code_point;
  28. // 3. If code point is U+00A5, return byte 0x5C.
  29. if (code_point === 0x00A5)
  30. return 0x5C;
  31. // 4. If code point is U+203E, return byte 0x7E.
  32. if (code_point === 0x203E)
  33. return 0x7E;
  34. // 5. If code point is in the range U+FF61 to U+FF9F, inclusive,
  35. // return a byte whose value is code point − 0xFF61 + 0xA1.
  36. if (inRange(code_point, 0xFF61, 0xFF9F))
  37. return code_point - 0xFF61 + 0xA1;
  38. // 6. If code point is U+2212, set it to U+FF0D.
  39. if (code_point === 0x2212)
  40. code_point = 0xFF0D;
  41. // 7. Let pointer be the index Shift_JIS pointer for code point.
  42. const pointer = indexShiftJISPointerFor(code_point);
  43. // 8. If pointer is null, return error with code point.
  44. if (pointer === null)
  45. return encoderError(code_point);
  46. // 9. Let lead be Math.floor(pointer / 188).
  47. const lead = Math.floor(pointer / 188);
  48. // 10. Let lead offset be 0x81, if lead is less than 0x1F, and
  49. // 0xC1 otherwise.
  50. const lead_offset = (lead < 0x1F) ? 0x81 : 0xC1;
  51. // 11. Let trail be pointer % 188.
  52. const trail = pointer % 188;
  53. // 12. Let offset be 0x40, if trail is less than 0x3F, and 0x41
  54. // otherwise.
  55. const offset = (trail < 0x3F) ? 0x40 : 0x41;
  56. // 13. Return two bytes whose values are lead + lead offset and
  57. // trail + offset.
  58. return [lead + lead_offset, trail + offset];
  59. }
  60. }
  61. //# sourceMappingURL=ShiftJISEncoder.js.map