@@ -37,12 +37,19 @@ public final class DataReader: Reader {
37
37
self . data = data
38
38
}
39
39
40
- public func seek( toOffset offset: UInt64 ) {
41
- byteOffset = Int ( offset)
40
+ public var totalBytes : Int {
41
+ data. count
42
+ }
43
+
44
+ public func seek( toOffset offset: Int ) {
45
+ precondition ( offset < data. count)
46
+
47
+ byteOffset = offset
42
48
}
43
49
44
50
/// Read a single byte from the stream and increment `byteOffset` by 1.
45
51
public func read( ) -> UInt8 {
52
+ precondition ( byteOffset + 1 <= data. count)
46
53
defer { byteOffset += 1 }
47
54
48
55
return data [ byteOffset]
@@ -51,6 +58,7 @@ public final class DataReader: Reader {
51
58
/// Read two bytes in little-endian order as a single `UInt16` value and
52
59
/// increment `byteOffset` by 2.
53
60
public func read( ) -> UInt16 {
61
+ precondition ( byteOffset + 2 <= data. count)
54
62
defer { byteOffset += 2 }
55
63
56
64
return ( UInt16 ( data [ byteOffset + 1 ] ) << 8 ) + UInt16( data [ byteOffset] )
@@ -59,6 +67,7 @@ public final class DataReader: Reader {
59
67
/// Read four bytes in little-endian order as a single `UInt32` value and
60
68
/// increment `byteOffset` by 4.
61
69
public func read( ) -> UInt32 {
70
+ precondition ( byteOffset + 4 <= data. count)
62
71
defer { byteOffset += 4 }
63
72
64
73
return ( UInt32 ( data [ byteOffset + 3 ] ) << 24 )
@@ -69,12 +78,15 @@ public final class DataReader: Reader {
69
78
70
79
/// Read a given `count` of bytes as raw data and increment `byteOffset` by `count`.
71
80
public func readData( ofLength length: Int ) -> Data {
81
+ precondition ( byteOffset + length <= data. count)
72
82
defer { byteOffset += length }
73
83
74
84
return data [ byteOffset..< byteOffset + length]
75
85
}
76
86
77
87
public func readDataToEnd( ) -> Data {
88
+ guard data. count > 0 else { return data }
89
+
78
90
defer { byteOffset = data. count - 1 }
79
91
80
92
return data [ byteOffset..< data. count]
0 commit comments