public WrappedByteBuffer compact ( ) { int remaining = remaining ( ) ; int capacity = capacity ( ) ; if ( capacity == 0 ) { return this ; } if ( remaining <= capacity >>> 2 && capacity > _minimumCapacity ) { int newCapacity = capacity ; int minCapacity = max ( _minimumCapacity , remaining << 1 ) ; for ( ; ; ) { if ( newCapacity >>> 1 < minCapacity ) { break ; } newCapacity >>>= 1 ; } newCapacity = max ( minCapacity , newCapacity ) ; if ( newCapacity == capacity ) { if ( _buf . remaining ( ) == 0 ) { _buf . position ( 0 ) ; _buf . limit ( _buf . capacity ( ) ) ; } else { java . nio . ByteBuffer dup = _buf . duplicate ( ) ; _buf . position ( 0 ) ; _buf . limit ( _buf . capacity ( ) ) ; _buf . put ( dup ) ; } return this ; } // Shrink and compact: // // Save the state. ByteOrder bo = order ( ) ; // // Sanity check. if ( remaining > newCapacity ) { throw new IllegalStateException ( "The amount of the remaining bytes is greater than " + "the new capacity." ) ; } // // Reallocate. java . nio . ByteBuffer oldBuf = _buf ; java . nio . ByteBuffer newBuf = java . nio . ByteBuffer . allocate ( newCapacity ) ; newBuf . put ( oldBuf ) ; _buf = newBuf ; // // Restore the state. _buf . order ( bo ) ; } else { _buf . compact ( ) ; } return this ; }
Compacts the buffer by removing leading bytes up to the buffer position and decrements the limit and position values accordingly .