scala.collection.immutable.VectorIterator

class VectorIterator[+A] extends AbstractIterator[A] with Iterator[A] with VectorPointer[A]

Type Members

class GroupedIterator[B >: A] extends AbstractIterator[Seq[B]] with Iterator[Seq[B]]

A flexible iterator for transforming an Iterator[A] into an Iterator[Seq[A]], with configurable sequence size, step, and strategy for dealing with elements which don’t fit evenly.

Typical uses can be achieved via methods grouped and sliding .

  • Definition Classes
    • Iterator

Value Members From scala.collection.Iterator

def ++[B >: A](that: ⇒ GenTraversableOnce[B]): Iterator[B]

[use case]

Concatenates this iterator with another.

  • that
    • the other iterator
  • returns
    • a new iterator that first yields the values produced by this iterator followed by the values produced by iterator that .
  • Definition Classes
    • Iterator

(defined at scala.collection.Iterator)

def buffered: BufferedIterator[A]

Creates a buffered iterator from this iterator.

  • returns
    • a buffered iterator producing the same values as this iterator.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.
  • See also
    • scala.collection.BufferedIterator

(defined at scala.collection.Iterator)

def collect[B](pf: PartialFunction[A, B]): Iterator[B]

Creates an iterator by transforming values produced by this iterator with a partial function, dropping those values for which the partial function is not defined.

  • pf
    • the partial function which filters and maps the iterator.
  • returns
    • a new iterator which yields each value x produced by this iterator for which pf is defined the image pf(x) .
  • Definition Classes
    • Iterator
  • Annotations
    • @migration
  • Migration
    • (Changed in version 2.8.0) collect has changed. The previous behavior can be reproduced with toSeq .
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def contains(elem: Any): Boolean

Tests whether this iterator contains a given value as an element.

Note: may not terminate for infinite iterators.

  • elem
    • the element to test.
  • returns
    • true if this iterator produces some value that is is equal (as determined by == ) to elem , false otherwise.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def copyToArray[B >: A](xs: Array[B], start: Int, len: Int): Unit

[use case]

Copies selected values produced by this iterator to an array. Fills the given array xs starting at index start with at most len values produced by this iterator. Copying will stop once either the end of the current iterator is reached, or the end of the array is reached, or len elements have been copied.

Note: will not terminate for infinite iterators.

  • xs
    • the array to fill.
  • start
    • the starting index.
  • len
    • the maximal number of elements to copy.
  • Definition Classes
    • Iterator → TraversableOnce → GenTraversableOnce

(defined at scala.collection.Iterator)

def corresponds[B](that: GenTraversableOnce[B])(p: (A, B) ⇒ Boolean): Boolean

Tests whether every element of this iterator relates to the corresponding element of another collection by satisfying a test predicate.

  • B
    • the type of the elements of that
  • that
    • the other collection
  • p
    • the test predicate, which relates elements from both collections
  • returns
    • true if both collections have the same length and p(x, y) is true for all corresponding elements x of this iterator and y of that , otherwise false
  • Definition Classes
    • Iterator

(defined at scala.collection.Iterator)

def drop(n: Int): Iterator[A]

Advances this iterator past the first n elements, or the length of the iterator, whichever is smaller.

  • n
    • the number of elements to drop
  • returns
    • an iterator which produces all values of the current iterator, except it omits the first n values.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def dropWhile(p: (A) ⇒ Boolean): Iterator[A]

Skips longest sequence of elements of this iterator which satisfy given predicate p , and returns an iterator of the remaining elements.

  • p
    • the predicate used to skip elements.
  • returns
    • an iterator consisting of the remaining elements
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def exists(p: (A) ⇒ Boolean): Boolean

Tests whether a predicate holds for some of the values produced by this iterator.

Note: may not terminate for infinite iterators.

  • p
    • the predicate used to test elements.
  • returns
    • true if the given predicate p holds for some of the values produced by this iterator, otherwise false .
  • Definition Classes
    • Iterator → TraversableOnce → GenTraversableOnce
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def filter(p: (A) ⇒ Boolean): Iterator[A]

Returns an iterator over all the elements of this iterator that satisfy the predicate p . The order of the elements is preserved.

  • p
    • the predicate used to test values.
  • returns
    • an iterator which produces those values of this iterator which satisfy the predicate p .
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def filterNot(p: (A) ⇒ Boolean): Iterator[A]

Creates an iterator over all the elements of this iterator which do not satisfy a predicate p.

  • p
    • the predicate used to test values.
  • returns
    • an iterator which produces those values of this iterator which do not satisfy the predicate p .
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def find(p: (A) ⇒ Boolean): Option[A]

Finds the first value produced by the iterator satisfying a predicate, if any.

Note: may not terminate for infinite iterators.

  • p
    • the predicate used to test values.
  • returns
    • an option value containing the first value produced by the iterator that satisfies predicate p , or None if none exists.
  • Definition Classes
    • Iterator → TraversableOnce → GenTraversableOnce
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def flatMap[B](f: (A) ⇒ GenTraversableOnce[B]): Iterator[B]

Creates a new iterator by applying a function to all values produced by this iterator and concatenating the results.

  • f
    • the function to apply on each element.
  • returns
    • the iterator resulting from applying the given iterator-valued function f to each value produced by this iterator and concatenating the results.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def forall(p: (A) ⇒ Boolean): Boolean

Tests whether a predicate holds for all values produced by this iterator.

Note: may not terminate for infinite iterators.

  • p
    • the predicate used to test elements.
  • returns
    • true if the given predicate p holds for all values produced by this iterator, otherwise false .
  • Definition Classes
    • Iterator → TraversableOnce → GenTraversableOnce
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def foreach[U](f: (A) ⇒ U): Unit

[use case]

Applies a function f to all values produced by this iterator.

  • f
    • the function that is applied for its side-effect to every element. The result of function f is discarded.
  • Definition Classes
    • Iterator → TraversableOnce → GenTraversableOnce

(defined at scala.collection.Iterator)

def grouped[B >: A](size: Int): GroupedIterator[B]

Returns an iterator which groups this iterator into fixed size blocks. Example usages:

// Returns List(List(1, 2, 3), List(4, 5, 6), List(7)))
(1 to 7).iterator grouped 3 toList
// Returns List(List(1, 2, 3), List(4, 5, 6))
(1 to 7).iterator grouped 3 withPartial false toList
// Returns List(List(1, 2, 3), List(4, 5, 6), List(7, 20, 25)
// Illustrating that withPadding's argument is by-name.
val it2 = Iterator.iterate(20)(_ + 5)
(1 to 7).iterator grouped 3 withPadding it2.next toList
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def indexOf[B >: A](elem: B): Int

Returns the index of the first occurrence of the specified object in this iterable object.

Note: may not terminate for infinite iterators.

  • elem
    • element to search for.
  • returns
    • the index of the first occurrence of elem in the values produced by this iterator, or -1 if such an element does not exist until the end of the iterator is reached.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def indexOf[B >: A](elem: B, from: Int): Int

Returns the index of the first occurrence of the specified object in this iterable object after or at some start index.

Note: may not terminate for infinite iterators.

  • elem
    • element to search for.
  • from
    • the start index
  • returns
    • the index >= from of the first occurrence of elem in the values produced by this iterator, or -1 if such an element does not exist until the end of the iterator is reached.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def indexWhere(p: (A) ⇒ Boolean): Int

Returns the index of the first produced value satisfying a predicate, or -1.

Note: may not terminate for infinite iterators.

  • p
    • the predicate to test values
  • returns
    • the index of the first produced value satisfying p , or -1 if such an element does not exist until the end of the iterator is reached.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def indexWhere(p: (A) ⇒ Boolean, from: Int): Int

Returns the index of the first produced value satisfying a predicate, or -1, after or at some start index.

Note: may not terminate for infinite iterators.

  • p
    • the predicate to test values
  • from
    • the start index
  • returns
    • the index >= from of the first produced value satisfying p , or -1 if such an element does not exist until the end of the iterator is reached.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def map[B](f: (A) ⇒ B): Iterator[B]

Creates a new iterator that maps all produced values of this iterator to new values using a transformation function.

  • f
    • the transformation function
  • returns
    • a new iterator which transforms every value produced by this iterator by applying the function f to it.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def padTo[A1 >: A](len: Int, elem: A1): Iterator[A1]

[use case]

Appends an element value to this iterator until a given target length is reached.

  • len
    • the target length
  • elem
    • the padding value
  • returns
    • a new iterator consisting of producing all values of this iterator, followed by the minimal number of occurrences of elem so that the number of produced values is at least len .
  • Definition Classes
    • Iterator

(defined at scala.collection.Iterator)

def partition(p: (A) ⇒ Boolean): (Iterator[A], Iterator[A])

Partitions this iterator in two iterators according to a predicate.

  • p
    • the predicate on which to partition
  • returns
    • a pair of iterators: the iterator that satisfies the predicate p and the iterator that does not. The relative order of the elements in the resulting iterators is the same as in the original iterator.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterators that were returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterators as well.

(defined at scala.collection.Iterator)

def patch[B >: A](from: Int, patchElems: Iterator[B], replaced: Int): Iterator[B]

