-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathencode.ts
More file actions
34 lines (30 loc) · 1.11 KB
/
encode.ts
File metadata and controls
34 lines (30 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* @module
* Encode utility.
*/
export const decodeBase64Url = (str: string): Uint8Array<ArrayBuffer> => {
return decodeBase64(str.replace(/_|-/g, (m) => ({ _: '/', '-': '+' })[m] ?? m))
}
export const encodeBase64Url = (buf: ArrayBufferLike): string =>
encodeBase64(buf).replace(/\/|\+/g, (m) => ({ '/': '_', '+': '-' })[m] ?? m)
// 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 => {
let binary = ''
const bytes = new Uint8Array(buf)
for (let i = 0, len = bytes.length; i < len; i++) {
binary += String.fromCharCode(bytes[i])
}
return btoa(binary)
}
// atob does not support utf-8 characters. So we need a little bit hack.
export const decodeBase64 = (str: string): Uint8Array<ArrayBuffer> => {
const binary = atob(str)
const bytes = new Uint8Array<ArrayBuffer>(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)
}
return bytes
}