Skip to content

Commit e3789b0

Browse files
tmmampagent
andauthored
test(swift): unmask scripted-server frames eight bytes at a time (#203)
TransportProbeTests' largeFramesBothWays(urlSession) failed on the iOS Simulator job when the scripted server got no frame within the probe's 30 s wait (the "Message too long" in the log is the next probe's expected line). The server unmasked the client's 11 MB frame one byte at a time: 0.8 s in a debug build on an idle Mac, and past 30 s on a starved CI simulator; with xctest throttled to 2.5% CPU it failed the same way. XORing eight bytes at a time takes 28 ms instead of 1.07 s, and passed under the same throttle. Amp-Thread-ID: https://ampcode.com/threads/T-fbae32eb-2a12-4ebe-a716-b1b0bf7c246f Co-authored-by: Amp <amp@ampcode.com>
1 parent e4f199a commit e3789b0

1 file changed

Lines changed: 19 additions & 1 deletion

File tree

‎swift/Tests/E2ETests/ScriptedServer.swift‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,9 +249,27 @@ final class ScriptedServer: Sendable {
249249
}
250250
guard b.count >= i + length else { return nil }
251251
var payload = Array(b[i..<(i + length)])
252-
for j in payload.indices { payload[j] ^= mask[j % 4] }
252+
if masked { unmask(&payload, mask) }
253253
return (Frame(fin: b[0] & 0x80 != 0, opcode: b[0] & 0x0F, payload: payload), i + length)
254254
}
255+
256+
/// XORs `payload` with the repeating four-byte `mask`, eight bytes at a time. Byte by byte, an 11 MB frame took most of a second in a debug build, and over the 30 s a probe waits for it on a busy iOS Simulator.
257+
static func unmask(_ payload: inout [UInt8], _ mask: [UInt8]) {
258+
let key = (mask + mask).withUnsafeBytes { $0.loadUnaligned(as: UInt64.self) }
259+
payload.withUnsafeMutableBytes { p in
260+
var j = 0
261+
while j + 8 <= p.count {
262+
p.storeBytes(
263+
of: p.loadUnaligned(fromByteOffset: j, as: UInt64.self) ^ key, toByteOffset: j,
264+
as: UInt64.self)
265+
j += 8
266+
}
267+
while j < p.count {
268+
p[j] ^= mask[j % 4]
269+
j += 1
270+
}
271+
}
272+
}
255273
}
256274
}
257275

0 commit comments

Comments
 (0)