export function decode ( data ) { let dataView = new DataView ( data ) ; let offset = 0 ; const commitRead = ( length , value ) => { offset += length ; return value ; } ; const readArrayBuffer = ( length ) => commitRead ( length , new Uint8Array ( data , offset , length ) ) ; const readUint8 = ( ) => commitRead ( 1 , dataView . getUint8 ( offset ) ) ; const readUint16 = ( ) => commitRead ( 2 , dataView . getUint16 ( offset ) ) ; const readBreak = ( ) => { if ( dataView . getUint8 ( offset ) !== 0xff ) return false ; offset += 1 ; return true ; } ; function readLength ( additionalInformation ) { if ( additionalInformation < 24 ) return additionalInformation ; if ( additionalInformation === 24 ) return readUint8 ( ) ; if ( additionalInformation === 25 ) return readUint16 ( ) ; if ( additionalInformation === 31 ) return - 1 ; } function readIndefiniteStringLength ( ) { let initialByte = readUint8 ( ) ; if ( initialByte === 0xff ) return - 1 ; return readLength ( initialByte & 0x1f ) ; } const decodeItem = ( ) : any => { let initialByte = readUint8 ( ) ; let majorType = initialByte >> 5 ; let additionalInformation = initialByte & 0x1f ; let i ; let length ; length = readLength ( additionalInformation ) ; if ( length < 0 && ( majorType < 2 || 6 < majorType ) ) throw "Invalid length" ; switch ( majorType ) { case 0 : return length ; case 1 : return - 1 - length ; case 2 : if ( length < 0 ) { let elements = [ ] ; let fullArrayLength = 0 ; while ( ( length = readIndefiniteStringLength ( ) ) >= 0 ) { fullArrayLength += length ; elements . push ( readArrayBuffer ( length ) ) ; } let fullArray = new Uint8Array ( fullArrayLength ) ; let fullArrayOffset = 0 ; for ( i = 0 ; i < elements . length ; ++ i ) { fullArray . set ( elements [ i ] , fullArrayOffset ) ; fullArrayOffset += elements [ i ] . length ; } return fullArray ; } return readArrayBuffer ( length ) ; case 4 : let retArray ; if ( length < 0 ) { retArray = [ ] ; while ( ! readBreak ( ) ) retArray . push ( decodeItem ( ) ) ; } else { retArray = new Array ( length ) ; for ( i = 0 ; i < length ; ++ i ) retArray [ i ] = decodeItem ( ) ; } return retArray ; } } ; return decodeItem ( ) ; }