From f404cdefa4aa85597e82ffc7fa9d0315f9c8ec96 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:42:41 -0500 Subject: [PATCH] perf(core): hoist stateless decoders/regexes and avoid redundant copies (#13696) --- src/adb/AdbDeviceOutput.ts | 14 +++++++++++-- src/domain/propertyListXmlText.ts | 10 +++++++-- src/domain/zip/zipMemberRegion.ts | 4 +++- src/ida/IdaMcpConnection.ts | 32 +++++++++++++++++++++-------- src/native/NativePlistSource.ts | 7 ++++++- src/process/Utf8NdjsonLineBuffer.ts | 15 ++++++++++---- 6 files changed, 64 insertions(+), 18 deletions(-) diff --git a/src/adb/AdbDeviceOutput.ts b/src/adb/AdbDeviceOutput.ts index 9dfad6070fb..ad0f075421f 100644 --- a/src/adb/AdbDeviceOutput.ts +++ b/src/adb/AdbDeviceOutput.ts @@ -59,8 +59,18 @@ export const hasOnlySuccessfulAdbStartupNotices = (output: string): boolean => { return started; }; -const metadataValue = (remainder: string, key: string): string | null => { - const match = new RegExp(`(?:^|\\s)${key}:(\\S+)`, "u").exec(remainder); +const ADB_METADATA_PATTERNS = { + usb: /(?:^|\s)usb:(\S+)/u, + product: /(?:^|\s)product:(\S+)/u, + model: /(?:^|\s)model:(\S+)/u, + device: /(?:^|\s)device:(\S+)/u, +} as const; + +const metadataValue = ( + remainder: string, + key: keyof typeof ADB_METADATA_PATTERNS, +): string | null => { + const match = ADB_METADATA_PATTERNS[key].exec(remainder); return match === null ? null : match[1]!; }; diff --git a/src/domain/propertyListXmlText.ts b/src/domain/propertyListXmlText.ts index 74c2657b5ad..1ed4b8affe2 100644 --- a/src/domain/propertyListXmlText.ts +++ b/src/domain/propertyListXmlText.ts @@ -1,6 +1,6 @@ import { ParseFailureError } from "./parseFailure.js"; import { byteOrderMarkEncoding } from "./textByteOrderMark.js"; -import { decodeStrictUtf8 } from "./strictUtf8.js"; +import { decodeStrictUtf8, strictUtf8Decoder } from "./strictUtf8.js"; const XML_PLIST_FORMAT = "xml-plist"; @@ -36,6 +36,12 @@ export class XmlPlistTextDecodeError extends ParseFailureError< } } +const XML_PLIST_DECODERS = { + "utf-8": strictUtf8Decoder("strip-signature"), + "utf-16le": new TextDecoder("utf-16le", { fatal: true }), + "utf-16be": new TextDecoder("utf-16be", { fatal: true }), +} as const; + /** Decode BOM-aware XML plist text and verify any declaration against its bytes. */ export const decodeXmlPlistText = (bytes: Uint8Array): string => { const marked = byteOrderMarkEncoding(bytes); @@ -54,7 +60,7 @@ export const decodeXmlPlistText = (bytes: Uint8Array): string => { if (prolog !== undefined) verifyEncodingDeclaration(declaration, encoding); let text: string; try { - text = new TextDecoder(encoding, { fatal: true }).decode(bytes); + text = XML_PLIST_DECODERS[encoding].decode(bytes); } catch (cause: unknown) { throw new XmlPlistTextDecodeError( "invalid-bytes", diff --git a/src/domain/zip/zipMemberRegion.ts b/src/domain/zip/zipMemberRegion.ts index 907f52ece63..d482eebf7ad 100644 --- a/src/domain/zip/zipMemberRegion.ts +++ b/src/domain/zip/zipMemberRegion.ts @@ -241,6 +241,8 @@ const dataDescriptorBytes = async ( return first; }; +const LATIN1_DECODER = new TextDecoder("latin1"); + /** Where a well-formed APK signing block ending at the directory starts, else the directory. */ const apkSigningBlockStart = async ( cursor: number, @@ -253,7 +255,7 @@ const apkSigningBlockStart = async ( directoryOffset - APK_SIGNING_BLOCK_FOOTER_BYTES, APK_SIGNING_BLOCK_FOOTER_BYTES, ); - const magic = new TextDecoder("latin1").decode( + const magic = LATIN1_DECODER.decode( footer.range(8, 16, "APK signing block magic"), ); if (magic !== APK_SIGNING_BLOCK_MAGIC) return directoryOffset; diff --git a/src/ida/IdaMcpConnection.ts b/src/ida/IdaMcpConnection.ts index b150ce65c77..8d7f0c9e750 100644 --- a/src/ida/IdaMcpConnection.ts +++ b/src/ida/IdaMcpConnection.ts @@ -277,17 +277,18 @@ const httpQuotedOctet = (code: number): boolean => (code >= 33 && code <= 126) || (code >= 128 && code <= 255); +const HTTP_TOKEN_PATTERN = /[!#$%&'*+.^_`|~0-9A-Za-z-]+/y; + /** Consume one complete RFC 9110 media type; never discard a malformed parameter. */ const parseIdaContentType = ( text: string, ): Result => { let cursor = 0; - const token = new RegExp("[!#$%&'*+.^_`|~0-9A-Za-z-]+", "y"); const readToken = (): string | undefined => { - token.lastIndex = cursor; - const match = token.exec(text); + HTTP_TOKEN_PATTERN.lastIndex = cursor; + const match = HTTP_TOKEN_PATTERN.exec(text); if (match === null) return undefined; - cursor = token.lastIndex; + cursor = HTTP_TOKEN_PATTERN.lastIndex; return match[0]; }; const readOws = (): void => { @@ -650,10 +651,25 @@ export const createIdaMcpConnection = ( const retainStderr = (chunk: unknown): void => { const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)); stderrBytes += bytes.length; - const combined = Buffer.concat([stderr, bytes]); - stderr = Buffer.from( - combined.subarray(Math.max(0, combined.length - IDA_STDERR_TAIL_BYTES)), - ); + if (bytes.length >= IDA_STDERR_TAIL_BYTES) { + stderr = Buffer.from( + bytes.subarray(bytes.length - IDA_STDERR_TAIL_BYTES), + ); + return; + } + const total = stderr.length + bytes.length; + if (total <= IDA_STDERR_TAIL_BYTES) { + stderr = + stderr.length === 0 + ? Buffer.from(bytes) + : Buffer.concat([stderr, bytes], total); + return; + } + const keepFromStderr = IDA_STDERR_TAIL_BYTES - bytes.length; + const next = Buffer.allocUnsafe(IDA_STDERR_TAIL_BYTES); + stderr.copy(next, 0, stderr.length - keepFromStderr); + bytes.copy(next, keepFromStderr); + stderr = next; }; const transport: OwnedMcpStdioTransport | StreamableHTTPClientTransport = "command" in config diff --git a/src/native/NativePlistSource.ts b/src/native/NativePlistSource.ts index 0fed3419ae4..18e2e3771d2 100644 --- a/src/native/NativePlistSource.ts +++ b/src/native/NativePlistSource.ts @@ -534,6 +534,11 @@ const readPlistSourceBytes = async ( * This is a probe window, not a document cap, and has no runtime override. */ const PLIST_MARKUP_PROBE_BYTES = 4096; +const PLIST_PROBE_DECODERS = { + "utf-8": new TextDecoder("utf-8"), + "utf-16le": new TextDecoder("utf-16le"), + "utf-16be": new TextDecoder("utf-16be"), +} as const; /** Source classification remains independent of plutil's converted value format. */ export const plistSourceFormat = ( @@ -552,7 +557,7 @@ export const plistSourceFormat = ( : head[0] === 0xfe && head[1] === 0xff ? "utf-16be" : "utf-8"; - const text = new TextDecoder(encoding).decode(head).trimStart(); + const text = PLIST_PROBE_DECODERS[encoding].decode(head).trimStart(); return /^<(?:[!?]|(?:plist|dict|array|string|integer|real|data|date|true|false)[\s/>])/u.test( text, ) diff --git a/src/process/Utf8NdjsonLineBuffer.ts b/src/process/Utf8NdjsonLineBuffer.ts index 8b27ecaabfc..64d22b63da5 100644 --- a/src/process/Utf8NdjsonLineBuffer.ts +++ b/src/process/Utf8NdjsonLineBuffer.ts @@ -80,7 +80,10 @@ export class Utf8NdjsonLineBuffer { if (refused !== undefined) yield err(refused); return; } - this.#buffer = Buffer.concat([this.#buffer, ...this.#fragments]); + this.#buffer = + this.#buffer.length === 0 && this.#fragments.length === 1 + ? this.#fragments[0]! + : Buffer.concat([this.#buffer, ...this.#fragments]); this.#fragments = []; this.#fragmentBytes = 0; if (this.#nextNewline < 0) this.#nextNewline = this.#buffer.indexOf(10); @@ -119,9 +122,13 @@ export class Utf8NdjsonLineBuffer { /** Validate the unfinished tail at EOF without treating it as a complete response. */ finish(): Result> { - const tail = this.#decode( - Buffer.concat([this.#buffer, ...this.#fragments]), - ); + const raw = + this.#fragments.length === 0 + ? this.#buffer + : this.#buffer.length === 0 && this.#fragments.length === 1 + ? this.#fragments[0]! + : Buffer.concat([this.#buffer, ...this.#fragments]); + const tail = this.#decode(raw); return tail.ok ? ok(null) : tail; }