import { TextEncoder } from 'util' ; class export class PacketLongString { public static from ( data ) { const length = data . readUInt16LE ( 0 ) ; const str = data . slice ( 2 , 2 + length ) . toString ( 'utf8' ) ; return new PacketLongString ( str , length ) ; } public str : string ; public actualStrLen : number ; public totalLen : number ; constructor ( str , rawLength = 0 ) { const expectedLen = new TextEncoder ( ) . encode ( str ) . length ; if ( rawLength !== 0 ) { if ( expectedLen !== rawLength ) { throw new Error ( 'The expected length is different from the one in the packet' ) ; } } this . str = str ; this . actualStrLen = expectedLen ; this . totalLen = this . actualStrLen + 2 ; } public toBuffer ( ) { const newBuffer = Buffer . alloc ( this . totalLen ) ; newBuffer . writeUInt16LE ( this . actualStrLen , 0 ) ; if ( this . str ) { newBuffer . write ( this . str , 2 , this . actualStrLen , 'utf8' ) ; } return newBuffer ; } }