Skip to content

Commit 199e221

Browse files
committed
Use defer in ByteReader's functions
This allows to express backwards logic explicitly as well as eliminate temporary variables in uintX() functions.
1 parent 218a2ed commit 199e221

1 file changed

Lines changed: 10 additions & 14 deletions

File tree

Sources/ByteReader.swift

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@ public class ByteReader {
4141
*/
4242
public func byte() -> UInt8 {
4343
precondition(self.offset < self.data.endIndex)
44-
self.offset += 1
45-
return self.data[self.offset - 1]
44+
defer { self.offset += 1 }
45+
return self.data[self.offset]
4646
}
4747

4848
/**
@@ -56,9 +56,8 @@ public class ByteReader {
5656
guard count > 0
5757
else { return [] }
5858
precondition(self.offset + count <= self.data.endIndex)
59-
let result = self.data[self.offset..<self.offset + count].toArray(type: UInt8.self, count: count)
60-
self.offset += count
61-
return result
59+
defer { self.offset += count }
60+
return self.data[self.offset..<self.offset + count].toArray(type: UInt8.self, count: count)
6261
}
6362

6463
/**
@@ -68,9 +67,8 @@ public class ByteReader {
6867
*/
6968
public func uint64() -> UInt64 {
7069
precondition(self.offset + 8 <= self.data.endIndex)
71-
let result = self.data[self.offset..<self.offset + 8].to(type: UInt64.self)
72-
self.offset += 8
73-
return result
70+
defer { self.offset += 8 }
71+
return self.data[self.offset..<self.offset + 8].to(type: UInt64.self)
7472
}
7573

7674
/**
@@ -80,9 +78,8 @@ public class ByteReader {
8078
*/
8179
public func uint32() -> UInt32 {
8280
precondition(self.offset + 4 <= self.data.endIndex)
83-
let result = self.data[self.offset..<self.offset + 4].to(type: UInt32.self)
84-
self.offset += 4
85-
return result
81+
defer { self.offset += 4 }
82+
return self.data[self.offset..<self.offset + 4].to(type: UInt32.self)
8683
}
8784

8885
/**
@@ -92,9 +89,8 @@ public class ByteReader {
9289
*/
9390
public func uint16() -> UInt16 {
9491
precondition(self.offset + 2 <= self.data.endIndex)
95-
let result = self.data[self.offset..<self.offset + 2].to(type: UInt16.self)
96-
self.offset += 2
97-
return result
92+
defer { self.offset += 2 }
93+
return self.data[self.offset..<self.offset + 2].to(type: UInt16.self)
9894
}
9995

10096
}

0 commit comments

Comments
 (0)