internal.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Export Node.js internal encodings.
  2. var utf16lebom = new Buffer([0xFF, 0xFE]);
  3. module.exports = {
  4. // Encodings
  5. utf8: { type: "_internal", enc: "utf8" },
  6. cesu8: { type: "_internal", enc: "utf8" },
  7. unicode11utf8: { type: "_internal", enc: "utf8" },
  8. ucs2: { type: "_internal", enc: "ucs2", bom: utf16lebom },
  9. utf16le:{ type: "_internal", enc: "ucs2", bom: utf16lebom },
  10. binary: { type: "_internal", enc: "binary" },
  11. base64: { type: "_internal", enc: "base64" },
  12. hex: { type: "_internal", enc: "hex" },
  13. // Codec.
  14. _internal: function(options) {
  15. if (!options || !options.enc)
  16. throw new Error("Internal codec is called without encoding type.")
  17. return {
  18. encoder: options.enc == "base64" ? encoderBase64 : encoderInternal,
  19. decoder: decoderInternal,
  20. enc: options.enc,
  21. bom: options.bom,
  22. };
  23. },
  24. };
  25. // We use node.js internal decoder. It's signature is the same as ours.
  26. var StringDecoder = require('string_decoder').StringDecoder;
  27. if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method.
  28. StringDecoder.prototype.end = function() {};
  29. function decoderInternal() {
  30. return new StringDecoder(this.enc);
  31. }
  32. // Encoder is mostly trivial
  33. function encoderInternal() {
  34. return {
  35. write: encodeInternal,
  36. end: function() {},
  37. enc: this.enc,
  38. }
  39. }
  40. function encodeInternal(str) {
  41. return new Buffer(str, this.enc);
  42. }
  43. // Except base64 encoder, which must keep its state.
  44. function encoderBase64() {
  45. return {
  46. write: encodeBase64Write,
  47. end: encodeBase64End,
  48. prevStr: '',
  49. };
  50. }
  51. function encodeBase64Write(str) {
  52. str = this.prevStr + str;
  53. var completeQuads = str.length - (str.length % 4);
  54. this.prevStr = str.slice(completeQuads);
  55. str = str.slice(0, completeQuads);
  56. return new Buffer(str, "base64");
  57. }
  58. function encodeBase64End() {
  59. return new Buffer(this.prevStr, "base64");
  60. }