nitro-renderer/src/core/utils/BinaryWriter.ts

110 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-10-30 05:02:19 +01:00
import { IBinaryWriter } from '../../api';
export class BinaryWriter implements IBinaryWriter
2021-03-17 03:02:09 +01:00
{
private _buffer: Uint8Array;
2021-07-29 23:40:55 +02:00
private _position: number;
2021-03-17 03:02:09 +01:00
constructor()
{
this._buffer = new Uint8Array();
2021-07-29 23:40:55 +02:00
this._position = 0;
2021-03-17 03:02:09 +01:00
}
2022-10-30 05:02:19 +01:00
public writeByte(byte: number): IBinaryWriter
2021-03-17 03:02:09 +01:00
{
const array = new Uint8Array(1);
array[0] = byte;
this.appendArray(array);
return this;
}
2022-10-30 05:02:19 +01:00
public writeBytes(bytes: ArrayBuffer | number[]): IBinaryWriter
2021-03-17 03:02:09 +01:00
{
const array = new Uint8Array(bytes);
this.appendArray(array);
return this;
}
2022-10-30 05:02:19 +01:00
public writeShort(short: number): IBinaryWriter
2021-03-17 03:02:09 +01:00
{
const array = new Uint8Array(2);
array[0] = short >> 8;
array[1] = short & 0xFF;
this.appendArray(array);
return this;
}
2022-10-30 05:02:19 +01:00
public writeInt(integer: number): IBinaryWriter
2021-03-17 03:02:09 +01:00
{
const array = new Uint8Array(4);
array[0] = integer >> 24;
array[1] = integer >> 16;
array[2] = integer >> 8;
array[3] = integer & 0xFF;
this.appendArray(array);
return this;
}
2022-10-30 05:02:19 +01:00
public writeString(string: string, includeLength: boolean = true): IBinaryWriter
2021-03-17 03:02:09 +01:00
{
const array = new TextEncoder().encode(string);
2022-11-02 23:44:30 +01:00
if(includeLength)
2021-03-17 03:02:09 +01:00
{
this.writeShort(array.length);
this.appendArray(array);
}
else
{
this.appendArray(array);
}
return this;
}
private appendArray(array: Uint8Array): void
{
2022-11-02 23:44:30 +01:00
if(!array) return;
2021-03-17 03:02:09 +01:00
2022-10-30 05:02:19 +01:00
const mergedArray = new Uint8Array(((this.position + array.length) > this._buffer.length) ? (this.position + array.length) : this._buffer.length);
2021-03-17 03:02:09 +01:00
mergedArray.set(this._buffer);
2021-07-29 23:40:55 +02:00
mergedArray.set(array, this.position);
2021-03-17 03:02:09 +01:00
this._buffer = mergedArray;
2021-07-29 23:40:55 +02:00
this.position += array.length;
2021-03-17 03:02:09 +01:00
}
public getBuffer(): ArrayBuffer
{
return this._buffer.buffer;
}
2021-07-29 23:40:55 +02:00
public get position(): number
{
return this._position;
}
public set position(pos: number)
{
this._position = pos;
}
2021-03-17 03:02:09 +01:00
public toString(encoding?: string): string
{
return new TextDecoder(encoding).decode(this._buffer);
}
2021-07-29 23:40:55 +02:00
}