base64.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  2. const codes = new Uint8Array(256)
  3. for (let i = 0; i < alphabet.length; i++) {
  4. codes[alphabet.charCodeAt(i)] = i
  5. }
  6. codes[/* - */ 0x2d] = 62
  7. codes[/* _ */ 0x5f] = 63
  8. function byteLength (string) {
  9. let len = string.length
  10. if (string.charCodeAt(len - 1) === 0x3d) len--
  11. if (len > 1 && string.charCodeAt(len - 1) === 0x3d) len--
  12. return (len * 3) >>> 2
  13. }
  14. function toString (buffer) {
  15. const len = buffer.byteLength
  16. let result = ''
  17. for (let i = 0; i < len; i += 3) {
  18. result += (
  19. alphabet[buffer[i] >> 2] +
  20. alphabet[((buffer[i] & 3) << 4) | (buffer[i + 1] >> 4)] +
  21. alphabet[((buffer[i + 1] & 15) << 2) | (buffer[i + 2] >> 6)] +
  22. alphabet[buffer[i + 2] & 63]
  23. )
  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, offset = 0, length = byteLength(string)) {
  33. const len = Math.min(length, buffer.byteLength - offset)
  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. }