0
0
mirror of https://github.com/honojs/hono.git synced 2024-12-01 10:51:01 +00:00
hono/deno_dist/utils/encode.ts

26 lines
963 B
TypeScript
Raw Normal View History

2023-03-19 09:19:01 +00:00
export const decodeBase64Url = (str: string): Uint8Array => {
return decodeBase64(str.replace(/_|-/g, (m) => ({ _: '/', '-': '+' }[m] ?? m)))
2022-07-02 06:09:45 +00:00
}
2023-03-19 09:19:01 +00:00
export const encodeBase64Url = (buf: ArrayBufferLike): string =>
encodeBase64(buf).replace(/\/|\+/g, (m) => ({ '/': '_', '+': '-' }[m] ?? m))
2022-07-02 06:09:45 +00:00
2023-03-19 09:19:01 +00:00
// This approach is written in MDN.
// btoa does not support utf-8 characters. So we need a little bit hack.
export const encodeBase64 = (buf: ArrayBufferLike): string => {
const binary = String.fromCharCode(...new Uint8Array(buf))
return btoa(binary)
2022-07-02 06:09:45 +00:00
}
2023-03-19 09:19:01 +00:00
// atob does not support utf-8 characters. So we need a little bit hack.
export const decodeBase64 = (str: string): Uint8Array => {
const binary = atob(str)
const bytes = new Uint8Array(new ArrayBuffer(binary.length))
const half = binary.length / 2
for (let i = 0, j = binary.length - 1; i <= half; i++, j--) {
bytes[i] = binary.charCodeAt(i)
bytes[j] = binary.charCodeAt(j)
2022-07-02 06:09:45 +00:00
}
2023-03-19 09:19:01 +00:00
return bytes
2022-07-02 06:09:45 +00:00
}