base32.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import { assertU8 } from './_utils.js'
  2. import { nativeEncoder, nativeDecoder, isHermes } from './platform.js'
  3. import { encodeAscii, decodeAscii } from './latin1.js'
  4. // See https://datatracker.ietf.org/doc/html/rfc4648
  5. const BASE32_HELPERS = [{}, {}, {}]
  6. const BASE32_ALPHABETS = [
  7. [...'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'], // RFC 4648, #6
  8. [...'0123456789ABCDEFGHIJKLMNOPQRSTUV'], // RFC 4648, #7
  9. [...'0123456789ABCDEFGHJKMNPQRSTVWXYZ'], // Crockford, base (see extra below in fromMap)
  10. ]
  11. export const E_CHAR = 'Invalid character in base32 input'
  12. export const E_PADDING = 'Invalid base32 padding'
  13. export const E_LENGTH = 'Invalid base32 length'
  14. export const E_LAST = 'Invalid last chunk'
  15. const useTemplates = isHermes // Faster on Hermes and JSC, but we use it only on Hermes
  16. // We construct output by concatenating chars, this seems to be fine enough on modern JS engines
  17. export function toBase32(arr, mode, padding) {
  18. assertU8(arr)
  19. const fullChunks = Math.floor(arr.length / 5)
  20. const fullChunksBytes = fullChunks * 5
  21. let o = ''
  22. let i = 0
  23. const alphabet = BASE32_ALPHABETS[mode]
  24. const helpers = BASE32_HELPERS[mode]
  25. if (!helpers.pairs) {
  26. helpers.pairs = []
  27. if (nativeDecoder) {
  28. // Lazy to save memory in case if this is not needed
  29. helpers.codepairs = new Uint16Array(32 * 32)
  30. const u16 = helpers.codepairs
  31. const u8 = new Uint8Array(u16.buffer, u16.byteOffset, u16.byteLength) // write as 1-byte to ignore BE/LE difference
  32. for (let i = 0; i < 32; i++) {
  33. const ic = alphabet[i].charCodeAt(0)
  34. for (let j = 0; j < 32; j++) u8[(i << 6) | (j << 1)] = u8[(j << 6) | ((i << 1) + 1)] = ic
  35. }
  36. } else {
  37. const p = helpers.pairs
  38. for (let i = 0; i < 32; i++) {
  39. for (let j = 0; j < 32; j++) p.push(`${alphabet[i]}${alphabet[j]}`)
  40. }
  41. }
  42. }
  43. const { pairs, codepairs } = helpers
  44. // Fast path for complete blocks
  45. // This whole loop can be commented out, the algorithm won't change, it's just an optimization of the next loop
  46. if (nativeDecoder) {
  47. const oa = new Uint16Array(fullChunks * 4)
  48. for (let j = 0; i < fullChunksBytes; i += 5) {
  49. const a = arr[i]
  50. const b = arr[i + 1]
  51. const c = arr[i + 2]
  52. const d = arr[i + 3]
  53. const e = arr[i + 4]
  54. const x0 = (a << 2) | (b >> 6) // 8 + 8 - 5 - 5 = 6 left
  55. const x1 = ((b & 0x3f) << 4) | (c >> 4) // 6 + 8 - 5 - 5 = 4 left
  56. const x2 = ((c & 0xf) << 6) | (d >> 2) // 4 + 8 - 5 - 5 = 2 left
  57. const x3 = ((d & 0x3) << 8) | e // 2 + 8 - 5 - 5 = 0 left
  58. oa[j] = codepairs[x0]
  59. oa[j + 1] = codepairs[x1]
  60. oa[j + 2] = codepairs[x2]
  61. oa[j + 3] = codepairs[x3]
  62. j += 4
  63. }
  64. o = decodeAscii(oa)
  65. } else if (useTemplates) {
  66. // Templates are faster only on Hermes and JSC. Browsers have TextDecoder anyway
  67. for (; i < fullChunksBytes; i += 5) {
  68. const a = arr[i]
  69. const b = arr[i + 1]
  70. const c = arr[i + 2]
  71. const d = arr[i + 3]
  72. const e = arr[i + 4]
  73. const x0 = (a << 2) | (b >> 6) // 8 + 8 - 5 - 5 = 6 left
  74. const x1 = ((b & 0x3f) << 4) | (c >> 4) // 6 + 8 - 5 - 5 = 4 left
  75. const x2 = ((c & 0xf) << 6) | (d >> 2) // 4 + 8 - 5 - 5 = 2 left
  76. const x3 = ((d & 0x3) << 8) | e // 2 + 8 - 5 - 5 = 0 left
  77. o += `${pairs[x0]}${pairs[x1]}${pairs[x2]}${pairs[x3]}`
  78. }
  79. } else {
  80. for (; i < fullChunksBytes; i += 5) {
  81. const a = arr[i]
  82. const b = arr[i + 1]
  83. const c = arr[i + 2]
  84. const d = arr[i + 3]
  85. const e = arr[i + 4]
  86. const x0 = (a << 2) | (b >> 6) // 8 + 8 - 5 - 5 = 6 left
  87. const x1 = ((b & 0x3f) << 4) | (c >> 4) // 6 + 8 - 5 - 5 = 4 left
  88. const x2 = ((c & 0xf) << 6) | (d >> 2) // 4 + 8 - 5 - 5 = 2 left
  89. const x3 = ((d & 0x3) << 8) | e // 2 + 8 - 5 - 5 = 0 left
  90. o += pairs[x0]
  91. o += pairs[x1]
  92. o += pairs[x2]
  93. o += pairs[x3]
  94. }
  95. }
  96. // If we have something left, process it with a full algo
  97. let carry = 0
  98. let shift = 3 // First byte needs to be shifted by 3 to get 5 bits
  99. for (; i < arr.length; i++) {
  100. const x = arr[i]
  101. o += alphabet[carry | (x >> shift)] // shift >= 3, so this fits
  102. if (shift >= 5) {
  103. shift -= 5
  104. o += alphabet[(x >> shift) & 0x1f]
  105. }
  106. carry = (x << (5 - shift)) & 0x1f
  107. shift += 3 // Each byte prints 5 bits and leaves 3 bits
  108. }
  109. if (shift !== 3) o += alphabet[carry] // shift 3 means we have no carry left
  110. if (padding) o += ['', '======', '====', '===', '='][arr.length - fullChunksBytes]
  111. return o
  112. }
  113. // TODO: can this be optimized? This only affects non-Hermes barebone engines though
  114. const mapSize = nativeEncoder ? 128 : 65_536 // we have to store 64 KiB map or recheck everything if we can't decode to byte array
  115. export function fromBase32(str, mode) {
  116. let inputLength = str.length
  117. while (str[inputLength - 1] === '=') inputLength--
  118. const paddingLength = str.length - inputLength
  119. const tailLength = inputLength % 8
  120. const mainLength = inputLength - tailLength // multiples of 8
  121. if (![0, 2, 4, 5, 7].includes(tailLength)) throw new SyntaxError(E_LENGTH) // fast verification
  122. if (paddingLength > 7 || (paddingLength !== 0 && str.length % 8 !== 0)) {
  123. throw new SyntaxError(E_PADDING)
  124. }
  125. const alphabet = BASE32_ALPHABETS[mode]
  126. const helpers = BASE32_HELPERS[mode]
  127. if (!helpers.fromMap) {
  128. helpers.fromMap = new Int8Array(mapSize).fill(-1) // no regex input validation here, so we map all other bytes to -1 and recheck sign
  129. const m = helpers.fromMap
  130. alphabet.forEach((c, i) => {
  131. m[c.charCodeAt(0)] = m[c.toLowerCase().charCodeAt(0)] = i
  132. })
  133. if (mode === 2) {
  134. // Extra Crockford mapping
  135. m[73] = m[76] = m[105] = m[108] = m[49] // ILil -> 1
  136. m[79] = m[111] = m[48] // Oo -> 0
  137. }
  138. }
  139. const m = helpers.fromMap
  140. const arr = new Uint8Array(Math.floor((inputLength * 5) / 8))
  141. let at = 0
  142. let i = 0
  143. if (nativeEncoder) {
  144. const codes = encodeAscii(str, E_CHAR)
  145. for (; i < mainLength; i += 8) {
  146. // each 5 bits, grouped 5 * 4 = 20
  147. const x0 = codes[i]
  148. const x1 = codes[i + 1]
  149. const x2 = codes[i + 2]
  150. const x3 = codes[i + 3]
  151. const x4 = codes[i + 4]
  152. const x5 = codes[i + 5]
  153. const x6 = codes[i + 6]
  154. const x7 = codes[i + 7]
  155. const a = (m[x0] << 15) | (m[x1] << 10) | (m[x2] << 5) | m[x3]
  156. const b = (m[x4] << 15) | (m[x5] << 10) | (m[x6] << 5) | m[x7]
  157. if (a < 0 || b < 0) throw new SyntaxError(E_CHAR)
  158. arr[at] = a >> 12
  159. arr[at + 1] = (a >> 4) & 0xff
  160. arr[at + 2] = ((a << 4) & 0xff) | (b >> 16)
  161. arr[at + 3] = (b >> 8) & 0xff
  162. arr[at + 4] = b & 0xff
  163. at += 5
  164. }
  165. } else {
  166. for (; i < mainLength; i += 8) {
  167. // each 5 bits, grouped 5 * 4 = 20
  168. const x0 = str.charCodeAt(i)
  169. const x1 = str.charCodeAt(i + 1)
  170. const x2 = str.charCodeAt(i + 2)
  171. const x3 = str.charCodeAt(i + 3)
  172. const x4 = str.charCodeAt(i + 4)
  173. const x5 = str.charCodeAt(i + 5)
  174. const x6 = str.charCodeAt(i + 6)
  175. const x7 = str.charCodeAt(i + 7)
  176. const a = (m[x0] << 15) | (m[x1] << 10) | (m[x2] << 5) | m[x3]
  177. const b = (m[x4] << 15) | (m[x5] << 10) | (m[x6] << 5) | m[x7]
  178. if (a < 0 || b < 0) throw new SyntaxError(E_CHAR)
  179. arr[at] = a >> 12
  180. arr[at + 1] = (a >> 4) & 0xff
  181. arr[at + 2] = ((a << 4) & 0xff) | (b >> 16)
  182. arr[at + 3] = (b >> 8) & 0xff
  183. arr[at + 4] = b & 0xff
  184. at += 5
  185. }
  186. }
  187. // Last block, valid tailLength: 0 2 4 5 7, checked already
  188. // We check last chunk to be strict
  189. if (tailLength < 2) return arr
  190. const ab = (m[str.charCodeAt(i++)] << 5) | m[str.charCodeAt(i++)]
  191. if (ab < 0) throw new SyntaxError(E_CHAR)
  192. arr[at++] = ab >> 2
  193. if (tailLength < 4) {
  194. if (ab & 0x3) throw new SyntaxError(E_LAST)
  195. return arr
  196. }
  197. const cd = (m[str.charCodeAt(i++)] << 5) | m[str.charCodeAt(i++)]
  198. if (cd < 0) throw new SyntaxError(E_CHAR)
  199. arr[at++] = ((ab << 6) & 0xff) | (cd >> 4)
  200. if (tailLength < 5) {
  201. if (cd & 0xf) throw new SyntaxError(E_LAST)
  202. return arr
  203. }
  204. const e = m[str.charCodeAt(i++)]
  205. if (e < 0) throw new SyntaxError(E_CHAR)
  206. arr[at++] = ((cd << 4) & 0xff) | (e >> 1) // 4 + 4
  207. if (tailLength < 7) {
  208. if (e & 0x1) throw new SyntaxError(E_LAST)
  209. return arr
  210. }
  211. const fg = (m[str.charCodeAt(i++)] << 5) | m[str.charCodeAt(i++)]
  212. if (fg < 0) throw new SyntaxError(E_CHAR)
  213. arr[at++] = ((e << 7) & 0xff) | (fg >> 3) // 1 + 5 + 2
  214. // Can't be 8, so no h
  215. if (fg & 0x7) throw new SyntaxError(E_LAST)
  216. return arr
  217. }