Skip to content

Commit

Permalink
fix(op_crates/web): throw TypeError on invalid input types in TextDec…
Browse files Browse the repository at this point in the history
…oder.decode() (#7179)
  • Loading branch information
asos-craigmorten authored Aug 24, 2020
1 parent 545ea8e commit 2d800f2
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
8 changes: 6 additions & 2 deletions op_crates/web/08_text_encoding.js
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,8 @@

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isEitherArrayBuffer(x) {
return x instanceof SharedArrayBuffer || x instanceof ArrayBuffer;
return x instanceof SharedArrayBuffer || x instanceof ArrayBuffer ||
typeof x === "undefined";
}

class TextDecoder {
Expand Down Expand Up @@ -442,6 +443,7 @@
bytes = new Uint8Array(input);
} else if (
typeof input === "object" &&
input !== null &&
"buffer" in input &&
isEitherArrayBuffer(input.buffer)
) {
Expand All @@ -451,7 +453,9 @@
input.byteLength,
);
} else {
bytes = new Uint8Array(0);
throw new TypeError(
"Provided input is not of type ArrayBuffer or ArrayBufferView",
);
}

// For simple utf-8 decoding "Deno.core.decode" can be used for performance
Expand Down
41 changes: 41 additions & 0 deletions op_crates/web/text_encoding_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,44 @@ function textDecoderErrorEncoding() {
assert(didThrow);
}

function textDecoderHandlesUndefined() {
const fixture = undefined;
const decoder = new TextDecoder();
assert(decoder.decode(fixture) === "");
}

function textDecoderThrowsOnEmpty() {
const fixture = "";
const decoder = new TextDecoder();
let didThrow = false;
try {
decoder.decode(fixture);
} catch (e) {
didThrow = true;
assert(
e.message ===
"Provided input is not of type ArrayBuffer or ArrayBufferView",
);
}
assert(didThrow);
}

function textDecoderThrowsOnNull() {
const fixture = null;
const decoder = new TextDecoder();
let didThrow = false;
try {
decoder.decode(fixture);
} catch (e) {
didThrow = true;
assert(
e.message ===
"Provided input is not of type ArrayBuffer or ArrayBufferView",
);
}
assert(didThrow);
}

function textEncoder() {
const fixture = "𝓽𝓮𝔁𝓽";
const encoder = new TextEncoder();
Expand Down Expand Up @@ -231,6 +269,9 @@ function main() {
textDecoderNotBOM();
textDecoderASCII();
textDecoderErrorEncoding();
textDecoderHandlesUndefined();
textDecoderThrowsOnEmpty();
textDecoderThrowsOnNull();
textEncoder();
textEncodeInto();
textEncodeInto2();
Expand Down

0 comments on commit 2d800f2

Please sign in to comment.