001/*
002 * Licensed to the author under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package de.cuioss.test.generator.internal.net.java.quickcheck.generator.iterable;
018
019import static java.util.Objects.requireNonNull;
020
021import java.util.Iterator;
022import java.util.NoSuchElementException;
023
024import de.cuioss.test.generator.internal.net.java.quickcheck.Generator;
025import de.cuioss.test.generator.internal.net.java.quickcheck.QuickCheck;
026import de.cuioss.test.generator.internal.net.java.quickcheck.generator.Generators;
027
028public final class Iterables {
029
030    private Iterables() {
031    }
032
033    /**
034     * Convert a generator into a {@link Iterable iterable}.<br>
035     *
036     * The generator will be run {@link QuickCheck#MAX_NUMBER_OF_RUNS} times.
037     */
038    public static <T> Iterable<T> toIterable(final Generator<T> generator) {
039        return Generators.toIterable(generator);
040    }
041
042    /**
043     * Convert a generator into an {@link Iterable iterable}.
044     *
045     * @param numberOfRuns to execute the runner
046     */
047    public static <T> Iterable<T> toIterable(final Generator<T> generator, final int numberOfRuns) {
048        return Generators.toIterable(generator, numberOfRuns);
049    }
050
051    /**
052     * Calculate the size of an {@link Iterable}.
053     * <p>
054     * The size of an {@link Iterable} is the number of {@link Iterator#next()}
055     * calls not throwing a {@link NoSuchElementException}.
056     * </p>
057     *
058     * @param iterable to calculate the size of
059     */
060    public static <T> int sizeOf(Iterable<T> iterable) {
061        requireNonNull(iterable, "iterable");
062        int size = 0;
063        // noinspection StatementWithEmptyBody
064        for (Iterator<T> iter = iterable.iterator(); iter.hasNext(); iter.next(), size++)
065            ;
066        return size;
067    }
068}