public int decode ( final InputStream stream , final ByteBuffer buffer ) throws IOException { if ( reachedEOF ) { return - 1 ; } // TODO: Don't decode more than single runs, because some writers add pad bytes inside the stream... while ( buffer . hasRemaining ( ) ) { int n ; if ( splitRun ) { // Continue run n = leftOfRun ; splitRun = false ; } else { // Start new run int b = stream . read ( ) ; if ( b < 0 ) { reachedEOF = true ; break ; } n = ( byte ) b ; } // Split run at or before max if ( n >= 0 && n + 1 > buffer . remaining ( ) ) { leftOfRun = n ; splitRun = true ; break ; } else if ( n < 0 && - n + 1 > buffer . remaining ( ) ) { leftOfRun = n ; splitRun = true ; break ; } try { if ( n >= 0 ) { // Copy next n + 1 bytes literally readFully ( stream , buffer , sample . length * ( n + 1 ) ) ; } // Allow -128 for compatibility, see above else if ( disableNoOp || n != - 128 ) { // Replicate the next byte -n + 1 times for ( int s = 0 ; s < sample . length ; s ++ ) { sample [ s ] = readByte ( stream ) ; } for ( int i = - n + 1 ; i > 0 ; i -- ) { buffer . put ( sample ) ; } } // else NOOP (-128) } catch ( IndexOutOfBoundsException e ) { throw new DecodeException ( "Error in PackBits decompression, data seems corrupt" , e ) ; } } return buffer . position ( ) ; }
Decodes bytes from the given input stream to the given buffer .