hex.node.js 1.3 KB

12345678910111213141516171819202122232425262728
  1. import { typedView } from './array.js'
  2. import { assertU8, E_STRING } from './fallback/_utils.js'
  3. import { E_HEX } from './fallback/hex.js'
  4. if (Buffer.TYPED_ARRAY_SUPPORT) throw new Error('Unexpected Buffer polyfill')
  5. const { toHex: webHex } = Uint8Array.prototype // Modern engines have this
  6. const denoBug = Buffer.from('ag', 'hex').length > 0
  7. export function toHex(arr) {
  8. assertU8(arr)
  9. if (arr.length === 0) return ''
  10. if (webHex && arr.toHex === webHex) return arr.toHex()
  11. if (arr.constructor === Buffer && Buffer.isBuffer(arr)) return arr.hexSlice(0, arr.byteLength)
  12. return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength).hexSlice(0, arr.byteLength)
  13. }
  14. // Unlike Buffer.from(), throws on invalid input
  15. export const fromHex = Uint8Array.fromHex
  16. ? (str, format = 'uint8') => typedView(Uint8Array.fromHex(str), format)
  17. : (str, format = 'uint8') => {
  18. if (typeof str !== 'string') throw new TypeError(E_STRING)
  19. if (str.length % 2 !== 0) throw new SyntaxError(E_HEX)
  20. if (denoBug && /[^\dA-Fa-f]/.test(str)) throw new SyntaxError(E_HEX)
  21. const buf = Buffer.from(str, 'hex') // will stop on first non-hex character, so we can just validate length
  22. if (buf.length * 2 !== str.length) throw new SyntaxError(E_HEX)
  23. return typedView(buf, format)
  24. }