package com.timgroup.eventstore.archiver;

import com.google.protobuf.CodedInputStream;
import com.google.protobuf.Message;
import com.google.protobuf.Parser;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

public class ProtobufsEventIterator<T extends Message> implements Iterator<T> {
    private final CodedInputStream in;
    private final Parser<? extends T> parser;

    public ProtobufsEventIterator(Parser<? extends T> parser, InputStream inputStream) {
        this.parser = parser;
        in = CodedInputStream.newInstance(inputStream);
    }

    @Override
    public boolean hasNext() {
        try {
            return !in.isAtEnd();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public T next() {
        try {
            int size = in.readFixed32();
            T msg = parser.parseFrom(in.readRawBytes(size));
            in.resetSizeCounter();
            return msg;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

@@ -859,24 +859,71 @@
 dFixed32();%0A
+            int oldLimit = in.pushLimit(size);%0A
             
@@ -953,27 +953,8 @@
 m(in
-.readRawBytes(size)
 );%0A 
@@ -971,25 +971,25 @@
  in.
-resetSizeCounter(
+popLimit(oldLimit
 );%0A 

use pushLimit/popLimit to avoid creating another byte array for each message