Returns this iterator with patched values. Patching at negative indices is the same as patching starting at 0. Patching at indices at or larger than the length of the original iterator appends the patch to the end. If more values are replaced than actually exist, the excess is ignored.

  • from
    • The start index from which to patch
  • patchElems
    • The iterator of patch values
  • replaced
    • The number of values in the original iterator that are replaced by the patch.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, as well as the one passed as a parameter, and use only the iterator that was returned. Using the old iterators is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def sameElements(that: Iterator[_]): Boolean

Tests if another iterator produces the same values as this one.

Note: will not terminate for infinite iterators.

  • that
    • the other iterator
  • returns
    • true , if both iterators produce the same elements in the same order, false otherwise.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, as well as the one passed as parameter. Using the old iterators is undefined and subject to change.

(defined at scala.collection.Iterator)

def scanLeft[B](z: B)(op: (B, A) ⇒ B): Iterator[B]

Produces a collection containing cumulative results of applying the operator going left to right.

Note: will not terminate for infinite iterators.

Note: might return different results for different runs, unless the underlying collection type is ordered.

  • B
    • the type of the elements in the resulting collection
  • z
    • the initial value
  • op
    • the binary operator applied to the intermediate result and the element
  • returns
    • iterator with intermediate results
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def scanRight[B](z: B)(op: (A, B) ⇒ B): Iterator[B]

Produces a collection containing cumulative results of applying the operator going right to left. The head of the collection is the last cumulative result.

Note: will not terminate for infinite iterators.

Note: might return different results for different runs, unless the underlying collection type is ordered.

  • B
    • the type of the elements in the resulting collection
  • z
    • the initial value
  • op
    • the binary operator applied to the intermediate result and the element
  • returns
    • iterator with intermediate results
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

Example:

Iterator(1, 2, 3, 4).scanRight(0)(_ + _).toList == List(10, 9, 7, 4, 0)

(defined at scala.collection.Iterator)

def slice(from: Int, until: Int): Iterator[A]

Creates an iterator returning an interval of the values produced by this iterator.

  • from
    • the index of the first element in this iterator which forms part of the slice. If negative, the slice starts at zero.
  • until
    • the index of the first element following the slice. If negative, the slice is empty.
  • returns
    • an iterator which advances this iterator past the first from elements using drop , and then takes until - from elements, using take .
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def sliceIterator(from: Int, until: Int): Iterator[A]

Creates an optionally bounded slice, unbounded if until is negative.

  • Attributes
    • protected
  • Definition Classes
    • Iterator

(defined at scala.collection.Iterator)

def sliding[B >: A](size: Int, step: Int = 1): GroupedIterator[B]

Returns an iterator which presents a “sliding window” view of another iterator. The first argument is the window size, and the second is how far to advance the window on each iteration; defaults to 1 . Example usages:

// Returns List(List(1, 2, 3), List(2, 3, 4), List(3, 4, 5))
(1 to 5).iterator.sliding(3).toList
// Returns List(List(1, 2, 3, 4), List(4, 5))
(1 to 5).iterator.sliding(4, 3).toList
// Returns List(List(1, 2, 3, 4))
(1 to 5).iterator.sliding(4, 3).withPartial(false).toList
// Returns List(List(1, 2, 3, 4), List(4, 5, 20, 25))
// Illustrating that withPadding's argument is by-name.
val it2 = Iterator.iterate(20)(_ + 5)
(1 to 5).iterator.sliding(4, 3).withPadding(it2.next).toList
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def span(p: (A) ⇒ Boolean): (Iterator[A], Iterator[A])

Splits this Iterator into a prefix/suffix pair according to a predicate.

  • p
    • the test predicate
  • returns
    • a pair of Iterators consisting of the longest prefix of this whose elements all satisfy p , and the rest of the Iterator.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterators that were returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterators as well.

(defined at scala.collection.Iterator)

def take(n: Int): Iterator[A]

Selects first n values of this iterator.

  • n
    • the number of values to take
  • returns
    • an iterator producing only the first n values of this iterator, or else the whole iterator, if it produces fewer than n values.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def takeWhile(p: (A) ⇒ Boolean): Iterator[A]

Takes longest prefix of values produced by this iterator that satisfy a predicate.

  • p
    • The predicate used to test elements.
  • returns
    • An iterator returning the values produced by this iterator, until this iterator produces a value that does not satisfy the predicate p .
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def toStream: Stream[A]

Converts this traversable or iterator to a stream.

  • returns
    • a stream containing all elements of this traversable or iterator.
  • Definition Classes
    • Iterator → GenTraversableOnce

(defined at scala.collection.Iterator)

def toTraversable: collection.Traversable[A]

Converts this traversable or iterator to an unspecified Traversable. Will return the same collection if this instance is already Traversable.

Note: will not terminate for infinite iterators.

  • returns
    • a Traversable containing all elements of this traversable or iterator.
  • Definition Classes
    • Iterator → TraversableOnce → GenTraversableOnce

(defined at scala.collection.Iterator)

def withFilter(p: (A) ⇒ Boolean): Iterator[A]

Creates an iterator over all the elements of this iterator that satisfy the predicate p . The order of the elements is preserved.

Note: withFilter is the same as filter on iterators. It exists so that for-expressions with filters work over iterators.

  • p
    • the predicate used to test values.
  • returns
    • an iterator which produces those values of this iterator which satisfy the predicate p .
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def zipAll[B, A1 >: A, B1 >: B](that: Iterator[B], thisElem: A1, thatElem: B1): Iterator[(A1, B1)]

[use case]

Creates an iterator formed from this iterator and another iterator by combining corresponding elements in pairs. If one of the two iterators is shorter than the other, placeholder elements are used to extend the shorter iterator to the length of the longer.

  • that
    • iterator that may have a different length as the self iterator.
  • thisElem
    • element thisElem is used to fill up the resulting iterator if the self iterator is shorter than that
  • thatElem
    • element thatElem is used to fill up the resulting iterator if that is shorter than the self iterator
  • returns
    • a new iterator containing pairs consisting of corresponding values of this iterator and that . The length of the returned iterator is the maximum of the lengths of this iterator and that . If this iterator is shorter than that , thisElem values are used to pad the result. If that is shorter than this iterator, thatElem values are used to pad the result.
  • Definition Classes
    • Iterator

(defined at scala.collection.Iterator)

def zip[B](that: Iterator[B]): Iterator[(A, B)]

Creates an iterator formed from this iterator and another iterator by combining corresponding values in pairs. If one of the two iterators is longer than the other, its remaining elements are ignored.

  • that
    • The iterator providing the second half of each result pair
  • returns
    • a new iterator containing pairs consisting of corresponding elements of this iterator and that . The number of elements returned by the new iterator is the minimum of the number of elements returned by this iterator and that .
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, as well as the one passed as a parameter, and use only the iterator that was returned. Using the old iterators is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

Value Members From scala.collection.TraversableOnce

def /:[B](z: B)(op: (B, A) ⇒ B): B

Applies a binary operator to a start value and all elements of this traversable or iterator, going left to right.

Note: /: is alternate syntax for foldLeft ; z /: xs is the same as xs foldLeft z .

Examples:

Note that the folding function used to compute b is equivalent to that used to compute c.

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = (5 /: a)(_+_)
b: Int = 15

scala> val c = (5 /: a)((x,y) => x + y)
c: Int = 15

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • z
    • the start value.
  • op
    • the binary operator.
  • returns
    • the result of inserting op between consecutive elements of this traversable or iterator, going left to right with the start value z on the left:
    op(...op(op(z, x_1), x_2), ..., x_n)
    
where `x1, ..., xn` are the elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def :\[B](z: B)(op: (A, B) ⇒ B): B

Applies a binary operator to all elements of this traversable or iterator and a start value, going right to left.

Note: :\ is alternate syntax for foldRight ; xs :\ z is the same as xs foldRight z .

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

Examples:

Note that the folding function used to compute b is equivalent to that used to compute c.

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = (a :\ 5)(_+_)
b: Int = 15

scala> val c = (a :\ 5)((x,y) => x + y)
c: Int = 15
  • B
    • the result type of the binary operator.
  • z
    • the start value
  • op
    • the binary operator
  • returns
    • the result of inserting op between consecutive elements of this traversable or iterator, going right to left with the start value z on the right:
    op(x_1, op(x_2, ... op(x_n, z)...))
    
where `x1, ..., xn` are the elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def addString(b: StringBuilder): StringBuilder

Appends all elements of this traversable or iterator to a string builder. The written text consists of the string representations (w.r.t. the method toString ) of all elements of this traversable or iterator without any separator string.

Example:

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = new StringBuilder()
b: StringBuilder =

scala> val h = a.addString(b)
h: StringBuilder = 1234
  • b
    • the string builder to which elements are appended.
  • returns
    • the string builder b to which elements were appended.
  • Definition Classes
    • TraversableOnce

(defined at scala.collection.TraversableOnce)

def addString(b: StringBuilder, sep: String): StringBuilder

Appends all elements of this traversable or iterator to a string builder using a separator string. The written text consists of the string representations (w.r.t. the method toString ) of all elements of this traversable or iterator, separated by the string sep .

Example:

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = new StringBuilder()
b: StringBuilder =

