base32.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { assertEmptyRest } from './assert.js'
  2. import { fromUint8, E_STRING } from './fallback/_utils.js'
  3. import * as js from './fallback/base32.js'
  4. // See https://datatracker.ietf.org/doc/html/rfc4648
  5. // 8 chars per 5 bytes
  6. function fromBase32common(str, mode, padding, format, rest) {
  7. if (typeof str !== 'string') throw new TypeError(E_STRING)
  8. if (rest !== null) assertEmptyRest(rest)
  9. if (padding === true) {
  10. if (str.length % 8 !== 0) throw new SyntaxError(js.E_PADDING)
  11. } else if (padding === false) {
  12. if (str.endsWith('=')) throw new SyntaxError('Did not expect padding in base32 input')
  13. } else if (padding !== 'both') {
  14. throw new TypeError('Invalid padding option')
  15. }
  16. return fromUint8(js.fromBase32(str, mode), format)
  17. }
  18. // By default, valid padding is accepted but not required
  19. const fromBase32wrap = (mode) => (str, options) => {
  20. if (!options) return fromBase32common(str, mode, 'both', 'uint8', null)
  21. const { format = 'uint8', padding = 'both', ...rest } = options
  22. return fromBase32common(str, mode, padding, format, rest)
  23. }
  24. export const fromBase32 = fromBase32wrap(0)
  25. export const fromBase32hex = fromBase32wrap(1)
  26. export const fromBase32crockford = fromBase32wrap(2)
  27. export const toBase32 = (arr, { padding = false } = {}) => js.toBase32(arr, 0, padding)
  28. export const toBase32hex = (arr, { padding = false } = {}) => js.toBase32(arr, 1, padding)
  29. export const toBase32crockford = (arr, { padding = false } = {}) => js.toBase32(arr, 2, padding)