index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. var buffer = require('buffer')
  2. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  3. module.exports = buffer
  4. } else {
  5. // Copy properties from require('buffer')
  6. Object.keys(buffer).forEach(function (prop) {
  7. exports[prop] = buffer[prop]
  8. })
  9. exports.Buffer = SafeBuffer
  10. }
  11. function SafeBuffer (arg, encodingOrOffset, length) {
  12. return Buffer(arg, encodingOrOffset, length)
  13. }
  14. // Copy static methods from Buffer
  15. Object.keys(Buffer).forEach(function (prop) {
  16. SafeBuffer[prop] = Buffer[prop]
  17. })
  18. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  19. if (typeof arg === 'number') {
  20. throw new TypeError('Argument must not be a number')
  21. }
  22. return Buffer(arg, encodingOrOffset, length)
  23. }
  24. SafeBuffer.alloc = function (size, fill, encoding) {
  25. if (typeof size !== 'number') {
  26. throw new TypeError('Argument must be a number')
  27. }
  28. var buf = Buffer(size)
  29. if (fill !== undefined) {
  30. if (typeof encoding === 'string') {
  31. buf.fill(fill, encoding)
  32. } else {
  33. buf.fill(fill)
  34. }
  35. } else {
  36. buf.fill(0)
  37. }
  38. return buf
  39. }
  40. SafeBuffer.allocUnsafe = function (size) {
  41. if (typeof size !== 'number') {
  42. throw new TypeError('Argument must be a number')
  43. }
  44. return Buffer(size)
  45. }
  46. SafeBuffer.allocUnsafeSlow = function (size) {
  47. if (typeof size !== 'number') {
  48. throw new TypeError('Argument must be a number')
  49. }
  50. return buffer.SlowBuffer(size)
  51. }