fix: performance issue of Uint8Array concat

This commit is contained in:
Siyuan Miao 2025-09-11 02:56:47 +02:00
parent a86b516f9a
commit 1e2cee7060
2 changed files with 15 additions and 8 deletions

View File

@ -232,15 +232,20 @@ export class KeyboardMacroReportMessage extends RpcMessage {
} }
marshal(): Uint8Array { marshal(): Uint8Array {
const dataHeader = new Uint8Array([ // validate if length is correct
if (this.length !== this.steps.length) {
throw new Error(`Length ${this.length} is not equal to the number of steps ${this.steps.length}`);
}
const data = new Uint8Array(this.length * 9 + 6);
data.set(new Uint8Array([
this.messageType, this.messageType,
this.isPaste ? 1 : 0, this.isPaste ? 1 : 0,
...fromUint32toUint8(this.length), ...fromUint32toUint8(this.length),
]); ]), 0);
let dataBody = new Uint8Array(); for (let i = 0; i < this.length; i++) {
const step = this.steps[i];
for (const step of this.steps) {
if (!withinUint8Range(step.modifier)) { if (!withinUint8Range(step.modifier)) {
throw new Error(`Modifier ${step.modifier} is not within the uint8 range`); throw new Error(`Modifier ${step.modifier} is not within the uint8 range`);
} }
@ -264,10 +269,13 @@ export class KeyboardMacroReportMessage extends RpcMessage {
...keys, ...keys,
...fromUint16toUint8(step.delay), ...fromUint16toUint8(step.delay),
]); ]);
const offset = 6 + i * 9;
dataBody = new Uint8Array([...dataBody, ...macroBinary]);
data.set(macroBinary, offset);
} }
return new Uint8Array([...dataHeader, ...dataBody]);
return data;
} }
} }

View File

@ -75,7 +75,6 @@ export function useHidRpc(onHidRpcMessage?: (payload: RpcMessage) => void) {
(macro: KeyboardMacroStep[]) => { (macro: KeyboardMacroStep[]) => {
const d = new KeyboardMacroReportMessage(false, macro.length, macro); const d = new KeyboardMacroReportMessage(false, macro.length, macro);
sendMessage(d); sendMessage(d);
console.log("Sent keyboard macro report", d, d.marshal());
}, },
[sendMessage], [sendMessage],
); );