Skip to content

Instantly share code, notes, and snippets.

@jeffque
Created August 23, 2024 12:48
Show Gist options
  • Save jeffque/d5dab9728e0e8963fb76966c14703cad to your computer and use it in GitHub Desktop.
Save jeffque/d5dab9728e0e8963fb76966c14703cad to your computer and use it in GitHub Desktop.
Pequena alternativa para responder como input stream uma coleção de elementos
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.function.Function;
public class ServeInputStream<T> extends InputStream {
private final Iterator<T> iterator;
private final Function<T, byte[]> serializer;
private byte[] lastElementSerialized;
private int lastElementSize = -1;
private int readHead = -1;
private boolean valid = true;
public ServeInputStream(Iterable<T> iterable, Function<T, byte[]> serializer) {
this.iterator = iterable.iterator();
this.serializer = serializer;
}
@Override
public int read() throws IOException {
ensureFill();
if (!valid) {
return -1;
}
int r = lastElementSerialized[readHead];
readHead++;
return r;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
ensureFill();
if (!valid) {
return -1;
}
final int maxPossibleBytesRead = Math.min(len, lastElementSize - readHead);
System.arraycopy(lastElementSerialized, readHead, b, off, maxPossibleBytesRead);
readHead += maxPossibleBytesRead;
return maxPossibleBytesRead;
}
private void ensureFill() {
if (!valid) {
return;
}
if (readHead < lastElementSize) {
return;
}
if (!iterator.hasNext()) {
valid = false;
readHead = lastElementSize = -1;
return;
}
lastElementSerialized = serializer.apply(iterator.next());
readHead = 0;
lastElementSize = lastElementSerialized.length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment