@Override
  public PactRecord peek() {
    if (readNext) {
      int bytesRead =
          currentReadRecord.deserialize(segments, CURRENT_READ_SEGMENT_INDEX, currentReadOffset);
      while (bytesRead > 0) {
        if (currentReadSegment.size() - currentReadOffset > bytesRead) {
          currentReadOffset += bytesRead;
          bytesRead = 0;
        } else {
          bytesRead -= (currentReadSegment.size() - currentReadOffset);

          // Remove old read segment from list & release in memory manager
          MemorySegment unused = segments.remove(CURRENT_READ_SEGMENT_INDEX);
          memoryManager.release(unused);

          // Update reference to new read segment
          currentReadSegment = segments.get(CURRENT_READ_SEGMENT_INDEX);
          currentReadOffset = 0;
        }
      }
      readNext = false;
    }

    return currentReadRecord;
  }
 @Override
 public int size() {
   if (count == 0) {
     // A memory segment can be left if it was not completely full
     if (segments.size() == 1) {
       currentWriteSegment = null;
       memoryManager.release(segments);
     } else if (segments.size() > 1) {
       throw new RuntimeException("Too many memory segments left");
     }
   }
   return count;
 }
 @Override
 public void clear() {
   memoryManager.release(segments);
   segments.clear();
   count = 0;
 }