scala> a.addString(b, ", ")
res0: StringBuilder = 1, 2, 3, 4
  • b
    • the string builder to which elements are appended.
  • sep
    • the separator string.
  • returns
    • the string builder b to which elements were appended.
  • Definition Classes
    • TraversableOnce

(defined at scala.collection.TraversableOnce)

def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder

Appends all elements of this traversable or iterator to a string builder using start, end, and separator strings. The written text begins with the string start and ends with the string end . Inside, the string representations (w.r.t. the method toString ) of all elements of this traversable or iterator are separated by the string sep .

Example:

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = new StringBuilder()
b: StringBuilder =

scala> a.addString(b , "List(" , ", " , ")")
res5: StringBuilder = List(1, 2, 3, 4)
  • b
    • the string builder to which elements are appended.
  • start
    • the starting string.
  • sep
    • the separator string.
  • end
    • the ending string.
  • returns
    • the string builder b to which elements were appended.
  • Definition Classes
    • TraversableOnce

(defined at scala.collection.TraversableOnce)

def aggregate[B](z: ⇒ B)(seqop: (B, A) ⇒ B, combop: (B, B) ⇒ B): B

Aggregates the results of applying an operator to subsequent elements.

This is a more general form of fold and reduce . It is similar to foldLeft in that it doesn’t require the result to be a supertype of the element type. In addition, it allows parallel collections to be processed in chunks, and then combines the intermediate results.

aggregate splits the traversable or iterator into partitions and processes each partition by sequentially applying seqop , starting with z (like foldLeft ). Those intermediate results are then combined by using combop (like fold ). The implementation of this operation may operate on an arbitrary number of collection partitions (even 1), so combop may be invoked an arbitrary number of times (even 0).

As an example, consider summing up the integer values of a list of chars. The initial value for the sum is 0. First, seqop transforms each input character to an Int and adds it to the sum (of the partition). Then, combop just needs to sum up the intermediate results of the partitions:

List('a', 'b', 'c').aggregate(0)({ (sum, ch) => sum + ch.toInt }, { (p1, p2) => p1 + p2 })
  • B
    • the type of accumulated results
  • z
    • the initial value for the accumulated result of the partition - this will typically be the neutral element for the seqop operator (e.g. Nil for list concatenation or 0 for summation) and may be evaluated more than once
  • seqop
    • an operator used to accumulate results within a partition
  • combop
    • an associative operator used to combine results from different partitions
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def collectFirst[B](pf: PartialFunction[A, B]): Option[B]

Finds the first element of the traversable or iterator for which the given partial function is defined, and applies the partial function to it.

Note: may not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered.

  • pf
    • the partial function
  • returns
    • an option value containing pf applied to the first value for which it is defined, or None if none exists.
  • Definition Classes
    • TraversableOnce

Example:

Seq("a", 1, 5L).collectFirst({ case x: Int => x*10 }) = Some(10)

(defined at scala.collection.TraversableOnce)

def copyToArray[B >: A](xs: Array[B]): Unit

[use case]

Copies the elements of this traversable or iterator to an array. Fills the given array xs with values of this traversable or iterator. Copying will stop once either the end of the current traversable or iterator is reached, or the end of the target array is reached.

Note: will not terminate for infinite iterators.

  • xs
    • the array to fill.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def copyToArray[B >: A](xs: Array[B], start: Int): Unit

[use case]

Copies the elements of this traversable or iterator to an array. Fills the given array xs with values of this traversable or iterator, beginning at index start . Copying will stop once either the end of the current traversable or iterator is reached, or the end of the target array is reached.

Note: will not terminate for infinite iterators.

  • xs
    • the array to fill.
  • start
    • the starting index.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def copyToBuffer[B >: A](dest: Buffer[B]): Unit

Copies all elements of this traversable or iterator to a buffer.

Note: will not terminate for infinite-sized collections.

  • dest
    • The buffer to which elements are copied.
  • Definition Classes
    • TraversableOnce

(defined at scala.collection.TraversableOnce)

def count(p: (A) ⇒ Boolean): Int

Counts the number of elements in the traversable or iterator which satisfy a predicate.

  • p
    • the predicate used to test elements.
  • returns
    • the number of elements satisfying the predicate p .
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def foldLeft[B](z: B)(op: (B, A) ⇒ B): B

Applies a binary operator to a start value and all elements of this traversable or iterator, going left to right.

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • z
    • the start value.
  • op
    • the binary operator.
  • returns
    • the result of inserting op between consecutive elements of this traversable or iterator, going left to right with the start value z on the left:
    op(...op(z, x_1), x_2, ..., x_n)
    
where `x1, ..., xn` are the elements of this traversable or iterator.
Returns `z` if this traversable or iterator is empty.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def foldRight[B](z: B)(op: (A, B) ⇒ B): B

Applies a binary operator to all elements of this traversable or iterator and a start value, going right to left.

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • z
    • the start value.
  • op
    • the binary operator.
  • returns
    • the result of inserting op between consecutive elements of this traversable or iterator, going right to left with the start value z on the right:
    op(x_1, op(x_2, ... op(x_n, z)...))
    
where `x1, ..., xn` are the elements of this traversable or iterator.
Returns `z` if this traversable or iterator is empty.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1

Folds the elements of this traversable or iterator using the specified associative binary operator.

The order in which operations are performed on elements is unspecified and may be nondeterministic.

Note: will not terminate for infinite-sized collections.

  • A1
    • a type parameter for the binary operator, a supertype of A .
  • z
    • a neutral element for the fold operation; may be added to the result an arbitrary number of times, and must not change the result (e.g., Nil for list concatenation, 0 for addition, or 1 for multiplication).
  • op
    • a binary operator that must be associative.
  • returns
    • the result of applying the fold operator op between all the elements and z , or z if this traversable or iterator is empty.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def maxBy[B](f: (A) ⇒ B)(implicit cmp: Ordering[B]): A

[use case]

Finds the first element which yields the largest value measured by function f.

  • B
    • The result type of the function f.
  • f
    • The measuring function.
  • returns
    • the first element of this traversable or iterator with the largest value measured by function f.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def minBy[B](f: (A) ⇒ B)(implicit cmp: Ordering[B]): A

[use case]

Finds the first element which yields the smallest value measured by function f.

  • B
    • The result type of the function f.
  • f
    • The measuring function.
  • returns
    • the first element of this traversable or iterator with the smallest value measured by function f.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def mkString(sep: String): String

Displays all elements of this traversable or iterator in a string using a separator string.

  • sep
    • the separator string.
  • returns
    • a string representation of this traversable or iterator. In the resulting string the string representations (w.r.t. the method toString ) of all elements of this traversable or iterator are separated by the string sep .
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

Example:

List(1, 2, 3).mkString("|") = "1|2|3"

(defined at scala.collection.TraversableOnce)

def mkString(start: String, sep: String, end: String): String

Displays all elements of this traversable or iterator in a string using start, end, and separator strings.

  • start
    • the starting string.
  • sep
    • the separator string.
  • end
    • the ending string.
  • returns
    • a string representation of this traversable or iterator. The resulting string begins with the string start and ends with the string end . Inside, the string representations (w.r.t. the method toString ) of all elements of this traversable or iterator are separated by the string sep .
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

Example:

List(1, 2, 3).mkString("(", "; ", ")") = "(1; 2; 3)"

(defined at scala.collection.TraversableOnce)

def reduceLeftOption[B >: A](op: (B, A) ⇒ B): Option[B]

Optionally applies a binary operator to all elements of this traversable or iterator, going left to right.

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • op
    • the binary operator.
  • returns
    • an option value containing the result of reduceLeft(op) if this traversable or iterator is nonempty, None otherwise.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def reduceLeft[B >: A](op: (B, A) ⇒ B): B

Applies a binary operator to all elements of this traversable or iterator, going left to right.

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • op
    • the binary operator.
  • returns
    • the result of inserting op between consecutive elements of this traversable or iterator, going left to right:
    op( op( ... op(x_1, x_2) ..., x_{n-1}), x_n)
    
where `x1, ..., xn` are the elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce
  • Exceptions thrown
    • UnsupportedOperationException if this traversable or iterator is empty.

(defined at scala.collection.TraversableOnce)

def reduceOption[A1 >: A](op: (A1, A1) ⇒ A1): Option[A1]

Reduces the elements of this traversable or iterator, if any, using the specified associative binary operator.

The order in which operations are performed on elements is unspecified and may be nondeterministic.

  • A1
    • A type parameter for the binary operator, a supertype of A .
  • op
    • A binary operator that must be associative.
  • returns
    • An option value containing result of applying reduce operator op between all the elements if the collection is nonempty, and None otherwise.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def reduceRightOption[B >: A](op: (A, B) ⇒ B): Option[B]

Optionally applies a binary operator to all elements of this traversable or iterator, going right to left.

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • op
    • the binary operator.
  • returns
    • an option value containing the result of reduceRight(op) if this traversable or iterator is nonempty, None otherwise.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def reduceRight[B >: A](op: (A, B) ⇒ B): B

Applies a binary operator to all elements of this traversable or iterator, going right to left.

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • op
    • the binary operator.
  • returns
    • the result of inserting op between consecutive elements of this traversable or iterator, going right to left:
    op(x_1, op(x_2, ..., op(x_{n-1}, x_n)...))
    
