Exemplo n.º 1
0
 /**
  * @param path path to first element
  * @param pathTo path to second element
  * @return environment in which the generic parameters in the path to the first element are bound
  *     to those in the path to the second element, or null type on error
  */
 public static ResolvedName mapGenericParameters(
     final Deque<? extends INamedElement> path, final Deque<? extends INamedElement> pathTo) {
   // Construct an environment in which the current function's generic parameters
   // are bound to those of the eventual override.
   final Deque<List<? extends ResolvedName>> tableau =
       new LinkedList<>(ResolvedName.fromNamedElement(path.getLast()).tableau());
   final Iterator<? extends INamedElement> pathIt = path.descendingIterator();
   while (pathIt.hasNext()) {
     pathIt.next();
     tableau.removeLast();
   }
   CachedIterator<? extends INamedElement> itPathTo = null;
   CachedIterator<? extends IGenericParameter> itGPTo = null;
   boolean end = false;
   {
     // Initialise iterators into direct override's generic parameters.
     boolean foundValid = false;
     itPathTo = Iterators.cached(pathTo.iterator());
     while (!foundValid && itPathTo.hasItem()) {
       itGPTo = Iterators.cached(itPathTo.item().genericParameters().iterator());
       while (!foundValid && itGPTo.hasItem()) {
         foundValid = true;
         if (!foundValid) itGPTo.next();
       }
       if (!foundValid) itPathTo.next();
     }
     if (!foundValid) end = true;
   }
   for (final INamedElement elt : path) {
     final List<ResolvedName> row = new ArrayList<>();
     for (@SuppressWarnings("unused")
     final IGenericParameter genericParameter : elt.genericParameters()) {
       if (end) return null;
       row.add(ResolvedName.fromNamedElement(itGPTo.item()));
       {
         // Increment iterators into direct override's generic parameters.
         boolean init = true;
         boolean foundValid = false;
         if (!init) itPathTo = Iterators.cached(pathTo.iterator());
         while (!foundValid && itPathTo.hasItem()) {
           if (!init) itGPTo = Iterators.cached(itPathTo.item().genericParameters().iterator());
           while (!foundValid && itGPTo.hasItem()) {
             if (!init) foundValid = true;
             init = false;
             if (!foundValid) itGPTo.next();
           }
           if (!foundValid) itPathTo.next();
         }
         if (!foundValid) end = true;
       }
     }
     tableau.add(row);
   }
   if (!end) return null;
   return ResolvedName.newNameReference(path.getLast(), tableau);
 }
Exemplo n.º 2
0
 /**
  * Returns the element at the specified position in an iterable or a default value otherwise.
  *
  * @param position position of the element to return
  * @param defaultValue the default value to return if {@code position} is greater than or equal to
  *     the size of the iterable
  * @return the element at the specified position in {@code iterable} or {@code defaultValue} if
  *     {@code iterable} contains fewer than {@code position + 1} elements.
  * @throws IndexOutOfBoundsException if {@code position} is negative
  * @since 4.0
  */
 @Nullable
 public static <T> T get(Iterable<? extends T> iterable, int position, @Nullable T defaultValue) {
   checkNotNull(iterable);
   Iterators.checkNonnegative(position);
   if (iterable instanceof List) {
     List<? extends T> list = Lists.cast(iterable);
     return (position < list.size()) ? list.get(position) : defaultValue;
   } else {
     Iterator<? extends T> iterator = iterable.iterator();
     Iterators.advance(iterator, position);
     return Iterators.getNext(iterator, defaultValue);
   }
 }
Exemplo n.º 3
0
 public void testChainedIterables() {
   final List<List<Integer>> data = new ArrayList<List<Integer>>();
   final List<Integer> result = new ArrayList<Integer>();
   for (int i = 0; i < TEST_SEQS; i++) {
     List<Integer> l = createSequentialList(TEST_SEQ_SIZE);
     data.add(l);
     result.addAll(l);
   }
   Iterable<Integer> i = Iterators.chained(data);
   assertEquals(result, i);
   // Next try, didn't work in prev version
   i = Iterators.chained(data);
   assertEquals(result, i);
 }
 @Test
 public void unmodifiableIteratorShouldNotSupportRemoval() {
   thrown.expect(UnsupportedOperationException.class);
   thrown.expectMessage("UnmodifiableIterator.remove()");
   Iterator<String> subject = Iterators.unmodifiable(Arrays.asList("test").iterator());
   subject.remove();
 }
Exemplo n.º 5
0
 /**
  * Adds all elements in {@code iterable} to {@code collection}.
  *
  * @return {@code true} if {@code collection} was modified as a result of this operation.
  */
 public static <T> boolean addAll(Collection<T> addTo, Iterable<? extends T> elementsToAdd) {
   if (elementsToAdd instanceof Collection) {
     Collection<? extends T> c = Collections2.cast(elementsToAdd);
     return addTo.addAll(c);
   }
   return Iterators.addAll(addTo, checkNotNull(elementsToAdd).iterator());
 }
