write-core.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // write-core.js
  2. var ExtBuffer = require("./ext-buffer").ExtBuffer;
  3. var ExtPacker = require("./ext-packer");
  4. var WriteType = require("./write-type");
  5. var CodecBase = require("./codec-base");
  6. CodecBase.install({
  7. addExtPacker: addExtPacker,
  8. getExtPacker: getExtPacker,
  9. init: init
  10. });
  11. exports.preset = init.call(CodecBase.preset);
  12. function getEncoder(options) {
  13. var writeType = WriteType.getWriteType(options);
  14. return encode;
  15. function encode(encoder, value) {
  16. var func = writeType[typeof value];
  17. if (!func) throw new Error("Unsupported type \"" + (typeof value) + "\": " + value);
  18. func(encoder, value);
  19. }
  20. }
  21. function init() {
  22. var options = this.options;
  23. this.encode = getEncoder(options);
  24. if (options && options.preset) {
  25. ExtPacker.setExtPackers(this);
  26. }
  27. return this;
  28. }
  29. function addExtPacker(etype, Class, packer) {
  30. packer = CodecBase.filter(packer);
  31. var name = Class.name;
  32. if (name && name !== "Object") {
  33. var packers = this.extPackers || (this.extPackers = {});
  34. packers[name] = extPacker;
  35. } else {
  36. // fallback for IE
  37. var list = this.extEncoderList || (this.extEncoderList = []);
  38. list.unshift([Class, extPacker]);
  39. }
  40. function extPacker(value) {
  41. if (packer) value = packer(value);
  42. return new ExtBuffer(value, etype);
  43. }
  44. }
  45. function getExtPacker(value) {
  46. var packers = this.extPackers || (this.extPackers = {});
  47. var c = value.constructor;
  48. var e = c && c.name && packers[c.name];
  49. if (e) return e;
  50. // fallback for IE
  51. var list = this.extEncoderList || (this.extEncoderList = []);
  52. var len = list.length;
  53. for (var i = 0; i < len; i++) {
  54. var pair = list[i];
  55. if (c === pair[0]) return pair[1];
  56. }
  57. }