/*
 * Copyright (C) 2002-2017 Sebastiano Vigna
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package PACKAGE;

import java.util.Iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Objects;

/** A class providing static methods and objects that do useful things with type-specific iterators.
 *
 * @see Iterator
 */

public final class ITERATORS {

	private ITERATORS() {}

	/** A class returning no elements and a type-specific iterator interface.
	 *
	 * <p>This class may be useful to implement your own in case you subclass
	 * a type-specific iterator.
	 */

	public static class EmptyIterator KEY_GENERIC implements KEY_LIST_ITERATOR KEY_GENERIC, java.io.Serializable, Cloneable {

		private static final long serialVersionUID = -7046029254386353129L;

		protected EmptyIterator() {}

		@Override
		public boolean hasNext() { return false; }

		@Override
		public boolean hasPrevious() { return false; }

		@Override
		public KEY_GENERIC_TYPE NEXT_KEY() { throw new NoSuchElementException(); }

		@Override
		public KEY_GENERIC_TYPE PREV_KEY() { throw new NoSuchElementException(); }

		@Override
		public int nextIndex() { return 0; }

		@Override
		public int previousIndex() { return -1; }

		@Override
		public int skip(int n) { return 0; };

		@Override
		public int back(int n) { return 0; };

		@Override
		public Object clone() { return EMPTY_ITERATOR; }

		private Object readResolve() { return EMPTY_ITERATOR; }
	}

	/** An empty iterator. It is serializable and cloneable.
	 *
	 * <p>The class of this objects represent an abstract empty iterator
	 * that can iterate as a type-specific (list) iterator.
	 */

	SUPPRESS_WARNINGS_KEY_RAWTYPES
	public static final EmptyIterator EMPTY_ITERATOR = new EmptyIterator();

#if KEYS_REFERENCE
	/** Returns an empty iterator. It is serializable and cloneable.
	 *
	 * <p>The class of the object returned represent an abstract empty iterator
	 * that can iterate as a type-specific (list) iterator.
	 *
	 * <p>This method provides a typesafe access to {@link #EMPTY_ITERATOR}.
	 * @return an empty iterator.
	 */
	@SuppressWarnings("unchecked")
	public static KEY_GENERIC KEY_ITERATOR KEY_GENERIC emptyIterator() { return EMPTY_ITERATOR; }
#endif


	/** An iterator returning a single element. */

	private static class SingletonIterator KEY_GENERIC implements KEY_LIST_ITERATOR KEY_GENERIC {
		private final KEY_GENERIC_TYPE element;
		private int curr;

		public SingletonIterator(final KEY_GENERIC_TYPE element) {
			this.element = element;
		}

		@Override
		public boolean hasNext() { return curr == 0; }

		@Override
		public boolean hasPrevious() { return curr == 1; }

		@Override
		public KEY_GENERIC_TYPE NEXT_KEY() {
			if (! hasNext()) throw new NoSuchElementException();
			curr = 1;
			return element;
		}

		@Override
		public KEY_GENERIC_TYPE PREV_KEY() {
			if (! hasPrevious()) throw new NoSuchElementException();
			curr = 0;
			return element;
		}

		@Override
		public int nextIndex() {
			return curr;
		}

		@Override
		public int previousIndex() {
			return curr - 1;
		}
	}


	/** Returns an immutable iterator that iterates just over the given element.
	 *
	 * @param element the only element to be returned by a type-specific list iterator.
	 * @return an immutable iterator that iterates just over {@code element}.
	 */
	public static KEY_GENERIC KEY_LIST_ITERATOR KEY_GENERIC singleton(final KEY_GENERIC_TYPE element) {
		return new SingletonIterator KEY_GENERIC_DIAMOND(element);
	}


	/** A class to wrap arrays in iterators. */

	private static class ArrayIterator KEY_GENERIC implements KEY_LIST_ITERATOR KEY_GENERIC {
		private final KEY_GENERIC_TYPE[] array;
		private final int offset, length;
		private int curr;

		public ArrayIterator(final KEY_GENERIC_TYPE[] array, final int offset, final int length) {
			this.array = array;
			this.offset = offset;
			this.length = length;
		}

		@Override
		public boolean hasNext() { return curr < length; }

		@Override
		public boolean hasPrevious() { return curr > 0; }

		@Override
		public KEY_GENERIC_TYPE NEXT_KEY() {
			if (! hasNext()) throw new NoSuchElementException();
			return array[offset + curr++];
		}