Exemplo n.º 6
0
 /**
  * Returns {@code true} if {@code iterable} contains any object for which {@code equals(element)}
  * is true.
  */
 public static boolean contains(Iterable<?> iterable, @Nullable Object element) {
   if (iterable instanceof Collection) {
     Collection<?> collection = (Collection<?>) iterable;
     return Collections2.safeContains(collection, element);
   }
   return Iterators.contains(iterable.iterator(), element);
 }
Exemplo n.º 7
0
 /**
  * Returns the number of elements in the specified iterable that equal the specified object. This
  * implementation avoids a full iteration when the iterable is a {@link Multiset} or {@link Set}.
  *
  * @see Collections#frequency
  */
 public static int frequency(Iterable<?> iterable, @Nullable Object element) {
   if ((iterable instanceof Multiset)) {
     return ((Multiset<?>) iterable).count(element);
   } else if ((iterable instanceof Set)) {
     return ((Set<?>) iterable).contains(element) ? 1 : 0;
   }
   return Iterators.frequency(iterable.iterator(), element);
 }
Exemplo n.º 8
0
 @Test
 public void combine1() {
   List<Integer> l = Arrays.asList(1, 2, 3, 4);
   Iterator<Integer> combine = Iterators.combine(Arrays.asList(l.iterator()), NATURAL_INT);
   assertEquals(1, combine.next().intValue());
   assertEquals(2, combine.next().intValue());
   assertEquals(3, combine.next().intValue());
   assertEquals(4, combine.next().intValue());
   assertFalse(combine.hasNext());
 }
Exemplo n.º 9
0
 /**
  * Determines whether two iterables contain equal elements in the same order. More specifically,
  * this method returns {@code true} if {@code iterable1} and {@code iterable2} contain the same
  * number of elements and every element of {@code iterable1} is equal to the corresponding element
  * of {@code iterable2}.
  */
 @CheckReturnValue
 public static boolean elementsEqual(Iterable<?> iterable1, Iterable<?> iterable2) {
   if (iterable1 instanceof Collection && iterable2 instanceof Collection) {
     Collection<?> collection1 = (Collection<?>) iterable1;
     Collection<?> collection2 = (Collection<?>) iterable2;
     if (collection1.size() != collection2.size()) {
       return false;
     }
   }
   return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator());
 }
Exemplo n.º 10
0
  /**
   * Returns the last element of {@code iterable}.
   *
   * @return the last element of {@code iterable}
   * @throws NoSuchElementException if the iterable is empty
   */
  public static <T> T getLast(Iterable<T> iterable) {
    // TODO(kevinb): Support a concurrently modified collection?
    if (iterable instanceof List) {
      List<T> list = (List<T>) iterable;
      if (list.isEmpty()) {
        throw new NoSuchElementException();
      }
      return getLastInNonemptyList(list);
    }

    return Iterators.getLast(iterable.iterator());
  }
Exemplo n.º 11
0
 @Override
 public boolean putAll(K key, Iterable<? extends V> values) {
   checkNotNull(values);
   // make sure we only call values.iterator() once
   // and we only call get(key) if values is nonempty
   if (values instanceof Collection) {
     Collection<? extends V> valueCollection = (Collection<? extends V>) values;
     return !valueCollection.isEmpty() && get(key).addAll(valueCollection);
   } else {
     Iterator<? extends V> valueItr = values.iterator();
     return valueItr.hasNext() && Iterators.addAll(get(key), valueItr);
   }
 }
Exemplo n.º 12
0
  /**
   * Returns the last element of {@code iterable} or {@code defaultValue} if the iterable is empty.
   *
   * @param defaultValue the value to return if {@code iterable} is empty
   * @return the last element of {@code iterable} or the default value
   * @since 3.0
   */
  @Nullable
  public static <T> T getLast(Iterable<? extends T> iterable, @Nullable T defaultValue) {
    if (iterable instanceof Collection) {
      Collection<? extends T> c = Collections2.cast(iterable);
      if (c.isEmpty()) {
        return defaultValue;
      } else if (iterable instanceof List) {
        return getLastInNonemptyList(Lists.cast(iterable));
      }
    }

    return Iterators.getLast(iterable.iterator(), defaultValue);
  }
Exemplo n.º 13
0
 @Test
 public void combine4() {
   List<Integer> l1 = Arrays.asList(1, 4, 8, 9, 19);
   List<Integer> l2 = Arrays.asList(2, 7, 10, 14, 18);
   List<Integer> l3 = Arrays.asList(3, 5, 6, 11, 15);
   List<Integer> l4 = Arrays.asList(12, 13, 16, 17, 20);
   Iterator<Integer> combine =
       Iterators.combine(
           Arrays.asList(l1.iterator(), l2.iterator(), l3.iterator(), l4.iterator()), NATURAL_INT);
   for (int i = 1; i <= 20; i++) {
     assertEquals(i, combine.next().intValue());
   }
   assertFalse(combine.hasNext());
 }
