read-core.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // read-core.js
  2. var ExtBuffer = require("./ext-buffer").ExtBuffer;
  3. var ExtUnpacker = require("./ext-unpacker");
  4. var readUint8 = require("./read-format").readUint8;
  5. var ReadToken = require("./read-token");
  6. var CodecBase = require("./codec-base");
  7. CodecBase.install({
  8. addExtUnpacker: addExtUnpacker,
  9. getExtUnpacker: getExtUnpacker,
  10. init: init
  11. });
  12. exports.preset = init.call(CodecBase.preset);
  13. function getDecoder(options) {
  14. var readToken = ReadToken.getReadToken(options);
  15. return decode;
  16. function decode(decoder) {
  17. var type = readUint8(decoder);
  18. var func = readToken[type];
  19. if (!func) throw new Error("Invalid type: " + (type ? ("0x" + type.toString(16)) : type));
  20. return func(decoder);
  21. }
  22. }
  23. function init() {
  24. var options = this.options;
  25. this.decode = getDecoder(options);
  26. if (options && options.preset) {
  27. ExtUnpacker.setExtUnpackers(this);
  28. }
  29. return this;
  30. }
  31. function addExtUnpacker(etype, unpacker) {
  32. var unpackers = this.extUnpackers || (this.extUnpackers = []);
  33. unpackers[etype] = CodecBase.filter(unpacker);
  34. }
  35. function getExtUnpacker(type) {
  36. var unpackers = this.extUnpackers || (this.extUnpackers = []);
  37. return unpackers[type] || extUnpacker;
  38. function extUnpacker(buffer) {
  39. return new ExtBuffer(buffer, type);
  40. }
  41. }