estimateDataURLDecodedBytes.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * Estimate decoded byte length of a data:// URL *without* allocating large buffers.
  3. * - For base64: compute exact decoded size using length and padding;
  4. * handle %XX at the character-count level (no string allocation).
  5. * - For non-base64: use UTF-8 byteLength of the encoded body as a safe upper bound.
  6. *
  7. * @param {string} url
  8. * @returns {number}
  9. */
  10. export default function estimateDataURLDecodedBytes(url) {
  11. if (!url || typeof url !== 'string') return 0;
  12. if (!url.startsWith('data:')) return 0;
  13. const comma = url.indexOf(',');
  14. if (comma < 0) return 0;
  15. const meta = url.slice(5, comma);
  16. const body = url.slice(comma + 1);
  17. const isBase64 = /;base64/i.test(meta);
  18. if (isBase64) {
  19. let effectiveLen = body.length;
  20. const len = body.length; // cache length
  21. for (let i = 0; i < len; i++) {
  22. if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) {
  23. const a = body.charCodeAt(i + 1);
  24. const b = body.charCodeAt(i + 2);
  25. const isHex =
  26. ((a >= 48 && a <= 57) || (a >= 65 && a <= 70) || (a >= 97 && a <= 102)) &&
  27. ((b >= 48 && b <= 57) || (b >= 65 && b <= 70) || (b >= 97 && b <= 102));
  28. if (isHex) {
  29. effectiveLen -= 2;
  30. i += 2;
  31. }
  32. }
  33. }
  34. let pad = 0;
  35. let idx = len - 1;
  36. const tailIsPct3D = (j) =>
  37. j >= 2 &&
  38. body.charCodeAt(j - 2) === 37 && // '%'
  39. body.charCodeAt(j - 1) === 51 && // '3'
  40. (body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd'
  41. if (idx >= 0) {
  42. if (body.charCodeAt(idx) === 61 /* '=' */) {
  43. pad++;
  44. idx--;
  45. } else if (tailIsPct3D(idx)) {
  46. pad++;
  47. idx -= 3;
  48. }
  49. }
  50. if (pad === 1 && idx >= 0) {
  51. if (body.charCodeAt(idx) === 61 /* '=' */) {
  52. pad++;
  53. } else if (tailIsPct3D(idx)) {
  54. pad++;
  55. }
  56. }
  57. const groups = Math.floor(effectiveLen / 4);
  58. const bytes = groups * 3 - (pad || 0);
  59. return bytes > 0 ? bytes : 0;
  60. }
  61. return Buffer.byteLength(body, 'utf8');
  62. }