		@Override
		public KEY_GENERIC_TYPE PREV_KEY() {
			if (! hasPrevious()) throw new NoSuchElementException();
			return array[offset + --curr];
		}

		@Override
		public int skip(int n) {
			if (n <= length - curr) {
				curr += n;
				return n;
			}
			n = length - curr;
			curr = length;
			return n;
		}

		@Override
		public int back(int n) {
			if (n <= curr) {
				curr -= n;
				return n;
			}
			n = curr;
			curr = 0;
			return n;
		}

		@Override
		public int nextIndex() {
			return curr;
		}

		@Override
		public int previousIndex() {
			return curr - 1;
		}
	}


	/** Wraps the given part of an array into a type-specific list iterator.
	 *
	 * <p>The type-specific list iterator returned by this method will iterate
	 * {@code length} times, returning consecutive elements of the given
	 * array starting from the one with index {@code offset}.
	 *
	 * @param array an array to wrap into a type-specific list iterator.
	 * @param offset the first element of the array to be returned.
	 * @param length the number of elements to return.
	 * @return an iterator that will return {@code length} elements of {@code array} starting at position {@code offset}.
	 */
	public static KEY_GENERIC KEY_LIST_ITERATOR KEY_GENERIC wrap(final KEY_GENERIC_TYPE[] array, final int offset, final int length) {
		ARRAYS.ensureOffsetLength(array, offset, length);
		return new ArrayIterator KEY_GENERIC_DIAMOND(array, offset, length);
	}

	/** Wraps the given array into a type-specific list iterator.
	 *
	 * <p>The type-specific list iterator returned by this method will return
	 * all elements of the given array.
	 *
	 * @param array an array to wrap into a type-specific list iterator.
	 * @return an iterator that will the elements of {@code array}.
	 */
	public static KEY_GENERIC KEY_LIST_ITERATOR KEY_GENERIC wrap(final KEY_GENERIC_TYPE[] array) {
		return new ArrayIterator KEY_GENERIC_DIAMOND(array, 0, array.length);
	}


	/** Unwraps an iterator into an array starting at a given offset for a given number of elements.
	 *
	 * <p>This method iterates over the given type-specific iterator and stores the elements
	 * returned, up to a maximum of {@code length}, in the given array starting at {@code offset}.
	 * The number of actually unwrapped elements is returned (it may be less than {@code max} if
	 * the iterator emits less than {@code max} elements).
	 *
	 * @param i a type-specific iterator.
	 * @param array an array to contain the output of the iterator.
	 * @param offset the first element of the array to be returned.
	 * @param max the maximum number of elements to unwrap.
	 * @return the number of elements unwrapped.
	 */
	public static KEY_GENERIC int unwrap(final STD_KEY_ITERATOR KEY_EXTENDS_GENERIC i, final KEY_GENERIC_TYPE array[], int offset, final int max) {
		if (max < 0) throw new IllegalArgumentException("The maximum number of elements (" + max + ") is negative");
		if (offset < 0 || offset + max > array.length) throw new IllegalArgumentException();
		int j = max;
		while(j-- != 0 && i.hasNext()) array[offset++] = i.NEXT_KEY();
		return max - j - 1;
	}

	/** Unwraps an iterator into an array.
	 *
	 * <p>This method iterates over the given type-specific iterator and stores the
	 * elements returned in the given array. The iteration will stop when the
	 * iterator has no more elements or when the end of the array has been reached.
	 *
	 * @param i a type-specific iterator.
	 * @param array an array to contain the output of the iterator.
	 * @return the number of elements unwrapped.
	 */
	public static KEY_GENERIC int unwrap(final STD_KEY_ITERATOR KEY_EXTENDS_GENERIC i, final KEY_GENERIC_TYPE array[]) {
		return unwrap(i, array, 0, array.length);
	}

	/** Unwraps an iterator, returning an array, with a limit on the number of elements.
	 *
	 * <p>This method iterates over the given type-specific iterator and returns an array
	 * containing the elements returned by the iterator. At most {@code max} elements
	 * will be returned.
	 *
	 * @param i a type-specific iterator.
	 * @param max the maximum number of elements to be unwrapped.
	 * @return an array containing the elements returned by the iterator (at most {@code max}).
	 */
	SUPPRESS_WARNINGS_KEY_UNCHECKED
	public static KEY_GENERIC KEY_GENERIC_TYPE[] unwrap(final STD_KEY_ITERATOR KEY_EXTENDS_GENERIC i, int max) {
		if (max < 0) throw new IllegalArgumentException("The maximum number of elements (" + max + ") is negative");
		KEY_GENERIC_TYPE array[] = KEY_GENERIC_ARRAY_CAST new KEY_TYPE[16];
		int j = 0;

		while(max-- != 0 && i.hasNext()) {
			if (j == array.length) array = ARRAYS.grow(array, j + 1);
			array[j++] = i.NEXT_KEY();
		}

		return ARRAYS.trim(array, j);
	}


