UNPKG

@hazae41/kcp

Version:

Zero-copy KCP protocol for the web

114 lines (111 loc) 3.08 kB
import { Opaque } from '@hazae41/binary'; class KcpSegment { conversation; command; count; window; timestamp; serial; unackSerial; fragment; fragmentSize; static commands = { push: 81, ack: 82, wask: 83, wins: 84 }; constructor( /** * conv */ conversation, /** * cmd */ command, /** * frg */ count = 0, /** * wnd */ window = 65535, /** * ts */ timestamp = Math.ceil(Date.now() / 1000), /** * sn */ serial, /** * una */ unackSerial, /** * data */ fragment, /** * data size */ fragmentSize) { this.conversation = conversation; this.command = command; this.count = count; this.window = window; this.timestamp = timestamp; this.serial = serial; this.unackSerial = unackSerial; this.fragment = fragment; this.fragmentSize = fragmentSize; } static empty(params) { const { conversation, command, count, window, timestamp, serial, unackSerial, fragment } = params; return new KcpSegment(conversation, command, count, window, timestamp, serial, unackSerial, fragment, 0); } static newOrThrow(params) { const { conversation, command, count, window, timestamp, serial, unackSerial, fragment } = params; return new KcpSegment(conversation, command, count, window, timestamp, serial, unackSerial, fragment, fragment.sizeOrThrow()); } sizeOrThrow() { return 0 + 4 + 1 + 1 + 2 + 4 + 4 + 4 + 4 + this.fragmentSize; } writeOrThrow(cursor) { cursor.writeUint32OrThrow(this.conversation, true); cursor.writeUint8OrThrow(this.command); cursor.writeUint8OrThrow(this.count); cursor.writeUint16OrThrow(this.window, true); cursor.writeUint32OrThrow(this.timestamp, true); cursor.writeUint32OrThrow(this.serial, true); cursor.writeUint32OrThrow(this.unackSerial, true); cursor.writeUint32OrThrow(this.fragmentSize, true); this.fragment.writeOrThrow(cursor); } static readOrThrow(cursor) { const conversation = cursor.readUint32OrThrow(true); const command = cursor.readUint8OrThrow(); const count = cursor.readUint8OrThrow(); const window = cursor.readUint16OrThrow(true); const timestamp = cursor.readUint32OrThrow(true); const serial = cursor.readUint32OrThrow(true); const unackSerial = cursor.readUint32OrThrow(true); const length = cursor.readUint32OrThrow(true); const bytes = cursor.readAndCopyOrThrow(length); const fragment = new Opaque(bytes); return KcpSegment.newOrThrow({ conversation, command, count, window, timestamp, serial, unackSerial, fragment }); } } export { KcpSegment }; //# sourceMappingURL=segment.mjs.map