index.js 1.5 KB

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