Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sbcs-codec.js 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. // Prepare char buffer for decoding.
  10. if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256))
  11. throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)");
  12. if (codecOptions.chars.length === 128) {
  13. var asciiString = "";
  14. for (var i = 0; i < 128; i++)
  15. asciiString += String.fromCharCode(i);
  16. codecOptions.chars = asciiString + codecOptions.chars;
  17. }
  18. this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2');
  19. // Encoding buffer.
  20. var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));
  21. for (var i = 0; i < codecOptions.chars.length; i++)
  22. encodeBuf[codecOptions.chars.charCodeAt(i)] = i;
  23. this.encodeBuf = encodeBuf;
  24. }
  25. SBCSCodec.prototype.encoder = SBCSEncoder;
  26. SBCSCodec.prototype.decoder = SBCSDecoder;
  27. function SBCSEncoder(options, codec) {
  28. this.encodeBuf = codec.encodeBuf;
  29. }
  30. SBCSEncoder.prototype.write = function(str) {
  31. var buf = Buffer.alloc(str.length);
  32. for (var i = 0; i < str.length; i++)
  33. buf[i] = this.encodeBuf[str.charCodeAt(i)];
  34. return buf;
  35. }
  36. SBCSEncoder.prototype.end = function() {
  37. }
  38. function SBCSDecoder(options, codec) {
  39. this.decodeBuf = codec.decodeBuf;
  40. }
  41. SBCSDecoder.prototype.write = function(buf) {
  42. // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
  43. var decodeBuf = this.decodeBuf;
  44. var newBuf = Buffer.alloc(buf.length*2);
  45. var idx1 = 0, idx2 = 0;
  46. for (var i = 0; i < buf.length; i++) {
  47. idx1 = buf[i]*2; idx2 = i*2;
  48. newBuf[idx2] = decodeBuf[idx1];
  49. newBuf[idx2+1] = decodeBuf[idx1+1];
  50. }
  51. return newBuf.toString('ucs2');
  52. }
  53. SBCSDecoder.prototype.end = function() {
  54. }