11import Foundation
22
33public struct Binary {
4- private let bytes : [ UInt8 ]
4+ public let bytes : [ UInt8 ]
5+ var readingOffset : Int = 0
56
67 public init ( bytes: [ UInt8 ] ) {
78 self . bytes = bytes
@@ -22,10 +23,6 @@ public struct Binary {
2223 return ( byte >> bitPosition) & 0x01
2324 }
2425
25- public func bit( position: Int ) -> Bit {
26- return self . bit ( position) == 1 ? Bit . One : Bit . Zero
27- }
28-
2926 public func bits( range: Range < Int > ) -> Int {
3027 return range. reverse ( ) . enumerate ( ) . reduce ( 0 ) {
3128 $0 + ( bit ( $1. element) << $1. index)
@@ -48,4 +45,34 @@ public struct Binary {
4845 return bits ( start*8, length*8)
4946 }
5047
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