Skip to content

Commit 159b944

Browse files
committed
Use TextEncoder/TextDecoder is available
1 parent 61ab98d commit 159b944

1 file changed

Lines changed: 17 additions & 3 deletions

File tree

packages/cbor/cbor.ts

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,20 @@ import { ByteReader } from "@stablelib/bytereader";
1111
import { isSafeInteger } from "@stablelib/int";
1212
import { isNegativeZero, fround } from "@stablelib/float";
1313

14+
15+
let decodeUTF8: (data: Uint8Array) => string;
16+
let encodeUTF8: (str: string) => Uint8Array;
17+
18+
if (typeof TextEncoder === "undefined" || typeof TextDecoder === "undefined") {
19+
decodeUTF8 = utf8.decode;
20+
encodeUTF8 = utf8.encode;
21+
} else {
22+
const decoder = new TextDecoder("utf-8", { fatal: true })
23+
const encoder = new TextEncoder();
24+
decodeUTF8 = data => decoder.decode(data);
25+
encodeUTF8 = str => encoder.encode(str);
26+
}
27+
1428
/**
1529
* CBOR (Concise Binary Object Representation)
1630
* https://tools.ietf.org/html/rfc7049
@@ -377,7 +391,7 @@ export class Encoder {
377391
encodeString(value: string): this {
378392
// TODO(dchest): use byte-by-byte utf8 encoding
379393
// to (probably) improve performance.
380-
const b = utf8.encode(value);
394+
const b = encodeUTF8(value);
381395
this._writeMajorTypeAndLength(MT_TEXT_STRING, b.length);
382396
this._buf.write(b);
383397
return this;
@@ -855,7 +869,7 @@ export class Decoder {
855869
if (length > this._maxByteLength) {
856870
throw new CBORLengthExceededError(this._maxByteLength);
857871
}
858-
return utf8.decode(this._r.readNoCopy(length));
872+
return decodeUTF8(this._r.readNoCopy(length));
859873
}
860874

861875
private _decodeIndefiniteString(): string {
@@ -874,7 +888,7 @@ export class Decoder {
874888
if (majorType !== MT_TEXT_STRING || length === Infinity) {
875889
throw new CBORInvalidFormatError("cbor: incorrect indefinite string encoding");
876890
}
877-
result += utf8.decode(this._r.readNoCopy(length));
891+
result += decodeUTF8(this._r.readNoCopy(length));
878892
}
879893
return result;
880894
}

0 commit comments

Comments
 (0)