diff --git a/src/main/java/io/gitlab/jfronny/commons/OnceSupplier.java b/src/main/java/io/gitlab/jfronny/commons/OnceSupplier.java new file mode 100644 index 0000000..f69f944 --- /dev/null +++ b/src/main/java/io/gitlab/jfronny/commons/OnceSupplier.java @@ -0,0 +1,32 @@ +package io.gitlab.jfronny.commons; + +import java.util.Objects; +import java.util.function.Supplier; + +public final class OnceSupplier implements Supplier { + private final T value; + private boolean supplied = false; + + public OnceSupplier(T value) { + this.value = value; + } + + @Override + public T get() { + if (supplied) throw new IllegalStateException("Attempted to use already used OnceSupplier"); + supplied = true; + return value; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (!(obj instanceof OnceSupplier that)) return false; + return Objects.equals(this.value, that.value); + } + + @Override + public int hashCode() { + return Objects.hash(value); + } +} diff --git a/src/main/java/io/gitlab/jfronny/commons/StreamIterable.java b/src/main/java/io/gitlab/jfronny/commons/StreamIterable.java new file mode 100644 index 0000000..2ab7075 --- /dev/null +++ b/src/main/java/io/gitlab/jfronny/commons/StreamIterable.java @@ -0,0 +1,25 @@ +package io.gitlab.jfronny.commons; + +import org.jetbrains.annotations.NotNull; + +import java.util.Iterator; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.stream.Stream; + +public record StreamIterable(Supplier> source) implements Iterable { + public StreamIterable(Stream source) { + this(new OnceSupplier<>(source)); + } + + @NotNull + @Override + public Iterator iterator() { + return source.get().iterator(); + } + + @Override + public void forEach(Consumer action) { + this.source.get().forEach(action); + } +}