/
ByteVector.scala
2330 lines (2092 loc) · 79.1 KB
/
ByteVector.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, Scodec
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package scodec.bits
import java.io.OutputStream
import java.nio.{ByteBuffer, CharBuffer}
import java.nio.charset.{CharacterCodingException, Charset}
import java.security.{
AlgorithmParameters,
GeneralSecurityException,
Key,
MessageDigest,
SecureRandom
}
import java.util.UUID
import java.util.concurrent.atomic.AtomicLong
import java.util.zip.{DataFormatException, Deflater, Inflater}
import javax.crypto.Cipher
import scala.annotation.tailrec
/** An immutable vector of bytes, backed by a balanced binary tree of
* chunks. Most operations are logarithmic in the depth of this tree,
* including `++`, `:+`, `+:`, `update`, and `insert`. Where possible,
* operations return lazy views rather than copying any underlying bytes.
* Use `copy` to copy all underlying bytes to a fresh, array-backed `ByteVector`.
*
* Unless otherwise noted, operations follow the same naming as the scala
* standard library collections, though this class does not extend any of the
* standard scala collections. Use `toIndexedSeq`, `toSeq`, or `toIterable`
* to obtain a regular `scala.collection` type.
*
* @groupname collection Collection Like Methods
* @groupprio collection 0
*
* @groupname bitwise Bitwise Operations
* @groupprio bitwise 1
*
* @groupname conversions Conversions
* @groupprio conversions 2
*
* @groupname buffer Buffering
* @groupprio buffer 3
*
* @groupname crypto Cryptography
* @groupprio crypto 4
*
* @define bitwiseOperationsReprDescription bit vector
* @define returnsView This method returns a view and hence, is O(1). Call [[compact]] to generate a new strict vector.
*/
sealed abstract class ByteVector
extends BitwiseOperations[ByteVector, Long]
with Ordered[ByteVector]
with Serializable {
import ByteVector._
/** Returns the number of bytes in this vector.
* @group collection
*/
def size: Long
/** Returns the number of bytes in this vector, or `None` if the size does not
* fit into an `Int`.
*
* @group collection
*/
final def intSize: Option[Int] = if (size <= Int.MaxValue) Some(size.toInt) else None
/** Alias for [[size]].
* @group collection
*/
final def length: Long = size
/** Returns true if this vector has no bytes.
* @group collection
*/
final def isEmpty: Boolean = size == 0
/** Returns true if this vector has a non-zero number of bytes.
* @group collection
*/
final def nonEmpty: Boolean = !isEmpty
/** Gets the byte at the specified index.
* @throws IndexOutOfBoundsException if the specified index is not in `[0, size)`
* @group collection
*/
def get(index: Long): Byte = {
checkIndex(index)
getImpl(index)
}
protected def getImpl(index: Long): Byte
/** Alias for [[get]].
* @throws IndexOutOfBoundsException if the specified index is not in `[0, size)`
* @group collection
*/
final def apply(index: Long): Byte = get(index)
/** Returns the byte at the specified index, or `None` if the index is out of range.
* @group collection
*/
final def lift(index: Long): Option[Byte] =
if (index >= 0 && index < size) Some(apply(index))
else None
/** Returns a vector with the byte at the specified index replaced with the specified byte.
* @group collection
*/
final def update(idx: Long, b: Byte): ByteVector = {
checkIndex(idx)
(take(idx) :+ b) ++ drop(idx + 1)
}
/** Returns a vector with the specified byte inserted at the specified index.
* @group collection
*/
final def insert(idx: Long, b: Byte): ByteVector =
(take(idx) :+ b) ++ drop(idx)
/** Returns a vector with the specified byte vector inserted at the specified index.
* @group collection
*/
final def splice(idx: Long, b: ByteVector): ByteVector =
take(idx) ++ b ++ drop(idx)
/** Returns a vector with the specified byte vector replacing bytes `[idx, idx + b.size]`.
* @group collection
*/
final def patch(idx: Long, b: ByteVector): ByteVector =
take(idx) ++ b ++ drop(idx + b.size)
/** Returns a new byte vector representing this vector's contents followed by the specified vector's contents.
* @group collection
*/
def ++(other: ByteVector): ByteVector =
if (this.isEmpty) other
else Chunks(Append(this, other)).bufferBy(64)
/** Returns a new vector with the specified byte prepended.
* @group collection
*/
final def +:(byte: Byte): ByteVector = ByteVector(byte) ++ this
/** Returns a new vector with the specified byte appended.
* @group collection
*/
def :+(byte: Byte): ByteVector =
this ++ ByteVector(byte)
/** Returns a vector of all bytes in this vector except the first `n` bytes.
*
* The resulting vector's size is `0 max (size - n)`.
*
* @group collection
*/
def drop(n: Long): ByteVector = {
val n1 = n.min(size).max(0)
if (n1 == size) ByteVector.empty
else if (n1 == 0) this
else {
@annotation.tailrec
def go(cur: ByteVector, n1: Long, accR: List[ByteVector]): ByteVector =
cur match {
case Chunk(bs) => accR.foldLeft(Chunk(bs.drop(n1)): ByteVector)(_ ++ _).unbuffer
case Append(l, r) =>
if (n1 > l.size) go(r, n1 - l.size, accR)
else go(l, n1, r :: accR)
case b: Buffer =>
if (n1 > b.hd.size) go(b.lastBytes, n1 - b.hd.size, accR)
else go(b.hd, n1, b.lastBytes :: accR)
case c: Chunks => go(c.chunks, n1, accR)
}
go(this, n1, Nil)
}
}
/** Returns a vector of all bytes in this vector except the last `n` bytes.
*
* The resulting vector's size is `0 max (size - n)`.
*
* @group collection
*/
final def dropRight(n: Long): ByteVector =
take(size - n.max(0))
/** Drops the longest prefix of this vector such that every byte of the prefix satisfies the specific predicate.
*
* @group collection
*/
final def dropWhile(f: Byte => Boolean): ByteVector = {
var toDrop = 0L
foreachSPartial(new F1BB {
def apply(b: Byte) = {
val cont = f(b)
if (cont) toDrop += 1
cont
}
})
drop(toDrop)
}
/** Returns a vector of the first `n` bytes of this vector.
*
* The resulting vector's size is `n min size`.
*
* Note: if an `n`-byte vector is required, use the `acquire` method instead.
*
* @see acquire
* @group collection
*/
def take(n: Long): ByteVector = {
val n1 = n.min(size).max(0)
if (n1 == size) this
else if (n1 == 0) ByteVector.empty
else {
@annotation.tailrec
def go(accL: ByteVector, cur: ByteVector, n1: Long): ByteVector =
cur match {
case Chunk(bs) => accL ++ Chunk(bs.take(n1))
case Append(l, r) =>
if (n1 > l.size) go(accL ++ l, r, n1 - l.size)
else go(accL, l, n1)
case c: Chunks => go(accL, c.chunks, n1)
case b: Buffer => go(accL, b.unbuffer, n1)
}
go(ByteVector.empty, this, n1)
}
}
/** Returns a vector of the last `n` bytes of this vector.
*
* The resulting vector's size is `n min size`.
*
* @group collection
*/
final def takeRight(n: Long): ByteVector =
drop(size - n)
/** Returns the longest prefix of this vector such that every byte satisfies the specific predicate.
*
* @group collection
*/
final def takeWhile(f: Byte => Boolean): ByteVector = {
var toTake = 0L
foreachSPartial(new F1BB {
def apply(b: Byte) = {
val cont = f(b)
if (cont) toTake += 1
cont
}
})
take(toTake)
}
/** Returns a pair of vectors that is equal to `(take(n), drop(n))`.
* @group collection
*/
final def splitAt(n: Long): (ByteVector, ByteVector) = (take(n), drop(n))
/** Returns a vector made up of the bytes starting at index `from` up to index `until`.
* @group collection
*/
final def slice(from: Long, until: Long): ByteVector =
drop(from).take(until - (from.max(0)))
/** Returns a vector whose contents are the results of taking the first `n` bytes of this vector.
*
* If this vector does not contain at least `n` bytes, an error message is returned.
*
* @see take
* @group collection
*/
def acquire(n: Long): Either[String, ByteVector] =
if (n <= size) Right(take(n))
else Left(s"cannot acquire $n bytes from a vector that contains $size bytes")
/** Consumes the first `n` bytes of this vector and decodes them with the specified function,
* resulting in a vector of the remaining bytes and the decoded value. If this vector
* does not have `n` bytes or an error occurs while decoding, an error is returned instead.
*
* @group collection
*/
final def consume[A](
n: Long
)(decode: ByteVector => Either[String, A]): Either[String, (ByteVector, A)] =
for {
toDecode <- acquire(n)
decoded <- decode(toDecode)
} yield (drop(n), decoded)
/** Applies a binary operator to a start value and all elements of this vector, going left to right.
* @param z starting value
* @param f operator to apply
* @group collection
*/
final def foldLeft[A](z: A)(f: (A, Byte) => A): A = {
var acc = z
foreachS(new F1BU { def apply(b: Byte) = acc = f(acc, b) })
acc
}
/** Applies a binary operator to a start value and all elements of this vector, going right to left.
* @param z starting value
* @param f operator to apply
* @group collection
*/
final def foldRight[A](z: A)(f: (Byte, A) => A): A =
reverse.foldLeft(z)((tl, h) => f(h, tl))
/** Applies a binary operator to a start value and all segments(views) of this ByteVector expressed as read-only ByteBuffer, going left to right.
* @param z Starting value
* @param f operator to apply
* @group collection
*/
final def foldLeftBB[A](z: A)(f: (A, ByteBuffer) => A): A = {
@annotation.tailrec
def go(rem: List[ByteVector], a: A): A =
rem match {
case Chunk(bs) :: rem => go(rem, f(a, bs.at.asByteBuffer(bs.offset, bs.size.toInt)))
case Append(l, r) :: rem => go(l :: r :: rem, a)
case Chunks(Append(l, r)) :: rem => go(l :: r :: rem, a)
case (b: Buffer) :: rem => go(b.unbuffer :: rem, a)
case Nil => a
}
go(this :: Nil, z)
}
/** Applies a binary operator to a start value and all segments(views) of this ByteVector expressed as read-only ByteBuffer, going right ot left.
* @param z Starting value
* @param f operator to apply
* @group collection
*/
final def foldRightBB[A](z: A)(f: (ByteBuffer, A) => A): A =
reverse.foldLeftBB(z)((tl, h) => f(h, tl))
/** Applies the specified function to each element of this vector.
* @group collection
*/
final def foreach(f: Byte => Unit): Unit = foreachS(new F1BU { def apply(b: Byte) = f(b) })
private[scodec] final def foreachS(f: F1BU): Unit = foreachV(_.foreach(f))
private[scodec] final def foreachSPartial(f: F1BB): Boolean = foreachVPartial(_.foreachPartial(f))
private[scodec] final def foreachV(f: View => Unit): Unit = {
@annotation.tailrec
def go(rem: List[ByteVector]): Unit =
rem match {
case Chunk(bs) :: rem => f(bs); go(rem)
case Append(l, r) :: rem => go(l :: r :: rem)
case Chunks(Append(l, r)) :: rem => go(l :: r :: rem)
case (b: Buffer) :: rem => go(b.unbuffer :: rem)
case Nil => ()
}
go(this :: Nil)
}
private[scodec] final def foreachVPartial(f: View => Boolean): Boolean = {
@annotation.tailrec
def go(rem: List[ByteVector]): Boolean =
rem match {
case Chunk(bs) :: rem => if (f(bs)) go(rem) else false
case Append(l, r) :: rem => go(l :: r :: rem)
case Chunks(Append(l, r)) :: rem => go(l :: r :: rem)
case (b: Buffer) :: rem => go(b.unbuffer :: rem)
case Nil => true
}
go(this :: Nil)
}
/** Returns true if this byte vector starts with the specified vector.
* @group collection
*/
final def startsWith(b: ByteVector): Boolean =
take(b.size) === b
/** Returns true if this byte vector ends with the specified vector.
* @group collection
*/
final def endsWith(b: ByteVector): Boolean =
takeRight(b.size) === b
/** Finds the first index of the specified byte pattern in this vector.
* @return index of slice or -1 if not found
* @group collection
*/
final def indexOfSlice(slice: ByteVector): Long = indexOfSlice(slice, 0)
/** Finds the first index after `from` of the specified byte pattern in this vector.
* @return index of slice or -1 if not found
* @group collection
*/
final def indexOfSlice(slice: ByteVector, from: Long): Long = {
@annotation.tailrec
def go(b: ByteVector, idx: Long): Long =
if (b.startsWith(slice)) idx
else if (b.isEmpty) -1
else go(b.tail, idx + 1)
go(drop(from), from)
}
/** Determines if the specified slice is in this vector.
* @group collection
*/
final def containsSlice(slice: ByteVector): Boolean = indexOfSlice(slice) >= 0
// This was public before version 1.1.8 so it must stay here for bincompat
// The public grouped method is adding via an extension method defined in the companion
private[bits] final def grouped(chunkSize: Long): Stream[ByteVector] =
groupedIterator(chunkSize).toStream
private final def groupedIterator(chunkSize: Long): Iterator[ByteVector] =
if (isEmpty) Iterator.empty
else if (size <= chunkSize) Iterator(this)
else Iterator(take(chunkSize)) ++ drop(chunkSize).groupedIterator(chunkSize)
/** Returns the first byte of this vector or throws if vector is emtpy.
* @group collection
*/
final def head: Byte = apply(0)
/** Returns the first byte of this vector or `None` if vector is emtpy.
* @group collection
*/
final def headOption: Option[Byte] = lift(0)
/** Returns a vector of all bytes in this vector except the first byte.
* @group collection
*/
final def tail: ByteVector = drop(1)
/** Returns a vector of all bytes in this vector except the last byte.
* @group collection
*/
final def init: ByteVector = dropRight(1)
/** Returns the last byte in this vector or throws if vector is empty.
* @group collection
*/
final def last: Byte = apply(size - 1)
/** Returns the last byte in this vector or returns `None` if vector is empty.
* @group collection
*/
final def lastOption: Option[Byte] = lift(size - 1)
/** Alias for `padRight`.
*
* @throws IllegalArgumentException if `n < size`
* @group collection
*/
final def padTo(n: Long): ByteVector = padRight(n)
/** Returns an `n`-byte vector whose contents are this vector's contents followed by 0 or more zero bytes.
*
* @throws IllegalArgumentException if `n < size`
* @group collection
*/
final def padRight(n: Long): ByteVector =
if (n < size) throw new IllegalArgumentException(s"ByteVector.padRight($n)")
else this ++ ByteVector.fill(n - size)(0)
/** Returns an `n`-bytes vector whose contents are 0 or more zero bytes followed by this vector's contents.
*
* @throws IllegalArgumentException if `n < size`
* @group collection
*/
final def padLeft(n: Long): ByteVector =
if (n < size) throw new IllegalArgumentException(s"ByteVector.padLeft($n)")
else ByteVector.fill(n - size)(0) ++ this
/** Returns a vector where each byte is the result of applying the specified function to the corresponding byte in this vector.
* $returnsView
* @group collection
*/
final def map(f: Byte => Byte): ByteVector =
ByteVector.viewAt((i: Long) => f(apply(i)), size)
/** Returns a vector where each byte is the result of applying the specified function to the corresponding byte in this vector.
* Only the least significant byte is used (the three most significant bytes are ignored).
* $returnsView
* @group collection
*/
final def mapI(f: Byte => Int): ByteVector =
map(f.andThen(_.toByte))
private[scodec] final def mapS(f: F1B): ByteVector =
ByteVector.view(new At { def apply(i: Long) = f(ByteVector.this(i)) }, size)
/** Returns a vector with the bytes of this vector in reverse order.
* $returnsView
* @group collection
*/
final def reverse: ByteVector =
ByteVector.viewAt((l: Long) => apply(size - l - 1), size)
final def shiftLeft(n: Long): ByteVector =
BitVector(this).shiftLeft(n).toByteVector
final def shiftRight(n: Long, signExtension: Boolean): ByteVector =
BitVector(this).shiftRight(n, signExtension).toByteVector
final def rotateLeft(n: Long): ByteVector =
BitVector(this).rotateLeft(n).toByteVector
final def rotateRight(n: Long): ByteVector =
BitVector(this).rotateRight(n).toByteVector
/** Returns a vector with the same contents but represented as a single tree node internally.
*
* This may involve copying data, but has the advantage that lookups index directly into a single
* node rather than traversing a logarithmic number of nodes in this tree.
*
* Calling this method on an already compacted vector is a no-op.
*
* @group collection
*/
final def compact: ByteVector =
this match {
case Chunk(_) => this
case _ => this.copy
}
/** Invokes `compact` on any subtrees whose size is `<= chunkSize`.
* @group collection
*/
final def partialCompact(chunkSize: Long): ByteVector =
this match {
case small if small.size <= chunkSize => small.compact
case Append(l, r) => Append(l.partialCompact(chunkSize), r.partialCompact(chunkSize))
case _ => this
}
/** Returns a vector with the same contents as this vector but with a single compacted node made up
* by evaluating all internal nodes and concatenating their values.
* @group collection
*/
final def copy: ByteVector = {
val sz = size
if (sz <= Int.MaxValue) {
val arr = this.toArray
Chunk(View(new AtArray(arr), 0, sz))
} else
take(Int.MaxValue).copy ++ drop(Int.MaxValue).copy
}
/** Converts the contents of this vector to a byte array.
*
* @group conversions
*/
final def toArray: Array[Byte] = {
val buf = new Array[Byte](toIntSize(size))
copyToArray(buf, 0)
buf
}
/** Copies the contents of this vector to array `xs`, beginning at index `start`.
*
* @group conversions
*/
final def copyToArray(xs: Array[Byte], start: Int): Unit = {
var i = start
foreachV { v =>
v.copyToArray(xs, i); i += toIntSize(v.size)
}
}
/** Copies `size` bytes of this vector, starting at index `offset`, to array `xs`, beginning at index `start`.
*
* @group conversions
*/
final def copyToArray(xs: Array[Byte], start: Int, offset: Long, size: Int): Unit = {
var i = 0L
var voffset = 0L
foreachV { v =>
if (i < size) {
val reloff = (offset - voffset).max(0)
if (voffset >= offset || reloff < v.size) {
val sz = (size - i).min(v.size - reloff)
v.copyToArray(xs, toIntSize(start + i), reloff, toIntSize(sz))
i += sz
}
voffset += v.size
}
}
}
/** Copies as many bytes as possible to the given [[ByteBuffer]], starting from its
* current position. This method will not overflow the buffer.
*
* @param buffer a ByteBuffer to copy bytes to
* @return the number of bytes actually copied
* @group conversions
*/
final def copyToBuffer(buffer: ByteBuffer): Int = {
var copied = 0
foreachVPartial { v =>
val copiedFromView = v.copyToBuffer(buffer)
copied += copiedFromView
(copiedFromView == v.size)
}
copied
}
/** Copies the contents of this vector to OutputStream `s`.
*
* @group conversions
*/
final def copyToStream(s: OutputStream): Unit =
foreachV(_.copyToStream(s))
/** Converts the contents of this vector to an `IndexedSeq`.
*
* @group conversions
*/
final def toIndexedSeq: IndexedSeq[Byte] =
new IndexedSeq[Byte] {
val length = toIntSize(ByteVector.this.size)
def apply(i: Int) = ByteVector.this.apply(i.toLong)
override def foldRight[B](z: B)(op: (Byte, B) => B): B = ByteVector.this.foldRight(z)(op)
}
/** Converts the contents of this vector to a `Seq`.
*
* @group conversions
*/
final def toSeq: Seq[Byte] = toIndexedSeq
/** Converts the contents of this vector to an `Iterable`.
*
* @group conversions
*/
final def toIterable: Iterable[Byte] = toIndexedSeq
/** Converts the contents of this vector to a bit vector of `size * 8` bits.
* @group conversions
*/
final def toBitVector: BitVector = BitVector(this)
/** Alias for [[toBitVector]].
* @group conversions
*/
final def bits: BitVector = toBitVector
/** Allocate (unobservable) mutable scratch space at the end of this
* `ByteVector`, which will be used to support fast `:+` and `++`
* of small vectors. A default chunk size is used.
*
* Note that `:+`, `++`, and `drop` on the result of a call to `buffer`
* are guaranteed to return another buffered `ByteVector`.
*
* @group buffer
*/
final def buffer: ByteVector = bufferBy(1024)
/** Allocate (unobservable) mutable scratch space at the end of this
* `ByteVector`, with chunks of the given size, which will be used to
* support fast `:+` and `++` of small vectors.
*
* Note that `:+`, `++`, and `drop` on the result of a call to `buffer`
* are guaranteed to return another buffered `ByteVector`, with the
* same size scratch space.
*
* @group buffer
*/
final def bufferBy(chunkSize: Int): ByteVector =
this match {
case b: Buffer =>
if (b.lastChunk.length >= chunkSize) b
else b.rebuffer(chunkSize)
case _ => Buffer(new AtomicLong(0), 0, this, new Array[Byte](chunkSize), 0)
}
/** Collapse any buffered chunks at the end of this `ByteVector`,
* resulting in an unbuffered `ByteVector`.
*
* @group buffer
*/
def unbuffer: ByteVector = this
/** Represents the contents of this vector as a read-only `java.nio.ByteBuffer`.
*
* The returned buffer is read-only with limit set to the minimum number of bytes needed to
* represent the contents of this vector, position set to zero, and remaining set to the limit.
*
* @group conversions
*/
final def toByteBuffer: ByteBuffer =
this match {
case Chunk(v) => v.asByteBuffer
case _ => ByteBuffer.wrap(toArray).asReadOnlyBuffer()
}
/** Converts the contents of this byte vector to a binary string of `size * 8` digits.
*
* @group conversions
*/
final def toBin: String = toBin(Bases.Alphabets.Binary)
/** Converts the contents of this byte vector to a binary string of `size * 8` digits.
*
* @group conversions
*/
final def toBin(alphabet: Bases.BinaryAlphabet): String = {
val bldr = new StringBuilder
foreachS {
new F1BU {
def apply(b: Byte) = {
var n = 7
while (n >= 0) {
val idx = 1 & (b >> n)
bldr.append(alphabet.toChar(idx))
n -= 1
}
}
}
}
bldr.toString
}
/** Converts the contents of this byte vector to a hexadecimal string of `size * 2` nibbles.
*
* @group conversions
*/
final def toHex: String = toHex(Bases.Alphabets.HexLowercase)
/** Converts the contents of this byte vector to a hexadecimal string of `size * 2` nibbles.
*
* @group conversions
*/
final def toHex(alphabet: Bases.HexAlphabet): String = {
val bldr = new StringBuilder
foreachS {
new F1BU {
def apply(b: Byte) = {
bldr
.append(alphabet.toChar((b >> 4 & 0x0f).toByte.toInt))
.append(alphabet.toChar((b & 0x0f).toByte.toInt))
()
}
}
}
bldr.toString
}
/** Helper alias for [[toHex:String*]]
*
* @group conversions
*/
final def toBase16: String = toHex
/** Helper alias for [[toHex(alphabet:scodec\.bits\.Bases\.HexAlphabet):String*]]
*
* @group conversions
*/
final def toBase16(alphabet: Bases.HexAlphabet): String = toHex(alphabet)
/** Converts the contents of this vector to a base 32 string.
*
* @group conversions
*/
final def toBase32: String = toBase32(Bases.Alphabets.Base32)
/** Selects at most 8 bits from a byte array as a right aligned byte */
private final def bitsAtOffset(bytes: Array[Byte], bitIndex: Long, length: Int): Int = {
val i = (bitIndex / 8).toInt
if (i >= bytes.length) 0
else {
val off = (bitIndex - (i * 8)).toInt
val mask = ((1 << length) - 1) << (8 - length)
val half = (bytes(i) << off) & mask
val full =
if (off + length <= 8 || i + 1 >= bytes.length) half
else half | ((bytes(i + 1) & ((mask << (8 - off)) & 0xff)) >>> (8 - off))
full >>> (8 - length)
}
}
/** Converts the contents of this vector to a base 32 string using the specified alphabet.
*
* @group conversions
*/
final def toBase32(alphabet: Bases.Base32Alphabet): String = {
val bitsPerChar = 5
val bytesPerGroup = 5
val charsPerGroup = bytesPerGroup * 8 / bitsPerChar
val bytes = toArray
val bldr =
CharBuffer.allocate((bytes.length + bytesPerGroup - 1) / bytesPerGroup * charsPerGroup)
{
var bidx: Long = 0
while ((bidx / 8) < bytes.length) {
val char = alphabet.toChar(bitsAtOffset(bytes, bidx, bitsPerChar))
bldr.append(char)
bidx += bitsPerChar
}
}
if (alphabet.pad != 0.toChar) {
val padLen =
(((bytes.length + bitsPerChar - 1) / bitsPerChar * bitsPerChar) - bytes.length) * 8 / bitsPerChar
var i = 0
while (i < padLen) {
bldr.append(alphabet.pad)
i += 1
}
}
bldr.flip.toString
}
/** Converts the contents of this vector to a base 58 string.
*
* @group conversions
*/
final def toBase58: String = toBase58(Bases.Alphabets.Base58)
/** Converts the contents of this vector to a base 58 string using the specified alphabet.
*
* @group conversions
*/
final def toBase58(alphabet: Bases.Alphabet): String =
if (isEmpty)
""
else {
val ZERO = BigInt(0)
val RADIX = BigInt(58L)
val ones = List.fill(takeWhile(_ == 0).length.toInt)('1')
@tailrec
def go(value: BigInt, chars: List[Char]): String =
value match {
case ZERO => (ones ++ chars).mkString
case _ =>
val (div, rem) = value /% RADIX
go(div, alphabet.toChar(rem.toInt) +: chars)
}
go(BigInt(1, toArray), List.empty)
}
/** Converts the contents of this vector to a base 64 string.
*
* @group conversions
*/
final def toBase64: String = toBase64(Bases.Alphabets.Base64)
/** Converts the contents of this vector to a base 64 string using the specified alphabet.
*
* @group conversions
*/
final def toBase64(alphabet: Bases.Base64Alphabet): String = {
val bytes = toArray
val bldr = CharBuffer.allocate(((bytes.length + 2) / 3) * 4)
var idx = 0
val mod = bytes.length % 3
while (idx < bytes.length - mod) {
var buffer =
((bytes(idx) & 0x0ff) << 16) | ((bytes(idx + 1) & 0x0ff) << 8) | (bytes(idx + 2) & 0x0ff)
val fourth = buffer & 0x3f
buffer = buffer >> 6
val third = buffer & 0x3f
buffer = buffer >> 6
val second = buffer & 0x3f
buffer = buffer >> 6
val first = buffer
bldr
.append(alphabet.toChar(first))
.append(alphabet.toChar(second))
.append(alphabet.toChar(third))
.append(alphabet.toChar(fourth))
idx = idx + 3
}
if (mod == 1) {
var buffer = (bytes(idx) & 0x0ff) << 4
val second = buffer & 0x3f
buffer = buffer >> 6
val first = buffer
bldr
.append(alphabet.toChar(first))
.append(alphabet.toChar(second))
if (alphabet.pad != 0.toChar)
bldr
.append(alphabet.pad)
.append(alphabet.pad)
} else if (mod == 2) {
var buffer = ((bytes(idx) & 0x0ff) << 10) | ((bytes(idx + 1) & 0x0ff) << 2)
val third = buffer & 0x3f
buffer = buffer >> 6
val second = buffer & 0x3f
buffer = buffer >> 6
val first = buffer
bldr
.append(alphabet.toChar(first))
.append(alphabet.toChar(second))
.append(alphabet.toChar(third))
if (alphabet.pad != 0.toChar) bldr.append(alphabet.pad)
}
bldr.flip.toString
}
/** Converts the contents of this vector to a base 64 string without padding.
*
* @group conversions
*/
final def toBase64NoPad: String = toBase64(Bases.Alphabets.Base64NoPad)
/** Converts the contents of this vector to a base 64 url string with padding.
*
* @group conversions
*/
final def toBase64Url: String = toBase64(Bases.Alphabets.Base64Url)
/** Converts the contents of this vector to a base 64 url string without padding.
*
* @group conversions
*/
final def toBase64UrlNoPad: String = toBase64(Bases.Alphabets.Base64UrlNoPad)
/** Converts the contents of this vector to a byte.
*
* @param signed whether sign extension should be performed
* @throws IllegalArgumentException if size is greater than 8
* @group conversions
*/
final def toByte(signed: Boolean = true): Byte =
bits.toByte(signed)
/** Converts the contents of this vector to a short.
*
* @param signed whether sign extension should be performed
* @param ordering order bytes should be processed in
* @throws IllegalArgumentException if size is greater than 16
* @group conversions
*/
final def toShort(
signed: Boolean = true,
ordering: ByteOrdering = ByteOrdering.BigEndian
): Short =
bits.toShort(signed, ordering)
/** Converts the contents of this vector to an int.
*
* @param signed whether sign extension should be performed
* @param ordering order bytes should be processed in
* @throws IllegalArgumentException if size is greater than 32
* @group conversions
*/
final def toInt(signed: Boolean = true, ordering: ByteOrdering = ByteOrdering.BigEndian): Int =
bits.toInt(signed, ordering)
/** Converts the contents of this vector to an int.
*
* @param signed whether sign extension should be performed
* @param ordering order bytes should be processed in
* @throws IllegalArgumentException if size is greater than 64
* @group conversions
*/
final def toLong(signed: Boolean = true, ordering: ByteOrdering = ByteOrdering.BigEndian): Long =
bits.toLong(signed, ordering)
/** Converts the contents of this byte vector to a UUID.
*
* @throws IllegalArgumentException if size is not exactly 16.