where `x1, ..., xn` are the elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce
  • Exceptions thrown
    • UnsupportedOperationException if this traversable or iterator is empty.

(defined at scala.collection.TraversableOnce)

def reduce[A1 >: A](op: (A1, A1) ⇒ A1): A1

Reduces the elements of this traversable or iterator using the specified associative binary operator.

The order in which operations are performed on elements is unspecified and may be nondeterministic.

  • A1
    • A type parameter for the binary operator, a supertype of A .
  • op
    • A binary operator that must be associative.
  • returns
    • The result of applying reduce operator op between all the elements if the traversable or iterator is nonempty.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce
  • Exceptions thrown
    • UnsupportedOperationException if this traversable or iterator is empty.

(defined at scala.collection.TraversableOnce)

def reversed: scala.List[A]

  • Attributes
    • protected[this]
  • Definition Classes
    • TraversableOnce

(defined at scala.collection.TraversableOnce)

def toBuffer[B >: A]: Buffer[B]

Uses the contents of this traversable or iterator to create a new mutable buffer.

Note: will not terminate for infinite-sized collections.

  • returns
    • a buffer containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toIndexedSeq: IndexedSeq[A]

Converts this traversable or iterator to an indexed sequence.

Note: will not terminate for infinite-sized collections.

  • returns
    • an indexed sequence containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toIterable: collection.Iterable[A]

Converts this traversable or iterator to an iterable collection. Note that the choice of target Iterable is lazy in this default implementation as this TraversableOnce may be lazy and unevaluated (i.e. it may be an iterator which is only traversable once).

Note: will not terminate for infinite-sized collections.

  • returns
    • an Iterable containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toList: scala.List[A]

Converts this traversable or iterator to a list.

Note: will not terminate for infinite-sized collections.

  • returns
    • a list containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toMap[T, U](implicit ev: <:<[A, (T, U)]): Map[T, U]

[use case]

Converts this traversable or iterator to a map. This method is unavailable unless the elements are members of Tuple2, each ((T, U)) becoming a key-value pair in the map. Duplicate keys will be overwritten by later keys: if this is an unordered collection, which key is in the resulting map is undefined.

Note: will not terminate for infinite iterators.

  • returns
    • a map of type immutable.Map[T, U] containing all key/value pairs of type (T, U) of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toSeq: collection.Seq[A]

Converts this traversable or iterator to a sequence. As with toIterable , it’s lazy in this default implementation, as this TraversableOnce may be lazy and unevaluated.

Note: will not terminate for infinite-sized collections.

  • returns
    • a sequence containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toSet[B >: A]: Set[B]

Converts this traversable or iterator to a set.

Note: will not terminate for infinite-sized collections.

  • returns
    • a set containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toVector: scala.Vector[A]

Converts this traversable or iterator to a Vector.

Note: will not terminate for infinite-sized collections.

  • returns
    • a vector containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

Instance Constructors From scala.collection.immutable.VectorIterator

new VectorIterator(_startIndex: Int, endIndex: Int)

(defined at scala.collection.immutable.VectorIterator)

Full Source:

/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2013, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala
package collection
package immutable

import scala.annotation.unchecked.uncheckedVariance
import scala.compat.Platform
import scala.collection.generic._
import scala.collection.mutable.{Builder, ReusableBuilder}
import scala.collection.parallel.immutable.ParVector

/** Companion object to the Vector class
 */
object Vector extends IndexedSeqFactory[Vector] {
  def newBuilder[A]: Builder[A, Vector[A]] = new VectorBuilder[A]
  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Vector[A]] =
    ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]]
  private[immutable] val NIL = new Vector[Nothing](0, 0, 0)
  override def empty[A]: Vector[A] = NIL
  
  // Constants governing concat strategy for performance
  private final val Log2ConcatFaster = 5
  private final val TinyAppendFaster = 2
}

// in principle, most members should be private. however, access privileges must
// be carefully chosen to not prevent method inlining

/** Vector is a general-purpose, immutable data structure.  It provides random access and updates
 *  in effectively constant time, as well as very fast append and prepend.  Because vectors strike
 *  a good balance between fast random selections and fast random functional updates, they are
 *  currently the default implementation of immutable indexed sequences.  It is backed by a little
 *  endian bit-mapped vector trie with a branching factor of 32.  Locality is very good, but not
 *  contiguous, which is good for very large sequences.
 *
 *  @see [[http://docs.scala-lang.org/overviews/collections/concrete-immutable-collection-classes.html#vectors "Scala's Collection Library overview"]]
 *  section on `Vectors` for more information.
 *
 *  @tparam A the element type
 *
 *  @define Coll `Vector`
 *  @define coll vector
 *  @define thatinfo the class of the returned collection. In the standard library configuration,
 *    `That` is always `Vector[B]` because an implicit of type `CanBuildFrom[Vector, B, That]`
 *    is defined in object `Vector`.
 *  @define bfinfo an implicit value of class `CanBuildFrom` which determines the
 *    result class `That` from the current representation type `Repr`
 *    and the new element type `B`. This is usually the `canBuildFrom` value
 *    defined in object `Vector`.
 *  @define orderDependent
 *  @define orderDependentFold
 *  @define mayNotTerminateInf
 *  @define willNotTerminateInf
 */
