59 lines
1.3 KiB
TypeScript
59 lines
1.3 KiB
TypeScript
|
|
import { decodeText, encodeText } from "./byte_util";
|
||
|
|
import { Bytes } from "./rtmt";
|
||
|
|
|
||
|
|
const headerLenght = 4
|
||
|
|
|
||
|
|
export type Message = {
|
||
|
|
channel : string,
|
||
|
|
data : Bytes,
|
||
|
|
}
|
||
|
|
//
|
||
|
|
// channel is string, message is byte array
|
||
|
|
//
|
||
|
|
export function encode(message : Message) {
|
||
|
|
const {channel, data} = message
|
||
|
|
const channelLenght = channel.length
|
||
|
|
const messageLenght = data.length
|
||
|
|
const totalLenght = headerLenght + channelLenght + messageLenght
|
||
|
|
|
||
|
|
const buffer = new ArrayBuffer(totalLenght);
|
||
|
|
const view = new DataView(buffer);
|
||
|
|
|
||
|
|
view.setUint32(0, channelLenght);
|
||
|
|
|
||
|
|
const channelBytes = encodeText(channel)
|
||
|
|
|
||
|
|
let count = headerLenght
|
||
|
|
channelBytes.forEach((byte : any)=>{
|
||
|
|
view.setUint8(count, byte)
|
||
|
|
count++
|
||
|
|
})
|
||
|
|
|
||
|
|
for (const byte of data) {
|
||
|
|
view.setUint8(count, byte)
|
||
|
|
count++
|
||
|
|
}
|
||
|
|
|
||
|
|
return buffer
|
||
|
|
}
|
||
|
|
|
||
|
|
//
|
||
|
|
// return { channel : string, message : byte array}
|
||
|
|
//
|
||
|
|
export function decode(bytes : Bytes) : Message {
|
||
|
|
const view = new DataView(bytes.buffer);
|
||
|
|
|
||
|
|
const channelLenght = view.getUint32(0)
|
||
|
|
|
||
|
|
|
||
|
|
const channel = decodeText(
|
||
|
|
bytes.slice(headerLenght, headerLenght + channelLenght))
|
||
|
|
|
||
|
|
const message = bytes.slice(headerLenght + channelLenght)
|
||
|
|
|
||
|
|
return {
|
||
|
|
"channel": channel,
|
||
|
|
"data": message,
|
||
|
|
}
|
||
|
|
}
|