diff --git a/src/encode.ts b/src/encode.ts index 06ed3329..7ca99e8c 100644 --- a/src/encode.ts +++ b/src/encode.ts @@ -1,5 +1,6 @@ import { ExtensionCodec, ExtensionCodecType } from "./ExtensionCodec"; import { Encoder } from "./Encoder"; +import { WritableBuffer } from "./utils/WritableBuffer"; export type EncodeOptions = Readonly<{ maxDepth: number; @@ -8,8 +9,8 @@ export type EncodeOptions = Readonly<{ export const DEFAULT_MAX_DEPTH = 100; -export function encode(value: unknown, options: Partial = {}): Array { - const output: Array = []; +export function encode(value: unknown, options: Partial = {}): Uint8Array { + const output = new WritableBuffer(); const context = new Encoder( options.maxDepth || DEFAULT_MAX_DEPTH, @@ -17,5 +18,5 @@ export function encode(value: unknown, options: Partial = {}): Ar ); context.encode(output, value, 1); - return output; + return output.toUint8Array(); } diff --git a/src/utils/WritableBuffer.ts b/src/utils/WritableBuffer.ts new file mode 100644 index 00000000..1ce81660 --- /dev/null +++ b/src/utils/WritableBuffer.ts @@ -0,0 +1,35 @@ +import { Writable } from "../Writable"; + +// Experimental `push(...bytes)`-able buffer +// Unfortunately, it is always slower than Array. + +export class WritableBuffer implements Writable { + private length = 0; + private buffer = new Uint8Array(128); + + push(...bytes: ReadonlyArray): void { + const offset = this.length; + const bytesLen = bytes.length; + const newLength = offset + bytesLen; + + if (this.buffer.length < newLength) { + this.grow(newLength); + } + + const buffer = this.buffer; + for (let i = 0; i < bytesLen; i++) { + buffer[offset + i] = bytes[i]; + } + this.length = newLength; + } + + grow(newLength: number) { + const newBuffer = new Uint8Array(newLength * 2); + newBuffer.set(this.buffer); + this.buffer = newBuffer; + } + + toUint8Array(): Uint8Array { + return this.buffer.subarray(0, this.length); + } +} diff --git a/tsconfig.json b/tsconfig.json index 7a09086c..fb5d4ef1 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { /* Basic Options */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ + "target": "es2019", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ "lib": ["es2019", "dom"], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ diff --git a/tsconfig.production.json b/tsconfig.production.json index d78a9246..a5b54a3b 100644 --- a/tsconfig.production.json +++ b/tsconfig.production.json @@ -1,6 +1,7 @@ { "extends": "./tsconfig.json", "compilerOptions": { + "target": "es5", "outDir": "./dist", "declaration": true, "noEmitOnError": true,