	/** Unwraps an iterator, returning an array.
	 *
	 * <p>This method iterates over the given type-specific iterator and returns an array
	 * containing the elements returned by the iterator.
	 *
	 * @param i a type-specific iterator.
	 * @return an array containing the elements returned by the iterator.
	 */

	public static KEY_GENERIC KEY_GENERIC_TYPE[] unwrap(final STD_KEY_ITERATOR KEY_EXTENDS_GENERIC i) {
		return unwrap(i, Integer.MAX_VALUE);
	}


	/** Unwraps an iterator into a type-specific collection, with a limit on the number of elements.
	 *
	 * <p>This method iterates over the given type-specific iterator and stores the elements
	 * returned, up to a maximum of {@code max}, in the given type-specific collection.
	 * The number of actually unwrapped elements is returned (it may be less than {@code max} if
	 * the iterator emits less than {@code max} elements).
	 *
	 * @param i a type-specific iterator.
	 * @param c a type-specific collection array to contain the output of the iterator.
	 * @param max the maximum number of elements to unwrap.
	 * @return the number of elements unwrapped. Note that
	 * this is the number of elements returned by the iterator, which is not necessarily the number
	 * of elements that have been added to the collection (because of duplicates).
	 */
	public static KEY_GENERIC int unwrap(final STD_KEY_ITERATOR KEY_GENERIC i, final COLLECTION KEY_SUPER_GENERIC c, final int max) {
		if (max < 0) throw new IllegalArgumentException("The maximum number of elements (" + max + ") is negative");
		int j = max;
		while(j-- != 0 && i.hasNext()) c.add(i.NEXT_KEY());
		return max - j - 1;
	}

	/** Unwraps an iterator into a type-specific collection.
	 *
	 * <p>This method iterates over the given type-specific iterator and stores the
	 * elements returned in the given type-specific collection. The returned count on the number
	 * unwrapped elements is a long, so that it will work also with very large collections.
	 *
	 * @param i a type-specific iterator.
	 * @param c a type-specific collection to contain the output of the iterator.
	 * @return the number of elements unwrapped. Note that
	 * this is the number of elements returned by the iterator, which is not necessarily the number
	 * of elements that have been added to the collection (because of duplicates).
	 */
	public static KEY_GENERIC long unwrap(final STD_KEY_ITERATOR KEY_GENERIC i, final COLLECTION KEY_SUPER_GENERIC c) {
		long n = 0;
		while(i.hasNext()) {
			c.add(i.NEXT_KEY());
			n++;
		}
		return n;
	}


	/** Pours an iterator into a type-specific collection, with a limit on the number of elements.
	 *
	 * <p>This method iterates over the given type-specific iterator and adds
	 * the returned elements to the given collection (up to {@code max}).
	 *
	 * @param i a type-specific iterator.
	 * @param s a type-specific collection.
	 * @param max the maximum number of elements to be poured.
	 * @return the number of elements poured. Note that
	 * this is the number of elements returned by the iterator, which is not necessarily the number
	 * of elements that have been added to the collection (because of duplicates).
	 */

	public static KEY_GENERIC int pour(final STD_KEY_ITERATOR KEY_GENERIC i, final COLLECTION KEY_SUPER_GENERIC s, final int max) {
		if (max < 0) throw new IllegalArgumentException("The maximum number of elements (" + max + ") is negative");
		int j = max;
		while(j-- != 0 && i.hasNext()) s.add(i.NEXT_KEY());
		return max - j - 1;
	}

	/** Pours an iterator into a type-specific collection.
	 *
	 * <p>This method iterates over the given type-specific iterator and adds
	 * the returned elements to the given collection.
	 *
	 * @param i a type-specific iterator.
	 * @param s a type-specific collection.
	 * @return the number of elements poured. Note that
	 * this is the number of elements returned by the iterator, which is not necessarily the number
	 * of elements that have been added to the collection (because of duplicates).
	 */

