index.js 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. }