Merge pull request #23 from acniray/perf/optimize-qoder-body-encoding

perf: optimize Qoder body encoding for large requests
This commit is contained in:
Simon Shi
2026-09-06 17:49:13 +08:00
committed by GitHub
+38 -16
View File
@@ -1,24 +1,46 @@
const qoderCustomAlphabet = "_doRTgHZBKcGVjlvpC,@aFSx#DPuNJme&i*MzLOEn)sUrthbf%Y^w.(kIQyXqWA!"; const qoderCustomAlphabet = "_doRTgHZBKcGVjlvpC,@aFSx#DPuNJme&i*MzLOEn)sUrthbf%Y^w.(kIQyXqWA!";
const qoderStdAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const qoderStdAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const encodeTable = new Uint8Array(256);
for (let i = 0; i < encodeTable.length; i++) {
encodeTable[i] = i;
}
for (let i = 0; i < qoderStdAlphabet.length; i++) {
encodeTable[qoderStdAlphabet.charCodeAt(i)] = qoderCustomAlphabet.charCodeAt(i);
}
// Qoder uses "$" instead of standard Base64 "=" padding.
encodeTable["=".charCodeAt(0)] = "$".charCodeAt(0);
export function qoderEncodeBody(plaintext: string | Buffer): string { export function qoderEncodeBody(plaintext: string | Buffer): string {
const std = Buffer.isBuffer(plaintext) ? plaintext.toString("base64") : Buffer.from(plaintext).toString("base64"); const std = Buffer.isBuffer(plaintext) ? plaintext.toString("base64") : Buffer.from(plaintext).toString("base64");
const n = std.length;
const src = Buffer.from(std, "ascii");
const n = src.length;
const a = Math.floor(n / 3); const a = Math.floor(n / 3);
const rearranged = std.slice(n - a) + std.slice(a, n - a) + std.slice(0, a);
let out = ""; const out = Buffer.allocUnsafe(n);
for (let i = 0; i < n; i++) { let dst = 0;
const c = rearranged[i];
if (c === "=") { // Equivalent to:
out += "$"; // std.slice(n - a) + std.slice(a, n - a) + std.slice(0, a)
} else { //
const idx = qoderStdAlphabet.indexOf(c); // Translate directly into the output buffer to avoid building a large
if (idx >= 0) { // rearranged string and repeatedly concatenating one-character strings.
out += qoderCustomAlphabet[idx]; for (let i = n - a; i < n; i++) {
} else { out[dst++] = encodeTable[src[i]];
out += c;
}
}
} }
return out;
for (let i = a; i < n - a; i++) {
out[dst++] = encodeTable[src[i]];
}
for (let i = 0; i < a; i++) {
out[dst++] = encodeTable[src[i]];
}
return out.toString("ascii");
} }