Skip to content

Commit

Permalink
perf: move from Buffer to Uint8Array
Browse files Browse the repository at this point in the history
  • Loading branch information
johannschopplich committed Apr 4, 2024
1 parent 2d3ef20 commit d569eb7
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 17 deletions.
16 changes: 14 additions & 2 deletions 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('_', '/')
}
6 changes: 2 additions & 4 deletions 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.
*
Expand Down Expand Up @@ -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}`
}
11 changes: 0 additions & 11 deletions 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))
Expand Down Expand Up @@ -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<T extends (...args: any[]) => void>(
fn: T,
delay: number,
Expand Down

0 comments on commit d569eb7

Please sign in to comment.