index.js 1.6 KB

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