-
Notifications
You must be signed in to change notification settings - Fork 595
/
Chunk.scala
1299 lines (1117 loc) · 45.1 KB
/
Chunk.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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2013 Functional Streams for Scala
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package fs2
import scala.annotation.tailrec
import scala.collection.immutable.{Queue => SQueue}
import scala.collection.{IndexedSeq => GIndexedSeq, Seq => GSeq, mutable}
import scala.reflect.ClassTag
import scodec.bits.{BitVector, ByteVector}
import java.nio.{Buffer => JBuffer, ByteBuffer => JByteBuffer, CharBuffer => JCharBuffer}
import cats._
import cats.data.{Chain, NonEmptyList}
import cats.syntax.all._
import fs2.internal._
/** Immutable, strict, finite sequence of values that supports efficient index-based random access of elements,
* is memory efficient for all sizes, and avoids unnecessary copying.
*
* `Chunk`s can be created from a variety of collection types using methods on the `Chunk` companion
* (e.g., `Chunk.array`, `Chunk.seq`, `Chunk.vector`).
*
* Chunks can be appended via the `++` method. The returned chunk is a composite of the input
* chunks -- that is, there's no copying of the source chunks. For example, `Chunk(1, 2) ++ Chunk(3, 4) ++ Chunk(5, 6)`
* returns a `Chunk.Queue(Chunk(1, 2), Chunk(3, 4), Chunk(5, 6))`. As a result, indexed based lookup of
* an appended chunk is amortized `O(log2(number of underlying chunks))`. In the worst case, where each constituent chunk
* has size 1, indexed lookup is `O(log2(size))`. To restore `O(1)` lookup, call `compact`, which copies all the underlying
* chunk elements to a single array backed chunk. Note `compact` requires a `ClassTag` of the element type.
*
* Alternatively, a collection of chunks can be directly copied to a new array backed chunk via
* `Chunk.concat(chunks)`. Like `compact`, `Chunk.concat` requires a `ClassTag` for the element type.
*
* Various subtypes of `Chunk` are exposed for efficiency reasons:
* - `Chunk.Singleton`
* - `Chunk.ArraySlice`
* - `Chunk.Queue`
*
* In particular, calling `.toArraySlice` on a chunk returns a `Chunk.ArraySlice`, which provides
* access to the underlying backing array, along with an offset and length, referring to a slice
* of that array.
*/
abstract class Chunk[+O] extends Serializable with ChunkPlatform[O] with ChunkRuntimePlatform[O] {
self =>
/** Returns the number of elements in this chunk. */
def size: Int
/** Returns the element at the specified index. Throws if index is < 0 or >= size. */
def apply(i: Int): O
/** Returns a chunk which consists of the elements of this chunk and the elements of
* the supplied chunk. This operation is amortized O(1).
*/
def ++[O2 >: O](that: Chunk[O2]): Chunk[O2] =
if (isEmpty) that
else
that match {
case that if that.isEmpty => this
case that: Chunk.Queue[O2] => this +: that
case that => Chunk.Queue(this, that)
}
/** More efficient version of `filter(pf.isDefinedAt).map(pf)`. */
def collect[O2](pf: PartialFunction[O, O2]): Chunk[O2] = {
val b = makeArrayBuilder[Any]
b.sizeHint(size)
foreach(o => if (pf.isDefinedAt(o)) b += pf(o))
Chunk.array(b.result()).asInstanceOf[Chunk[O2]]
}
/** Copies the elements of this chunk in to the specified array at the specified start index. */
def copyToArray[O2 >: O](xs: Array[O2], start: Int = 0): Unit
/** Converts this chunk to a chunk backed by a single array.
*
* Alternatively, call `toIndexedChunk` to get back a chunk with guaranteed O(1) indexed lookup
* while also minimizing copying.
*/
def compact[O2 >: O](implicit ct: ClassTag[O2]): Chunk.ArraySlice[O2] =
Chunk.ArraySlice(toArray[O2], 0, size)
/** Like `compact` but does not require a `ClassTag`. Elements are boxed and stored in an `Array[Any]`. */
@deprecated("Unsound when used with primitives, use compactBoxed instead", "3.1.6")
def compactUntagged[O2 >: O]: Chunk.ArraySlice[O2] =
Chunk.ArraySlice(toArray[Any], 0, size).asInstanceOf[Chunk.ArraySlice[O2]]
/** Drops the first `n` elements of this chunk. */
def drop(n: Int): Chunk[O] = splitAt(n)._2
/** Drops the right-most `n` elements of this chunk queue in a way that preserves chunk structure. */
def dropRight(n: Int): Chunk[O] = if (n <= 0) this else take(size - n)
protected def thisClassTag: ClassTag[Any] = implicitly[ClassTag[Any]]
/** Returns a chunk that has only the elements that satisfy the supplied predicate. */
def filter(p: O => Boolean): Chunk[O] = {
val b = makeArrayBuilder(thisClassTag)
b.sizeHint(size)
foreach(e => if (p(e)) b += e)
Chunk.array(b.result()).asInstanceOf[Chunk[O]]
}
/** Returns the first element for which the predicate returns true or `None` if no elements satisfy the predicate. */
def find(p: O => Boolean): Option[O] =
iterator.find(p)
/** Maps `f` over the elements of this chunk and concatenates the result. */
def flatMap[O2](f: O => Chunk[O2]): Chunk[O2] =
if (isEmpty) Chunk.empty
else if (size == 1) f(apply(0))
else {
var acc = Chunk.Queue.empty[O2]
foreach(o => acc = acc :+ f(o))
acc
}
/** Left-folds the elements of this chunk. */
def foldLeft[A](init: A)(f: (A, O) => A): A = {
var res = init
foreach(o => res = f(res, o))
res
}
/** Returns true if the predicate passes for all elements. */
def forall(p: O => Boolean): Boolean =
iterator.forall(p)
/** Invokes the supplied function for each element of this chunk. */
def foreach(f: O => Unit): Unit = {
var i = 0
while (i < size) {
f(apply(i))
i += 1
}
}
/** Like `foreach` but includes the index of the element. */
def foreachWithIndex(f: (O, Int) => Unit): Unit = {
var i = 0
while (i < size) {
f(apply(i), i)
i += 1
}
}
/** Gets the first element of this chunk. */
def head: Option[O] = if (isEmpty) None else Some(apply(0))
/** True if size is zero, false otherwise. */
final def isEmpty: Boolean = size == 0
/** Creates an iterator that iterates the elements of this chunk. The returned iterator is not thread safe. */
def iterator: Iterator[O] =
new Iterator[O] {
private[this] var i = 0
def hasNext = i < self.size
def next() = { val result = apply(i); i += 1; result }
}
/** Returns the index of the first element which passes the specified predicate (i.e., `p(i) == true`)
* or `None` if no elements pass the predicate.
*/
def indexWhere(p: O => Boolean): Option[Int] = {
val idx = iterator.indexWhere(p)
if (idx < 0) None else Some(idx)
}
/** Gets the last element of this chunk. */
def last: Option[O] = if (isEmpty) None else Some(apply(size - 1))
/** Creates a new chunk by applying `f` to each element in this chunk. */
def map[O2](f: O => O2): Chunk[O2] = {
val arr = new Array[Any](size)
foreachWithIndex((o, i) => arr(i) = f(o))
Chunk.array(arr).asInstanceOf[Chunk[O2]]
}
/** Maps the supplied stateful function over each element, outputting the final state and the accumulated outputs.
* The first invocation of `f` uses `init` as the input state value. Each successive invocation uses
* the output state of the previous invocation.
*/
def mapAccumulate[S, O2](init: S)(f: (S, O) => (S, O2)): (S, Chunk[O2]) = {
val arr = new Array[Any](size)
var s = init
foreachWithIndex { (o, i) =>
val (s2, o2) = f(s, o)
arr(i) = o2
s = s2
}
s -> Chunk.array(arr).asInstanceOf[Chunk[O2]]
}
/** Maps the supplied function over each element and returns a chunk of just the defined results. */
def mapFilter[O2](f: O => Option[O2]): Chunk[O2] = {
val b = makeArrayBuilder[Any]
b.sizeHint(size)
foreach { o =>
val o2 = f(o)
if (o2.isDefined) b += o2.get
}
Chunk.array(b.result()).asInstanceOf[Chunk[O2]]
}
/** False if size is zero, true otherwise. */
final def nonEmpty: Boolean = !isEmpty
/** Creates an iterator that iterates the elements of this chunk in reverse order. The returned iterator is not thread safe. */
def reverseIterator: Iterator[O] =
new Iterator[O] {
private[this] var i = self.size - 1
def hasNext = i >= 0
def next() = { val result = apply(i); i -= 1; result }
}
/** Like `foldLeft` but emits each intermediate result of `f`. */
def scanLeft[O2](z: O2)(f: (O2, O) => O2): Chunk[O2] =
scanLeft_(z, true)(f)._1
/** Like `scanLeft` except the final element is emitted as a standalone value instead of as
* the last element of the accumulated chunk.
*
* Equivalent to `val b = a.scanLeft(z)(f); val (c, carry) = b.splitAt(b.size - 1)`.
*/
def scanLeftCarry[O2](z: O2)(f: (O2, O) => O2): (Chunk[O2], O2) =
scanLeft_(z, false)(f)
protected def scanLeft_[O2](z: O2, emitZero: Boolean)(f: (O2, O) => O2): (Chunk[O2], O2) = {
val arr = new Array[Any](if (emitZero) size + 1 else size)
var acc = z
if (emitZero) arr(0) = acc
var i = if (emitZero) 1 else 0
foreach { o =>
acc = f(acc, o)
arr(i) = acc
i += 1
}
Chunk.array(arr).asInstanceOf[Chunk[O2]] -> acc
}
/** Splits this chunk in to two chunks at the specified index. */
def splitAt(n: Int): (Chunk[O], Chunk[O]) =
if (n <= 0) (Chunk.empty, this)
else if (n >= size) (this, Chunk.empty)
else splitAtChunk_(n)
/** Splits this chunk in to two chunks at the specified index `n`, which is guaranteed to be in-bounds. */
protected def splitAtChunk_(n: Int): (Chunk[O], Chunk[O])
/** Check to see if this starts with the items in the given chunk. */
def startsWith[O2 >: O](chunk: Chunk[O2]): Boolean =
take(chunk.size) == chunk
/** Check to see if this starts with the items in the given seq. */
def startsWith[O2 >: O](seq: Seq[O2]): Boolean =
startsWith(Chunk.seq(seq))
/** Takes the first `n` elements of this chunk. */
def take(n: Int): Chunk[O] = splitAt(n)._1
/** Takes the right-most `n` elements of this chunk queue in a way that preserves chunk structure. */
def takeRight(n: Int): Chunk[O] = if (n <= 0) Chunk.empty else drop(size - n)
/** Converts this chunk to a new collection using the supplied collector.
* @example {{{
* scala> Chunk(1, 2, 3).to(Set)
* }}}
*/
def to(collector: Collector[O]): collector.Out = {
val bldr = collector.newBuilder
bldr += this
bldr.result
}
/** Copies the elements of this chunk to an array. */
def toArray[O2 >: O: ClassTag]: Array[O2] = {
val arr = new Array[O2](size)
copyToArray(arr, 0)
arr
}
/** Converts this chunk to a `Chunk.ArraySlice`. */
def toArraySlice[O2 >: O](implicit ct: ClassTag[O2]): Chunk.ArraySlice[O2] =
Chunk.ArraySlice(toArray, 0, size)
/** Converts this chunk to a `java.nio.ByteBuffer`.
* @note that even "read-only" interaction with a `ByteBuffer` may increment its `position`,
* so this method should be considered as unsafely allocating mutable state.
*/
def toByteBuffer[B >: O](implicit ev: B =:= Byte): JByteBuffer = {
val slice = this.asInstanceOf[Chunk[Byte]].toArraySlice
JByteBuffer.wrap(slice.values, slice.offset, slice.length)
}
/** Converts this chunk to a `java.nio.CharBuffer`.
* @note that even "read-only" interaction with a `CharBuffer` may increment its position,
* so this method should be considered as unsafely allocating mutable state.
*/
def toCharBuffer[C >: O](implicit ev: C =:= Char): JCharBuffer = {
val slice = this.asInstanceOf[Chunk[Char]].toArraySlice
JCharBuffer.wrap(slice.values, slice.offset, slice.length)
}
/** Converts this chunk to a NonEmptyList */
def toNel: Option[NonEmptyList[O]] =
NonEmptyList.fromList(toList)
/** Converts this chunk to a chain. */
def toChain: Chain[O] =
if (isEmpty) Chain.empty
else Chain.fromSeq(toList)
/** Returns a chunk with guaranteed O(1) lookup by index.
*
* Unlike `compact`, this operation does not copy any elements unless this chunk
* does not provide O(1) lookup by index -- e.g., a chunk built via 1 or more usages
* of `++`.
*/
def toIndexedChunk: Chunk[O] = this match {
case _: Chunk.Queue[_] =>
val b = makeArrayBuilder[Any]
b.sizeHint(size)
foreach(o => b += o)
Chunk.array(b.result()).asInstanceOf[Chunk[O]]
case other => other
}
/** Converts this chunk to a list. */
def toList: List[O] =
if (isEmpty) Nil
else {
val buf = new collection.mutable.ListBuffer[O]
foreach(o => buf += o)
buf.result()
}
/** Converts this chunk to a vector. */
def toVector: Vector[O] =
if (isEmpty) Vector.empty
else {
val buf = new collection.immutable.VectorBuilder[O]
buf.sizeHint(size)
foreach(o => buf += o)
buf.result()
}
/** Converts this chunk to a scodec-bits ByteVector. */
def toByteVector[B >: O](implicit ev: B =:= Byte): ByteVector =
ByteVector.viewAt(i => apply(i.toInt), size.toLong)
/** Converts this chunk to a scodec-bits BitVector. */
def toBitVector[B >: O](implicit ev: B =:= Byte): BitVector = toByteVector[B].bits
def traverse[F[_], O2](f: O => F[O2])(implicit F: Applicative[F]): F[Chunk[O2]] =
if (isEmpty) F.pure(Chunk.empty[O2])
else if (size == 1) f(apply(0)).map(Chunk.singleton)
else {
// we branch out by this factor
val width = 128
// By making a tree here we don't blow the stack
// even if the Chunk is very long
// by construction, this is never called with start == end
def loop(start: Int, end: Int): Eval[F[Chain[O2]]] =
if (end - start <= width) {
// Here we are at the leafs of the trees
// we don't use map2Eval since it is always
// at most width in size.
var flist = f(apply(end - 1)).map(_ :: Nil)
var idx = end - 2
while (start <= idx) {
flist = F.map2(f(apply(idx)), flist)(_ :: _)
idx = idx - 1
}
Eval.now(flist.map(Chain.fromSeq(_)))
} else {
// we have width + 1 or more nodes left
val step = (end - start) / width
var fchain = Eval.defer(loop(start, start + step))
var start0 = start + step
var end0 = start0 + step
while (start0 < end) {
// Make sure these are vals, to avoid capturing mutable state
// in the lazy context of Eval
val end1 = math.min(end, end0)
val start1 = start0
fchain = fchain.flatMap(F.map2Eval(_, Eval.defer(loop(start1, end1)))(_.concat(_)))
start0 = start0 + step
end0 = end0 + step
}
fchain
}
F.map(loop(0, size).value)(Chunk.chain)
}
def traverseFilter[F[_], O2](f: O => F[Option[O2]])(implicit F: Applicative[F]): F[Chunk[O2]] =
if (isEmpty) F.pure(Chunk.empty[O2])
else {
// we branch out by this factor
val width = 128
// By making a tree here we don't blow the stack
// even if the Chunk is very long
// by construction, this is never called with start == end
def loop(start: Int, end: Int): Eval[F[Chain[O2]]] =
if (end - start <= width) {
// Here we are at the leafs of the trees
// we don't use map2Eval since it is always
// at most width in size.
var flist = f(apply(end - 1)).map {
case Some(a) => a :: Nil
case None => Nil
}
var idx = end - 2
while (start <= idx) {
flist = F.map2(f(apply(idx)), flist) { (optO2, list) =>
if (optO2.isDefined) optO2.get :: list
else list
}
idx = idx - 1
}
Eval.now(flist.map(Chain.fromSeq(_)))
} else {
// we have width + 1 or more nodes left
val step = (end - start) / width
var fchain = Eval.defer(loop(start, start + step))
var start0 = start + step
var end0 = start0 + step
while (start0 < end) {
// Make sure these are vals, to avoid capturing mutable state
// in the lazy context of Eval
val end1 = math.min(end, end0)
val start1 = start0
fchain = fchain.flatMap(F.map2Eval(_, Eval.defer(loop(start1, end1)))(_.concat(_)))
start0 = start0 + step
end0 = end0 + step
}
fchain
}
F.map(loop(0, size).value)(Chunk.chain)
}
/** Zips this chunk the the supplied chunk, returning a chunk of tuples.
*/
def zip[O2](that: Chunk[O2]): Chunk[(O, O2)] = zipWith(that)(Tuple2.apply)
/** Zips this chunk with the supplied chunk, passing each pair to `f`, resulting in
* an output chunk.
*/
def zipWith[O2, O3](that: Chunk[O2])(f: (O, O2) => O3): Chunk[O3] = {
val sz = size.min(that.size)
val arr = new Array[Any](sz)
var i = 0
iterator.zip(that.iterator).foreach { case (o, o2) =>
arr(i) = f(o, o2)
i += 1
}
Chunk.array(arr).asInstanceOf[Chunk[O3]]
}
/** Zips the elements of the input chunk with its indices, and returns the new chunk.
*
* @example {{{
* scala> Chunk("The", "quick", "brown", "fox").zipWithIndex.toList
* res0: List[(String, Int)] = List((The,0), (quick,1), (brown,2), (fox,3))
* }}}
*/
def zipWithIndex: Chunk[(O, Int)] = {
val arr = new Array[(O, Int)](size)
foreachWithIndex((o, i) => arr(i) = (o, i))
Chunk.array(arr)
}
override def hashCode: Int = {
import util.hashing.MurmurHash3
var h = MurmurHash3.stringHash("Chunk")
foreach(o => h = MurmurHash3.mix(h, o.##))
MurmurHash3.finalizeHash(h, size)
}
override def equals(a: Any): Boolean =
a match {
case c: Chunk[_] =>
size == c.size && iterator.sameElements(c.iterator)
case _ => false
}
override def toString: String =
iterator.mkString("Chunk(", ", ", ")")
}
object Chunk
extends CollectorK[Chunk]
with ChunkCompanionPlatform
with ChunkCompanionRuntimePlatform {
private val empty_ : Chunk[Nothing] = new EmptyChunk
private final class EmptyChunk extends Chunk[Nothing] {
def size = 0
def apply(i: Int) = sys.error(s"Chunk.empty.apply($i)")
def copyToArray[O2 >: Nothing](xs: Array[O2], start: Int): Unit = ()
protected def splitAtChunk_(n: Int): (Chunk[Nothing], Chunk[Nothing]) =
sys.error("impossible")
override def map[O2](f: Nothing => O2): Chunk[O2] = this
override def toByteVector[B](implicit ev: B =:= Byte): ByteVector = ByteVector.empty
override def toString = "empty"
}
private[fs2] val unit: Chunk[Unit] = singleton(())
/** Chunk with no elements. */
def empty[A]: Chunk[A] = empty_
/** Creates a singleton chunk or returns an empty one */
def fromOption[O](opt: Option[O]): Chunk[O] = opt.map(singleton).getOrElse(empty_)
/** Creates a chunk consisting of a single element. */
def singleton[O](o: O): Chunk[O] = new Singleton(o)
final class Singleton[O](val value: O) extends Chunk[O] {
def size: Int = 1
def apply(i: Int): O =
if (i == 0) value else throw new IndexOutOfBoundsException()
def copyToArray[O2 >: O](xs: Array[O2], start: Int): Unit = xs(start) = value
override def toByteVector[B >: O](implicit ev: B =:= Byte): ByteVector =
ByteVector.fromByte(value)
protected def splitAtChunk_(n: Int): (Chunk[O], Chunk[O]) =
sys.error("impossible")
override def map[O2](f: O => O2): Chunk[O2] = singleton(f(value))
}
def constant[A](value: A, size: Int): Chunk[A] =
if (size <= 0) empty
else if (size == 1) singleton(value)
else new Constant(value, size)
final class Constant[A](value: A, override val size: Int) extends Chunk[A] {
def apply(i: Int): A =
if (0 <= i && i < size) value else throw new IndexOutOfBoundsException()
def copyToArray[O2 >: A](xs: Array[O2], start: Int): Unit = {
@tailrec
def go(ix: Int): Unit =
if (ix < size) {
xs(start + ix) = value
go(ix + 1)
}
go(0)
}
protected def splitAtChunk_(n: Int): (Chunk[A], Chunk[A]) =
constant(value, n) -> constant(value, size - n)
}
/** Creates a chunk backed by a vector. */
def vector[O](v: Vector[O]): Chunk[O] = indexedSeq(v)
/** Creates a chunk backed by an `IndexedSeq`. */
def indexedSeq[O](s: GIndexedSeq[O]): Chunk[O] =
if (s.isEmpty) empty
else if (s.size == 1)
singleton(s.head) // Use size instead of tail.isEmpty as indexed seqs know their size
else new IndexedSeqChunk(s)
private final class IndexedSeqChunk[O](s: GIndexedSeq[O]) extends Chunk[O] {
def size = s.length
def apply(i: Int) = s(i)
def copyToArray[O2 >: O](xs: Array[O2], start: Int): Unit = {
s.copyToArray(xs, start)
()
}
override def toByteVector[B >: O](implicit ev: B =:= Byte): ByteVector =
ByteVector.viewAt(idx => s(idx.toInt), s.length.toLong)
override def toVector = s.toVector
override def drop(n: Int): Chunk[O] =
if (n <= 0) this
else if (n >= size) Chunk.empty
else indexedSeq(s.drop(n))
override def take(n: Int): Chunk[O] =
if (n <= 0) Chunk.empty
else if (n >= size) this
else indexedSeq(s.take(n))
protected def splitAtChunk_(n: Int): (Chunk[O], Chunk[O]) = {
val (fst, snd) = s.splitAt(n)
indexedSeq(fst) -> indexedSeq(snd)
}
override def map[O2](f: O => O2): Chunk[O2] = indexedSeq(s.map(f))
}
/** Creates a chunk from a `scala.collection.Seq`. */
def seq[O](s: GSeq[O]): Chunk[O] = iterable(s)
/** Creates a chunk from a `scala.collection.Iterable`. */
def iterable[O](i: collection.Iterable[O]): Chunk[O] =
platformIterable(i).getOrElse(i match {
case a: mutable.ArraySeq[o] => arraySeq[o](a).asInstanceOf[Chunk[O]]
case v: Vector[O] => vector(v)
case l: List[O] =>
if (l.isEmpty) empty
else if (l.tail.isEmpty) singleton(l.head)
else {
val bldr = makeArrayBuilder[Any]
bldr ++= l
array(bldr.result()).asInstanceOf[Chunk[O]]
}
case ix: GIndexedSeq[O] => indexedSeq(ix)
case _ =>
if (i.isEmpty) empty
else iterator(i.iterator)
})
/** Creates a chunk from a `scala.collection.Iterator`. */
def iterator[O](itr: collection.Iterator[O]): Chunk[O] =
if (itr.isEmpty) empty
else {
val head = itr.next()
if (itr.hasNext) {
val bldr = makeArrayBuilder[Any]
bldr += head
bldr ++= itr
array(bldr.result()).asInstanceOf[Chunk[O]]
} else singleton(head)
}
/** Creates a chunk backed by a mutable `ArraySeq`.
*/
def arraySeq[O](arraySeq: mutable.ArraySeq[O]): Chunk[O] = {
val arr = arraySeq.array.asInstanceOf[Array[O]]
array(arr)(ClassTag(arr.getClass.getComponentType))
}
/** Creates a chunk backed by a `Chain`. */
def chain[O](c: Chain[O]): Chunk[O] =
if (c.isEmpty) empty
else iterator(c.iterator)
/** Creates a chunk backed by a mutable buffer. The underlying buffer must not be modified after
* it is passed to this function.
*/
@deprecated(
"Chunk is no longer specialized for collection.mutable.Buffer - use array or indexedSeq instead",
"3.2.4"
)
def buffer[O](b: collection.mutable.Buffer[O]): Chunk[O] =
if (b.isEmpty) empty
else if (b.size == 1) singleton(b.head)
else {
val bldr = makeArrayBuilder[Any]
bldr ++= b
Chunk.array(bldr.result()).asInstanceOf[Chunk[O]]
}
/** Creates a chunk with the specified values. */
def apply[O](os: O*): Chunk[O] = seq(os)
/** Creates a chunk backed by an array. */
def array[O: ClassTag](values: Array[O]): Chunk[O] =
array(values, 0, values.length)
/** Creates a chunk backed by a slice of an array. */
def array[O: ClassTag](values: Array[O], offset: Int, length: Int): Chunk[O] =
length match {
case 0 => empty
case 1 => singleton(values(offset))
case _ => ArraySlice(values, offset, length)
}
case class ArraySlice[O](values: Array[O], offset: Int, length: Int)(implicit
ct: ClassTag[O]
) extends Chunk[O] {
// note: we don't really need the ct implicit here as we can compute it on demand via
// ClassTag(values.getClass.getComponentType) -- we only keep it for bincompat
require(
offset >= 0 && offset <= values.size && length >= 0 && length <= values.size && offset + length <= values.size
)
override protected def thisClassTag: ClassTag[Any] = ct.asInstanceOf[ClassTag[Any]]
def size = length
def apply(i: Int) =
if (i < 0 || i >= size) throw new IndexOutOfBoundsException()
else values(offset + i)
override def compact[O2 >: O](implicit ct: ClassTag[O2]): ArraySlice[O2] =
if ((ct.wrap.runtimeClass eq values.getClass) && offset == 0 && length == values.length)
this.asInstanceOf[ArraySlice[O2]]
else super.compact
@deprecated("Unsound", "3.1.6")
override def compactUntagged[O2 >: O]: ArraySlice[O2] =
if ((classOf[Array[Any]] eq values.getClass) && offset == 0 && length == values.length)
this.asInstanceOf[ArraySlice[O2]]
else super.compactUntagged
def copyToArray[O2 >: O](xs: Array[O2], start: Int): Unit =
if (xs.getClass eq ct.wrap.runtimeClass)
System.arraycopy(values, offset, xs, start, length)
else {
values.iterator.slice(offset, offset + length).copyToArray(xs, start)
()
}
override def toByteVector[B >: O](implicit ev: B =:= Byte): ByteVector =
if (values.isInstanceOf[Array[Byte]])
ByteVector.view(values.asInstanceOf[Array[Byte]], offset, length)
else ByteVector.viewAt(i => apply(i.toInt), size.toLong)
protected def splitAtChunk_(n: Int): (Chunk[O], Chunk[O]) =
ArraySlice(values, offset, n) -> ArraySlice(values, offset + n, length - n)
override def drop(n: Int): Chunk[O] =
if (n <= 0) this
else if (n >= size) Chunk.empty
else ArraySlice(values, offset + n, length - n)
override def take(n: Int): Chunk[O] =
if (n <= 0) Chunk.empty
else if (n >= size) this
else ArraySlice(values, offset, n)
override def toArraySlice[O2 >: O](implicit ct: ClassTag[O2]): Chunk.ArraySlice[O2] =
if (ct.wrap.runtimeClass eq values.getClass)
asInstanceOf[Chunk.ArraySlice[O2]]
else super.toArraySlice
}
object ArraySlice {
def apply[O: ClassTag](values: Array[O]): ArraySlice[O] = ArraySlice(values, 0, values.length)
}
sealed abstract class Buffer[A <: Buffer[A, B, C], B <: JBuffer, C](
buf: B,
val offset: Int,
val size: Int
)(implicit ct: ClassTag[C])
extends Chunk[C] {
def readOnly(b: B): B
def buffer(b: B): A
def get(b: B, n: Int): C
def get(b: B, dest: Array[C], offset: Int, length: Int): B
def duplicate(b: B): B
def apply(i: Int): C =
get(buf, offset + i)
override def drop(n: Int): Chunk[C] =
if (n <= 0) this
else if (n >= size) Chunk.empty
else {
val second = duplicate(buf)
(second: JBuffer).position(n + offset)
buffer(second)
}
override def take(n: Int): Chunk[C] =
if (n <= 0) Chunk.empty
else if (n >= size) this
else {
val first = duplicate(buf)
(first: JBuffer).limit(n + offset)
buffer(first)
}
def copyToArray[O2 >: C](xs: Array[O2], start: Int): Unit = {
val b = duplicate(buf)
(b: JBuffer).position(offset)
(b: JBuffer).limit(offset + size)
val arr = new Array[C](size)
get(b, arr, 0, size)
arr.copyToArray(xs, start)
()
}
protected def splitAtChunk_(n: Int): (A, A) = {
val first = duplicate(buf)
(first: JBuffer).limit(n + offset)
val second = duplicate(buf)
(second: JBuffer).position(n + offset)
(buffer(first), buffer(second))
}
override def toArray[O2 >: C](implicit o2ct: ClassTag[O2]): Array[O2] =
if (o2ct.runtimeClass == ct.runtimeClass) {
val bs = new Array[O2](size)
val b = duplicate(buf)
(b: JBuffer).position(offset)
get(b, bs.asInstanceOf[Array[C]], 0, size)
bs
} else super.toArray
}
object CharBuffer {
def apply(buf: JCharBuffer): CharBuffer =
view(buf.duplicate())
def view(buf: JCharBuffer): CharBuffer =
new CharBuffer(buf, buf.position, buf.remaining)
}
case class CharBuffer(buf: JCharBuffer, override val offset: Int, override val size: Int)
extends Buffer[CharBuffer, JCharBuffer, Char](buf, offset, size) {
def readOnly(b: JCharBuffer): JCharBuffer =
b.asReadOnlyBuffer()
def get(b: JCharBuffer, n: Int) =
b.get(n)
def buffer(b: JCharBuffer): CharBuffer = CharBuffer.view(b)
override def get(b: JCharBuffer, dest: Array[Char], offset: Int, length: Int): JCharBuffer =
b.get(dest, offset, length)
def duplicate(b: JCharBuffer): JCharBuffer = b.duplicate()
override def toByteVector[B >: Char](implicit ev: B =:= Byte): ByteVector =
throw new UnsupportedOperationException
override def toArraySlice[O2 >: Char](implicit ct: ClassTag[O2]): Chunk.ArraySlice[O2] =
if (ct.runtimeClass == classOf[Char] && buf.hasArray)
Chunk
.ArraySlice(buf.array, buf.arrayOffset + offset, size)
.asInstanceOf[Chunk.ArraySlice[O2]]
else super.toArraySlice
override def toCharBuffer[C >: Char](implicit ev: C =:= Char): JCharBuffer = {
val b = buf.duplicate // share contents, independent position/limit
(b: JBuffer).position(offset.toInt)
(b: JBuffer).limit(offset.toInt + size)
b
}
}
/** Creates a chunk backed by an char buffer, bounded by the current position and limit */
def charBuffer(buf: JCharBuffer): Chunk[Char] = CharBuffer(buf)
object ByteBuffer {
def apply(buf: JByteBuffer): ByteBuffer =
view(buf.duplicate())
def view(buf: JByteBuffer): ByteBuffer =
new ByteBuffer(buf, buf.position, buf.remaining)
}
case class ByteBuffer private (
buf: JByteBuffer,
override val offset: Int,
override val size: Int
) extends Buffer[ByteBuffer, JByteBuffer, Byte](buf, offset, size) {
def readOnly(b: JByteBuffer): JByteBuffer =
b.asReadOnlyBuffer()
def get(b: JByteBuffer, n: Int) =
b.get(n)
def buffer(b: JByteBuffer): ByteBuffer = ByteBuffer.view(b)
override def get(b: JByteBuffer, dest: Array[Byte], offset: Int, length: Int): JByteBuffer =
b.get(dest, offset, length)
def duplicate(b: JByteBuffer): JByteBuffer = b.duplicate()
override def toByteVector[B >: Byte](implicit ev: B =:= Byte): ByteVector = {
val bb = buf.duplicate()
(bb: JBuffer).position(offset)
(bb: JBuffer).limit(offset + size)
ByteVector.view(bb)
}
override def toArraySlice[O2 >: Byte](implicit ct: ClassTag[O2]): Chunk.ArraySlice[O2] =
if (ct.runtimeClass == classOf[Byte] && buf.hasArray)
Chunk
.ArraySlice(buf.array, buf.arrayOffset + offset, size)
.asInstanceOf[Chunk.ArraySlice[O2]]
else super.toArraySlice
override def toByteBuffer[B >: Byte](implicit ev: B =:= Byte): JByteBuffer = {
val b = buf.duplicate // share contents, independent position/limit
(b: JBuffer).position(offset.toInt)
(b: JBuffer).limit(offset.toInt + size)
b
}
}
/** Creates a chunk backed by an byte buffer, bounded by the current position and limit */
def byteBuffer(buf: JByteBuffer): Chunk[Byte] = ByteBuffer(buf)
/** Creates a chunk backed by a byte vector. */
def byteVector(bv: ByteVector): Chunk[Byte] =
ByteVectorChunk(bv)
private case class ByteVectorChunk(bv: ByteVector) extends Chunk[Byte] {
def apply(i: Int): Byte =
bv(i.toLong)
def size: Int =
bv.size.toInt
def copyToArray[O2 >: Byte](xs: Array[O2], start: Int): Unit =
if (xs.isInstanceOf[Array[Byte]])
bv.copyToArray(xs.asInstanceOf[Array[Byte]], start)
else {
bv.toIndexedSeq.copyToArray(xs, start)
()
}
override def drop(n: Int): Chunk[Byte] =
if (n <= 0) this
else if (n >= size) Chunk.empty
else ByteVectorChunk(bv.drop(n.toLong))
override def take(n: Int): Chunk[Byte] =
if (n <= 0) Chunk.empty
else if (n >= size) this
else ByteVectorChunk(bv.take(n.toLong))
protected def splitAtChunk_(n: Int): (Chunk[Byte], Chunk[Byte]) = {
val (before, after) = bv.splitAt(n.toLong)
(ByteVectorChunk(before), ByteVectorChunk(after))
}
override def map[O2](f: Byte => O2): Chunk[O2] =
Chunk.indexedSeq(bv.toIndexedSeq.map(f))
override def toByteVector[B >: Byte](implicit ev: B =:= Byte): ByteVector = bv
@deprecated("Retained for bincompat", "3.2.12")
def toByteVector() = bv
override def toArraySlice[O2 >: Byte](implicit ct: ClassTag[O2]): Chunk.ArraySlice[O2] =
if (ct.runtimeClass == classOf[Byte])
Chunk.ArraySlice[Byte](bv.toArrayUnsafe, 0, size).asInstanceOf[Chunk.ArraySlice[O2]]
else super.toArraySlice
override def toByteBuffer[B >: Byte](implicit ev: B =:= Byte): JByteBuffer =
bv.toByteBuffer
}
/** Concatenates the specified sequence of chunks in to a single chunk, avoiding boxing. */
def concat[A: ClassTag](chunks: GSeq[Chunk[A]]): Chunk[A] =
concat(chunks, chunks.foldLeft(0)(_ + _.size))
/** Concatenates the specified sequence of chunks in to a single chunk, avoiding boxing.
* The `totalSize` parameter must be equal to the sum of the size of each chunk or
* otherwise an exception may be thrown.
*/
def concat[A: ClassTag](chunks: GSeq[Chunk[A]], totalSize: Int): Chunk[A] =
if (totalSize == 0)
Chunk.empty
else {
val arr = new Array[A](totalSize)
var offset = 0
chunks.foreach { c =>
if (!c.isEmpty) {
c.copyToArray(arr, offset)
offset += c.size
}
}
Chunk.array(arr)
}
/** Creates a chunk consisting of the elements of `queue`.
*/
def queue[A](queue: collection.immutable.Queue[A]): Chunk[A] = seq(queue)
/** Creates a chunk consisting of the first `n` elements of `queue` and returns the remainder.
*/
def queueFirstN[A](
queue: collection.immutable.Queue[A],
n: Int