single-byte.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { end_of_stream, finished, isASCIIByte, decoderError, encoderError, isASCIICodePoint } from './text_decoder_utils.js'
  2. import { indexPointerFor } from './text_decoder_indexes.js'
  3. //
  4. // 10. Legacy single-byte encodings
  5. //
  6. // 10.1 single-byte decoder
  7. /**
  8. * @implements {Decoder}
  9. */
  10. export class SingleByteDecoder {
  11. /**
  12. * @param {!Array.<number>} index The encoding index.
  13. * @param {{fatal: boolean}} options
  14. */
  15. constructor(index, options) {
  16. const { fatal } = options
  17. this.fatal = fatal
  18. this.index = index
  19. }
  20. /**
  21. * @param {Stream} stream The stream of bytes being decoded.
  22. * @param {number} bite The next byte read from the stream.
  23. */
  24. handler(stream, bite) {
  25. // 1. If byte is end-of-stream, return finished.
  26. if (bite === end_of_stream)
  27. return finished
  28. // 2. If byte is an ASCII byte, return a code point whose value
  29. // is byte.
  30. if (isASCIIByte(bite))
  31. return bite
  32. // 3. Let code point be the index code point for byte − 0x80 in
  33. // index single-byte.
  34. var code_point = this.index[bite - 0x80]
  35. // 4. If code point is null, return error.
  36. if (code_point === null)
  37. return decoderError(this.fatal)
  38. // 5. Return a code point whose value is code point.
  39. return code_point
  40. }
  41. }
  42. // 10.2 single-byte encoder
  43. /**
  44. * @implements {Encoder}
  45. */
  46. export class SingleByteEncoder {
  47. /**
  48. * @param {!Array.<?number>} index The encoding index.
  49. */
  50. constructor(index) {
  51. this.index = index
  52. }
  53. /**
  54. * @param {Stream} stream Input stream.
  55. * @param {number} code_point Next code point read from the stream.
  56. * @return {(number|!Array.<number>)} Byte(s) to emit.
  57. */
  58. handler(stream, code_point) {
  59. // 1. If code point is end-of-stream, return finished.
  60. if (code_point === end_of_stream)
  61. return finished
  62. // 2. If code point is an ASCII code point, return a byte whose
  63. // value is code point.
  64. if (isASCIICodePoint(code_point))
  65. return code_point
  66. // 3. Let pointer be the index pointer for code point in index
  67. // single-byte.
  68. const pointer = indexPointerFor(code_point, this.index)
  69. // 4. If pointer is null, return error with code point.
  70. if (pointer === null)
  71. encoderError(code_point)
  72. // 5. Return a byte whose value is pointer + 0x80.
  73. return pointer + 0x80
  74. }
  75. }