browser.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* globals atob, btoa, crypto */
  2. /* istanbul ignore file */
  3. 'use strict'
  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. let buffer
  9. if (typeof _from === 'string') {
  10. if (!_encoding) {
  11. _encoding = 'utf-8'
  12. } else if (_encoding === 'base64') {
  13. buffer = Uint8Array.from(atob(_from), c => c.charCodeAt(0)).buffer
  14. return new DataView(buffer)
  15. }
  16. if (_encoding !== 'utf-8') throw new Error('Browser support for encodings other than utf-8 not implemented')
  17. return new DataView((new TextEncoder()).encode(_from).buffer)
  18. } else if (typeof _from === 'object') {
  19. if (ArrayBuffer.isView(_from)) {
  20. if (_from.byteLength === _from.buffer.byteLength) return new DataView(_from.buffer)
  21. else return new DataView(_from.buffer, _from.byteOffset, _from.byteLength)
  22. }
  23. }
  24. throw new Error('Unkown type. Cannot convert to ArrayBuffer')
  25. }
  26. bytes.toString = (_from, encoding) => {
  27. _from = bytes(_from, encoding)
  28. const uint = new Uint8Array(_from.buffer, _from.byteOffset, _from.byteLength)
  29. const str = String.fromCharCode(...uint)
  30. if (encoding === 'base64') {
  31. /* would be nice to find a way to do this directly from a buffer
  32. * instead of doing two string conversions
  33. */
  34. return btoa(str)
  35. } else {
  36. return str
  37. }
  38. }
  39. bytes.native = (_from, encoding) => {
  40. if (_from instanceof Uint8Array) return _from
  41. _from = bytes.from(_from, encoding)
  42. return new Uint8Array(_from.buffer, _from.byteOffset, _from.byteLength)
  43. }
  44. if (process.browser) bytes._randomFill = (...args) => crypto.getRandomValues(...args)
  45. module.exports = bytes