Skip to content

Commit

Permalink
Test and avoid bugs around empty and singleton iterators.
Browse files Browse the repository at this point in the history
  • Loading branch information
JervenBolleman committed Mar 15, 2024
1 parent e137af4 commit 6ba911d
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -58,22 +58,25 @@ public interface AutoClosedIterator<T> extends AutoCloseable, Iterator<T> {
public static <T> AutoClosedIterator<T> 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;
}
}
};
}
Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Object> empty = AutoClosedIterator.empty()) {
assertFalse(empty.hasNext());
assertThrows(NoSuchElementException.class, () -> empty.next());
}
}

@Test
public void concatTwoEmptyIterators() {
try (AutoClosedIterator<Object> empty1 = AutoClosedIterator.empty();
AutoClosedIterator<Object> empty2 = AutoClosedIterator.empty();
AutoClosedIterator<Object> both = AutoClosedIterator.concat(empty1, empty2)) {
assertFalse(both.hasNext());
assertThrows(NoSuchElementException.class, () -> both.next());
}
}

@Test
public void concatEmptyThenFullIterators() {
try (AutoClosedIterator<Object> empty1 = AutoClosedIterator.empty();
AutoClosedIterator<Object> notEmpty= AutoClosedIterator.of("String");
AutoClosedIterator<Object> both = AutoClosedIterator.concat(empty1, notEmpty)) {
assertTrue(both.hasNext());
assertNotNull(both.next());
assertFalse(both.hasNext());
assertThrows(NoSuchElementException.class, () -> both.next());
}
}
}

0 comments on commit 6ba911d

Please sign in to comment.