sbcs-codec.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. "use strict"
  2. var Buffer = require("safer-buffer").Buffer
  3. // Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that
  4. // correspond to encoded bytes (if 128 - then lower half is ASCII).
  5. exports._sbcs = SBCSCodec
  6. function SBCSCodec (codecOptions, iconv) {
  7. if (!codecOptions) {
  8. throw new Error("SBCS codec is called without the data.")
  9. }
  10. // Prepare char buffer for decoding.
  11. if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) {
  12. throw new Error("Encoding '" + codecOptions.type + "' has incorrect 'chars' (must be of len 128 or 256)")
  13. }
  14. if (codecOptions.chars.length === 128) {
  15. var asciiString = ""
  16. for (var i = 0; i < 128; i++) {
  17. asciiString += String.fromCharCode(i)
  18. }
  19. codecOptions.chars = asciiString + codecOptions.chars
  20. }
  21. this.decodeBuf = Buffer.from(codecOptions.chars, "ucs2")
  22. // Encoding buffer.
  23. var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0))
  24. for (var i = 0; i < codecOptions.chars.length; i++) {
  25. encodeBuf[codecOptions.chars.charCodeAt(i)] = i
  26. }
  27. this.encodeBuf = encodeBuf
  28. }
  29. SBCSCodec.prototype.encoder = SBCSEncoder
  30. SBCSCodec.prototype.decoder = SBCSDecoder
  31. function SBCSEncoder (options, codec) {
  32. this.encodeBuf = codec.encodeBuf
  33. }
  34. SBCSEncoder.prototype.write = function (str) {
  35. var buf = Buffer.alloc(str.length)
  36. for (var i = 0; i < str.length; i++) {
  37. buf[i] = this.encodeBuf[str.charCodeAt(i)]
  38. }
  39. return buf
  40. }
  41. SBCSEncoder.prototype.end = function () {
  42. }
  43. function SBCSDecoder (options, codec) {
  44. this.decodeBuf = codec.decodeBuf
  45. }
  46. SBCSDecoder.prototype.write = function (buf) {
  47. // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
  48. var decodeBuf = this.decodeBuf
  49. var newBuf = Buffer.alloc(buf.length * 2)
  50. var idx1 = 0; var idx2 = 0
  51. for (var i = 0; i < buf.length; i++) {
  52. idx1 = buf[i] * 2; idx2 = i * 2
  53. newBuf[idx2] = decodeBuf[idx1]
  54. newBuf[idx2 + 1] = decodeBuf[idx1 + 1]
  55. }
  56. return newBuf.toString("ucs2")
  57. }
  58. SBCSDecoder.prototype.end = function () {
  59. }