author Sean Owen
  export default class BitSourceBuilder { private output : Array < number > ; private nextByte : number ; private bitsLeftInNextByte : number ; public constructor ( ) { this . output = new Array < number > ( ) ; this . nextByte = 0 ; this . bitsLeftInNextByte = 8 ; } public write ( value , numBits ) { if ( numBits <= this . bitsLeftInNextByte ) { const nb = ( this . nextByte << numBits ) & 0xFFFFFFFF ; this . nextByte = nb | value ; this . bitsLeftInNextByte -= numBits ; if ( this . bitsLeftInNextByte === 0 ) { const byte = this . nextByte & 0xFF ; this . output . push ( byte ) ; this . nextByte = 0 ; this . bitsLeftInNextByte = 8 ; } } else { const bitsToWriteNow = this . bitsLeftInNextByte ; const numRestOfBits = numBits - bitsToWriteNow ; const mask = 0xFF >> ( 8 - bitsToWriteNow ) ; const valueToWriteNow = ( value >>> numRestOfBits ) & mask ; this . write ( valueToWriteNow , bitsToWriteNow ) ; this . write ( value , numRestOfBits ) ; } } public toByteArray ( ) { if ( this . bitsLeftInNextByte < 8 ) { this . write ( 0 , this . bitsLeftInNextByte ) ; } return Uint8Array . from ( this . output ) ; } }