-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathIntAccumulator.scala
491 lines (428 loc) · 14.8 KB
/
IntAccumulator.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.jdk
import java.io.{ObjectInputStream, ObjectOutputStream}
import java.util.Spliterator
import java.util.function.{Consumer, IntConsumer}
import java.{lang => jl}
import scala.collection.Stepper.EfficientSplit
import scala.collection.{AnyStepper, Factory, IntStepper, SeqFactory, Stepper, StepperShape, mutable}
import scala.language.implicitConversions
/** A specialized Accumulator that holds `Int`s without boxing, see [[Accumulator]]. */
final class IntAccumulator
extends Accumulator[Int, AnyAccumulator, IntAccumulator]
with mutable.SeqOps[Int, AnyAccumulator, IntAccumulator]
with Serializable {
private[jdk] var current: Array[Int] = IntAccumulator.emptyIntArray
private[jdk] var history: Array[Array[Int]] = IntAccumulator.emptyIntArrayArray
private[jdk] def cumulative(i: Int) = { val x = history(i); x(x.length-2).toLong << 32 | (x(x.length-1)&0xFFFFFFFFL) }
override protected[this] def className: String = "IntAccumulator"
def efficientStepper[S <: Stepper[_]](implicit shape: StepperShape[Int, S]): S with EfficientSplit = {
val st = new IntAccumulatorStepper(this)
val r =
if (shape.shape == StepperShape.IntShape) st
else {
assert(shape.shape == StepperShape.ReferenceShape, s"unexpected StepperShape: $shape")
AnyStepper.ofParIntStepper(st)
}
r.asInstanceOf[S with EfficientSplit]
}
private def expand(): Unit = {
if (index > 0) {
val cuml = (if (hIndex > 0) cumulative(hIndex-1) else 0) + index
current(current.length-2) = (cuml >>> 32).toInt
current(current.length-1) = (cuml & 0xFFFFFFFFL).toInt
if (hIndex >= history.length) hExpand()
history(hIndex) = current
hIndex += 1
}
current = new Array[Int](nextBlockSize+1)
index = 0
}
private def hExpand(): Unit = {
if (hIndex == 0) history = new Array[Array[Int]](4)
else history = java.util.Arrays.copyOf(history, history.length << 1)
}
/** Appends an element to this `IntAccumulator`. */
def addOne(a: Int): this.type = {
totalSize += 1
if (index+2 >= current.length) expand()
current(index) = a
index += 1
this
}
/** Result collection consisting of all elements appended so far. */
override def result(): IntAccumulator = this
/** Removes all elements from `that` and appends them to this `IntAccumulator`. */
def drain(that: IntAccumulator): Unit = {
var h = 0
var prev = 0L
var more = true
while (more && h < that.hIndex) {
val cuml = that.cumulative(h)
val n = (cuml - prev).toInt
if (current.length - index - 2 >= n) {
System.arraycopy(that.history(h), 0, current, index, n)
prev = cuml
index += n
h += 1
}
else more = false
}
if (h >= that.hIndex && current.length - index - 2 >= that.index) {
if (that.index > 0) System.arraycopy(that.current, 0, current, index, that.index)
index += that.index
}
else {
val slots = (if (index > 0) 1 else 0) + that.hIndex - h
if (hIndex + slots > history.length) {
val n = math.max(4, 1 << (32 - jl.Integer.numberOfLeadingZeros(1 + hIndex + slots)))
history = java.util.Arrays.copyOf(history, n)
}
var pv = if (hIndex > 0) cumulative(hIndex-1) else 0L
if (index > 0) {
val x =
if (index < (current.length >>> 3) && current.length - 1 > 32) {
val ans = java.util.Arrays.copyOf(current, index + 2)
ans(ans.length - 2) = current(current.length - 2)
ans(ans.length - 1) = current(current.length - 1)
ans
}
else current
pv = pv + index
x(x.length - 2) = (pv >>> 32).toInt
x(x.length - 1) = (pv & 0xFFFFFFFFL).toInt
history(hIndex) = x
hIndex += 1
}
while (h < that.hIndex) {
val cuml = that.cumulative(h)
pv = pv + cuml - prev
prev = cuml
val x = that.history(h)
x(x.length - 2) = (pv >>> 32).toInt
x(x.length - 1) = (pv & 0xFFFFFFFFL).toInt
history(hIndex) = x
h += 1
hIndex += 1
}
index = that.index
current = that.current
}
totalSize += that.totalSize
that.clear()
}
override def clear(): Unit = {
super.clear()
current = IntAccumulator.emptyIntArray
history = IntAccumulator.emptyIntArrayArray
}
/** Retrieves the `ix`th element. */
def apply(ix: Long): Int = {
if (totalSize - ix <= index || hIndex == 0) current((ix - (totalSize - index)).toInt)
else {
val w = seekSlot(ix)
history((w >>> 32).toInt)((w & 0xFFFFFFFFL).toInt)
}
}
/** Retrieves the `ix`th element, using an `Int` index. */
def apply(i: Int): Int = apply(i.toLong)
def update(idx: Long, elem: Int): Unit = {
if (totalSize - idx <= index || hIndex == 0) current((idx - (totalSize - index)).toInt) = elem
else {
val w = seekSlot(idx)
history((w >>> 32).toInt)((w & 0xFFFFFFFFL).toInt) = elem
}
}
def update(idx: Int, elem: Int): Unit = update(idx.toLong, elem)
/** Returns an `Iterator` over the contents of this `IntAccumulator`. The `Iterator` is not specialized. */
def iterator: Iterator[Int] = stepper.iterator
override def foreach[U](f: Int => U): Unit = {
val s = stepper
while (s.hasStep) f(s.nextStep())
}
def map(f: Int => Int): IntAccumulator = {
val b = newSpecificBuilder
val s = stepper
while (s.hasStep)
b.addOne(f(s.nextStep()))
b.result()
}
def flatMap(f: Int => IterableOnce[Int]): IntAccumulator = {
val b = newSpecificBuilder
val s = stepper
while (s.hasStep)
b.addAll(f(s.nextStep()))
b.result()
}
def collect(pf: PartialFunction[Int, Int]): IntAccumulator = {
val b = newSpecificBuilder
val s = stepper
while (s.hasStep) {
val n = s.nextStep()
pf.runWith(b.addOne)(n)
}
b.result()
}
private def filterAccImpl(pred: Int => Boolean, not: Boolean): IntAccumulator = {
val b = newSpecificBuilder
val s = stepper
while (s.hasStep) {
val n = s.nextStep()
if (pred(n) != not) b.addOne(n)
}
b.result()
}
override def filter(pred: Int => Boolean): IntAccumulator = filterAccImpl(pred, not = false)
override def filterNot(pred: Int => Boolean): IntAccumulator = filterAccImpl(pred, not = true)
override def forall(p: Int => Boolean): Boolean = {
val s = stepper
while (s.hasStep)
if (!p(s.nextStep())) return false
true
}
override def exists(p: Int => Boolean): Boolean = {
val s = stepper
while (s.hasStep)
if (p(s.nextStep())) return true
false
}
override def count(p: Int => Boolean): Int = {
var r = 0
val s = stepper
while (s.hasStep)
if (p(s.nextStep())) r += 1
r
}
def countLong(p: Int => Boolean): Long = {
var r = 0L
val s = stepper
while (s.hasStep)
if (p(s.nextStep())) r += 1
r
}
/** Copies the elements in this `IntAccumulator` into an `Array[Int]` */
def toArray: Array[Int] = {
if (totalSize > Int.MaxValue) throw new IllegalArgumentException("Too many elements accumulated for an array: "+totalSize.toString)
val a = new Array[Int](totalSize.toInt)
var j = 0
var h = 0
var pv = 0L
while (h < hIndex) {
val x = history(h)
val cuml = cumulative(h)
val n = (cuml - pv).toInt
pv = cuml
System.arraycopy(x, 0, a, j, n)
j += n
h += 1
}
System.arraycopy(current, 0, a, j, index)
j += index
a
}
/** Copies the elements in this `IntAccumulator` to a `List` */
override def toList: List[Int] = {
var ans: List[Int] = Nil
var i = index - 1
while (i >= 0) {
ans = current(i) :: ans
i -= 1
}
var h = hIndex - 1
while (h >= 0) {
val a = history(h)
i = (cumulative(h) - (if (h == 0) 0L else cumulative(h-1))).toInt - 1
while (i >= 0) {
ans = a(i) :: ans
i -= 1
}
h -= 1
}
ans
}
/**
* Copy the elements in this `IntAccumulator` to a specified collection.
* Note that the target collection is not specialized.
* Usage example: `acc.to(Vector)`
*/
override def to[C1](factory: Factory[Int, C1]): C1 = {
if (totalSize > Int.MaxValue) throw new IllegalArgumentException("Too many elements accumulated for a Scala collection: "+totalSize.toString)
factory.fromSpecific(iterator)
}
override protected def fromSpecific(coll: IterableOnce[Int]): IntAccumulator = IntAccumulator.fromSpecific(coll)
override protected def newSpecificBuilder: IntAccumulator = IntAccumulator.newBuilder
override def iterableFactory: SeqFactory[AnyAccumulator] = AnyAccumulator
override def empty: IntAccumulator = IntAccumulator.empty
private def writeReplace(): AnyRef = new IntAccumulator.SerializationProxy(this)
}
object IntAccumulator extends collection.SpecificIterableFactory[Int, IntAccumulator] {
private val emptyIntArray = new Array[Int](0)
private val emptyIntArrayArray = new Array[Array[Int]](0)
implicit def toJavaIntegerAccumulator(ia: IntAccumulator.type): collection.SpecificIterableFactory[jl.Integer, IntAccumulator] = IntAccumulator.asInstanceOf[collection.SpecificIterableFactory[jl.Integer, IntAccumulator]]
import java.util.{function => jf}
/** A `Supplier` of `IntAccumulator`s, suitable for use with `java.util.stream.IntStream`'s `collect` method. Suitable for `Stream[Int]` also. */
def supplier: jf.Supplier[IntAccumulator] = () => new IntAccumulator
/** A `BiConsumer` that adds an element to an `IntAccumulator`, suitable for use with `java.util.stream.IntStream`'s `collect` method. */
def adder: jf.ObjIntConsumer[IntAccumulator] = (ac: IntAccumulator, a: Int) => ac addOne a
/** A `BiConsumer` that adds a boxed `Int` to an `IntAccumulator`, suitable for use with `java.util.stream.Stream`'s `collect` method. */
def boxedAdder: jf.BiConsumer[IntAccumulator, Int] = (ac: IntAccumulator, a: Int) => ac addOne a
/** A `BiConsumer` that merges `IntAccumulator`s, suitable for use with `java.util.stream.IntStream`'s `collect` method. Suitable for `Stream[Int]` also. */
def merger: jf.BiConsumer[IntAccumulator, IntAccumulator] = (a1: IntAccumulator, a2: IntAccumulator) => a1 drain a2
private def fromArray(a: Array[Int]): IntAccumulator = {
val r = new IntAccumulator
var i = 0
while (i < a.length) { r addOne a(i); i += 1 }
r
}
override def fromSpecific(it: IterableOnce[Int]): IntAccumulator = it match {
case acc: IntAccumulator => acc
case as: collection.immutable.ArraySeq.ofInt => fromArray(as.unsafeArray)
case as: collection.mutable.ArraySeq.ofInt => fromArray(as.array) // this case ensures Array(1).to(Accumulator) doesn't box
case _ => (new IntAccumulator).addAll(it)
}
override def empty: IntAccumulator = new IntAccumulator
override def newBuilder: IntAccumulator = new IntAccumulator
class SerializationProxy[A](@transient private val acc: IntAccumulator) extends Serializable {
@transient private var result: IntAccumulator = _
private def writeObject(out: ObjectOutputStream): Unit = {
out.defaultWriteObject()
val size = acc.sizeLong
out.writeLong(size)
val st = acc.stepper
while (st.hasStep)
out.writeInt(st.nextStep())
}
private def readObject(in: ObjectInputStream): Unit = {
in.defaultReadObject()
val res = new IntAccumulator()
var elems = in.readLong()
while (elems > 0) {
res += in.readInt()
elems -= 1L
}
result = res
}
private def readResolve(): AnyRef = result
}
}
private[jdk] class IntAccumulatorStepper(private val acc: IntAccumulator) extends IntStepper with EfficientSplit {
import java.util.Spliterator._
private var h: Int = 0
private var i: Int = 0
private var a: Array[Int] = if (acc.hIndex > 0) acc.history(0) else acc.current
private var n: Long = if (acc.hIndex > 0) acc.cumulative(0) else acc.index
private var N: Long = acc.totalSize
private def duplicateSelf(limit: Long): IntAccumulatorStepper = {
val ans = new IntAccumulatorStepper(acc)
ans.h = h
ans.i = i
ans.a = a
ans.n = n
ans.N = limit
ans
}
private def loadMore(): Unit = {
h += 1
if (h < acc.hIndex) { a = acc.history(h); n = acc.cumulative(h) - acc.cumulative(h-1) }
else { a = acc.current; n = acc.index }
i = 0
}
def characteristics: Int = ORDERED | SIZED | SUBSIZED | NONNULL
def estimateSize: Long = N
def hasStep: Boolean = N > 0
def nextStep(): Int =
if (N <= 0) throw new NoSuchElementException("next on empty Stepper")
else {
if (i >= n) loadMore()
val ans = a(i)
i += 1
N -= 1
ans
}
def trySplit(): IntStepper =
if (N <= 1) null
else {
val half = N >> 1
val M = (if (h <= 0) 0L else acc.cumulative(h-1)) + i
val R = M + half
val ans = duplicateSelf(half)
if (h < acc.hIndex) {
val w = acc.seekSlot(R)
h = (w >>> 32).toInt
if (h < acc.hIndex) {
a = acc.history(h)
n = acc.cumulative(h) - (if (h > 0) acc.cumulative(h-1) else 0)
}
else {
a = acc.current
n = acc.index
}
i = (w & 0xFFFFFFFFL).toInt
}
else i += half.toInt
N -= half
ans
}
override def spliterator[B >: Int]: Spliterator.OfInt = new IntStepper.IntStepperSpliterator(this) {
// Overridden for efficiency
override def tryAdvance(c: IntConsumer): Boolean =
if (N <= 0) false
else {
if (i >= n) loadMore()
c.accept(a(i))
i += 1
N -= 1
true
}
// Overridden for efficiency
override def tryAdvance(c: Consumer[_ >: jl.Integer]): Boolean = (c: AnyRef) match {
case ic: IntConsumer => tryAdvance(ic)
case _ =>
if (N <= 0) false
else {
if (i >= n) loadMore()
c.accept(a(i))
i += 1
N -= 1
true
}
}
// Overridden for efficiency
override def forEachRemaining(c: IntConsumer): Unit =
while (N > 0) {
if (i >= n) loadMore()
val i0 = i
if ((n-i) > N) n = i + N.toInt
while (i < n) {
c.accept(a(i))
i += 1
}
N -= (n - i0)
}
// Overridden for efficiency
override def forEachRemaining(c: Consumer[_ >: jl.Integer]): Unit = (c: AnyRef) match {
case ic: IntConsumer => forEachRemaining(ic)
case _ =>
while (N > 0) {
if (i >= n) loadMore()
val i0 = i
if ((n-i) > N) n = i + N.toInt
while (i < n) {
c.accept(a(i))
i += 1
}
N -= (n - i0)
}
}
}
}