Skip to content

Commit 9d7346f

Browse files
authored
feat(encoding/unstable): add Uint8Array support to decodeBase64, 32, and hex (#6508)
1 parent bf393b7 commit 9d7346f

File tree

3 files changed

+18
-19
lines changed

3 files changed

+18
-19
lines changed

encoding/unstable_base32.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,9 @@ export function encodeRawBase32(
159159

160160
/**
161161
* `decodeBase32` takes an input source and decodes it into a
162-
* {@linkcode Uint8Array<ArrayBuffer>} using the specified format.
162+
* {@linkcode Uint8Array<ArrayBuffer>} using the specified format. If a
163+
* {@linkcode Uint8Array<ArrayBuffer>} is provided as input then a subarray of
164+
* the input containing the decoded data is returned.
163165
*
164166
* @experimental **UNSTABLE**: New API, yet to be vetted.
165167
*
@@ -189,15 +191,13 @@ export function encodeRawBase32(
189191
* ```
190192
*/
191193
export function decodeBase32(
192-
input: string,
194+
input: string | Uint8Array_,
193195
format: Base32Format = "Base32",
194196
): Uint8Array_ {
195-
const output = new TextEncoder().encode(input) as Uint8Array_;
196-
return output
197-
.subarray(
198-
0,
199-
decode(output, 0, 0, rAlphabet[format], padding),
200-
);
197+
if (typeof input === "string") {
198+
input = new TextEncoder().encode(input) as Uint8Array_;
199+
}
200+
return input.subarray(0, decode(input, 0, 0, rAlphabet[format], padding));
201201
}
202202

203203
/**

encoding/unstable_base64.ts

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -185,15 +185,13 @@ export function encodeRawBase64(
185185
* ```
186186
*/
187187
export function decodeBase64(
188-
input: string,
188+
input: string | Uint8Array_,
189189
format: Base64Format = "Base64",
190190
): Uint8Array_ {
191-
const output = new TextEncoder().encode(input) as Uint8Array_;
192-
return output
193-
.subarray(
194-
0,
195-
decode(output, 0, 0, rAlphabet[format], padding),
196-
);
191+
if (typeof input === "string") {
192+
input = new TextEncoder().encode(input) as Uint8Array_;
193+
}
194+
return input.subarray(0, decode(input, 0, 0, rAlphabet[format], padding));
197195
}
198196

199197
/**

encoding/unstable_hex.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -146,11 +146,12 @@ export function encodeRawHex(
146146
* ```
147147
*/
148148
export function decodeHex(
149-
input: string,
149+
input: string | Uint8Array_,
150150
): Uint8Array_ {
151-
const output = new TextEncoder().encode(input) as Uint8Array_;
152-
return output
153-
.subarray(0, decode(output, 0, 0, rAlphabet));
151+
if (typeof input === "string") {
152+
input = new TextEncoder().encode(input) as Uint8Array_;
153+
}
154+
return input.subarray(0, decode(input, 0, 0, rAlphabet));
154155
}
155156

156157
/**

0 commit comments

Comments
 (0)