summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorAndrej Mihajlov <and@mullvad.net>2022-05-18 09:40:50 +0200
committerAndrej Mihajlov <and@mullvad.net>2022-05-18 09:40:50 +0200
commit0a3bddd728a1fdd4252bd5dbfb0d53b17060026d (patch)
tree80289324de6024370052eab6bc99f98a00740945
parent92edd7fdfe5ab31bd6ba02614b9d520dfcb82ea2 (diff)
parent97da2c5c572c6e6667db377cb3f41857f4667ddd (diff)
downloadmullvadvpn-0a3bddd728a1fdd4252bd5dbfb0d53b17060026d.tar.xz
mullvadvpn-0a3bddd728a1fdd4252bd5dbfb0d53b17060026d.zip
Merge branch 'refactor-checksum'
-rw-r--r--ios/PacketTunnel/Pinger.swift30
1 files changed, 10 insertions, 20 deletions
diff --git a/ios/PacketTunnel/Pinger.swift b/ios/PacketTunnel/Pinger.swift
index ea143d0ca6..fd76fdc5ec 100644
--- a/ios/PacketTunnel/Pinger.swift
+++ b/ios/PacketTunnel/Pinger.swift
@@ -231,27 +231,17 @@ extension Pinger {
}
private func in_chksum(_ data: Data) -> UInt16 {
- return data.withUnsafeBytes { buffer in
- let length = buffer.count
-
- var sum: Int32 = 0
-
- let isOdd = length % 2 != 0
- let strideTo = isOdd ? length - 1 : length
-
- for offset in stride(from: 0, to: strideTo, by: 2) {
- let word = buffer.load(fromByteOffset: offset, as: UInt16.self)
- sum += Int32(word)
- }
-
- if isOdd {
- let byte = buffer.load(fromByteOffset: length - 1, as: UInt8.self)
- sum += Int32(byte)
+ let words = sequence(state: data.makeIterator()) { iterator in
+ return iterator.next().map { byte in
+ return iterator.next().map { nextByte in
+ return [byte, nextByte].withUnsafeBytes { buffer in
+ return buffer.load(as: UInt16.self)
+ }
+ } ?? UInt16(byte)
}
+ }
- sum = (sum >> 16) + (sum & 0xffff)
- sum += (sum >> 16)
+ let sum = words.reduce(0, &+)
- return UInt16(truncatingIfNeeded: ~sum)
- }
+ return ~sum
}