base32.js 1.5 KB

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