node.js 904 B

123456789101112131415161718192021222324252627282930
  1. 'use strict'
  2. const crypto = require('crypto')
  3. const fallback = require('./browser').from
  4. const bytes = require('./core')
  5. bytes.from = (_from, encoding) => {
  6. if (_from instanceof DataView) return _from
  7. if (_from instanceof ArrayBuffer) return new DataView(_from)
  8. if (typeof _from === 'string') {
  9. _from = Buffer.from(_from, encoding)
  10. }
  11. if (Buffer.isBuffer(_from)) {
  12. return new DataView(_from.buffer, _from.byteOffset, _from.byteLength)
  13. }
  14. return fallback(_from, encoding)
  15. }
  16. bytes.toString = (_from, encoding) => {
  17. _from = bytes(_from)
  18. return Buffer.from(_from.buffer, _from.byteOffset, _from.byteLength).toString(encoding)
  19. }
  20. bytes.native = (_from, encoding) => {
  21. if (Buffer.isBuffer(_from)) return _from
  22. _from = bytes(_from, encoding)
  23. return Buffer.from(_from.buffer, _from.byteOffset, _from.byteLength)
  24. }
  25. bytes._randomFill = crypto.randomFillSync
  26. module.exports = bytes