	public static KEY_GENERIC int pour(final STD_KEY_ITERATOR KEY_GENERIC i, final COLLECTION KEY_SUPER_GENERIC s) {
		return pour(i, s, Integer.MAX_VALUE);
	}

	/** Pours an iterator, returning a type-specific list, with a limit on the number of elements.
	 *
	 * <p>This method iterates over the given type-specific iterator and returns
	 * a type-specific list containing the returned elements (up to {@code max}). Iteration
	 * on the returned list is guaranteed to produce the elements in the same order
	 * in which they appeared in the iterator.
	 *
	 *
	 * @param i a type-specific iterator.
	 * @param max the maximum number of elements to be poured.
	 * @return a type-specific list containing the returned elements, up to {@code max}.
	 */

	public static KEY_GENERIC LIST KEY_GENERIC pour(final STD_KEY_ITERATOR KEY_GENERIC i, int max) {
		final ARRAY_LIST KEY_GENERIC l = new ARRAY_LIST KEY_GENERIC_DIAMOND();
		pour(i, l, max);
		l.trim();
		return l;
	}

	/** Pours an iterator, returning a type-specific list.
	 *
	 * <p>This method iterates over the given type-specific iterator and returns
	 * a list containing the returned elements. Iteration
	 * on the returned list is guaranteed to produce the elements in the same order
	 * in which they appeared in the iterator.
	 *
	 * @param i a type-specific iterator.
	 * @return a type-specific list containing the returned elements.
	 */

	public static KEY_GENERIC LIST KEY_GENERIC pour(final STD_KEY_ITERATOR KEY_GENERIC i) {
		return pour(i, Integer.MAX_VALUE);
	}

	private static class IteratorWrapper KEY_GENERIC implements KEY_ITERATOR KEY_GENERIC {
		final Iterator<KEY_GENERIC_CLASS> i;

		public IteratorWrapper(final Iterator<KEY_GENERIC_CLASS> i) {
			this.i = i;
		}

		@Override
		public boolean hasNext() { return i.hasNext(); }
		@Override
		public void remove() { i.remove(); }
		@Override
		public KEY_GENERIC_TYPE NEXT_KEY() { return KEY_CLASS2TYPE(i.next()); }
	}

	/** Wraps a standard iterator into a type-specific iterator.
	 *
	 * <p>This method wraps a standard iterator into a type-specific one which will handle the
	 * type conversions for you. Of course, any attempt to wrap an iterator returning the
	 * instances of the wrong class will generate a {@link ClassCastException}. The
	 * returned iterator is backed by {@code i}: changes to one of the iterators
	 * will affect the other, too.
	 *
	 * <p>If {@code i} is already type-specific, it will returned and no new object
	 * will be generated.
	 *
	 * @param i an iterator.
	 * @return a type-specific iterator  backed by {@code i}.
	 */
#if KEYS_PRIMITIVE
	@SuppressWarnings({"unchecked","rawtypes"})
#endif
 	public static KEY_GENERIC KEY_ITERATOR KEY_GENERIC AS_KEY_ITERATOR(final Iterator KEY_GENERIC i) {
		if (i instanceof KEY_ITERATOR) return (KEY_ITERATOR KEY_GENERIC)i;
		return new IteratorWrapper KEY_GENERIC_DIAMOND(i);
	}


	private static class ListIteratorWrapper KEY_GENERIC implements KEY_LIST_ITERATOR KEY_GENERIC {
		final ListIterator<KEY_GENERIC_CLASS> i;

		public ListIteratorWrapper(final ListIterator<KEY_GENERIC_CLASS> i) {
			this.i = i;
		}

		@Override
		public boolean hasNext() { return i.hasNext(); }

		@Override
		public boolean hasPrevious() { return i.hasPrevious(); }

		@Override
		public int nextIndex() { return i.nextIndex(); }

		@Override
		public int previousIndex() { return i.previousIndex(); }

		@Override
		public void set(KEY_GENERIC_TYPE k) { i.set(KEY2OBJ(k)); }

		@Override
		public void add(KEY_GENERIC_TYPE k) { i.add(KEY2OBJ(k)); }

		@Override
		public void remove() { i.remove(); }

		@Override
		public KEY_GENERIC_TYPE NEXT_KEY() { return KEY_CLASS2TYPE(i.next()); }

		@Override
		public KEY_GENERIC_TYPE PREV_KEY() { return KEY_CLASS2TYPE(i.previous()); }
	}

