import * as ByteBuffer from 'bytebuffer' ; import { HEADER_SIZE , MESSAGE_HEADER_BYTE , BUFFER_SIZE } from '../../config' ; type Options < Chunked > = { chunked : Chunked ; addTrezorHeaders : boolean ; messageType : number ; } ; function encode ( data , options ) ; function encode ( data , options ) ; function encode ( data , options ) { const { addTrezorHeaders , chunked , messageType } = options ; const fullSize = ( addTrezorHeaders ? HEADER_SIZE : HEADER_SIZE - 2 ) + data . limit ; const encodedByteBuffer = new ByteBuffer ( fullSize ) ; if ( addTrezorHeaders ) { encodedByteBuffer . writeByte ( MESSAGE_HEADER_BYTE ) ; encodedByteBuffer . writeByte ( MESSAGE_HEADER_BYTE ) ; } encodedByteBuffer . writeUint16 ( messageType ) ; encodedByteBuffer . writeUint32 ( data . limit ) ; encodedByteBuffer . append ( data . buffer ) ; encodedByteBuffer . reset ( ) ; if ( chunked === false ) { return encodedByteBuffer ; } const result = [ ] ; const size = BUFFER_SIZE ; const count = Math . floor ( ( encodedByteBuffer . limit - 1 ) / size ) + 1 || 1 ; for ( let i = 0 ; i < count ; i ++ ) { const start = i * size ; const end = Math . min ( ( i + 1 ) * size , encodedByteBuffer . limit ) ; const slice = encodedByteBuffer . slice ( start , end ) ; slice . compact ( ) ; result . push ( slice . buffer ) ; } return result ; } export { encode } ;