Decode Binary Packets With Swift's Safe RawSpan Loads
A small binary packet arrives from an accessory. It starts with a version byte, followed immediately by a 32-bit sequence number. Reading that number at byte offset one looks innocent, until an aligned pointer load objects to the seating arrangement.
Swift 6.4 adds safe loading APIs for RawSpan, including integer loads with an explicit byte order. We can read that unaligned field without writing an unsafe pointer closure or copying each field into a temporary Data value.
There is still a parser to write. A memory-safe bounds check can terminate the process when input is too short. Our job is to turn malformed packets into ordinary errors before attempting the load.
Start with a wire format, not a Swift struct layout
A Stack Overflow question about storing differently typed values in Data captures both traps: an unaligned integer load and an attempt to reconstruct a String from its in-memory representation. That question has an answer. The current API makes the integer-reading part much clearer.
For this article, we’ll invent a small sensor record. This is a teaching format, not a claim about a particular accessory protocol:
| Byte offset | Field | Encoding |
|---|---|---|
| 0 | Version | One unsigned byte; must be 1 |
| 1 | Sequence number | Four bytes, unsigned, big-endian |
| 5 | Sample count | Two bytes, unsigned, big-endian; 0–256 |
| 7 | Samples | Count × two bytes, signed, big-endian |
Each sample is a temperature in hundredths of a degree Celsius. This format accepts values from −5,000 through 15,000, representing −50°C through 150°C. Zero samples is a valid empty record. Trailing bytes are an error.
Those are protocol choices. They do not come from MemoryLayout<SensorPacket>. Swift’s object representation is not our file format, and loading a String object would not decode a sequence of UTF-8 bytes.
The code below needs Swift 6.4 and iOS 27 or macOS 27. The installed Xcode 27 SDK marks the integer-loading overload that accepts ByteOrder with those OS requirements. Installing a new compiler does not remove that deployment requirement.
Define the decoded value and its errors
Put the following blocks in one Swift file, in order. Foundation is the only import; no package dependency is required.
import Foundation
nonisolated struct SensorPacket: Equatable, Sendable {
let sequence: UInt32
let hundredthsCelsius: [Int16]
}
nonisolated enum PacketError: Error, Equatable {
case truncatedHeader
case unsupportedVersion(UInt8)
case tooManySamples(Int)
case wrongPayloadSize(expected: Int, actual: Int)
case invalidTemperature(index: Int, value: Int16)
}
Keep the integer readings in the decoded model. A UI can convert them to Double and divide by 100 for display. The parser’s responsibility is to preserve and validate the transmitted values.
Check lengths before loading fields
Data.bytes supplies a borrowed RawSpan over the data. A span does not own that storage, and its lifetime is constrained by the value it borrows. We keep the span local to this synchronous decoder and return owned values. Apple’s RawSpan documentation describes this relationship.
nonisolated func decodeSensorPacket(_ data: Data) throws -> SensorPacket {
let headerSize = 7
let maximumSamples = 256
let bytes = data.bytes
guard bytes.byteCount >= headerSize else {
throw PacketError.truncatedHeader
}
let version = bytes.load(fromByteOffset: 0, as: UInt8.self)
guard version == 1 else {
throw PacketError.unsupportedVersion(version)
}
let sequence = bytes.load(
fromByteOffset: 1, as: UInt32.self, .bigEndian
)
let count = Int(bytes.load(
fromByteOffset: 5, as: UInt16.self, .bigEndian
))
guard count <= maximumSamples else {
throw PacketError.tooManySamples(count)
}
// The cap makes the multiplication small and safe.
let expectedBytes = count * 2
let actualBytes = bytes.byteCount - headerSize
guard actualBytes == expectedBytes else {
throw PacketError.wrongPayloadSize(
expected: expectedBytes, actual: actualBytes
)
}
var readings: [Int16] = []
readings.reserveCapacity(count)
for index in 0..<count {
let value = bytes.load(
fromByteOffset: headerSize + index * 2,
as: Int16.self,
.bigEndian
)
guard (-5_000...15_000).contains(value) else {
throw PacketError.invalidTemperature(index: index, value: value)
}
readings.append(value)
}
return SensorPacket(sequence: sequence, hundredthsCelsius: readings)
}
There are three separate checks here:
- Can we read the header? The first guard establishes enough bytes for every fixed field.
- Does the packet have the allowed shape? The count cap limits output allocation and loop work. Exact payload-length equality rejects both truncation and surplus bytes.
- Do the decoded values satisfy this protocol? Any
Int16bit pattern is a valid integer. It is not necessarily a valid sensor reading.
The sequence number starts at offset one. Under SE-0525’s safe loading contract, this integer load does not require pointer alignment. The .bigEndian argument interprets the transmitted byte order, so do not byte-swap the returned value again.
The safe API constrains the types it can load and checks bounds. It does not throw PacketError for us. A direct load outside the span would still violate a precondition; the guards are what make corrupt input recoverable.
Avoid “simplifying” the payload into an aligned Span<Int16> view. That introduces a different alignment contract, and a typed view alone does not interpret the packet’s byte order. Reading the declared fields explicitly keeps both concerns visible.
Use a fixture whose byte order is obvious
A sequence number of zero is a poor endian test: all four bytes vote for the same answer. Use different bytes instead.
nonisolated func checkExamplePacket() throws {
let data = Data([
0x01, // Version 1
0x01, 0x02, 0x03, 0x04, // Sequence 0x01020304
0x00, 0x02, // Two samples
0x09, 0xC4, // 2,500 = 25.00 degrees C
0xFE, 0x0C // -500 = -5.00 degrees C
])
let packet = try decodeSensorPacket(data)
precondition(packet.sequence == 0x01020304)
precondition(packet.hundredthsCelsius == [2_500, -500])
}
Call try checkExamplePacket() from a throwing test or another throwing function. The hexadecimal fixture tests byte order, an unaligned multi-byte field, and a negative signed reading together.
A slice of Data can have a nonzero startIndex. Our decoder uses byte offsets into the span, starting at zero, rather than treating Data collection indices as protocol offsets. The verification fixtures include a packet sliced from a larger buffer to check that distinction.
Make malformed input boring
The decoder’s most useful tests are packets it refuses to accept:
| Input | Expected behavior |
|---|---|
| Fewer than seven bytes | truncatedHeader |
| Full header with version 2 | unsupportedVersion(2) |
| Count 257, even before supplying its payload | tooManySamples(257) |
| Count 2 with only one sample | wrongPayloadSize |
| Count 2 with one extra trailing byte | wrongPayloadSize |
| Count 0 and no payload | Empty readings |
| Count 256 and a complete valid payload | All 256 readings |
A sample equal to Int16.min | invalidTemperature |
Test every truncated prefix of a known valid record. Also test the permitted temperature endpoints and the first invalid value on either side. These cases exercise the boundary between “an integer we can load” and “data the application accepts.”
The exact article blocks compile with Xcode 27.0 and Swift 6.4 for iOS 27 and macOS 27, in both ordinary and MainActor default isolation, with warnings treated as errors. Runtime checks on macOS 27.0.1 cover the success and rejection cases, nonzero-index slices, and a deterministic malformed-input corpus. They do not constitute a Bluetooth device or iOS runtime test.
Keep the decoder’s boundary small
This function expects exactly one complete record. If a transport fragments messages or combines several records, frame them before calling it. The format has no checksum or authentication; parsing successfully does not establish who sent the bytes.
The span lets us inspect input without creating a separate Data for every field. The returned readings array still allocates, and this article makes no measured speed claim. Bound incoming message size at the transport or file-reading layer too: a parser’s sample cap cannot undo a giant allocation that already happened upstream.
For larger, nested formats, Apple’s swift-binary-parsing package is worth exploring rather than growing a forest of offsets. For a small fixed record, the complete decoder above makes every byte, bound, and rejected value easy to inspect.