region CloseableIterator Implementation
542941
@Override
    public DurableDataLog.ReadItem getNext() throws DurableDataLogException {
        Exceptions.checkNotClosed(this.closed.get(), this);

        if (this.currentLedger == null) {
            // First time we call this. Locate the first ledger based on the metadata truncation address. We don't know
            // how many entries are in that first ledger, so open it anyway so we can figure out.
            openNextLedger(this.metadata.getNextAddress(this.metadata.getTruncationAddress(), Long.MAX_VALUE));
        }

        while (this.currentLedger != null && (!this.currentLedger.canRead())) {
            // We have reached the end of the current ledger. Find next one, and skip over empty ledgers).
            val lastAddress = new LedgerAddress(this.currentLedger.metadata, this.currentLedger.handle.getLastAddConfirmed());
            Ledgers.close(this.currentLedger.handle);
            openNextLedger(this.metadata.getNextAddress(lastAddress, this.currentLedger.handle.getLastAddConfirmed()));
        }

        // Try to read from the current reader.
        if (this.currentLedger == null || this.currentLedger.reader == null) {
            return null;
        }

        return new LogReader.ReadItem(this.currentLedger.reader.nextElement(), this.currentLedger.metadata);
    }
833411
public static <F, T> CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function) {
        return wrap(Iterators.transform(iterator, function::apply), iterator);
    }
1189553
@Override
  public Iterator<Entry<K,V>> iterator() {
    checkClosed();
    final Iterator<K> _keyIterator = cache.keys().iterator();
    return new Iterator<Entry<K, V>>() {

      CacheEntry<K, V> entry;

      @Override
      public boolean hasNext() {
        while(_keyIterator.hasNext()) {
          entry = cache.getEntry(_keyIterator.next());
          if (entry.getException() == null) {
            return true;
          }
        }
        entry = null;
        return false;
      }

      @Override
      public Entry<K, V> next() {
        if (entry == null && !hasNext()) {
          throw new NoSuchElementException();
        }
        return new Entry<K, V>() {
          @Override
          public K getKey() {
            return entry.getKey();
          }

          @Override
          public V getValue() {
            return entry.getValue();
          }

          @SuppressWarnings("unchecked")
          @Override
          public <T> T unwrap(Class<T> _class) {
            if (CacheEntry.class.equals(_class)) {
              return (T) entry;
            }
            return null;
          }
        };
      }

      @Override
      public void remove() {
        if (entry == null) {
          throw new IllegalStateException("hasNext() / next() not called or end of iteration reached");
        }
        cache.remove(entry.getKey());
      }
    };
  }
1329845
@Override
	public CloseableIterator<CaptureSearchResult> getPrefixReverseIterator(String prefix)
		throws ResourceIndexNotAvailableException {
		try {
			return adaptIterator(getReverseRecordIterator(prefix));
		} catch (IOException e) {
			e.printStackTrace();
			throw new ResourceIndexNotAvailableException(e.getMessage()); 
		}
	}
599757
@Deprecated
    public static <T> CloseableIterable<T> wrap(final Iterable<T> iterable) {
        return fromIterable(iterable);
    }
735363
@Override
    @SuppressWarnings("unchecked")
    public Spliterator<E_OUT> spliterator() {
        if (linkedOrConsumed)
            throw new IllegalStateException(MSG_STREAM_LINKED);
        linkedOrConsumed = true;

        if (this == sourceStage) {
            if (sourceStage.sourceSpliterator != null) {
                @SuppressWarnings("unchecked")
                Spliterator<E_OUT> s = (Spliterator<E_OUT>) sourceStage.sourceSpliterator;
                sourceStage.sourceSpliterator = null;
                return s;
            }
            else if (sourceStage.sourceSupplier != null) {
                @SuppressWarnings("unchecked")
                Supplier<Spliterator<E_OUT>> s = (Supplier<Spliterator<E_OUT>>) sourceStage.sourceSupplier;
                sourceStage.sourceSupplier = null;
                return lazySpliterator(s);
            }
            else {
                throw new IllegalStateException(MSG_CONSUMED);
            }
        }
        else {
            return wrap(this, () -> sourceSpliterator(0), isParallel());
        }
    }
113000
private static ImmutableList<Range<Integer>> findAllOpenCloseParens(final String parse) {
    final ImmutableList.Builder<Range<Integer>> ret = ImmutableList.builder();
    final Stack<Integer> openPositions = new Stack<>();
    for (int pos = 0; pos < parse.length(); pos++) {
      // push
      if (parse.charAt(pos) == '(') {
        openPositions.push(pos);
      }
      // pop
      if (parse.charAt(pos) == ')') {
        Integer open = openPositions.pop();
        ret.add(Range.closed(open, pos));
      }
    }

    return ret.build();
  }
1176535
public static <T> CloseableIterator<T> concat(final CloseableIterator<? extends Iterator<? extends T>> iterators) {
        return wrap(Iterators.concat(iterators), iterators);
    }
