diff --git a/src/main/java/io/github/jervenbolleman/handlegraph4j/iterators/AutoClosedIterator.java b/src/main/java/io/github/jervenbolleman/handlegraph4j/iterators/AutoClosedIterator.java index c4f15a5..1bde557 100644 --- a/src/main/java/io/github/jervenbolleman/handlegraph4j/iterators/AutoClosedIterator.java +++ b/src/main/java/io/github/jervenbolleman/handlegraph4j/iterators/AutoClosedIterator.java @@ -58,22 +58,25 @@ public interface AutoClosedIterator extends AutoCloseable, Iterator { public static AutoClosedIterator of(T stat) { return new AutoClosedIterator<>() { - T t = stat; - + private final T t = stat; + boolean consumed = false; @Override public void close() { } @Override public boolean hasNext() { - return t != null; + return !consumed; } @Override public T next() { - T temp = t; - t = null; - return temp; + if (consumed) { + throw new NoSuchElementException(); + } else { + consumed = true; + return t; + } } }; } @@ -100,7 +103,7 @@ public boolean hasNext() { @Override public T next() { - if (useFirst) { + if (useFirst && first.hasNext()) { T next = first.next(); useFirst = first.hasNext(); return next; diff --git a/src/test/java/io/github/jervenbolleman/handlegraph4j/iterators/AutoClosedIteratorTest.java b/src/test/java/io/github/jervenbolleman/handlegraph4j/iterators/AutoClosedIteratorTest.java new file mode 100644 index 0000000..519dcb1 --- /dev/null +++ b/src/test/java/io/github/jervenbolleman/handlegraph4j/iterators/AutoClosedIteratorTest.java @@ -0,0 +1,44 @@ +package io.github.jervenbolleman.handlegraph4j.iterators; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.NoSuchElementException; + +import org.junit.jupiter.api.Test; + +public class AutoClosedIteratorTest { + + @Test + public void empty() { + try (AutoClosedIterator empty = AutoClosedIterator.empty()) { + assertFalse(empty.hasNext()); + assertThrows(NoSuchElementException.class, () -> empty.next()); + } + } + + @Test + public void concatTwoEmptyIterators() { + try (AutoClosedIterator empty1 = AutoClosedIterator.empty(); + AutoClosedIterator empty2 = AutoClosedIterator.empty(); + AutoClosedIterator both = AutoClosedIterator.concat(empty1, empty2)) { + assertFalse(both.hasNext()); + assertThrows(NoSuchElementException.class, () -> both.next()); + } + } + + @Test + public void concatEmptyThenFullIterators() { + try (AutoClosedIterator empty1 = AutoClosedIterator.empty(); + AutoClosedIterator notEmpty= AutoClosedIterator.of("String"); + AutoClosedIterator both = AutoClosedIterator.concat(empty1, notEmpty)) { + assertTrue(both.hasNext()); + assertNotNull(both.next()); + assertFalse(both.hasNext()); + assertThrows(NoSuchElementException.class, () -> both.next()); + } + } +} +