	/** Wraps a standard list iterator into a type-specific list iterator.
	 *
	 * <p>This method wraps a standard list iterator into a type-specific one
	 * which will handle the type conversions for you. Of course, any attempt
	 * to wrap an iterator returning the instances of the wrong class will
	 * generate a {@link ClassCastException}. The
	 * returned iterator is backed by {@code i}: changes to one of the iterators
	 * will affect the other, too.
	 *
	 * <p>If {@code i} is already type-specific, it will returned and no new object
	 * will be generated.
	 *
	 * @param i a list iterator.
	 * @return a type-specific list iterator backed by {@code i}.
	 */
#if KEYS_PRIMITIVE
	@SuppressWarnings({"unchecked","rawtypes"})
#endif
 	public static KEY_GENERIC KEY_LIST_ITERATOR KEY_GENERIC AS_KEY_ITERATOR(final ListIterator KEY_GENERIC i) {
		if (i instanceof KEY_LIST_ITERATOR) return (KEY_LIST_ITERATOR KEY_GENERIC)i;
		return new ListIteratorWrapper KEY_GENERIC_DIAMOND(i);
	}

#ifdef JDK_PRIMITIVE_PREDICATE
	public static boolean any(final KEY_ITERATOR iterator, final JDK_PRIMITIVE_PREDICATE predicate) {
#else
	public static KEY_GENERIC boolean any(final KEY_ITERATOR KEY_GENERIC iterator, final java.util.function.Predicate<? super KEY_GENERIC_CLASS> predicate) {
#endif
		return indexOf(iterator, predicate) != -1;
	}

#ifdef JDK_PRIMITIVE_PREDICATE
	public static boolean all(final KEY_ITERATOR iterator, final JDK_PRIMITIVE_PREDICATE predicate) {
#else
	public static KEY_GENERIC boolean all(final KEY_ITERATOR KEY_GENERIC iterator, final java.util.function.Predicate<? super KEY_GENERIC_CLASS> predicate) {
#endif
		Objects.requireNonNull(predicate);

		do {
			if (!iterator.hasNext()) return true;
#if KEY_CLASS_Boolean
		} while (predicate.test(Boolean.valueOf(iterator.nextBoolean())));
#else
		} while (predicate.test(iterator.NEXT_KEY()));
#endif
		return false;
	}

#ifdef JDK_PRIMITIVE_PREDICATE
	public static int indexOf(final KEY_ITERATOR iterator, final JDK_PRIMITIVE_PREDICATE predicate) {
#else
	public static KEY_GENERIC int indexOf(final KEY_ITERATOR KEY_GENERIC iterator, final java.util.function.Predicate<? super KEY_GENERIC_CLASS> predicate) {
#endif
		Objects.requireNonNull(predicate);

		for (int i = 0; iterator.hasNext(); ++i) {
#if KEY_CLASS_Boolean
			if (predicate.test(Boolean.valueOf(iterator.nextBoolean()))) return i;
#else
			if (predicate.test(iterator.NEXT_KEY())) return i;
#endif
		}

		return -1;
	}

#if KEY_CLASS_Integer || KEY_CLASS_Byte || KEY_CLASS_Short || KEY_CLASS_Character || KEY_CLASS_Long

#if KEY_CLASS_Long
	private static class IntervalIterator implements KEY_BIDI_ITERATOR {
#else
	private static class IntervalIterator implements KEY_LIST_ITERATOR {
#endif
		private final KEY_TYPE from, to;
		KEY_TYPE curr;

		public IntervalIterator(final KEY_TYPE from, final KEY_TYPE to) {
			this.from = this.curr = from;
			this.to = to;
		}

		@Override
		public boolean hasNext() { return curr < to; }

		@Override
		public boolean hasPrevious() { return curr > from; }

		@Override
		public KEY_TYPE NEXT_KEY() {
			if (! hasNext()) throw new NoSuchElementException();
			return curr++;
		}

		@Override
		public KEY_TYPE PREV_KEY() {
			if (! hasPrevious()) throw new NoSuchElementException();
			return --curr;
		}

#if ! KEY_CLASS_Long
		@Override
		public int nextIndex() { return curr - from; }

		@Override
		public int previousIndex() { return curr - from - 1; }
#endif

		@Override
		public int skip(int n) {
			if (curr + n <= to) {
				curr += n;
				return n;
			}
#if ! KEY_CLASS_Long
			n = to - curr;
#else
			n = (int)(to - curr);
#endif
			curr = to;
			return n;
		}

		@Override
		public int back(int n) {
			if (curr - n >= from) {
				curr -= n;
				return n;
			}
#if ! KEY_CLASS_Long
			n = curr - from ;
#else
			n = (int)(curr - from);
#endif
			curr = from;
			return n;
		}
	}

#if KEY_CLASS_Long
	/** Creates a type-specific bidirectional iterator over an interval.
	 *
	 * <p>The type-specific bidirectional iterator returned by this method will return the
	 * elements {@code from}, {@code from+1},&hellip;, {@code to-1}.
	 *
	 * <p>Note that all other type-specific interval iterator are <em>list</em>
	 * iterators. Of course, this is not possible with longs as the index
	 * returned by {@link java.util.ListIterator#nextIndex() nextIndex()}/{@link
	 * java.util.ListIterator#previousIndex() previousIndex()} would exceed an integer.
	 *
	 * @param from the starting element (inclusive).
	 * @param to the ending element (exclusive).
	 * @return a type-specific bidirectional iterator enumerating the elements from {@code from} to {@code to}.
	 */
	public static KEY_BIDI_ITERATOR fromTo(final KEY_TYPE from, final KEY_TYPE to) {
		return new IntervalIterator(from, to);
	}
#else

	/** Creates a type-specific list iterator over an interval.
	 *
	 * <p>The type-specific list iterator returned by this method will return the
	 * elements {@code from}, {@code from+1},&hellip;, {@code to-1}.
	 *
	 * @param from the starting element (inclusive).
	 * @param to the ending element (exclusive).
	 * @return a type-specific list iterator enumerating the elements from {@code from} to {@code to}.
	 */
	public static KEY_LIST_ITERATOR fromTo(final KEY_TYPE from, final KEY_TYPE to) {
		return new IntervalIterator(from, to);
	}

#endif

#endif

	private static class IteratorConcatenator KEY_GENERIC implements KEY_ITERATOR KEY_GENERIC {
		final KEY_ITERATOR KEY_EXTENDS_GENERIC a[];
		int offset, length, lastOffset = -1;

		public IteratorConcatenator(final KEY_ITERATOR KEY_EXTENDS_GENERIC a[], int offset, int length) {
			this.a = a;
			this.offset = offset;
			this.length = length;
			advance();
		}

		private void advance() {
			while(length != 0) {
				if (a[offset].hasNext()) break;
				length--;
				offset++;
			}

			return;
		}

		@Override
		public boolean hasNext() {
			return length > 0;
		}

		@Override
		public KEY_GENERIC_TYPE NEXT_KEY() {
			if (! hasNext()) throw new NoSuchElementException();
			KEY_GENERIC_TYPE next = a[lastOffset = offset].NEXT_KEY();
			advance();
			return next;
		}

		@Override
		public void remove() {
			if (lastOffset == -1) throw new IllegalStateException();
			a[lastOffset].remove();
		}

		@Override
		public int skip(int n) {
			lastOffset = -1;

			int skipped = 0;

			while(skipped < n && length != 0) {
				skipped += a[offset].skip(n - skipped);
				if (a[offset].hasNext()) break;
				length--;
				offset++;
			}

			return skipped;
		}
	}


	/** Concatenates all iterators contained in an array.
	 *
	 * <p>This method returns an iterator that will enumerate in order the elements returned
	 * by all iterators contained in the given array.
	 *
	 * @param a an array of iterators.
	 * @return an iterator obtained by concatenation.
	 */

	public static KEY_GENERIC KEY_ITERATOR KEY_GENERIC concat(final KEY_ITERATOR KEY_EXTENDS_GENERIC a[]) {
		return concat(a, 0, a.length);
	}


	/** Concatenates a sequence of iterators contained in an array.
	 *
	 * <p>This method returns an iterator that will enumerate in order the elements returned
	 * by {@code a[offset]}, then those returned
	 * by {@code a[offset + 1]}, and so on up to
	 * {@code a[offset + length - 1]}.
	 *
	 * @param a an array of iterators.
	 * @param offset the index of the first iterator to concatenate.
	 * @param length the number of iterators to concatenate.
	 * @return an iterator obtained by concatenation of {@code length} elements of {@code a} starting at {@code offset}.
	 */

	public static KEY_GENERIC KEY_ITERATOR KEY_GENERIC concat(final KEY_ITERATOR KEY_EXTENDS_GENERIC a[], final int offset, final int length) {
		return new IteratorConcatenator KEY_GENERIC_DIAMOND(a, offset, length);
	}


  	/** An unmodifiable wrapper class for iterators. */


	public static class UnmodifiableIterator KEY_GENERIC implements KEY_ITERATOR KEY_GENERIC {
		protected final KEY_ITERATOR KEY_GENERIC i;

		public UnmodifiableIterator(final KEY_ITERATOR KEY_GENERIC i) {
			this.i = i;
		}

		@Override
		public boolean hasNext() { return i.hasNext(); }

		@Override
		public KEY_GENERIC_TYPE NEXT_KEY() { return i.NEXT_KEY(); }
	}


	/** Returns an unmodifiable iterator backed by the specified iterator.
	 *
	 * @param i the iterator to be wrapped in an unmodifiable iterator.
	 * @return an unmodifiable view of the specified iterator.
	 */
	public static KEY_GENERIC KEY_ITERATOR KEY_GENERIC unmodifiable(final KEY_ITERATOR KEY_GENERIC i) { return new UnmodifiableIterator KEY_GENERIC_DIAMOND(i); }



  	/** An unmodifiable wrapper class for bidirectional iterators. */

	public static class UnmodifiableBidirectionalIterator KEY_GENERIC implements KEY_BIDI_ITERATOR KEY_GENERIC {
		protected final KEY_BIDI_ITERATOR KEY_GENERIC i;

		public UnmodifiableBidirectionalIterator(final KEY_BIDI_ITERATOR KEY_GENERIC i) {
			this.i = i;
		}

		@Override
		public boolean hasNext() { return i.hasNext(); }

		@Override
		public boolean hasPrevious() { return i.hasPrevious(); }

		@Override
		public KEY_GENERIC_TYPE NEXT_KEY() { return i.NEXT_KEY(); }

		@Override
		public KEY_GENERIC_TYPE PREV_KEY() { return i.PREV_KEY(); }
	}


	/** Returns an unmodifiable bidirectional iterator backed by the specified bidirectional iterator.
	 *
	 * @param i the bidirectional iterator to be wrapped in an unmodifiable bidirectional iterator.
	 * @return an unmodifiable view of the specified bidirectional iterator.
	 */
	public static KEY_GENERIC KEY_BIDI_ITERATOR KEY_GENERIC unmodifiable(final KEY_BIDI_ITERATOR KEY_GENERIC i) { return new UnmodifiableBidirectionalIterator KEY_GENERIC_DIAMOND(i); }


  	/** An unmodifiable wrapper class for list iterators. */

	public static class UnmodifiableListIterator KEY_GENERIC implements KEY_LIST_ITERATOR KEY_GENERIC {
		protected final KEY_LIST_ITERATOR KEY_GENERIC i;

		public UnmodifiableListIterator(final KEY_LIST_ITERATOR KEY_GENERIC i) {
			this.i = i;
		}

		@Override
		public boolean hasNext() { return i.hasNext(); }

		@Override
		public boolean hasPrevious() { return i.hasPrevious(); }

		@Override
		public KEY_GENERIC_TYPE NEXT_KEY() { return i.NEXT_KEY(); }

		@Override
		public KEY_GENERIC_TYPE PREV_KEY() { return i.PREV_KEY(); }

		@Override
		public int nextIndex() { return i.nextIndex(); }

		@Override
		public int previousIndex() { return i.previousIndex(); }
	}

	/** Returns an unmodifiable list iterator backed by the specified list iterator.
	 *
	 * @param i the list iterator to be wrapped in an unmodifiable list iterator.
	 * @return an unmodifiable view of the specified list iterator.
	 */
	public static KEY_GENERIC KEY_LIST_ITERATOR KEY_GENERIC unmodifiable(final KEY_LIST_ITERATOR KEY_GENERIC i) { return new UnmodifiableListIterator KEY_GENERIC_DIAMOND(i); }

#if SMALL_TYPES && (KEY_CLASS_Short || KEY_CLASS_Integer || KEY_CLASS_Long || KEY_CLASS_Float || KEY_CLASS_Double)

  	/** A wrapper promoting the results of a ByteIterator. */

	protected static class ByteIteratorWrapper implements KEY_ITERATOR {
		final it.unimi.dsi.fastutil.bytes.ByteIterator iterator;

		public ByteIteratorWrapper(final it.unimi.dsi.fastutil.bytes.ByteIterator iterator) {
			this.iterator = iterator;
		}

		@Override
		public boolean hasNext() { return iterator.hasNext(); }

		@Deprecated
		@Override
		public KEY_GENERIC_CLASS next() { return KEY_GENERIC_CLASS.valueOf(iterator.nextByte()); }

		@Override
		public KEY_TYPE NEXT_KEY() { return iterator.nextByte(); }

		@Override
		public void remove() { iterator.remove(); }

		@Override
		public int skip(final int n) { return iterator.skip(n); }
	}

	/** Returns an iterator backed by the specified byte iterator.
	 * @param iterator a byte iterator.
	 * @return an iterator backed by the specified byte iterator.
	 */
	public static KEY_ITERATOR wrap(final it.unimi.dsi.fastutil.bytes.ByteIterator iterator) {
		return new ByteIteratorWrapper(iterator);
	}
#endif

#if SMALL_TYPES && (KEY_CLASS_Integer || KEY_CLASS_Long || KEY_CLASS_Float || KEY_CLASS_Double)

	/** A wrapper promoting the results of a ShortIterator. */

	protected static class ShortIteratorWrapper implements KEY_ITERATOR {
		final it.unimi.dsi.fastutil.shorts.ShortIterator iterator;

		public ShortIteratorWrapper(final it.unimi.dsi.fastutil.shorts.ShortIterator iterator) {
			this.iterator = iterator;
		}

		@Override
		public boolean hasNext() { return iterator.hasNext(); }

		@Deprecated
		@Override
		public KEY_GENERIC_CLASS next() { return KEY_GENERIC_CLASS.valueOf(iterator.nextShort()); }

		@Override
		public KEY_TYPE NEXT_KEY() { return iterator.nextShort(); }

		@Override
		public void remove() { iterator.remove(); }

		@Override
		public int skip(final int n) { return iterator.skip(n); }
	}

	/** Returns an iterator backed by the specified short iterator.
	 * @param iterator a short iterator.
	 * @return an iterator backed by the specified short iterator.
	 */
	public static KEY_ITERATOR wrap(final it.unimi.dsi.fastutil.shorts.ShortIterator iterator) {
		return new ShortIteratorWrapper(iterator);
	}

#endif

#if KEY_CLASS_Long || KEY_CLASS_Double

  	/** A wrapper promoting the results of an IntIterator. */

	protected static class IntIteratorWrapper implements KEY_ITERATOR {
		final it.unimi.dsi.fastutil.ints.IntIterator iterator;

		public IntIteratorWrapper(final it.unimi.dsi.fastutil.ints.IntIterator iterator) {
			this.iterator = iterator;
		}

		@Override
		public boolean hasNext() { return iterator.hasNext(); }

		@Deprecated
		@Override
		public KEY_GENERIC_CLASS next() { return KEY_GENERIC_CLASS.valueOf(iterator.nextInt()); }

		@Override
		public KEY_TYPE NEXT_KEY() { return iterator.nextInt(); }

		@Override
		public void remove() { iterator.remove(); }

		@Override
		public int skip(final int n) { return iterator.skip(n); }
	}

	/** Returns an iterator backed by the specified integer iterator.
	 * @param iterator an integer iterator.
	 * @return an iterator backed by the specified integer iterator.
	 */

	public static KEY_ITERATOR wrap(final it.unimi.dsi.fastutil.ints.IntIterator iterator) {
		return new IntIteratorWrapper(iterator);
	}

#endif

#if SMALL_TYPES && KEY_CLASS_Double

  	/** A wrapper promoting the results of a FloatIterator. */

	protected static class FloatIteratorWrapper implements KEY_ITERATOR {
		final it.unimi.dsi.fastutil.floats.FloatIterator iterator;

		public FloatIteratorWrapper(final it.unimi.dsi.fastutil.floats.FloatIterator iterator) {
			this.iterator = iterator;
		}

		@Override
		public boolean hasNext() { return iterator.hasNext(); }

		@Deprecated
		@Override
		public KEY_GENERIC_CLASS next() { return KEY_GENERIC_CLASS.valueOf(iterator.nextFloat()); }

		@Override
		public KEY_TYPE NEXT_KEY() { return iterator.nextFloat(); }

		@Override
		public void remove() { iterator.remove(); }

		@Override
		public int skip(final int n) { return iterator.skip(n); }
	}

	/** Returns an iterator backed by the specified float iterator.
	 * @param iterator a float iterator.
	 * @return an iterator backed by the specified float iterator.
	 */
	public static KEY_ITERATOR wrap(final it.unimi.dsi.fastutil.floats.FloatIterator iterator) {
		return new FloatIteratorWrapper(iterator);
	}
#endif
}
