Improve library

This commit is contained in:
2025-09-06 18:50:08 +01:00
parent 02c9cfdabc
commit dd8e6ee49f
7 changed files with 31 additions and 22 deletions

View File

@@ -10,7 +10,7 @@ export interface IncomingPacket {
export interface OutgoingPacket {
messageType: Uint8Array;
data: Uint8Array;
data?: Uint8Array;
}
/**
@@ -19,18 +19,21 @@ export interface OutgoingPacket {
* @returns A buffer containing the ready-to-send packet.
*/
export function packOutgoingPacket(outgoingPacket: OutgoingPacket): Uint8Array {
// Default to empty data if not provided
const data = outgoingPacket.data ?? new Uint8Array(0);
// Verify that the data does not exceed the maximum data length.
if (outgoingPacket.data.length > MAX_DATA_LENGTH) {
if (data.length > MAX_DATA_LENGTH) {
throw RangeError(
`Specified data of length ${outgoingPacket.data.length} exceeds max data length ${MAX_DATA_LENGTH}.`,
`Specified data of length ${data.length} exceeds max data length ${MAX_DATA_LENGTH}.`,
);
}
// Prepare the outgoing packet.
const buffer = new SmartBuffer();
buffer.writeBytes(outgoingPacket.messageType);
buffer.writeBytes(numberToUint16BE(outgoingPacket.data.length));
buffer.writeBytes(outgoingPacket.data);
buffer.writeBytes(numberToUint16BE(data.length));
buffer.writeBytes(data);
return buffer.data;
}