index.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* eslint-disable node/no-deprecated-api */
  2. var toString = Object.prototype.toString
  3. var isModern = (
  4. typeof Buffer !== 'undefined' &&
  5. typeof Buffer.alloc === 'function' &&
  6. typeof Buffer.allocUnsafe === 'function' &&
  7. typeof Buffer.from === 'function'
  8. )
  9. function isArrayBuffer (input) {
  10. return toString.call(input).slice(8, -1) === 'ArrayBuffer'
  11. }
  12. function fromArrayBuffer (obj, byteOffset, length) {
  13. byteOffset >>>= 0
  14. var maxLength = obj.byteLength - byteOffset
  15. if (maxLength < 0) {
  16. throw new RangeError("'offset' is out of bounds")
  17. }
  18. if (length === undefined) {
  19. length = maxLength
  20. } else {
  21. length >>>= 0
  22. if (length > maxLength) {
  23. throw new RangeError("'length' is out of bounds")
  24. }
  25. }
  26. return isModern
  27. ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
  28. : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
  29. }
  30. function fromString (string, encoding) {
  31. if (typeof encoding !== 'string' || encoding === '') {
  32. encoding = 'utf8'
  33. }
  34. if (!Buffer.isEncoding(encoding)) {
  35. throw new TypeError('"encoding" must be a valid string encoding')
  36. }
  37. return isModern
  38. ? Buffer.from(string, encoding)
  39. : new Buffer(string, encoding)
  40. }
  41. function bufferFrom (value, encodingOrOffset, length) {
  42. if (typeof value === 'number') {
  43. throw new TypeError('"value" argument must not be a number')
  44. }
  45. if (isArrayBuffer(value)) {
  46. return fromArrayBuffer(value, encodingOrOffset, length)
  47. }
  48. if (typeof value === 'string') {
  49. return fromString(value, encodingOrOffset)
  50. }
  51. return isModern
  52. ? Buffer.from(value)
  53. : new Buffer(value)
  54. }
  55. module.exports = bufferFrom