Skip to content

Instantly share code, notes, and snippets.

@zcaudate
Last active August 19, 2020 12:03
Show Gist options
  • Save zcaudate/269d8750b6316166f14be15bfb8aa500 to your computer and use it in GitHub Desktop.
Save zcaudate/269d8750b6316166f14be15bfb8aa500 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.io.NotSerializableException;
import java.util.Iterator;
import clojure.lang.ASeq;
import clojure.lang.ISeq;
import clojure.lang.IPersistentMap;
public class IteratorSeq extends ASeq{
final Iterator iter;
final State state;
static class State{
volatile Object val;
volatile Object _rest;
}
public static IteratorSeq create(Iterator iter){
if(iter.hasNext())
return new IteratorSeq(iter);
return null;
}
public IteratorSeq(Iterator iter){
this.iter = iter;
state = new State();
this.state.val = state;
this.state._rest = state;
}
public IteratorSeq(IPersistentMap meta, Iterator iter, State state){
super(meta);
this.iter = iter;
this.state = state;
}
public Object first() {
if(state.val == state) synchronized(state) {
if(state.val == state) state.val = iter.next();
}
return state.val;
}
public ISeq next(){
if(state._rest == state) {
synchronized(state) {
if(state._rest == state) {
first();
state._rest = iter.hasNext() ? new IteratorSeq(iter) : null;
}
}
}
return (ISeq) state._rest;
}
public IteratorSeq withMeta(IPersistentMap meta){
return new IteratorSeq(meta, iter, state);
}
private void writeObject (java.io.ObjectOutputStream out) throws IOException {
throw new NotSerializableException(getClass().getName());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment