-
Notifications
You must be signed in to change notification settings - Fork 61
/
BitVector.scala
2423 lines (2208 loc) · 80.4 KB
/
BitVector.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.nio.{ByteBuffer, ByteOrder}
import java.nio.charset.{CharacterCodingException, Charset}
import java.security.{
AlgorithmParameters,
GeneralSecurityException,
Key,
MessageDigest,
SecureRandom
}
import java.util.UUID
import java.util.zip.{DataFormatException, Deflater}
import javax.crypto.Cipher
/** Persistent vector of bits, stored as bytes.
*
* Bits are numbered left to right, starting at 0.
*
* @groupname collection Collection Like Methods
* @groupprio collection 0
*
* @groupname bitwise Bitwise Operations
* @groupprio bitwise 1
*
* @groupname conversions Conversions
* @groupprio conversions 2
*
* @groupname crypto Cryptography
* @groupprio crypto 3
*
* @define bitwiseOperationsReprDescription bit vector
*/
sealed abstract class BitVector
extends BitwiseOperations[BitVector, Long]
with Ordered[BitVector]
with Serializable {
import BitVector._
/** Returns number of bits in this vector.
*
* @group collection
*/
def size: Long
/** Alias for [[size]].
* @group collection
*/
final def length: Long = size
/** Returns true if this vector has no bits.
*
* @group collection
*/
final def isEmpty: Boolean = sizeLessThan(1)
/** Returns true if this vector has a non-zero number of bits.
*
* @group collection
*/
final def nonEmpty: Boolean = !isEmpty
/** Returns `true` if the size of this `BitVector` is greater than `n`. Unlike `size`, this
* forces this `BitVector` from left to right, halting as soon as it has a definite answer.
*
* @group collection
*/
final def sizeGreaterThan(n: Long): Boolean = n < 0 || !sizeLessThanOrEqual(n)
/** Returns `true` if the size of this `BitVector` is greater than or equal to `n`. Unlike `size`, this
* forces this `BitVector` from left to right, halting as soon as it has a definite answer.
*
* @group collection
*/
final def sizeGreaterThanOrEqual(n: Long): Boolean = n < 0 || !sizeLessThanOrEqual(n - 1)
/** Returns `true` if the size of this `BitVector` is less than `n`. Unlike `size`, this
* forces this `BitVector` from left to right, halting as soon as it has a definite answer.
*
* @group collection
*/
def sizeLessThan(n: Long): Boolean
/** Returns `true` if the size of this `BitVector` is less than or equal to `n`. Unlike `size`, this
* forces this `BitVector` from left to right, halting as soon as it has a definite answer.
*
* @group collection
*/
final def sizeLessThanOrEqual(n: Long): Boolean =
n == Long.MaxValue || sizeLessThan(n + 1)
/** Returns the number of bits 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
/** Returns true if the `n`th bit is high, false otherwise.
*
* @throws NoSuchElementException if `n >= size`
*
* @group collection
*/
def get(n: Long): Boolean
/** Returns the `n`th byte, 0-indexed.
*
* @throws NoSuchElementException if `n >= bytes.size`
*
* @group collection
*/
def getByte(n: Long): Byte
/** Alias for `get`.
*
* @group collection
* @see get(Long)
*/
final def apply(n: Long): Boolean = get(n)
/** Returns `Some(true)` if the `n`th bit is high, `Some(false)` if low, and `None` if `n >= size`.
*
* @group collection
*/
final def lift(n: Long): Option[Boolean] =
if (sizeGreaterThan(n)) Some(get(n))
else None
private[bits] def unchunk = this
/** Returns a new bit vector with the `n`th bit high if `high` is true or low if `high` is false.
*
* @group collection
*/
def update(n: Long, high: Boolean): BitVector
/** Returns a vector with the specified bit inserted at the specified index.
* @group collection
*/
final def insert(idx: Long, b: Boolean): BitVector =
(take(idx) :+ b) ++ drop(idx)
/** Returns a vector with the specified bit vector inserted at the specified index.
* @group collection
*/
final def splice(idx: Long, b: BitVector): BitVector =
take(idx) ++ b ++ drop(idx)
/** Returns a vector with the specified bit vector replacing bits `[idx, idx + b.size]`.
* @group collection
*/
final def patch(idx: Long, b: BitVector): BitVector =
take(idx) ++ b ++ drop(idx + b.size)
/** Returns a new bit vector with the `n`th bit high (and all other bits unmodified).
*
* @group collection
*/
final def set(n: Long): BitVector = update(n, true)
/** Returns a new bit vector with the `n`th bit low (and all other bits unmodified).
*
* @group collection
*/
final def clear(n: Long): BitVector = update(n, false)
/** Returns a new bit vector representing this vector's contents followed by the specified vector's contents.
*
* @group collection
*/
def ++(b2: BitVector): BitVector =
if (this.isEmpty) b2
else Chunks(Append(this, b2))
/** Returns a new vector with the specified bit prepended.
* @group collection
*/
final def +:(b: Boolean): BitVector = BitVector.bit(b) ++ this
/** Returns a new vector with the specified bit appended.
* @group collection
*/
final def :+(b: Boolean): BitVector = this ++ BitVector.bit(b)
/** Returns the depth of this tree. The result of `compact` has depth 0.
*/
private[bits] def depth: Int =
this match {
case Append(l, r) => 1 + (l.depth.max(r.depth))
case c: Chunks => 1 + c.chunks.depth
case _ => 0
}
/** Returns a vector of all bits in this vector except the first `n` bits.
*
* The resulting vector's size is `0 max (size - n)`.
*
* @group collection
*/
def drop(n: Long): BitVector
/** Returns a vector of all bits in this vector except the last `n` bits.
*
* The resulting vector's size is `0 max (size - n)`.
*
* @group collection
*/
final def dropRight(n: Long): BitVector =
if (n <= 0) this
else if (n >= size) BitVector.empty
else take(size - n)
/** Returns a vector of the first `n` bits of this vector.
*
* The resulting vector's size is `n min size`.
*
* Note: if an `n`-bit vector is required, use the `acquire` method instead.
*
* @see acquire
* @group collection
*/
def take(n: Long): BitVector
/** Returns a vector of the last `n` bits of this vector.
*
* The resulting vector's size is `n min size`.
*
* @group collection
*/
final def takeRight(n: Long): BitVector =
if (n < 0) throw new IllegalArgumentException(s"takeRight($n)")
else if (n >= size) this
else this.drop(size - n)
/** Returns a pair of vectors that is equal to `(take(n), drop(n))`.
* @group collection
*/
final def splitAt(n: Long): (BitVector, BitVector) = (take(n), drop(n))
/** Returns a vector made up of the bits starting at index `from` up to index `until`,
* not including the index `until`.
*
* @group collection
*/
final def slice(from: Long, until: Long): BitVector =
drop(from).take(until - (from.max(0)))
/** Returns a vector whose contents are the results of taking the first `n` bits of this vector.
*
* If this vector does not contain at least `n` bits, an error message is returned.
*
* @see take
* @group collection
*/
def acquire(n: Long): Either[String, BitVector] =
if (sizeGreaterThanOrEqual(n)) Right(take(n))
else Left(s"cannot acquire $n bits from a vector that contains $size bits")
/** Like `aquire`, but immediately consumes the `Either` via the pair of functions `err` and `f`.
*
* @see acquire
* @group collection
*/
final def acquireThen[R](n: Long)(err: String => R, f: BitVector => R): R =
if (sizeGreaterThanOrEqual(n)) f(take(n))
else err(s"cannot acquire $n bits from a vector that contains $size bits")
/** Consumes the first `n` bits of this vector and decodes them with the specified function,
* resulting in a vector of the remaining bits and the decoded value. If this vector
* does not have `n` bits or an error occurs while decoding, an error is returned instead.
*
* @group collection
*/
final def consume[A](
n: Long
)(decode: BitVector => Either[String, A]): Either[String, (BitVector, A)] =
for {
toDecode <- acquire(n)
decoded <- decode(toDecode)
} yield (drop(n), decoded)
/** If this vector has at least `n` bits, returns `f(take(n),drop(n))`,
* otherwise calls `err` with a meaningful error message. This function can be used
* to avoid intermediate allocations of `Either` objects when using `acquire` or `consume`
* directly.
*
* @see acquireThen
* @group collection
*/
final def consumeThen[R](n: Long)(err: String => R, f: (BitVector, BitVector) => R): R =
if (sizeGreaterThanOrEqual(n)) f(take(n), drop(n)) // todo unsafeTake, unsafeDrop
else err(s"cannot acquire $n bits from a vector that contains $size bits")
/** Returns true if this bit vector starts with the specified vector.
* @group collection
*/
final def startsWith(b: BitVector): Boolean =
take(b.size) === b
/** Returns true if this bit vector ends with the specified vector.
* @group collection
*/
final def endsWith(b: BitVector): Boolean =
takeRight(b.size) === b
/** Finds the first index of the specified bit pattern in this vector.
* @return index of slice or -1 if not found
* @group collection
*/
final def indexOfSlice(slice: BitVector): Long = indexOfSlice(slice, 0)
/** Finds the first index after `from` of the specified bit pattern in this vector.
* @return index of slice or -1 if not found
* @group collection
*/
final def indexOfSlice(slice: BitVector, from: Long): Long = {
@annotation.tailrec
def go(b: BitVector, 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: BitVector): 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(n: Long): Stream[BitVector] =
groupedIterator(n).toStream
private final def groupedIterator(n: Long): Iterator[BitVector] =
if (isEmpty) Iterator.empty
else Iterator(take(n)) ++ drop(n).groupedIterator(n)
/** Returns the first bit of this vector or throws if vector is emtpy.
* @group collection
*/
final def head: Boolean = get(0)
/** Returns the first bit of this vector or `None` if vector is emtpy.
* @group collection
*/
final def headOption: Option[Boolean] = lift(0)
/** Returns a vector of all bits in this vector except the first bit.
* @group collection
*/
final def tail: BitVector = drop(1)
/** Returns a vector of all bits in this vector except the last bit.
* @group collection
*/
final def init: BitVector = dropRight(1)
/** Returns the last bit in this vector or throws if vector is empty.
* @group collection
*/
final def last: Boolean = apply(size - 1)
/** Returns the last bit in this vector or returns `None` if vector is empty.
* @group collection
*/
final def lastOption: Option[Boolean] = lift(size - 1)
/** Alias for `padRight`.
*
* @throws IllegalArgumentException if `n < size`
* @group collection
*/
final def padTo(n: Long): BitVector = padRight(n)
/** Returns an `n`-bit vector whose contents are 0 or more low bits followed by this vector's contents.
*
* @throws IllegalArgumentException if `n < size`
* @group collection
*/
final def padRight(n: Long): BitVector =
if (n < size)
throw new IllegalArgumentException(
s"Trying to right-pad a vector of $size bits to only $n bits."
)
else this ++ BitVector.fill(n - size)(false)
/** Returns an `n`-bit vector whose contents are 0 or more low bits followed by this vector's contents.
*
* @throws IllegalArgumentException if `n < size`
* @group collection
*/
final def padLeft(n: Long): BitVector =
if (n < size)
throw new IllegalArgumentException(
s"Trying to left-pad a vector of $size bits to only $n bits."
)
else BitVector.fill(n - size)(false) ++ this
/** Reverse the bits of this vector.
*
* @group collection
*/
final def reverse: BitVector =
// todo: this has a log time implementation, assuming a balanced tree
BitVector(compact.underlying.reverse.map(reverseBitsInByte _))
.drop(8 - validBitsInLastByte(size))
/** Returns a new vector of the same size with the byte order reversed.
*
* Note that `reverseByteOrder.reverseByteOrder == identity` only when `size` is evenly divisble by 8.
* To invert `reverseByteOrder` for an arbitrary size, use `invertReverseByteOrder`.
*
* @group collection
*/
final def reverseByteOrder: BitVector =
if (size % 8 == 0) toBytes(compact.underlying.reverse, size)
else {
val validFinalBits = validBitsInLastByte(size)
val last = take(validFinalBits).compact
val b = drop(validFinalBits).toByteVector.reverse
val init = toBytes(b, size - last.size)
init ++ last
}
/** Inverse of `reverseByteOrder`.
*
* @group collection
*/
final def invertReverseByteOrder: BitVector =
if (size % 8 == 0) reverseByteOrder
else {
val validFinalBits = validBitsInLastByte(size)
val (init, last) = splitAt(size - validFinalBits)
last ++ init.bytes.reverse.bits
}
/** Returns a new vector of the same size with the bit order reversed.
*
* @group collection
*/
final def reverseBitOrder: BitVector =
BitVector(compact.underlying.map(reverseBitsInByte _)).drop(8 - validBitsInLastByte(size))
/** Returns the number of bits that are high.
*
* @group bitwise
*/
final def populationCount: Long = {
@annotation.tailrec
def go(b: BitVector, acc: Long): Long =
if (b.isEmpty) acc
else go(b.tail, if (b.head) acc + 1 else acc)
go(this, 0)
}
final def not: BitVector = mapBytes(_.not)
final def and(other: BitVector): BitVector = zipBytesWith(other)(_ & _)
final def or(other: BitVector): BitVector = zipBytesWith(other)(_ | _)
final def xor(other: BitVector): BitVector = zipBytesWith(other)(_ ^ _)
final def shiftLeft(n: Long): BitVector =
if (n <= 0) this
else if (n >= size) BitVector.low(size)
else drop(n) ++ BitVector.low(n)
final def shiftRight(n: Long, signExtension: Boolean): BitVector =
if (isEmpty || n <= 0) this
else {
val extensionHigh = signExtension && head
if (n >= size)
if (extensionHigh) BitVector.high(size) else BitVector.low(size)
else
(if (extensionHigh) BitVector.high(n) else BitVector.low(n)) ++ dropRight(n)
}
final def rotateLeft(n: Long): BitVector =
if (n <= 0) this
else if (isEmpty) this
else {
val n0 = n % size
if (n0 == 0) this
else drop(n0) ++ take(n0)
}
final def rotateRight(n: Long): BitVector =
if (n <= 0) this
else if (isEmpty) this
else {
val n0 = n % size
if (n0 == 0) this
else takeRight(n0) ++ dropRight(n0)
}
/** Return a `BitVector` with the same contents as `this`, but
* based off a single `ByteVector`.
*
* This may involve copying data to a fresh `ByteVector`, but
* has the advantage that lookups index directly into a single
* `ByteVector` 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: Bytes = {
if (bytesNeededForBits(size) > Int.MaxValue)
throw new IllegalArgumentException(
s"cannot compact bit vector of size ${size.toDouble / 8 / 1e9} GB"
)
// we collect up all the chunks, then merge them in O(n * log n)
@annotation.tailrec
def go(b: List[BitVector], acc: Vector[Bytes]): Vector[Bytes] =
b match {
case (s @ Suspend(_)) :: rem => go(s.underlying :: rem, acc)
case (b @ Bytes(_, _)) :: rem => go(rem, acc :+ b)
case Append(l, r) :: rem => go(l :: r :: rem, acc)
case (d: Drop) :: rem => go(rem, acc :+ d.interpretDrop)
case (c: Chunks) :: rem => go(c.chunks.left :: c.chunks.right :: rem, acc)
case _ => acc
}
this match {
// common case, we have a single flat `Bytes`, in which case we compact and return it directly
case bs @ Bytes(b, n) =>
val b2 = b.compact
if (b2 eq b) bs
else Bytes(b2, n)
// other common case is a drop of a single flat `Bytes`
case d: Drop =>
val bs = d.interpretDrop
val b2 = bs.underlying.compact
if (b2 eq bs.underlying) bs
else Bytes(b2, bs.size)
// otherwise we fall back to general purpose algorithm
case _ =>
reduceBalanced(go(List(this), Vector()))(_.size)(_.combine(_)) match {
case Bytes(b, n) => Bytes(b.compact, n) // we compact the underlying ByteVector as well
}
}
}
/** Produce a single flat `Bytes` by interpreting
* any non-byte-aligned appends or drops. Unlike
* `compact`, the underlying `ByteVector` is not
* necessarily copied.
*
* @group collection
*/
def align: Bytes
/** Return a `BitVector` with the same contents as `this`, but
* based off a single flat `ByteVector`. This function is guaranteed
* to copy all the bytes in this `BitVector`, unlike `compact`, which
* may no-op if this `BitVector` already consists of a single `ByteVector`
* chunk.
*
* @group collection
*/
final def copy: Bytes =
this match {
case Bytes(b, n) => Bytes(b.copy, n)
case _ => this.compact
}
/** Forces any `Suspend` nodes in this `BitVector` and ensures the tree is balanced.
*
* @group collection
*/
final def force: BitVector = {
@annotation.tailrec
def go(cont: Vector[BitVector]): BitVector =
if (cont.nonEmpty)
(cont.head, cont.tail) match {
case (cur, cont) =>
cur match {
case b @ Bytes(_, _) => cont.foldLeft[BitVector](b)(_ ++ _)
case Append(l, r) => go(l +: r +: cont)
case d @ Drop(_, _) => cont.foldLeft[BitVector](d)(_ ++ _)
case s @ Suspend(_) => go(s.underlying +: cont)
case b: Chunks => go(b.chunks +: cont)
}
}
else cont.foldLeft(BitVector.empty)(_ ++ _)
go(Vector(this))
}
/** Return the sequence of bits in this vector. The returned
* `IndexedSeq` is just a view; nothing is actually copied.
*
* @throws IllegalArgumentException if this vector's size exceeds Int.MaxValue
* @see acquire
* @see toIndexedSeq
* @group conversions
*/
final def toIndexedSeq: IndexedSeq[Boolean] =
intSize
.map { n =>
new IndexedSeq[Boolean] {
def length = n
def apply(idx: Int): Boolean = BitVector.this.get(idx.toLong)
override def foldRight[B](z: B)(op: (Boolean, B) => B): B = {
val it = reverseIterator
var b = z
while (it.hasNext)
b = op(it.next(), b)
b
}
}
}
.getOrElse {
throw new IllegalArgumentException(s"BitVector too big for Seq: $size")
}
/** Converts the contents of this vector to a byte vector.
*
* If this vector's size does not divide evenly by 8, the last byte of the returned vector
* will be zero-padded to the right.
*
* @group conversions
*/
final def toByteVector: ByteVector =
clearUnneededBits(size, compact.underlying)
/** Alias for [[toByteVector]].
* @group conversions
*/
final def bytes: ByteVector = toByteVector
/** Converts the contents of this vector to a byte array.
*
* If this vector's size does not divide evenly by 8, the last byte of the returned vector
* will be zero-padded to the right.
*
* @group conversions
*/
final def toByteArray: Array[Byte] = toByteVector.toArray
/** Converts the contents of this vector to a `java.nio.ByteBuffer`.
*
* The returned buffer is freshly allocated 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.
*
* @see toByteVector
* @group conversions
*/
final def toByteBuffer: java.nio.ByteBuffer = toByteVector.toByteBuffer
/** Converts the contents of this bit vector to a binary string of `size` digits.
*
* @group conversions
*/
final def toBin: String = toByteVector.toBin.take(size.toInt)
/** Converts the contents of this bit vector to a binary string of `size` digits.
*
* @group conversions
*/
final def toBin(alphabet: Bases.BinaryAlphabet): String =
toByteVector.toBin(alphabet).take(size.toInt)
/** Converts the contents of this bit vector to a hexadecimal string of `ceil(size / 4)` nibbles.
*
* The last nibble is right-padded with zeros if the size is not evenly divisible by 4.
*
* @group conversions
*/
final def toHex: String = toHex(Bases.Alphabets.HexLowercase)
/** Converts the contents of this bit vector to a hexadecimal string of `ceil(size / 4)` nibbles.
*
* The last nibble is right-padded with zeros if the size is not evenly divisible by 4.
*
* @group conversions
*/
final def toHex(alphabet: Bases.HexAlphabet): String = {
val full = toByteVector.toHex(alphabet)
size % 8 match {
case 0 => full
case n if n <= 4 => full.init
case _ => full
}
}
/** Helper alias of [[toHex():String*]]
*
* @group conversions
*/
final def toBase16: String = toHex
/** Helper alias of [[toHex(alpbabet: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.
*
* The last byte is right-padded with zeros if the size is not evenly divisible by 8.
*
* @group conversions
*/
final def toBase32: String = toBase32(Bases.Alphabets.Base32)
/** Converts the contents of this vector to a base 32 string using the specified alphabet.
*
* The last byte is right-padded with zeros if the size is not evenly divisible by 8.
*
* @group conversions
*/
final def toBase32(alphabet: Bases.Base32Alphabet): String = toByteVector.toBase32(alphabet)
/** Converts the contents of this vector to a base 58 string.
*
* the order is assumed to be the same as (Bitcoin)[[https://en.bitcoin.it/wiki/Base58Check_encoding#Base58_symbol_chart]]
*
* @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.
*
* the order is assumed to be the same as (Bitcoin)[[https://en.bitcoin.it/wiki/Base58Check_encoding#Base58_symbol_chart]]
*
* @group conversions
*/
final def toBase58(alphabet: Bases.Alphabet): String = toByteVector.toBase58(alphabet)
/** Converts the contents of this vector to a base 64 string.
*
* The last byte is right-padded with zeros if the size is not evenly divisible by 8.
*
* @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.
*
* The last byte is right-padded with zeros if the size is not evenly divisible by 8.
*
* @group conversions
*/
final def toBase64(alphabet: Bases.Base64Alphabet): String = toByteVector.toBase64(alphabet)
/** Converts the contents of this vector to a base 64 string without padding.
*
* @group conversions
*/
final def toBase64NoPad: String = toByteVector.toBase64NoPad
/** Converts the contents of this vector to a base 64 string without padding.
*
* @group conversions
*/
final def toBase64Url: String = toByteVector.toBase64Url
/** Converts the contents of this vector to a base 64 string without padding.
*
* @group conversions
*/
final def toBase64UrlNoPad: String = toByteVector.toBase64UrlNoPad
/** Convert a slice of bits from this vector (`start` until `start+bits`) to a `Byte`.
*
* @param signed whether sign extension should be performed
* @throws IllegalArgumentException if the slice refers to indices that are out of range
* @group conversions
*/
final def sliceToByte(start: Long, bits: Int, signed: Boolean = true): Byte =
if (start % 8 != 0) drop(start).sliceToByte(0, bits, signed)
else if (isEmpty || bits == 0) 0.toByte
else getByte(start, bits, signed)
private def getByte(start: Long, bits: Int, signed: Boolean): Byte = {
require(sizeGreaterThanOrEqual(start + bits) && bits >= 0 && bits <= 8)
var result = 0x0ff & getByte(start / 8)
if (bits != 0) result = result >>> (8 - bits)
// Sign extend if necessary
if (signed && bits != 8 && ((1 << (bits - 1)) & result) != 0) {
val toShift = 32 - bits
result = (result << toShift) >> toShift
}
result.toByte
}
/** 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 = {
require(sizeLessThanOrEqual(8))
if (isEmpty) 0.toByte
else getByte(0, size.toInt, signed)
}
/** Convert a slice of bits from this vector (`start` until `start+bits`) to a `Short`.
*
* @param signed whether sign extension should be performed
* @param ordering order bytes should be processed in
* @throws IllegalArgumentException if the slice refers to indices that are out of range
* @group conversions
*/
final def sliceToShort(
start: Long,
bits: Int,
signed: Boolean = true,
ordering: ByteOrdering = ByteOrdering.BigEndian
): Short =
if (start % 8 != 0) drop(start).sliceToShort(0, bits, signed, ordering)
else if (ordering == ByteOrdering.LittleEndian)
drop(start).invertReverseByteOrder.sliceToShort(0, bits, signed, ByteOrdering.BigEndian)
else getBigEndianShort(start, bits, signed)
private def getBigEndianShort(start: Long, bits: Int, signed: Boolean): Short = {
require(sizeGreaterThanOrEqual(start + bits) && bits >= 0 && bits <= 16)
val mod = bits % 8
var result = 0
val bytesNeeded = bytesNeededForBits(bits.toLong)
val base = start / 8
@annotation.tailrec
def go(i: Int): Unit =
if (i < bytesNeeded) {
result = (result << 8) | (0x0ff & this.getByte(base + i))
go(i + 1)
}
go(0)
if (mod != 0) result = result >>> (8 - mod)
// Sign extend if necessary
if (signed && bits != 16 && ((1 << (bits - 1)) & result) != 0) {
val toShift = 32 - bits
result = (result << toShift) >> toShift
}
result.toShort
}
/** 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 = {
require(sizeLessThanOrEqual(16))
if (ordering == ByteOrdering.LittleEndian)
invertReverseByteOrder.toShort(signed, ByteOrdering.BigEndian)
else getBigEndianShort(0, size.toInt, signed)
}
/** Convert a slice of bits from this vector (`start` until `start+bits`) to an `Int`.
*
* @param signed whether sign extension should be performed
* @param ordering order bytes should be processed in
* @throws IllegalArgumentException if the slice refers to indices that are out of range
* @group conversions
*/
final def sliceToInt(
start: Long,
bits: Int,
signed: Boolean = true,
ordering: ByteOrdering = ByteOrdering.BigEndian
): Int =
if (start % 8 != 0) drop(start).sliceToInt(0, bits, signed, ordering)
else if (ordering == ByteOrdering.LittleEndian)
drop(start).invertReverseByteOrder.sliceToInt(0, bits, signed, ByteOrdering.BigEndian)
else getBigEndianInt(start, bits, signed)
private def getBigEndianInt(start: Long, bits: Int, signed: Boolean): Int = {
require(sizeGreaterThanOrEqual(start + bits) && bits >= 0 && bits <= 32)
val mod = bits % 8
var result = 0
val bytesNeeded = bytesNeededForBits(bits.toLong)
val base = start / 8
@annotation.tailrec
def go(i: Int): Unit =
if (i < bytesNeeded) {
result = (result << 8) | (0x0ff & this.getByte(base + i))
go(i + 1)
}
go(0)
if (mod != 0) result = result >>> (8 - mod)
// Sign extend if necessary
if (signed && bits != 32 && ((1 << (bits - 1)) & result) != 0) {
val toShift = 32 - bits
result = (result << toShift) >> toShift
}
result
}
/** 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 = {
require(sizeLessThanOrEqual(32))
this match {
case bytes: Bytes =>
size.toInt match {
case 32 if signed =>
bytes.underlying.toByteBuffer.order(ordering.toJava).getInt
case 16 =>
val sh = bytes.underlying.toByteBuffer.order(ordering.toJava).getShort
if (signed) sh.toInt else sh & 0x0ffff
case 8 =>
val b = bytes.underlying.toByteBuffer.get
if (signed) b.toInt else b & 0x0ff
case bits =>
if (ordering == ByteOrdering.LittleEndian)
invertReverseByteOrder.toInt(signed, ByteOrdering.BigEndian)
else getBigEndianInt(0, bits, signed)
}
case _ =>
if (ordering == ByteOrdering.LittleEndian)
invertReverseByteOrder.toInt(signed, ByteOrdering.BigEndian)
else getBigEndianInt(0, size.toInt, signed)
}
}
/** Convert a slice of bits from this vector (`start` until `start+bits`) to a `Long`.
*
* @param signed whether sign extension should be performed
* @param ordering order bytes should be processed in
* @throws IllegalArgumentException if the slice refers to indices that are out of range
* @group conversions
*/
final def sliceToLong(
start: Long,
bits: Int,
signed: Boolean = true,
ordering: ByteOrdering = ByteOrdering.BigEndian
): Long =
if (start % 8 != 0) drop(start).sliceToLong(0, bits, signed, ordering)
else if (ordering == ByteOrdering.LittleEndian)
drop(start).invertReverseByteOrder.sliceToLong(0, bits, signed, ByteOrdering.BigEndian)
else getBigEndianLong(start, bits, signed)
private def getBigEndianLong(start: Long, bits: Int, signed: Boolean): Long = {
require(sizeGreaterThanOrEqual(start + bits) && bits >= 0 && bits <= 64)
val mod = bits % 8
var result = 0L
val bytesNeeded = bytesNeededForBits(bits.toLong)
val base = start / 8
@annotation.tailrec
def go(i: Int): Unit =
if (i < bytesNeeded) {
result = (result << 8) | (0x0ffL & this.getByte(base + i))
go(i + 1)
}
go(0)
if (mod != 0) result = result >>> (8 - mod)
// Sign extend if necessary
if (signed && bits != 64 && ((1L << (bits - 1)) & result) != 0) {
val toShift = 64 - bits
result = (result << toShift) >> toShift
}
result