public byte [ ] toByteArray ( ) { int oldDataPosition = dataPosition ; try { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; ObjectOutputStream oos = new ObjectOutputStream ( bos ) ; // NOTE: Serializing the data array would be simpler, and serialization would actually // preserve reference equality between entries. However, the length-encoded format here // preserves the previous format, which some tests appear to rely on. List < FakeEncodedItem > entries = new ArrayList <> ( ) ; // NOTE: Use readNextItem to scan so the contents can be proactively validated. dataPosition = 0 ; while ( dataPosition < dataSize ) { entries . add ( readNextItem ( Object . class ) ) ; } oos . writeInt ( entries . size ( ) ) ; for ( FakeEncodedItem item : entries ) { oos . writeInt ( item . sizeBytes ) ; oos . writeObject ( item . value ) ; } oos . flush ( ) ; return bos . toByteArray ( ) ; } catch ( IOException e ) { throw new UnreliableBehaviorError ( "ErrorProne unable to serialize its custom format" , e ) ; } finally { dataPosition = oldDataPosition ; } }
Converts a ByteBuffer to a raw byte array . This method should be symmetrical with fromByteArray .