Skip to content

Commit d569eb7

Browse files
perf: move from Buffer to Uint8Array
1 parent 2d3ef20 commit d569eb7

File tree

3 files changed

+16
-17
lines changed

3 files changed

+16
-17
lines changed

packages/core/src/thumbhash.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,20 @@
11
import { thumbHashToRGBA } from 'thumbhash'
2-
import { base64ToBytes } from './utils'
32
import { rgbaToDataUri } from './utils/dataUri'
43

54
export function createPngDataUri(hash: string) {
6-
const { w, h, rgba } = thumbHashToRGBA(base64ToBytes(hash))
5+
const hashArray = base64ToUint8Array(hash)
6+
const { w, h, rgba } = thumbHashToRGBA(hashArray)
7+
78
return rgbaToDataUri(w, h, rgba)
89
}
10+
11+
function base64ToUint8Array(base64String: string) {
12+
return Uint8Array.from(
13+
globalThis.atob(base64UrlToBase64(base64String)),
14+
x => x.charCodeAt(0),
15+
)
16+
}
17+
18+
function base64UrlToBase64(base64url: string) {
19+
return base64url.replaceAll('-', '+').replaceAll('_', '/')
20+
}

packages/core/src/utils/dataUri/png.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
/* eslint-disable node/prefer-global/buffer */
21
/* eslint-disable antfu/consistent-list-newline */
2+
33
/**
44
* Encodes an RGBA image to a PNG data URI. RGB should not be premultiplied by A.
55
*
@@ -65,9 +65,7 @@ export function rgbaToDataUri(
6565
bytes[end++] = c & 255
6666
}
6767

68-
const base64 = typeof Buffer !== 'undefined'
69-
? Buffer.from(new Uint8Array(bytes)).toString('base64')
70-
: btoa(String.fromCharCode(...bytes))
68+
const base64 = globalThis.btoa(String.fromCharCode(...bytes))
7169

7270
return `data:image/png;base64,${base64}`
7371
}

packages/core/src/utils/index.ts

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
/* eslint-disable node/prefer-global/buffer */
21
export const isSSR = typeof window === 'undefined'
32
export const isLazyLoadingSupported = !isSSR && 'loading' in HTMLImageElement.prototype
43
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)
3231
return { width, height }
3332
}
3433

35-
export function base64ToBytes(value: string) {
36-
const base64 = value.replace(/-/g, '+').replace(/_/g, '/')
37-
38-
const decodedData = typeof Buffer !== 'undefined'
39-
? Buffer.from(base64, 'base64')
40-
: Uint8Array.from(atob(base64), char => char.charCodeAt(0))
41-
42-
return new Uint8Array(decodedData)
43-
}
44-
4534
export function debounce<T extends (...args: any[]) => void>(
4635
fn: T,
4736
delay: number,

0 commit comments

Comments
 (0)