001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect.testing;
018
019import static java.util.Arrays.asList;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.collect.testing.features.CollectionSize;
023import java.util.ArrayList;
024import java.util.Collection;
025import java.util.List;
026import org.checkerframework.checker.nullness.qual.Nullable;
027
028/**
029 * Generator for collection of a particular size.
030 *
031 * @author George van den Driessche
032 */
033@GwtCompatible
034@ElementTypesAreNonnullByDefault
035public final class OneSizeGenerator<T, E extends @Nullable Object>
036    implements OneSizeTestContainerGenerator<T, E> {
037  private final TestContainerGenerator<T, E> generator;
038  private final CollectionSize collectionSize;
039
040  public OneSizeGenerator(TestContainerGenerator<T, E> generator, CollectionSize collectionSize) {
041    this.generator = generator;
042    this.collectionSize = collectionSize;
043  }
044
045  @Override
046  public TestContainerGenerator<T, E> getInnerGenerator() {
047    return generator;
048  }
049
050  @Override
051  public SampleElements<E> samples() {
052    return generator.samples();
053  }
054
055  @Override
056  public T create(Object... elements) {
057    return generator.create(elements);
058  }
059
060  @Override
061  public E[] createArray(int length) {
062    return generator.createArray(length);
063  }
064
065  @Override
066  public T createTestSubject() {
067    Collection<E> elements = getSampleElements(getCollectionSize().getNumElements());
068    return generator.create(elements.toArray());
069  }
070
071  @Override
072  public Collection<E> getSampleElements(int howMany) {
073    SampleElements<E> samples = samples();
074    List<E> allSampleElements =
075        asList(samples.e0(), samples.e1(), samples.e2(), samples.e3(), samples.e4());
076    return new ArrayList<>(allSampleElements.subList(0, howMany));
077  }
078
079  @Override
080  public CollectionSize getCollectionSize() {
081    return collectionSize;
082  }
083
084  @Override
085  public Iterable<E> order(List<E> insertionOrder) {
086    return generator.order(insertionOrder);
087  }
088}