|
| 1 | +/* |
| 2 | + * Scala (https://www.scala-lang.org) |
| 3 | + * |
| 4 | + * Copyright EPFL and Lightbend, Inc. |
| 5 | + * |
| 6 | + * Licensed under Apache License 2.0 |
| 7 | + * (http://www.apache.org/licenses/LICENSE-2.0). |
| 8 | + * |
| 9 | + * See the NOTICE file distributed with this work for |
| 10 | + * additional information regarding copyright ownership. |
| 11 | + */ |
| 12 | + |
| 13 | +package scala |
| 14 | +package collection |
| 15 | +package immutable |
| 16 | +import language.experimental.captureChecking |
| 17 | +import annotation.unchecked.uncheckedCaptures |
| 18 | + |
| 19 | +/** |
| 20 | + * Trait that overrides operations to take advantage of strict builders. |
| 21 | + */ |
| 22 | +trait StrictOptimizedSeqOps[+A, +CC[_], +C] |
| 23 | + extends Any |
| 24 | + with SeqOps[A, CC, C] |
| 25 | + with collection.StrictOptimizedSeqOps[A, CC, C] |
| 26 | + with StrictOptimizedIterableOps[A, CC, C] { |
| 27 | + |
| 28 | + override def distinctBy[B](f: A -> B): C = { |
| 29 | + if (lengthCompare(1) <= 0) coll |
| 30 | + else { |
| 31 | + val builder = newSpecificBuilder |
| 32 | + val seen = mutable.HashSet.empty[B @uncheckedCaptures] |
| 33 | + val it = this.iterator |
| 34 | + var different = false |
| 35 | + while (it.hasNext) { |
| 36 | + val next = it.next() |
| 37 | + if (seen.add(f(next))) builder += next else different = true |
| 38 | + } |
| 39 | + if (different) builder.result() else coll |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + override def updated[B >: A](index: Int, elem: B): CC[B] = { |
| 44 | + if (index < 0) throw new IndexOutOfBoundsException(s"$index is out of bounds (min 0, max ${if (knownSize>=0) knownSize else "unknown"})") |
| 45 | + val b = iterableFactory.newBuilder[B] |
| 46 | + if (knownSize >= 0) { |
| 47 | + b.sizeHint(size) |
| 48 | + } |
| 49 | + var i = 0 |
| 50 | + val it = iterator |
| 51 | + while (i < index && it.hasNext) { |
| 52 | + b += it.next() |
| 53 | + i += 1 |
| 54 | + } |
| 55 | + if (!it.hasNext) throw new IndexOutOfBoundsException(s"$index is out of bounds (min 0, max ${i-1})") |
| 56 | + b += elem |
| 57 | + it.next() |
| 58 | + while (it.hasNext) b += it.next() |
| 59 | + b.result() |
| 60 | + } |
| 61 | + |
| 62 | + override def patch[B >: A](from: Int, other: IterableOnce[B]^, replaced: Int): CC[B] = { |
| 63 | + val b = iterableFactory.newBuilder[B] |
| 64 | + var i = 0 |
| 65 | + val it = iterator |
| 66 | + while (i < from && it.hasNext) { |
| 67 | + b += it.next() |
| 68 | + i += 1 |
| 69 | + } |
| 70 | + b ++= other |
| 71 | + i = replaced |
| 72 | + while (i > 0 && it.hasNext) { |
| 73 | + it.next() |
| 74 | + i -= 1 |
| 75 | + } |
| 76 | + while (it.hasNext) b += it.next() |
| 77 | + b.result() |
| 78 | + } |
| 79 | + |
| 80 | + override def sorted[B >: A](implicit ord: Ordering[B]): C = super.sorted(ord) |
| 81 | + |
| 82 | +} |
0 commit comments