104480
@Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {

            private int index = start;
            private int lastReturnedIndex = -1;
            private boolean isFirst = full;

            @Override
            public boolean hasNext() {
                return isFirst || index != end;
            }

            @Override
            public E next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                isFirst = false;
                lastReturnedIndex = index;
                index = increment(index);
                return elements[lastReturnedIndex];
            }

            @Override
            public void remove() {
                if (lastReturnedIndex == -1) {
                    throw new IllegalStateException();
                }

                // First element can be removed quickly
                if (lastReturnedIndex == start) {
                    CircularFifoQueue.this.remove();
                    lastReturnedIndex = -1;
                    return;
                }

                int pos = lastReturnedIndex + 1;
                if (start < lastReturnedIndex && pos < end) {
                    // shift in one part
                    System.arraycopy(elements, pos, elements, lastReturnedIndex, end - pos);
                } else {
                    // Other elements require us to shift the subsequent elements
                    while (pos != end) {
                        if (pos >= maxElements) {
                            elements[pos - 1] = elements[0];
                            pos = 0;
                        } else {
                            elements[decrement(pos)] = elements[pos];
                            pos = increment(pos);
                        }
                    }
                }

                lastReturnedIndex = -1;
                end = decrement(end);
                elements[end] = null;
                full = false;
                index = decrement(index);
            }

        };
    }
1031532
function __Collection(iterableOrGenerator) {
                    _classCallCheck(this, __Collection);

                    //#endregion
                    //#region Iterable
                    this.__iterable = null;
                    __assert(__isIterable(iterableOrGenerator) || __isGenerator(iterableOrGenerator), 'iterable or generator', iterableOrGenerator);
                    this.__iterable = iterableOrGenerator;
                }
1140945
private static <T> UnmodifiableIterator<Iterator<? extends T>> iterators(Iterable<? extends CloseableIterable<? extends T>> iterables) {
        final Iterator<? extends Iterable<? extends T>> iterableIterator = iterables.iterator();
        return new UnmodifiableIterator<Iterator<? extends T>>() {
            @Override
            public boolean hasNext() {
                return iterableIterator.hasNext();
            }

            @Override
            public Iterator<? extends T> next() {
                return iterableIterator.next().iterator();
            }
        };
    }
1267169
private void writeMapSimple(SerIterator itemIterator) throws IOException {
        StringConverter<Object> keyConverter = settings.getConverter().findConverterNoGenerics(itemIterator.keyType());
        output.writeObjectStart();
        while (itemIterator.hasNext()) {
            itemIterator.next();
            Object key = itemIterator.key();
            if (key == null) {
                throw new IllegalArgumentException("Unable to write map key as it cannot be null");
            }
            String str = keyConverter.convertToString(itemIterator.key());
            if (str == null) {
                throw new IllegalArgumentException("Unable to write map key as it cannot be a null string");
            }
            output.writeObjectKey(str);
            writeObject(itemIterator.valueType(), itemIterator.value(), itemIterator);
        }
        output.writeObjectEnd();
    }
360435
@Override
    public ICodeBaseIterator iterator() throws InterruptedException {
        if (!searchPerformed) {
            rfs.search();
            searchPerformed = true;
        }

        return new DirectoryCodeBaseIterator();
    }
766565
@Override
	public CloseableIterator<CaptureSearchResult> getPrefixIterator(String prefix)
		throws ResourceIndexNotAvailableException {
		try {
			return adaptIterator(getRecordIterator(prefix));
		} catch (IOException e) {
			e.printStackTrace();
			throw new ResourceIndexNotAvailableException(e.getMessage()); 
		}
	}
227347
@Override
   public boolean retainAll(Collection<?> c) {
      boolean modified = false;
      try (CloseableIterator<O> it = iterator()) {
         while (it.hasNext()) {
            if (!c.contains(it.next())) {
               it.remove();
               modified = true;
            }
         }
         return modified;
      }
   }
546972
public CloseableIterator<T> mergeSort(Iterator<T> values) throws IOException {
        ChunkSizeIterator<T> csi = new ChunkSizeIterator<T>(values, config.chunkSize);
        if (csi.isMultipleChunks()) {
            List<File> sortedChunks = writeSortedChunks(csi);
            return mergeSortedChunks(sortedChunks);
        } else {
            if (config.distinct) {
                SortedSet<T> list = new TreeSet<T>(comparator);
                while (csi.hasNext()) {
                    list.add(csi.next());
                }
                return new DelegatingMergeIterator<T>(list.iterator());
            } else {
                List<T> list = new ArrayList<T>(csi.getHeadSize());
                while (csi.hasNext()) {
                    list.add(csi.next());
                }
                Collections.sort(list, comparator);
                return new DelegatingMergeIterator<T>(list.iterator());
            }
        }
    }
1267038
public static <T> UnmodifiableIterator<T> unmodifiableIterator(
      final Iterator<T> iterator) {
    checkNotNull(iterator);
    if (iterator instanceof UnmodifiableIterator) {
      return (UnmodifiableIterator<T>) iterator;
    }
    return new UnmodifiableIterator<T>() {
      @Override
      public boolean hasNext() {
        return iterator.hasNext();
      }
      @Override
      public T next() {
        return iterator.next();
      }
    };
  }