From 7219dfc5fd60e2b288bba0578a67c37a248bad3b Mon Sep 17 00:00:00 2001 From: Lonny Wong Date: Sat, 4 Nov 2023 11:09:20 +0800 Subject: [PATCH] improve base64 speed --- src/comm.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/comm.ts b/src/comm.ts index 1d7d8e0..365b94d 100644 --- a/src/comm.ts +++ b/src/comm.ts @@ -55,12 +55,24 @@ export function strToArrBuf(str: string): ArrayBuffer { return strToUint8(str).buffer; } +const _hasBuffer = typeof Buffer === "function"; + export function encodeBuffer(buf: string | Uint8Array): string { - return Base64.fromByteArray(Pako.deflate(buf)); + const buffer = Pako.deflate(buf); + if (_hasBuffer) { + return Buffer.from(buffer).toString("base64"); + } + return Base64.fromByteArray(buffer); } export function decodeBuffer(buf: string): Uint8Array { - return Pako.inflate(Base64.toByteArray(buf)); + let buffer: Uint8Array; + if (_hasBuffer) { + buffer = Buffer.from(buf, "base64"); + } else { + buffer = Base64.toByteArray(buf); + } + return Pako.inflate(buffer); } export class TrzszError extends Error {