2021-06-27 19:28:09 +03:00
|
|
|
import { decodeText, encodeText } from "./byte_util";
|
|
|
|
|
import { Bytes } from "./rtmt";
|
|
|
|
|
|
|
|
|
|
const headerLenght = 4
|
|
|
|
|
|
|
|
|
|
export type Message = {
|
2021-06-29 03:25:42 +03:00
|
|
|
channel: string,
|
|
|
|
|
data: Bytes,
|
2021-06-27 19:28:09 +03:00
|
|
|
}
|
2021-06-29 03:25:42 +03:00
|
|
|
|
2021-06-27 19:28:09 +03:00
|
|
|
//
|
|
|
|
|
// channel is string, message is byte array
|
|
|
|
|
//
|
2021-06-29 03:25:42 +03:00
|
|
|
export function encode(message: Message) {
|
|
|
|
|
const { channel, data } = message
|
2021-06-27 19:28:09 +03:00
|
|
|
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
|
2021-06-29 03:25:42 +03:00
|
|
|
channelBytes.forEach((byte: any) => {
|
|
|
|
|
view.setUint8(count, byte)
|
2021-06-27 19:28:09 +03:00
|
|
|
count++
|
|
|
|
|
})
|
|
|
|
|
|
2021-06-29 03:25:42 +03:00
|
|
|
data.forEach((byte: any) => {
|
2021-06-27 19:28:09 +03:00
|
|
|
view.setUint8(count, byte)
|
|
|
|
|
count++
|
2021-06-29 03:25:42 +03:00
|
|
|
})
|
2021-06-27 19:28:09 +03:00
|
|
|
|
|
|
|
|
return buffer
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//
|
|
|
|
|
// return { channel : string, message : byte array}
|
|
|
|
|
//
|
2021-06-29 03:25:42 +03:00
|
|
|
export function decode(bytes: Bytes): Message {
|
|
|
|
|
const channelLenght = bytes.readInt32BE(0)
|
2021-06-27 19:28:09 +03:00
|
|
|
const channel = decodeText(
|
|
|
|
|
bytes.slice(headerLenght, headerLenght + channelLenght))
|
|
|
|
|
|
2021-06-29 03:25:42 +03:00
|
|
|
const message = bytes.slice(headerLenght + channelLenght)
|
2021-06-27 19:28:09 +03:00
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
"channel": channel,
|
|
|
|
|
"data": message,
|
|
|
|
|
}
|
|
|
|
|
}
|