base64.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const alphabet =
  2. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  3. const codes = new Uint8Array(256)
  4. for (let i = 0; i < alphabet.length; i++) {
  5. codes[alphabet.charCodeAt(i)] = i
  6. }
  7. codes[/* - */ 0x2d] = 62
  8. codes[/* _ */ 0x5f] = 63
  9. function byteLength(string) {
  10. let len = string.length
  11. if (string.charCodeAt(len - 1) === 0x3d) len--
  12. if (len > 1 && string.charCodeAt(len - 1) === 0x3d) len--
  13. return (len * 3) >>> 2
  14. }
  15. function toString(buffer) {
  16. const len = buffer.byteLength
  17. let result = ''
  18. for (let i = 0; i < len; i += 3) {
  19. result +=
  20. alphabet[buffer[i] >> 2] +
  21. alphabet[((buffer[i] & 3) << 4) | (buffer[i + 1] >> 4)] +
  22. alphabet[((buffer[i + 1] & 15) << 2) | (buffer[i + 2] >> 6)] +
  23. alphabet[buffer[i + 2] & 63]
  24. }
  25. if (len % 3 === 2) {
  26. result = result.substring(0, result.length - 1) + '='
  27. } else if (len % 3 === 1) {
  28. result = result.substring(0, result.length - 2) + '=='
  29. }
  30. return result
  31. }
  32. function write(buffer, string) {
  33. const len = buffer.byteLength
  34. for (let i = 0, j = 0; j < len; i += 4) {
  35. const a = codes[string.charCodeAt(i)]
  36. const b = codes[string.charCodeAt(i + 1)]
  37. const c = codes[string.charCodeAt(i + 2)]
  38. const d = codes[string.charCodeAt(i + 3)]
  39. buffer[j++] = (a << 2) | (b >> 4)
  40. buffer[j++] = ((b & 15) << 4) | (c >> 2)
  41. buffer[j++] = ((c & 3) << 6) | (d & 63)
  42. }
  43. return len
  44. }
  45. module.exports = {
  46. byteLength,
  47. toString,
  48. write
  49. }