index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. // Copy static methods from Buffer
  21. copyProps(Buffer, SafeBuffer)
  22. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  23. if (typeof arg === 'number') {
  24. throw new TypeError('Argument must not be a number')
  25. }
  26. return Buffer(arg, encodingOrOffset, length)
  27. }
  28. SafeBuffer.alloc = function (size, fill, encoding) {
  29. if (typeof size !== 'number') {
  30. throw new TypeError('Argument must be a number')
  31. }
  32. var buf = Buffer(size)
  33. if (fill !== undefined) {
  34. if (typeof encoding === 'string') {
  35. buf.fill(fill, encoding)
  36. } else {
  37. buf.fill(fill)
  38. }
  39. } else {
  40. buf.fill(0)
  41. }
  42. return buf
  43. }
  44. SafeBuffer.allocUnsafe = function (size) {
  45. if (typeof size !== 'number') {
  46. throw new TypeError('Argument must be a number')
  47. }
  48. return Buffer(size)
  49. }
  50. SafeBuffer.allocUnsafeSlow = function (size) {
  51. if (typeof size !== 'number') {
  52. throw new TypeError('Argument must be a number')
  53. }
  54. return buffer.SlowBuffer(size)
  55. }