final class Vector[+A] private[immutable] (private[collection] val startIndex: Int, private[collection] val endIndex: Int, focus: Int)
extends AbstractSeq[A]
   with IndexedSeq[A]
   with GenericTraversableTemplate[A, Vector]
   with IndexedSeqLike[A, Vector[A]]
   with VectorPointer[A @uncheckedVariance]
   with Serializable
   with CustomParallelizable[A, ParVector[A]]
{ self =>

override def companion: GenericCompanion[Vector] = Vector

  //assert(startIndex >= 0, startIndex+"<0")
  //assert(startIndex <= endIndex, startIndex+">"+endIndex)
  //assert(focus >= 0, focus+"<0")
  //assert(focus <= endIndex, focus+">"+endIndex)

  private[immutable] var dirty = false

  def length = endIndex - startIndex

  override def par = new ParVector(this)

  override def toVector: Vector[A] = this

  override def lengthCompare(len: Int): Int = length - len

  private[collection] final def initIterator[B >: A](s: VectorIterator[B]) {
    s.initFrom(this)
    if (dirty) s.stabilize(focus)
    if (s.depth > 1) s.gotoPos(startIndex, startIndex ^ focus)
  }

  override def iterator: VectorIterator[A] = {
    val s = new VectorIterator[A](startIndex, endIndex)
    initIterator(s)
    s
  }


  // can still be improved
  override /*SeqLike*/
  def reverseIterator: Iterator[A] = new AbstractIterator[A] {
    private var i = self.length
    def hasNext: Boolean = 0 < i
    def next(): A =
      if (0 < i) {
        i -= 1
        self(i)
      } else Iterator.empty.next()
  }

  // TODO: reverse

  // TODO: check performance of foreach/map etc. should override or not?
  // Ideally, clients will inline calls to map all the way down, including the iterator/builder methods.
  // In principle, escape analysis could even remove the iterator/builder allocations and do it
  // with local variables exclusively. But we're not quite there yet ...

  def apply(index: Int): A = {
    val idx = checkRangeConvert(index)
    //println("get elem: "+index + "/"+idx + "(focus:" +focus+" xor:"+(idx^focus)+" depth:"+depth+")")
    getElem(idx, idx ^ focus)
  }

  private def checkRangeConvert(index: Int) = {
    val idx = index + startIndex
    if (0 <= index && idx < endIndex)
      idx
    else
      throw new IndexOutOfBoundsException(index.toString)
  }

  // If we have a default builder, there are faster ways to perform some operations
  @inline private[this] def isDefaultCBF[A, B, That](bf: CanBuildFrom[Vector[A], B, That]): Boolean =
    (bf eq IndexedSeq.ReusableCBF) || (bf eq collection.immutable.Seq.ReusableCBF) || (bf eq collection.Seq.ReusableCBF)
    
  // SeqLike api

  override def updated[B >: A, That](index: Int, elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That =
    if (isDefaultCBF[A, B, That](bf))
      updateAt(index, elem).asInstanceOf[That] // ignore bf--it will just give a Vector, and slowly
    else super.updated(index, elem)(bf)

  override def +:[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That =
    if (isDefaultCBF[A, B, That](bf))
      appendFront(elem).asInstanceOf[That] // ignore bf--it will just give a Vector, and slowly
    else super.+:(elem)(bf)

  override def :+[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That =
    if (isDefaultCBF(bf))
      appendBack(elem).asInstanceOf[That] // ignore bf--it will just give a Vector, and slowly
    else super.:+(elem)(bf)

  override def take(n: Int): Vector[A] = {
    if (n <= 0)
      Vector.empty
    else if (startIndex < endIndex - n)
      dropBack0(startIndex + n)
    else
      this
  }

  override def drop(n: Int): Vector[A] = {
    if (n <= 0)
      this
    else if (startIndex < endIndex - n)
      dropFront0(startIndex + n)
    else
      Vector.empty
  }

  override def takeRight(n: Int): Vector[A] = {
    if (n <= 0)
      Vector.empty
    else if (endIndex - n > startIndex)
      dropFront0(endIndex - n)
    else
      this
  }

  override def dropRight(n: Int): Vector[A] = {
    if (n <= 0)
      this
    else if (endIndex - n > startIndex)
      dropBack0(endIndex - n)
    else
      Vector.empty
  }

  override /*IterableLike*/ def head: A = {
    if (isEmpty) throw new UnsupportedOperationException("empty.head")
    apply(0)
  }

  override /*TraversableLike*/ def tail: Vector[A] = {
    if (isEmpty) throw new UnsupportedOperationException("empty.tail")
    drop(1)
  }

  override /*TraversableLike*/ def last: A = {
    if (isEmpty) throw new UnsupportedOperationException("empty.last")
    apply(length-1)
  }

  override /*TraversableLike*/ def init: Vector[A] = {
    if (isEmpty) throw new UnsupportedOperationException("empty.init")
    dropRight(1)
  }

  override /*IterableLike*/ def slice(from: Int, until: Int): Vector[A] =
    take(until).drop(from)

  override /*IterableLike*/ def splitAt(n: Int): (Vector[A], Vector[A]) = (take(n), drop(n))


  // concat (suboptimal but avoids worst performance gotchas)
  override def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[Vector[A], B, That]): That = {
    if (isDefaultCBF(bf)) {
      // We are sure we will create a Vector, so let's do it efficiently
      import Vector.{Log2ConcatFaster, TinyAppendFaster}
      if (that.isEmpty) this.asInstanceOf[That]
      else {
        val again = if (!that.isTraversableAgain) that.toVector else that.seq
        again.size match {
          // Often it's better to append small numbers of elements (or prepend if RHS is a vector)
          case n if n <= TinyAppendFaster || n < (this.size >> Log2ConcatFaster) => 
            var v: Vector[B] = this
            for (x <- again) v = v :+ x
            v.asInstanceOf[That]
          case n if this.size < (n >> Log2ConcatFaster) && again.isInstanceOf[Vector[_]] =>
            var v = again.asInstanceOf[Vector[B]]
            val ri = this.reverseIterator
            while (ri.hasNext) v = ri.next +: v
            v.asInstanceOf[That]
          case _ => super.++(again)
        }
      }
    }
    else super.++(that.seq)
  }



  // semi-private api

  private[immutable] def updateAt[B >: A](index: Int, elem: B): Vector[B] = {
    val idx = checkRangeConvert(index)
    val s = new Vector[B](startIndex, endIndex, idx)
    s.initFrom(this)
    s.dirty = dirty
    s.gotoPosWritable(focus, idx, focus ^ idx)  // if dirty commit changes; go to new pos and prepare for writing
    s.display0(idx & 0x1f) = elem.asInstanceOf[AnyRef]
    s
  }


  private def gotoPosWritable(oldIndex: Int, newIndex: Int, xor: Int) = if (dirty) {
    gotoPosWritable1(oldIndex, newIndex, xor)
  } else {
    gotoPosWritable0(newIndex, xor)
    dirty = true
  }

  private def gotoFreshPosWritable(oldIndex: Int, newIndex: Int, xor: Int) = if (dirty) {
    gotoFreshPosWritable1(oldIndex, newIndex, xor)
  } else {
    gotoFreshPosWritable0(oldIndex, newIndex, xor)
    dirty = true
  }

  private[immutable] def appendFront[B>:A](value: B): Vector[B] = {
    if (endIndex != startIndex) {
      val blockIndex = (startIndex - 1) & ~31
      val lo = (startIndex - 1) & 31

      if (startIndex != blockIndex + 32) {
        val s = new Vector(startIndex - 1, endIndex, blockIndex)
        s.initFrom(this)
        s.dirty = dirty
        s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex)
        s.display0(lo) = value.asInstanceOf[AnyRef]
        s
      } else {

        val freeSpace = ((1<<5*(depth)) - endIndex) // free space at the right given the current tree-structure depth
        val shift = freeSpace & ~((1<<5*(depth-1))-1) // number of elements by which we'll shift right (only move at top level)
        val shiftBlocks = freeSpace >>> 5*(depth-1) // number of top-level blocks

        //println("----- appendFront " + value + " at " + (startIndex - 1) + " reached block start")
        if (shift != 0) {
          // case A: we can shift right on the top level
          debug()
          //println("shifting right by " + shiftBlocks + " at level " + (depth-1) + " (had "+freeSpace+" free space)")

          if (depth > 1) {
            val newBlockIndex = blockIndex + shift
            val newFocus = focus + shift
            val s = new Vector(startIndex - 1 + shift, endIndex + shift, newBlockIndex)
            s.initFrom(this)
            s.dirty = dirty
            s.shiftTopLevel(0, shiftBlocks) // shift right by n blocks
            s.debug()
            s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex) // maybe create pos; prepare for writing
            s.display0(lo) = value.asInstanceOf[AnyRef]
            //assert(depth == s.depth)
            s
          } else {
            val newBlockIndex = blockIndex + 32
            val newFocus = focus

            //assert(newBlockIndex == 0)
            //assert(newFocus == 0)

            val s = new Vector(startIndex - 1 + shift, endIndex + shift, newBlockIndex)
            s.initFrom(this)
            s.dirty = dirty
            s.shiftTopLevel(0, shiftBlocks) // shift right by n elements
            s.gotoPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex) // prepare for writing
            s.display0(shift-1) = value.asInstanceOf[AnyRef]
            s.debug()
            s
          }
        } else if (blockIndex < 0) {
          // case B: we need to move the whole structure
          val move = (1 << 5*(depth+1)) - (1 << 5*(depth))
          //println("moving right by " + move + " at level " + (depth-1) + " (had "+freeSpace+" free space)")

          val newBlockIndex = blockIndex + move
          val newFocus = focus + move


          val s = new Vector(startIndex - 1 + move, endIndex + move, newBlockIndex)
          s.initFrom(this)
          s.dirty = dirty
          s.debug()
          s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex) // could optimize: we know it will create a whole branch
          s.display0(lo) = value.asInstanceOf[AnyRef]
          s.debug()
          //assert(s.depth == depth+1)
          s
        } else {
          val newBlockIndex = blockIndex
          val newFocus = focus

          val s = new Vector(startIndex - 1, endIndex, newBlockIndex)
          s.initFrom(this)
          s.dirty = dirty
          s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex)
          s.display0(lo) = value.asInstanceOf[AnyRef]
          //assert(s.depth == depth)
          s
        }

      }
    } else {
      // empty vector, just insert single element at the back
      val elems = new Array[AnyRef](32)
      elems(31) = value.asInstanceOf[AnyRef]
      val s = new Vector(31,32,0)
      s.depth = 1
      s.display0 = elems
      s
    }
  }

  private[immutable] def appendBack[B>:A](value: B): Vector[B] = {
//    //println("------- append " + value)
//    debug()
    if (endIndex != startIndex) {
      val blockIndex = endIndex & ~31
      val lo = endIndex & 31

      if (endIndex != blockIndex) {
        //println("will make writable block (from "+focus+") at: " + blockIndex)
        val s = new Vector(startIndex, endIndex + 1, blockIndex)
        s.initFrom(this)
        s.dirty = dirty
        s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex)
        s.display0(lo) = value.asInstanceOf[AnyRef]
        s
      } else {
        val shift = startIndex & ~((1<<5*(depth-1))-1)
        val shiftBlocks = startIndex >>> 5*(depth-1)

        //println("----- appendBack " + value + " at " + endIndex + " reached block end")

        if (shift != 0) {
          debug()
          //println("shifting left by " + shiftBlocks + " at level " + (depth-1) + " (had "+startIndex+" free space)")
          if (depth > 1) {
            val newBlockIndex = blockIndex - shift
            val newFocus = focus - shift
            val s = new Vector(startIndex - shift, endIndex + 1 - shift, newBlockIndex)
            s.initFrom(this)
            s.dirty = dirty
            s.shiftTopLevel(shiftBlocks, 0) // shift left by n blocks
            s.debug()
            s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex)
            s.display0(lo) = value.asInstanceOf[AnyRef]
            s.debug()
            //assert(depth == s.depth)
            s
          } else {
            val newBlockIndex = blockIndex - 32
            val newFocus = focus

            //assert(newBlockIndex == 0)
            //assert(newFocus == 0)

            val s = new Vector(startIndex - shift, endIndex + 1 - shift, newBlockIndex)
            s.initFrom(this)
            s.dirty = dirty
            s.shiftTopLevel(shiftBlocks, 0) // shift right by n elements
            s.gotoPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex)
            s.display0(32 - shift) = value.asInstanceOf[AnyRef]
            s.debug()
            s
          }
        } else {
          val newBlockIndex = blockIndex
          val newFocus = focus

          val s = new Vector(startIndex, endIndex + 1, newBlockIndex)
          s.initFrom(this)
          s.dirty = dirty
          s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex)
          s.display0(lo) = value.asInstanceOf[AnyRef]
          //assert(s.depth == depth+1) might or might not create new level!
          if (s.depth == depth+1) {
            //println("creating new level " + s.depth + " (had "+0+" free space)")
            s.debug()
          }
          s
        }
      }
    } else {
      val elems = new Array[AnyRef](32)
      elems(0) = value.asInstanceOf[AnyRef]
      val s = new Vector(0,1,0)
      s.depth = 1
      s.display0 = elems
      s
    }
  }


  // low-level implementation (needs cleanup, maybe move to util class)

  private def shiftTopLevel(oldLeft: Int, newLeft: Int) = (depth - 1) match {
    case 0 =>
      display0 = copyRange(display0, oldLeft, newLeft)
    case 1 =>
      display1 = copyRange(display1, oldLeft, newLeft)
    case 2 =>
      display2 = copyRange(display2, oldLeft, newLeft)
    case 3 =>
      display3 = copyRange(display3, oldLeft, newLeft)
    case 4 =>
      display4 = copyRange(display4, oldLeft, newLeft)
    case 5 =>
      display5 = copyRange(display5, oldLeft, newLeft)
  }

  private def zeroLeft(array: Array[AnyRef], index: Int): Unit = {
    var i = 0; while (i < index) { array(i) = null; i+=1 }
  }

  private def zeroRight(array: Array[AnyRef], index: Int): Unit = {
    var i = index; while (i < array.length) { array(i) = null; i+=1 }
  }

  private def copyLeft(array: Array[AnyRef], right: Int): Array[AnyRef] = {
//    if (array eq null)
//      println("OUCH!!! " + right + "/" + depth + "/"+startIndex + "/" + endIndex + "/" + focus)
    val a2 = new Array[AnyRef](array.length)
    Platform.arraycopy(array, 0, a2, 0, right)
    a2
  }
  private def copyRight(array: Array[AnyRef], left: Int): Array[AnyRef] = {
    val a2 = new Array[AnyRef](array.length)
    Platform.arraycopy(array, left, a2, left, a2.length - left)
    a2
  }

  private def preClean(depth: Int) = {
    this.depth = depth
    (depth - 1) match {
      case 0 =>
        display1 = null
        display2 = null
        display3 = null
        display4 = null
        display5 = null
      case 1 =>
        display2 = null
        display3 = null
        display4 = null
        display5 = null
      case 2 =>
        display3 = null
        display4 = null
        display5 = null
      case 3 =>
        display4 = null
        display5 = null
      case 4 =>
        display5 = null
      case 5 =>
    }
  }

  // requires structure is at index cutIndex and writable at level 0
  private def cleanLeftEdge(cutIndex: Int) = {
    if (cutIndex < (1 << 5)) {
      zeroLeft(display0, cutIndex)
    } else
    if (cutIndex < (1 << 10)) {
      zeroLeft(display0, cutIndex & 0x1f)
      display1 = copyRight(display1, (cutIndex >>>  5))
    } else
    if (cutIndex < (1 << 15)) {
      zeroLeft(display0, cutIndex & 0x1f)
      display1 = copyRight(display1, (cutIndex >>>  5) & 0x1f)
      display2 = copyRight(display2, (cutIndex >>> 10))
    } else
    if (cutIndex < (1 << 20)) {
      zeroLeft(display0, cutIndex & 0x1f)
      display1 = copyRight(display1, (cutIndex >>>  5) & 0x1f)
      display2 = copyRight(display2, (cutIndex >>> 10) & 0x1f)
      display3 = copyRight(display3, (cutIndex >>> 15))
    } else
    if (cutIndex < (1 << 25)) {
      zeroLeft(display0, cutIndex & 0x1f)
      display1 = copyRight(display1, (cutIndex >>>  5) & 0x1f)
      display2 = copyRight(display2, (cutIndex >>> 10) & 0x1f)
      display3 = copyRight(display3, (cutIndex >>> 15) & 0x1f)
      display4 = copyRight(display4, (cutIndex >>> 20))
    } else
    if (cutIndex < (1 << 30)) {
      zeroLeft(display0, cutIndex & 0x1f)
      display1 = copyRight(display1, (cutIndex >>>  5) & 0x1f)
      display2 = copyRight(display2, (cutIndex >>> 10) & 0x1f)
      display3 = copyRight(display3, (cutIndex >>> 15) & 0x1f)
      display4 = copyRight(display4, (cutIndex >>> 20) & 0x1f)
      display5 = copyRight(display5, (cutIndex >>> 25))
    } else {
      throw new IllegalArgumentException()
    }
  }

  // requires structure is writable and at index cutIndex
  private def cleanRightEdge(cutIndex: Int) = {

    // we're actually sitting one block left if cutIndex lies on a block boundary
    // this means that we'll end up erasing the whole block!!

    if (cutIndex <= (1 << 5)) {
      zeroRight(display0, cutIndex)
    } else
    if (cutIndex <= (1 << 10)) {
      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
      display1 = copyLeft(display1, (cutIndex >>>  5))
    } else
    if (cutIndex <= (1 << 15)) {
      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
      display1 = copyLeft(display1, (((cutIndex-1) >>>  5) & 0x1f) + 1)
      display2 = copyLeft(display2, (cutIndex >>> 10))
    } else
    if (cutIndex <= (1 << 20)) {
      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
      display1 = copyLeft(display1, (((cutIndex-1) >>>  5) & 0x1f) + 1)
      display2 = copyLeft(display2, (((cutIndex-1) >>> 10) & 0x1f) + 1)
      display3 = copyLeft(display3, (cutIndex >>> 15))
    } else
    if (cutIndex <= (1 << 25)) {
      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
      display1 = copyLeft(display1, (((cutIndex-1) >>>  5) & 0x1f) + 1)
      display2 = copyLeft(display2, (((cutIndex-1) >>> 10) & 0x1f) + 1)
      display3 = copyLeft(display3, (((cutIndex-1) >>> 15) & 0x1f) + 1)
      display4 = copyLeft(display4, (cutIndex >>> 20))
    } else
    if (cutIndex <= (1 << 30)) {
      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
      display1 = copyLeft(display1, (((cutIndex-1) >>>  5) & 0x1f) + 1)
      display2 = copyLeft(display2, (((cutIndex-1) >>> 10) & 0x1f) + 1)
      display3 = copyLeft(display3, (((cutIndex-1) >>> 15) & 0x1f) + 1)
      display4 = copyLeft(display4, (((cutIndex-1) >>> 20) & 0x1f) + 1)
      display5 = copyLeft(display5, (cutIndex >>> 25))
    } else {
      throw new IllegalArgumentException()
    }
  }

  private def requiredDepth(xor: Int) = {
    if (xor < (1 <<  5)) 1
    else if (xor < (1 << 10)) 2
    else if (xor < (1 << 15)) 3
    else if (xor < (1 << 20)) 4
    else if (xor < (1 << 25)) 5
    else if (xor < (1 << 30)) 6
    else throw new IllegalArgumentException()
  }

  private def dropFront0(cutIndex: Int): Vector[A] = {
    val blockIndex = cutIndex & ~31
    val xor = cutIndex ^ (endIndex - 1)
    val d = requiredDepth(xor)
    val shift = (cutIndex & ~((1 << (5*d))-1))

    //println("cut front at " + cutIndex + ".." + endIndex + " (xor: "+xor+" shift: " + shift + " d: " + d +")")

/*
    val s = new Vector(cutIndex-shift, endIndex-shift, blockIndex-shift)
    s.initFrom(this)
    if (s.depth > 1)
      s.gotoPos(blockIndex, focus ^ blockIndex)
    s.depth = d
    s.stabilize(blockIndex-shift)
    s.cleanLeftEdge(cutIndex-shift)
    s
*/

    // need to init with full display iff going to cutIndex requires swapping block at level >= d

    val s = new Vector(cutIndex-shift, endIndex-shift, blockIndex-shift)
    s.initFrom(this)
    s.dirty = dirty
    s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex)
    s.preClean(d)
    s.cleanLeftEdge(cutIndex - shift)
    s
  }

  private def dropBack0(cutIndex: Int): Vector[A] = {
    val blockIndex = (cutIndex - 1) & ~31
    val xor = startIndex ^ (cutIndex - 1)
    val d = requiredDepth(xor)
    val shift = (startIndex & ~((1 << (5*d))-1))

/*
    println("cut back at " + startIndex + ".." + cutIndex + " (xor: "+xor+" d: " + d +")")
    if (cutIndex == blockIndex + 32)
      println("OUCH!!!")
*/
    val s = new Vector(startIndex-shift, cutIndex-shift, blockIndex-shift)
    s.initFrom(this)
    s.dirty = dirty
    s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex)
    s.preClean(d)
    s.cleanRightEdge(cutIndex-shift)
    s
  }

}


