11import { floatToBinary } from './floatToBinary' ;
2+ import { uShortToBinary } from './uShortToBinary' ;
23import { uLongToBinary } from './uLongToBinary' ;
34import { intToBinary } from './intToBinary' ;
45import { uIntToBinary } from './uIntToBinary' ;
6+ import { numberToBinary } from './numberToBinary' ;
57
68export type BinaryWriter = {
79 binary : ( bits : string ) => void ;
810 boolean : ( bit : boolean ) => void ;
911 uInt : ( number : number ) => void ;
12+ uShort : ( number : number ) => void ;
1013 uLong : ( number : number ) => void ;
1114 float : ( number : number ) => void ;
1215 int : ( number : number ) => void ;
16+ char : ( char : string ) => void ;
17+ string : ( text : string ) => void ;
1318 flush : ( ) => string ;
1419} ;
1520
@@ -29,6 +34,10 @@ export const createBinaryWriter = (): BinaryWriter => {
2934 binary += uIntToBinary ( number ) ;
3035 } ,
3136
37+ uShort : function ( number : number ) {
38+ binary += uShortToBinary ( number ) ;
39+ } ,
40+
3241 uLong : function ( number : number ) {
3342 binary += uLongToBinary ( number ) ;
3443 } ,
@@ -41,6 +50,55 @@ export const createBinaryWriter = (): BinaryWriter => {
4150 binary += intToBinary ( number ) ;
4251 } ,
4352
53+ char : function ( char : string ) {
54+ const charCode = char . charCodeAt ( 0 ) ;
55+ const bits = numberToBinary ( charCode ) . padStart ( 8 , '0' ) ;
56+
57+ binary += bits ;
58+ } ,
59+
60+ string : function ( textBuffer : string ) {
61+ this . uShort ( textBuffer . length ) ;
62+
63+ if ( textBuffer . length === 0 ) return ;
64+
65+ /* Align bits. */
66+ const index = binary . length ;
67+ const offset = index % 8 === 0 ? 0 : 8 - ( index % 8 ) ;
68+
69+ if ( offset > 0 ) {
70+ const align = '0' . repeat ( offset ) ;
71+
72+ this . binary ( align ) ;
73+ }
74+
75+ let currentByte = ( binary . length % 32 ) / 8 ;
76+
77+ /* Garble text, ATT style. */
78+ let text = '' ;
79+ let bufferIndex = 0 ;
80+
81+ while ( currentByte < 4 && bufferIndex < textBuffer . length ) {
82+ text += textBuffer [ bufferIndex ++ ] ;
83+ currentByte ++ ;
84+ }
85+
86+ while ( bufferIndex + 4 <= textBuffer . length ) {
87+ const chars = textBuffer . substr ( bufferIndex , 4 ) ;
88+
89+ text += chars . split ( '' ) . reverse ( ) . join ( '' ) ;
90+ bufferIndex += 4 ;
91+ }
92+
93+ while ( bufferIndex < textBuffer . length ) {
94+ text += textBuffer [ bufferIndex ++ ] ;
95+ }
96+
97+ for ( const letter of text ) {
98+ this . char ( letter ) ;
99+ }
100+ } ,
101+
44102 flush : function ( ) {
45103 const result = binary ;
46104 binary = '' ;
0 commit comments