001/***************************************************
002 * Licensed under MIT No Attribution (SPDX: MIT-0) *
003 ***************************************************/
004
005package org.reactivestreams.tck.flow.support;
006
007import org.reactivestreams.example.unicast.AsyncIterablePublisher;
008
009import java.util.Iterator;
010import java.util.concurrent.Executor;
011
012public class InfiniteHelperPublisher<T> extends AsyncIterablePublisher<T> {
013
014    public InfiniteHelperPublisher(final Function<Integer, T> create, final Executor executor) {
015        super(new Iterable<T>() {
016          @Override public Iterator<T> iterator() {
017            return new Iterator<T>() {
018              private int at = 0;
019
020              @Override public boolean hasNext() { return true; }
021              @Override public T next() {
022                try {
023                  return create.apply(at++); // Wraps around on overflow
024                } catch (Throwable t) {
025                  throw new IllegalStateException(
026                    String.format("Failed to create element in %s for id %s!", getClass().getSimpleName(), at - 1), t);
027                }
028              }
029              @Override public void remove() { throw new UnsupportedOperationException(); }
030            };
031          }
032        }, executor);
033    }
034}