Add all BENNC message types with unit tests

This commit is contained in:
Jack Hadrill
2022-02-06 20:34:13 +00:00
parent 7d1a0991e4
commit e758de7ef4
28 changed files with 708 additions and 12539 deletions

55
src/messages/packet.ts Normal file
View File

@@ -0,0 +1,55 @@
import { MAX_DATA_LENGTH } from '../common'
import { numberToUint16BE } from '../utilities/number'
import { SmartBuffer } from '../utilities/smart-buffer'
export interface IncomingPacket {
messageType: number
senderId: number
data: Buffer
}
export interface OutgoingPacket {
messageType: Buffer
data: Buffer
}
/**
* Create an outgoing packet ready-to-send over a WebSocket in line with the BENNC basic message strucure specification.
* @param outgoingPacket The message type and data to send.
* @returns A buffer containing the ready-to-send packet.
*/
export function packOutgoingPacket (outgoingPacket: OutgoingPacket): Buffer {
// Verify that the data does not exceed the maximum data length.
if (outgoingPacket.data.length > MAX_DATA_LENGTH) {
throw RangeError(`Specified data of length ${outgoingPacket.data.length} exceeds max data length ${MAX_DATA_LENGTH}.`)
}
// Prepare the outgoing packet.
const buffer = Buffer.concat([
outgoingPacket.messageType,
numberToUint16BE(outgoingPacket.data.length),
outgoingPacket.data
])
return buffer
}
/**
* Unpack an incoming packet coming from a WebSocket in line with the BENNC basic message strucure specification.
* @param incomingPacket The incoming buffer from a WebSocket to unpack.
* @returns The unpacked data.
*/
export function unpackIncomingPacket (incomingPacket: ArrayBuffer): IncomingPacket {
const buffer = SmartBuffer.from(incomingPacket)
const messageType = buffer.readUInt16()
const senderId = buffer.readUInt32()
const length = buffer.readUInt16()
const data = buffer.readBytes(length)
return {
messageType: messageType,
senderId: senderId,
data: data
}
}