class VectorIterator[+A](_startIndex: Int, endIndex: Int)
extends AbstractIterator[A]
   with Iterator[A]
   with VectorPointer[A @uncheckedVariance] {

  private var blockIndex: Int = _startIndex & ~31
  private var lo: Int = _startIndex & 31

  private var endLo = math.min(endIndex - blockIndex, 32)

  def hasNext = _hasNext

  private var _hasNext = blockIndex + lo < endIndex

  def next(): A = {
    if (!_hasNext) throw new NoSuchElementException("reached iterator end")

    val res = display0(lo).asInstanceOf[A]
    lo += 1

    if (lo == endLo) {
      if (blockIndex + lo < endIndex) {
        val newBlockIndex = blockIndex+32
        gotoNextBlockStart(newBlockIndex, blockIndex ^ newBlockIndex)

        blockIndex = newBlockIndex
        endLo = math.min(endIndex - blockIndex, 32)
        lo = 0
      } else {
        _hasNext = false
      }
    }

    res
  }

  private[collection] def remainingElementCount: Int = (endIndex - (blockIndex + lo)) max 0

  /** Creates a new vector which consists of elements remaining in this iterator.
   *  Such a vector can then be split into several vectors using methods like `take` and `drop`.
   */
  private[collection] def remainingVector: Vector[A] = {
    val v = new Vector(blockIndex + lo, endIndex, blockIndex + lo)
    v.initFrom(this)
    v
  }
}

