001/*
002 * Copyright (C) 2007 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;
018
019import static com.google.common.base.Preconditions.checkState;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.errorprone.annotations.CanIgnoreReturnValue;
023import java.util.NoSuchElementException;
024
025/**
026 * This class provides a skeletal implementation of the {@code Iterator}
027 * interface, to make this interface easier to implement for certain types of
028 * data sources.
029 *
030 * <p>{@code Iterator} requires its implementations to support querying the
031 * end-of-data status without changing the iterator's state, using the {@link
032 * #hasNext} method. But many data sources, such as {@link
033 * java.io.Reader#read()}, do not expose this information; the only way to
034 * discover whether there is any data left is by trying to retrieve it. These
035 * types of data sources are ordinarily difficult to write iterators for. But
036 * using this class, one must implement only the {@link #computeNext} method,
037 * and invoke the {@link #endOfData} method when appropriate.
038 *
039 * <p>Another example is an iterator that skips over null elements in a backing
040 * iterator. This could be implemented as: <pre>   {@code
041 *
042 *   public static Iterator<String> skipNulls(final Iterator<String> in) {
043 *     return new AbstractIterator<String>() {
044 *       protected String computeNext() {
045 *         while (in.hasNext()) {
046 *           String s = in.next();
047 *           if (s != null) {
048 *             return s;
049 *           }
050 *         }
051 *         return endOfData();
052 *       }
053 *     };
054 *   }}</pre>
055 *
056 * <p>This class supports iterators that include null elements.
057 *
058 * @author Kevin Bourrillion
059 * @since 2.0
060 */
061// When making changes to this class, please also update the copy at
062// com.google.common.base.AbstractIterator
063@GwtCompatible
064public abstract class AbstractIterator<T> extends UnmodifiableIterator<T> {
065  private State state = State.NOT_READY;
066
067  /** Constructor for use by subclasses. */
068  protected AbstractIterator() {}
069
070  private enum State {
071    /** We have computed the next element and haven't returned it yet. */
072    READY,
073
074    /** We haven't yet computed or have already returned the element. */
075    NOT_READY,
076
077    /** We have reached the end of the data and are finished. */
078    DONE,
079
080    /** We've suffered an exception and are kaput. */
081    FAILED,
082  }
083
084  private T next;
085
086  /**
087   * Returns the next element. <b>Note:</b> the implementation must call {@link
088   * #endOfData()} when there are no elements left in the iteration. Failure to
089   * do so could result in an infinite loop.
090   *
091   * <p>The initial invocation of {@link #hasNext()} or {@link #next()} calls
092   * this method, as does the first invocation of {@code hasNext} or {@code
093   * next} following each successful call to {@code next}. Once the
094   * implementation either invokes {@code endOfData} or throws an exception,
095   * {@code computeNext} is guaranteed to never be called again.
096   *
097   * <p>If this method throws an exception, it will propagate outward to the
098   * {@code hasNext} or {@code next} invocation that invoked this method. Any
099   * further attempts to use the iterator will result in an {@link
100   * IllegalStateException}.
101   *
102   * <p>The implementation of this method may not invoke the {@code hasNext},
103   * {@code next}, or {@link #peek()} methods on this instance; if it does, an
104   * {@code IllegalStateException} will result.
105   *
106   * @return the next element if there was one. If {@code endOfData} was called
107   *     during execution, the return value will be ignored.
108   * @throws RuntimeException if any unrecoverable error happens. This exception
109   *     will propagate outward to the {@code hasNext()}, {@code next()}, or
110   *     {@code peek()} invocation that invoked this method. Any further
111   *     attempts to use the iterator will result in an
112   *     {@link IllegalStateException}.
113   */
114  protected abstract T computeNext();
115
116  /**
117   * Implementations of {@link #computeNext} <b>must</b> invoke this method when
118   * there are no elements left in the iteration.
119   *
120   * @return {@code null}; a convenience so your {@code computeNext}
121   *     implementation can use the simple statement {@code return endOfData();}
122   */
123  @CanIgnoreReturnValue
124  protected final T endOfData() {
125    state = State.DONE;
126    return null;
127  }
128
129  @CanIgnoreReturnValue // TODO(kak): Should we remove this? Some people are using it to prefetch?
130  @Override
131  public final boolean hasNext() {
132    checkState(state != State.FAILED);
133    switch (state) {
134      case DONE:
135        return false;
136      case READY:
137        return true;
138      default:
139    }
140    return tryToComputeNext();
141  }
142
143  private boolean tryToComputeNext() {
144    state = State.FAILED; // temporary pessimism
145    next = computeNext();
146    if (state != State.DONE) {
147      state = State.READY;
148      return true;
149    }
150    return false;
151  }
152
153  @CanIgnoreReturnValue // TODO(kak): Should we remove this?
154  @Override
155  public final T next() {
156    if (!hasNext()) {
157      throw new NoSuchElementException();
158    }
159    state = State.NOT_READY;
160    T result = next;
161    next = null;
162    return result;
163  }
164
165  /**
166   * Returns the next element in the iteration without advancing the iteration,
167   * according to the contract of {@link PeekingIterator#peek()}.
168   *
169   * <p>Implementations of {@code AbstractIterator} that wish to expose this
170   * functionality should implement {@code PeekingIterator}.
171   */
172  public final T peek() {
173    if (!hasNext()) {
174      throw new NoSuchElementException();
175    }
176    return next;
177  }
178}