1
1
import Foundation
2
2
3
3
public struct Binary {
4
- private let bytes : [ UInt8 ]
4
+ public let bytes : [ UInt8 ]
5
+ var readingOffset : Int = 0
5
6
6
7
public init ( bytes: [ UInt8 ] ) {
7
8
self . bytes = bytes
@@ -22,10 +23,6 @@ public struct Binary {
22
23
return ( byte >> bitPosition) & 0x01
23
24
}
24
25
25
- public func bit( position: Int ) -> Bit {
26
- return self . bit ( position) == 1 ? Bit . One : Bit . Zero
27
- }
28
-
29
26
public func bits( range: Range < Int > ) -> Int {
30
27
return range. reverse ( ) . enumerate ( ) . reduce ( 0 ) {
31
28
$0 + ( bit ( $1. element) << $1. index)
@@ -48,4 +45,34 @@ public struct Binary {
48
45
return bits ( start*8, length*8)
49
46
}
50
47
51
- }
48
+ public func bitsWithInternalOffsetAvailable( length: Int ) -> Bool {
49
+ return ( self . bytes. count * 8 ) >= ( self . readingOffset + length)
50
+ }
51
+
52
+ public mutating func next( bits length: Int ) -> Int {
53
+ if self . bitsWithInternalOffsetAvailable ( length) {
54
+ let returnValue = self . bits ( self . readingOffset, length)
55
+ self . readingOffset = self . readingOffset + length
56
+ return returnValue
57
+ } else {
58
+ fatalError ( " Couldn't extract Bits. " )
59
+ }
60
+ }
61
+
62
+ public func bytesWithInternalOffsetAvailable( length: Int ) -> Bool {
63
+ let availableBits = self . bytes. count * 8
64
+ let requestedBits = readingOffset + ( length * 8 )
65
+ let possible = availableBits >= requestedBits
66
+ return possible
67
+ }
68
+
69
+ public mutating func next( bytes length: Int ) -> [ UInt8 ] {
70
+ if bytesWithInternalOffsetAvailable ( length) {
71
+ let returnValue = self . bytes [ ( self . readingOffset / 8 ) ..< ( ( self . readingOffset / 8 ) + length) ]
72
+ self . readingOffset = self . readingOffset + ( length * 8 )
73
+ return Array ( returnValue)
74
+ } else {
75
+ fatalError ( " Couldn't extract Bytes. " )
76
+ }
77
+ }
78
+ }
0 commit comments