View Javadoc
1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.base;
16  
17  import static com.google.common.base.Preconditions.checkState;
18  
19  import com.google.common.annotations.GwtCompatible;
20  import com.google.errorprone.annotations.CanIgnoreReturnValue;
21  import java.util.Iterator;
22  import java.util.NoSuchElementException;
23  import javax.annotation.Nullable;
24  
25  /**
26   * Note this class is a copy of {@link com.google.common.collect.AbstractIterator} (for dependency
27   * reasons).
28   */
29  @GwtCompatible
30  abstract class AbstractIterator<T> implements Iterator<T> {
31    private State state = State.NOT_READY;
32  
33    protected AbstractIterator() {}
34  
35    private enum State {
36      READY,
37      NOT_READY,
38      DONE,
39      FAILED,
40    }
41  
42    private T next;
43  
44    protected abstract T computeNext();
45  
46    @Nullable
47    @CanIgnoreReturnValue
48    protected final T endOfData() {
49      state = State.DONE;
50      return null;
51    }
52  
53    @Override
54    public final boolean hasNext() {
55      checkState(state != State.FAILED);
56      switch (state) {
57        case READY:
58          return true;
59        case DONE:
60          return false;
61        default:
62      }
63      return tryToComputeNext();
64    }
65  
66    private boolean tryToComputeNext() {
67      state = State.FAILED; // temporary pessimism
68      next = computeNext();
69      if (state != State.DONE) {
70        state = State.READY;
71        return true;
72      }
73      return false;
74    }
75  
76    @Override
77    public final T next() {
78      if (!hasNext()) {
79        throw new NoSuchElementException();
80      }
81      state = State.NOT_READY;
82      T result = next;
83      next = null;
84      return result;
85    }
86  
87    @Override
88    public final void remove() {
89      throw new UnsupportedOperationException();
90    }
91  }