From d569eb7b8c01c498f2b02fa5792d855780607cab Mon Sep 17 00:00:00 2001 From: Johann Schopplich Date: Thu, 4 Apr 2024 21:52:17 +0200 Subject: [PATCH] perf: move from `Buffer` to `Uint8Array` --- packages/core/src/thumbhash.ts | 16 ++++++++++++++-- packages/core/src/utils/dataUri/png.ts | 6 ++---- packages/core/src/utils/index.ts | 11 ----------- 3 files changed, 16 insertions(+), 17 deletions(-) diff --git a/packages/core/src/thumbhash.ts b/packages/core/src/thumbhash.ts index 60da16e..f18747a 100644 --- a/packages/core/src/thumbhash.ts +++ b/packages/core/src/thumbhash.ts @@ -1,8 +1,20 @@ import { thumbHashToRGBA } from 'thumbhash' -import { base64ToBytes } from './utils' import { rgbaToDataUri } from './utils/dataUri' export function createPngDataUri(hash: string) { - const { w, h, rgba } = thumbHashToRGBA(base64ToBytes(hash)) + const hashArray = base64ToUint8Array(hash) + const { w, h, rgba } = thumbHashToRGBA(hashArray) + return rgbaToDataUri(w, h, rgba) } + +function base64ToUint8Array(base64String: string) { + return Uint8Array.from( + globalThis.atob(base64UrlToBase64(base64String)), + x => x.charCodeAt(0), + ) +} + +function base64UrlToBase64(base64url: string) { + return base64url.replaceAll('-', '+').replaceAll('_', '/') +} diff --git a/packages/core/src/utils/dataUri/png.ts b/packages/core/src/utils/dataUri/png.ts index 9546770..03486cd 100644 --- a/packages/core/src/utils/dataUri/png.ts +++ b/packages/core/src/utils/dataUri/png.ts @@ -1,5 +1,5 @@ -/* eslint-disable node/prefer-global/buffer */ /* eslint-disable antfu/consistent-list-newline */ + /** * Encodes an RGBA image to a PNG data URI. RGB should not be premultiplied by A. * @@ -65,9 +65,7 @@ export function rgbaToDataUri( bytes[end++] = c & 255 } - const base64 = typeof Buffer !== 'undefined' - ? Buffer.from(new Uint8Array(bytes)).toString('base64') - : btoa(String.fromCharCode(...bytes)) + const base64 = globalThis.btoa(String.fromCharCode(...bytes)) return `data:image/png;base64,${base64}` } diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts index e79e4e8..ebd28df 100644 --- a/packages/core/src/utils/index.ts +++ b/packages/core/src/utils/index.ts @@ -1,4 +1,3 @@ -/* eslint-disable node/prefer-global/buffer */ export const isSSR = typeof window === 'undefined' export const isLazyLoadingSupported = !isSSR && 'loading' in HTMLImageElement.prototype export const isCrawler = !isSSR && (!('onscroll' in window) || /(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent)) @@ -32,16 +31,6 @@ export function getScaledDimensions(aspectRatio: number, referenceSize: number) return { width, height } } -export function base64ToBytes(value: string) { - const base64 = value.replace(/-/g, '+').replace(/_/g, '/') - - const decodedData = typeof Buffer !== 'undefined' - ? Buffer.from(base64, 'base64') - : Uint8Array.from(atob(base64), char => char.charCodeAt(0)) - - return new Uint8Array(decodedData) -} - export function debounce void>( fn: T, delay: number,