/** A class to build instances of `Vector`.  This builder is reusable. */
final class VectorBuilder[A]() extends ReusableBuilder[A,Vector[A]] with VectorPointer[A @uncheckedVariance] {

  // possible alternative: start with display0 = null, blockIndex = -32, lo = 32
  // to avoid allocating initial array if the result will be empty anyways

  display0 = new Array[AnyRef](32)
  depth = 1

  private var blockIndex = 0
  private var lo = 0

  def += (elem: A): this.type = {
    if (lo >= display0.length) {
      val newBlockIndex = blockIndex+32
      gotoNextBlockStartWritable(newBlockIndex, blockIndex ^ newBlockIndex)
      blockIndex = newBlockIndex
      lo = 0
    }
    display0(lo) = elem.asInstanceOf[AnyRef]
    lo += 1
    this
  }

  override def ++=(xs: TraversableOnce[A]): this.type =
    super.++=(xs)

  def result: Vector[A] = {
    val size = blockIndex + lo
    if (size == 0)
      return Vector.empty
    val s = new Vector[A](0, size, 0) // should focus front or back?
    s.initFrom(this)
    if (depth > 1) s.gotoPos(0, size - 1) // we're currently focused to size - 1, not size!
    s
  }

  def clear(): Unit = {
    display0 = new Array[AnyRef](32)
    depth = 1
    blockIndex = 0
    lo = 0
  }
}



