001/************************************************************************
002 * Licensed under Public Domain (CC0)                                    *
003 *                                                                       *
004 * To the extent possible under law, the person who associated CC0 with  *
005 * this code has waived all copyright and related or neighboring         *
006 * rights to this code.                                                  *
007 *                                                                       *
008 * You should have received a copy of the CC0 legalcode along with this  *
009 * work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.*
010 ************************************************************************/
011
012package org.reactivestreams.tck.flow.support;
013
014import java.util.Collections;
015import java.util.Iterator;
016import java.util.concurrent.Executor;
017
018import org.reactivestreams.example.unicast.AsyncIterablePublisher;
019
020public class HelperPublisher<T> extends AsyncIterablePublisher<T> {
021  
022    public HelperPublisher(final int from, final int to, final Function<Integer, T> create, final Executor executor) {
023        super(new Iterable<T>() {
024          { if(from > to) throw new IllegalArgumentException("from must be equal or greater than to!"); }
025          @Override public Iterator<T> iterator() {
026            return new Iterator<T>() {
027              private int at = from;
028              @Override public boolean hasNext() { return at < to; }
029              @Override public T next() {
030                if (!hasNext()) return Collections.<T>emptyList().iterator().next();
031                else try {
032                  return create.apply(at++);
033                } catch (Throwable t) {
034                  throw new IllegalStateException(String.format("Failed to create element for id %d!", at - 1), t);
035                }
036              }
037              @Override public void remove() { throw new UnsupportedOperationException(); }
038            };
039          }
040        }, executor);
041    }
042}