import { SaveFileReader } from "./SaveFileReader" ; export interface BinaryStream { skip ( size ) : false ; read ( size , position ? ) : string ; readInt ( size , position ? ) : number ; readBool ( position ? ) : boolean ; done ( ) : string ; } export function binaryStream ( reader ) { let binary = "" ; let nextIndex = 0 ; const stream = { skip ( length ) { nextIndex = nextIndex + length ; return false ; } , read ( length , position = nextIndex ) { const missingBits = position + length - binary . length ; if ( missingBits > 0 ) { binary += toBinary ( reader . read ( Math . ceil ( missingBits / 8 ) ) ) ; } nextIndex = position + length ; return binary . slice ( position , position + length ) ; } , readInt ( size , position = nextIndex ) { return toInt ( stream . read ( size , position ) ) ; } , readBool ( position = nextIndex ) { return stream . read ( 1 , position ) === "1" ; } , done ( ) { return binary . slice ( 0 , nextIndex ) ; } , } ; return stream ; } function toInt ( binary ) { return parseInt ( binary . split ( "" ) . reverse ( ) . join ( "" ) , 2 ) ; } export function fromInt ( n , size ) { return n . toString ( 2 ) . padStart ( size , "0" ) . split ( "" ) . reverse ( ) . join ( "" ) ; } export function fromString ( s ) { return s . split ( "" ) . map ( ( char ) => fromInt ( char . charCodeAt ( 0 ) , 8 ) ) . join ( "" ) ; } function toBinary ( buffer ) { return buffer . reduce ( ( binary , byte ) => binary + fromInt ( byte , 8 ) , "" ) ; } export function fromBinary ( binary ) { const bytes = [ ] ; for ( let i = 0 ; i < binary . length / 8 ; i ++ ) { bytes . push ( toInt ( binary . slice ( 8 * i , 8 * ( i + 1 ) ) ) ) ; } return bytes ; }