private[immutable] trait VectorPointer[T] {
    private[immutable] var depth: Int = _
    private[immutable] var display0: Array[AnyRef] = _
    private[immutable] var display1: Array[AnyRef] = _
    private[immutable] var display2: Array[AnyRef] = _
    private[immutable] var display3: Array[AnyRef] = _
    private[immutable] var display4: Array[AnyRef] = _
    private[immutable] var display5: Array[AnyRef] = _

    // used
    private[immutable] final def initFrom[U](that: VectorPointer[U]): Unit = initFrom(that, that.depth)

    private[immutable] final def initFrom[U](that: VectorPointer[U], depth: Int) = {
      this.depth = depth
      (depth - 1) match {
        case -1 =>
        case 0 =>
          display0 = that.display0
        case 1 =>
          display1 = that.display1
          display0 = that.display0
        case 2 =>
          display2 = that.display2
          display1 = that.display1
          display0 = that.display0
        case 3 =>
          display3 = that.display3
          display2 = that.display2
          display1 = that.display1
          display0 = that.display0
        case 4 =>
          display4 = that.display4
          display3 = that.display3
          display2 = that.display2
          display1 = that.display1
          display0 = that.display0
        case 5 =>
          display5 = that.display5
          display4 = that.display4
          display3 = that.display3
          display2 = that.display2
          display1 = that.display1
          display0 = that.display0
      }
    }


    // requires structure is at pos oldIndex = xor ^ index
    private[immutable] final def getElem(index: Int, xor: Int): T = {
      if (xor < (1 << 5)) { // level = 0
        display0(index & 31).asInstanceOf[T]
      } else
      if (xor < (1 << 10)) { // level = 1
        display1((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
      } else
      if (xor < (1 << 15)) { // level = 2
        display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
      } else
      if (xor < (1 << 20)) { // level = 3
        display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]((index >> 10) & 31).asInstanceOf[Array[AnyRef]]((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
      } else
      if (xor < (1 << 25)) { // level = 4
        display4((index >> 20) & 31).asInstanceOf[Array[AnyRef]]((index >> 15) & 31).asInstanceOf[Array[AnyRef]]((index >> 10) & 31).asInstanceOf[Array[AnyRef]]((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
      } else
      if (xor < (1 << 30)) { // level = 5
        display5((index >> 25) & 31).asInstanceOf[Array[AnyRef]]((index >> 20) & 31).asInstanceOf[Array[AnyRef]]((index >> 15) & 31).asInstanceOf[Array[AnyRef]]((index >> 10) & 31).asInstanceOf[Array[AnyRef]]((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
      } else { // level = 6
        throw new IllegalArgumentException()
      }
    }


    // go to specific position
    // requires structure is at pos oldIndex = xor ^ index,
    // ensures structure is at pos index
    private[immutable] final def gotoPos(index: Int, xor: Int): Unit = {
      if (xor < (1 << 5)) { // level = 0 (could maybe removed)
      } else
      if (xor < (1 << 10)) { // level = 1
        display0 = display1((index >> 5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 15)) { // level = 2
        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = display1((index >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 20)) { // level = 3
        display2 = display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = display1((index >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 25)) { // level = 4
        display3 = display4((index >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = display1((index >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 30)) { // level = 5
        display4 = display5((index >> 25) & 31).asInstanceOf[Array[AnyRef]]
        display3 = display4((index >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = display1((index >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else { // level = 6
        throw new IllegalArgumentException()
      }
    }



    // USED BY ITERATOR

    // xor: oldIndex ^ index
    private[immutable] final def gotoNextBlockStart(index: Int, xor: Int): Unit = { // goto block start pos
      if (xor < (1 << 10)) { // level = 1
        display0 = display1((index >> 5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 15)) { // level = 2
        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = display1(0).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 20)) { // level = 3
        display2 = display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = display2(0).asInstanceOf[Array[AnyRef]]
        display0 = display1(0).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 25)) { // level = 4
        display3 = display4((index >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = display3(0).asInstanceOf[Array[AnyRef]]
        display1 = display2(0).asInstanceOf[Array[AnyRef]]
        display0 = display1(0).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 30)) { // level = 5
        display4 = display5((index >> 25) & 31).asInstanceOf[Array[AnyRef]]
        display3 = display4(0).asInstanceOf[Array[AnyRef]]
        display2 = display3(0).asInstanceOf[Array[AnyRef]]
        display1 = display2(0).asInstanceOf[Array[AnyRef]]
        display0 = display1(0).asInstanceOf[Array[AnyRef]]
      } else { // level = 6
        throw new IllegalArgumentException()
      }
    }

    // USED BY BUILDER

    // xor: oldIndex ^ index
    private[immutable] final def gotoNextBlockStartWritable(index: Int, xor: Int): Unit = { // goto block start pos
      if (xor < (1 << 10)) { // level = 1
        if (depth == 1) { display1 = new Array(32); display1(0) = display0; depth+=1}
        display0 = new Array(32)
        display1((index >>  5) & 31) = display0
      } else
      if (xor < (1 << 15)) { // level = 2
        if (depth == 2) { display2 = new Array(32); display2(0) = display1; depth+=1}
        display0 = new Array(32)
        display1 = new Array(32)
        display1((index >>  5) & 31) = display0
        display2((index >> 10) & 31) = display1
      } else
      if (xor < (1 << 20)) { // level = 3
        if (depth == 3) { display3 = new Array(32); display3(0) = display2; depth+=1}
        display0 = new Array(32)
        display1 = new Array(32)
        display2 = new Array(32)
        display1((index >>  5) & 31) = display0
        display2((index >> 10) & 31) = display1
        display3((index >> 15) & 31) = display2
      } else
      if (xor < (1 << 25)) { // level = 4
        if (depth == 4) { display4 = new Array(32); display4(0) = display3; depth+=1}
        display0 = new Array(32)
        display1 = new Array(32)
        display2 = new Array(32)
        display3 = new Array(32)
        display1((index >>  5) & 31) = display0
        display2((index >> 10) & 31) = display1
        display3((index >> 15) & 31) = display2
        display4((index >> 20) & 31) = display3
      } else
      if (xor < (1 << 30)) { // level = 5
        if (depth == 5) { display5 = new Array(32); display5(0) = display4; depth+=1}
        display0 = new Array(32)
        display1 = new Array(32)
        display2 = new Array(32)
        display3 = new Array(32)
        display4 = new Array(32)
        display1((index >>  5) & 31) = display0
        display2((index >> 10) & 31) = display1
        display3((index >> 15) & 31) = display2
        display4((index >> 20) & 31) = display3
        display5((index >> 25) & 31) = display4
      } else { // level = 6
        throw new IllegalArgumentException()
      }
    }



    // STUFF BELOW USED BY APPEND / UPDATE

    private[immutable] final def copyOf(a: Array[AnyRef]) = {
      val b = new Array[AnyRef](a.length)
      Platform.arraycopy(a, 0, b, 0, a.length)
      b
    }

    private[immutable] final def nullSlotAndCopy(array: Array[AnyRef], index: Int) = {
      //println("copy and null")
      val x = array(index)
      array(index) = null
      copyOf(x.asInstanceOf[Array[AnyRef]])
    }


    // make sure there is no aliasing
    // requires structure is at pos index
    // ensures structure is clean and at pos index and writable at all levels except 0

    private[immutable] final def stabilize(index: Int) = (depth - 1) match {
      case 5 =>
        display5 = copyOf(display5)
        display4 = copyOf(display4)
        display3 = copyOf(display3)
        display2 = copyOf(display2)
        display1 = copyOf(display1)
        display5((index >> 25) & 31) = display4
        display4((index >> 20) & 31) = display3
        display3((index >> 15) & 31) = display2
        display2((index >> 10) & 31) = display1
        display1((index >>  5) & 31) = display0
      case 4 =>
        display4 = copyOf(display4)
        display3 = copyOf(display3)
        display2 = copyOf(display2)
        display1 = copyOf(display1)
        display4((index >> 20) & 31) = display3
        display3((index >> 15) & 31) = display2
        display2((index >> 10) & 31) = display1
        display1((index >>  5) & 31) = display0
      case 3 =>
        display3 = copyOf(display3)
        display2 = copyOf(display2)
        display1 = copyOf(display1)
        display3((index >> 15) & 31) = display2
        display2((index >> 10) & 31) = display1
        display1((index >>  5) & 31) = display0
      case 2 =>
        display2 = copyOf(display2)
        display1 = copyOf(display1)
        display2((index >> 10) & 31) = display1
        display1((index >>  5) & 31) = display0
      case 1 =>
        display1 = copyOf(display1)
        display1((index >>  5) & 31) = display0
      case 0 =>
    }



    /// USED IN UPDATE AND APPEND BACK

    // prepare for writing at an existing position

    // requires structure is clean and at pos oldIndex = xor ^ newIndex,
    // ensures structure is dirty and at pos newIndex and writable at level 0
    private[immutable] final def gotoPosWritable0(newIndex: Int, xor: Int): Unit = (depth - 1) match {
      case 5 =>
        display5 = copyOf(display5)
        display4 = nullSlotAndCopy(display5, (newIndex >> 25) & 31).asInstanceOf[Array[AnyRef]]
        display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      case 4 =>
        display4 = copyOf(display4)
        display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      case 3 =>
        display3 = copyOf(display3)
        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      case 2 =>
        display2 = copyOf(display2)
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      case 1 =>
        display1 = copyOf(display1)
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      case 0 =>
        display0 = copyOf(display0)
    }


    // requires structure is dirty and at pos oldIndex,
    // ensures structure is dirty and at pos newIndex and writable at level 0
    private[immutable] final def gotoPosWritable1(oldIndex: Int, newIndex: Int, xor: Int): Unit = {
      if (xor < (1 <<  5)) { // level = 0
        display0 = copyOf(display0)
      } else
      if (xor < (1 << 10)) { // level = 1
        display1 = copyOf(display1)
        display1((oldIndex >> 5) & 31) = display0
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31)
      } else
      if (xor < (1 << 15)) { // level = 2
        display1 = copyOf(display1)
        display2 = copyOf(display2)
        display1((oldIndex >>  5) & 31) = display0
        display2((oldIndex >> 10) & 31) = display1
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 20)) { // level = 3
        display1 = copyOf(display1)
        display2 = copyOf(display2)
        display3 = copyOf(display3)
        display1((oldIndex >>  5) & 31) = display0
        display2((oldIndex >> 10) & 31) = display1
        display3((oldIndex >> 15) & 31) = display2
        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 25)) { // level = 4
        display1 = copyOf(display1)
        display2 = copyOf(display2)
        display3 = copyOf(display3)
        display4 = copyOf(display4)
        display1((oldIndex >>  5) & 31) = display0
        display2((oldIndex >> 10) & 31) = display1
        display3((oldIndex >> 15) & 31) = display2
        display4((oldIndex >> 20) & 31) = display3
        display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 30)) { // level = 5
        display1 = copyOf(display1)
        display2 = copyOf(display2)
        display3 = copyOf(display3)
        display4 = copyOf(display4)
        display5 = copyOf(display5)
        display1((oldIndex >>  5) & 31) = display0
        display2((oldIndex >> 10) & 31) = display1
        display3((oldIndex >> 15) & 31) = display2
        display4((oldIndex >> 20) & 31) = display3
        display5((oldIndex >> 25) & 31) = display4
        display4 = nullSlotAndCopy(display5, (newIndex >> 25) & 31).asInstanceOf[Array[AnyRef]]
        display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else { // level = 6
        throw new IllegalArgumentException()
      }
    }


    // USED IN DROP

    private[immutable] final def copyRange(array: Array[AnyRef], oldLeft: Int, newLeft: Int) = {
      val elems = new Array[AnyRef](32)
      Platform.arraycopy(array, oldLeft, elems, newLeft, 32 - math.max(newLeft,oldLeft))
      elems
    }




    // USED IN APPEND
    // create a new block at the bottom level (and possibly nodes on its path) and prepares for writing

    // requires structure is clean and at pos oldIndex,
    // ensures structure is dirty and at pos newIndex and writable at level 0
    private[immutable] final def gotoFreshPosWritable0(oldIndex: Int, newIndex: Int, xor: Int): Unit = { // goto block start pos
      if (xor < (1 << 5)) { // level = 0
        //println("XXX clean with low xor")
      } else
      if (xor < (1 << 10)) { // level = 1
        if (depth == 1) {
          display1 = new Array(32)
          display1((oldIndex >>  5) & 31) = display0
          depth +=1
        }
        display0 = new Array(32)
      } else
      if (xor < (1 << 15)) { // level = 2
        if (depth == 2) {
          display2 = new Array(32)
          display2((oldIndex >> 10) & 31) = display1
          depth +=1
        }
        display1 = display2((newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        if (display1 == null) display1 = new Array(32)
        display0 = new Array(32)
      } else
      if (xor < (1 << 20)) { // level = 3
        if (depth == 3) {
          display3 = new Array(32)
          display3((oldIndex >> 15) & 31) = display2
          depth +=1
        }
        display2 = display3((newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        if (display2 == null) display2 = new Array(32)
        display1 = display2((newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        if (display1 == null) display1 = new Array(32)
        display0 = new Array(32)
      } else
      if (xor < (1 << 25)) { // level = 4
        if (depth == 4) {
          display4 = new Array(32)
          display4((oldIndex >> 20) & 31) = display3
          depth +=1
        }
        display3 = display4((newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
        if (display3 == null) display3 = new Array(32)
        display2 = display3((newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        if (display2 == null) display2 = new Array(32)
        display1 = display2((newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        if (display1 == null) display1 = new Array(32)
        display0 = new Array(32)
      } else
      if (xor < (1 << 30)) { // level = 5
        if (depth == 5) {
          display5 = new Array(32)
          display5((oldIndex >>  25) & 31) = display4
          depth +=1
        }
        display4 = display5((newIndex >> 25) & 31).asInstanceOf[Array[AnyRef]]
        if (display4 == null) display4 = new Array(32)
        display3 = display4((newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
        if (display3 == null) display3 = new Array(32)
        display2 = display3((newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        if (display2 == null) display2 = new Array(32)
        display1 = display2((newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        if (display1 == null) display1 = new Array(32)
        display0 = new Array(32)
      } else { // level = 6
        throw new IllegalArgumentException()
      }
    }


    // requires structure is dirty and at pos oldIndex,
    // ensures structure is dirty and at pos newIndex and writable at level 0
    private[immutable] final def gotoFreshPosWritable1(oldIndex: Int, newIndex: Int, xor: Int): Unit = {
      stabilize(oldIndex)
      gotoFreshPosWritable0(oldIndex, newIndex, xor)
    }




    // DEBUG STUFF

    private[immutable] def debug(): Unit = {
      return
/*
      //println("DISPLAY 5: " + display5 + " ---> " + (if (display5 ne null) display5.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
      //println("DISPLAY 4: " + display4 + " ---> " + (if (display4 ne null) display4.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
      //println("DISPLAY 3: " + display3 + " ---> " + (if (display3 ne null) display3.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
      //println("DISPLAY 2: " + display2 + " ---> " + (if (display2 ne null) display2.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
      //println("DISPLAY 1: " + display1 + " ---> " + (if (display1 ne null) display1.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
      //println("DISPLAY 0: " + display0 + " ---> " + (if (display0 ne null) display0.map(x=> if (x eq null) "." else x.toString).mkString(" ") else "null"))
*/
      //println("DISPLAY 5: " + (if (display5 ne null) display5.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
      //println("DISPLAY 4: " + (if (display4 ne null) display4.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
      //println("DISPLAY 3: " + (if (display3 ne null) display3.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
      //println("DISPLAY 2: " + (if (display2 ne null) display2.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
      //println("DISPLAY 1: " + (if (display1 ne null) display1.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
      //println("DISPLAY 0: " + (if (display0 ne null) display0.map(x=> if (x eq null) "." else x.toString).mkString(" ") else "null"))
    }


}