polyfill.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. var bmi = require('./buffer-more-ints');
  3. Buffer.isContiguousInt = bmi.isContiguousInt;
  4. Buffer.assertContiguousInt = bmi.assertContiguousInt;
  5. ['UInt', 'Int'].forEach(function (signed) {
  6. ['24', '40', '48', '56', '64'].forEach(function (size) {
  7. ['BE', 'LE'].forEach(function (endian) {
  8. var read = 'read' + signed + size + endian;
  9. var reader = bmi[read];
  10. Buffer.prototype[read] = function(offset) {
  11. return reader(this, offset);
  12. };
  13. var write = 'write' + signed + size + endian;
  14. var writer = bmi[write];
  15. Buffer.prototype[write] = function(val, offset) {
  16. writer(this, val, offset);
  17. };
  18. });
  19. });
  20. });
  21. // Buffer.prototype.read{UInt,Int}8 returns undefined if the offset is
  22. // outside of the buffer, unlike for other widths. These functions
  23. // make it consistent with the others.
  24. var consistent_readX8 = {
  25. readUInt8: function (offset) {
  26. return this.readUInt8(offset) || 0;
  27. },
  28. readInt8: function (offset) {
  29. return this.readInt8(offset) || 0;
  30. }
  31. };
  32. function make_accessor(read, prefix, suffix) {
  33. var accessors = [false,
  34. (read ? consistent_readX8 : Buffer.prototype)[prefix + 8]];
  35. for (var i = 16; i <= 64; i += 8) {
  36. accessors.push(Buffer.prototype[prefix + i + suffix]);
  37. }
  38. if (read) {
  39. Buffer.prototype[prefix + suffix] = function (len, offset) {
  40. var reader = accessors[len];
  41. if (reader) {
  42. return reader.call(this, offset);
  43. } else {
  44. throw new Error("Cannot read integer of length " + len);
  45. }
  46. };
  47. } else {
  48. Buffer.prototype[prefix + suffix] = function (len, val, offset) {
  49. var writer = accessors[len];
  50. if (writer) {
  51. return writer.call(this, val, offset);
  52. } else {
  53. throw new Error("Cannot write integer of length " + len);
  54. }
  55. }
  56. }
  57. }
  58. ['UInt', 'Int'].forEach(function (t) {
  59. ['BE', 'LE'].forEach(function (e) {
  60. make_accessor(true, "read" + t, e);
  61. make_accessor(false, "write" + t, e);
  62. });
  63. });