Exemplo n.º 14
0
 private void assertTestRuns(int... failingIndices) {
   IntByRef counter = new IntByRef();
   TestResult result =
       new TestResult() {
         @Override
         public void testStarted(Test test) {
           super.testStarted(test);
           Assert.isInstanceOf(CountingTest.class, test);
         }
       };
   new TestRunner(Iterators.iterable(new SimpleTestSuite(counter, NUM_TESTS, failingIndices)))
       .run(result);
   Assert.areEqual(NUM_TESTS, result.testCount());
   Assert.areEqual(failingIndices.length, result.failures().size());
   Assert.areEqual(NUM_TESTS + 2, counter.value);
 }
Exemplo n.º 15
0
  private Iterator4 checkDuplicates(CompositeIterator4 executeAllCandidates) {
    return Iterators.filter(
        executeAllCandidates,
        new Predicate4() {
          private TreeInt ids = new TreeInt(0);

          public boolean match(Object current) {
            int id = ((Integer) current).intValue();
            if (ids.find(id) != null) {
              return false;
            }
            ids = (TreeInt) ids.add(new TreeInt(id));
            return true;
          }
        });
  }
Exemplo n.º 16
0
 public void testFilteredIterables() {
   final List<Integer> data = createSequentialList(TEST_SEQ_SIZE);
   final List<Integer> expected = new LinkedList<Integer>();
   final List<Integer> filtered = new LinkedList<Integer>();
   for (Integer i = 0; i < data.size(); i++) {
     Integer x = data.get(i);
     if (i % 2 == 0) {
       expected.add(x);
     } else {
       filtered.add(x);
     }
   }
   final Iterable<Integer> res =
       Iterators.filter(
           data,
           new Comparable<Integer>() {
             public int compareTo(Integer i) {
               return filtered.contains(i) ? 0 : -1;
             }
           });
   assertEquals(expected, res);
 }
 @Test
 public void unmodifiableIteratorShouldHasNextWhenWrappedIteratorHasNext() {
   Iterator<String> subject = Iterators.unmodifiable(Arrays.asList("test").iterator());
   assertTrue(subject.hasNext());
   assertThat(subject.next(), is("test"));
 }
Exemplo n.º 18
0
 public static void runTestAndExpect(Test test, int expFailures, boolean checkException) {
   runTestAndExpect(Iterators.singletonIterable(test), expFailures, checkException);
 }
Exemplo n.º 19
0
 @Override
 public boolean retainAll(Collection<?> c) {
   synchronized (mutex) {
     return Iterators.retainAll(delegate().iterator(), c);
   }
 }
Exemplo n.º 20
0
 public void testRunsGreen() {
   TestResult result = new TestResult();
   new TestRunner(Iterators.singletonIterable(new RunsGreen())).run(result);
   Assert.isTrue(result.failures().size() == 0, "not green");
 }
Exemplo n.º 21
0
 public void testRunsRed() {
   TestResult result = new TestResult();
   new TestRunner(Iterators.singletonIterable(new RunsRed(EXCEPTION))).run(result);
   Assert.isTrue(result.failures().size() == 1, "not red");
 }
Exemplo n.º 22
0
 /** {@inheritDoc} */
 @Override
 public Iterator<N> iterator() {
   return Iterators.transformedIterator(collection.iterator(), funcMtoN);
 }
Exemplo n.º 23
0
 @Override
 public UnmodifiableIterator<E> iterator() {
   return Iterators.singletonIterator(element);
 }
Exemplo n.º 24
0
 // The fake cast to E is safe because the creation methods only allow E's
 @SuppressWarnings("unchecked")
 @Override
 public UnmodifiableIterator<E> iterator() {
   return (UnmodifiableIterator<E>) Iterators.forArray(array, offset, size);
 }
Exemplo n.º 25
0
  @SuppressWarnings("unchecked")
  @Override
  public UnmodifiableListIterator<E> listIterator(int index) {

    return (UnmodifiableListIterator<E>) Iterators.forArray(array, offset, size, index);
  }
Exemplo n.º 26
0
 public ListIterator<Object> listIterator(int start) {
   Preconditions.checkPositionIndex(start, 0);
   return Iterators.emptyListIterator();
 }
Exemplo n.º 27
0
 public ListIterator<Object> listIterator() {
   return Iterators.emptyListIterator();
 }
Exemplo n.º 28
0
 @Override
 public UnmodifiableIterator<Object> iterator() {
   return Iterators.emptyIterator();
 }
 @Test
 public void emptyIteratorShouldNotHaveNextElement() {
   thrown.expect(NoSuchElementException.class);
   assertFalse(Iterators.empty().hasNext());
   Iterators.empty().next();
 }
 @Test
 public void emptyIteratorShouldNotSupportRemoval() {
   thrown.expect(IllegalStateException.class);
   Iterators.empty().remove();
 }