index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  2. /* eslint-disable node/no-deprecated-api */
  3. var buffer = require('buffer')
  4. var Buffer = buffer.Buffer
  5. // alternative to using Object.keys for old browsers
  6. function copyProps (src, dst) {
  7. for (var key in src) {
  8. dst[key] = src[key]
  9. }
  10. }
  11. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  12. module.exports = buffer
  13. } else {
  14. // Copy properties from require('buffer')
  15. copyProps(buffer, exports)
  16. exports.Buffer = SafeBuffer
  17. }
  18. function SafeBuffer (arg, encodingOrOffset, length) {
  19. return Buffer(arg, encodingOrOffset, length)
  20. }
  21. SafeBuffer.prototype = Object.create(Buffer.prototype)
  22. // Copy static methods from Buffer
  23. copyProps(Buffer, SafeBuffer)
  24. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  25. if (typeof arg === 'number') {
  26. throw new TypeError('Argument must not be a number')
  27. }
  28. return Buffer(arg, encodingOrOffset, length)
  29. }
  30. SafeBuffer.alloc = function (size, fill, encoding) {
  31. if (typeof size !== 'number') {
  32. throw new TypeError('Argument must be a number')
  33. }
  34. var buf = Buffer(size)
  35. if (fill !== undefined) {
  36. if (typeof encoding === 'string') {
  37. buf.fill(fill, encoding)
  38. } else {
  39. buf.fill(fill)
  40. }
  41. } else {
  42. buf.fill(0)
  43. }
  44. return buf
  45. }
  46. SafeBuffer.allocUnsafe = function (size) {
  47. if (typeof size !== 'number') {
  48. throw new TypeError('Argument must be a number')
  49. }
  50. return Buffer(size)
  51. }
  52. SafeBuffer.allocUnsafeSlow = function (size) {
  53. if (typeof size !== 'number') {
  54. throw new TypeError('Argument must be a number')
  55. }
  56. return buffer.SlowBuffer(size)
  57. }