Test iOS CBOR Integer Decoding on a Remote Mac
You finish writing device communication code on Windows, move the project to a cloud Mac, and find that the same counter value sometimes decodes successfully and sometimes gets rejected by the server. The network may not be at fault: CBOR allows integers to use different representation lengths, while your application protocol may accept only the shortest encoding. Running a standalone Swift test fixture from the remote macOS command line, then moving the same vectors into an iOS test target, makes these differences easier to isolate than repeatedly reconnecting the device.
Define a protocol for a single integer item first
This article handles only CBOR major type 0: unsigned integers. The input must contain exactly one item, its value must fit in UInt64, and it must use the shortest representation. Reject negative integers, tags, arrays, and indefinite-length items outright. Do not try to interpret unknown types as zero.
The first byte uses its upper 3 bits for the major type and its lower 5 bits for additional information. Values from 0 through 23 in the lower bits carry the integer directly. Values of 24, 25, 26, and 27 indicate that 1, 2, 4, or 8 value bytes follow, respectively, most significant byte first. Values 28 through 30 are reserved, and 31 cannot be used for this kind of integer.
Requiring the shortest encoding is an additional rule of the application protocol used here. Do not turn “this protocol rejects it” into “all CBOR decoders must reject it,” or assume that passing the integer checks means the complete message satisfies deterministic encoding requirements.
Write a decoder that does not depend on memory alignment
Create CBORCheck.swift in an empty directory on the cloud Mac and add the following code. It builds the value one byte at a time rather than casting the buffer to an integer pointer, so it does not depend on host byte order or address alignment. Input is limited to 9 bytes, with the length checked before allocating the array.
import Foundation
enum DecodeError: Error, Equatable {
case length
case type
case additional
case truncated
case trailing
case nonMinimal
}
func decodeUnsigned(_ data: Data) throws -> UInt64 {
guard !data.isEmpty, data.count <= 9 else {
throw DecodeError.length
}
let bytes = Array(data)
let head = bytes[0]
guard head >> 5 == 0 else {
throw DecodeError.type
}
let info = Int(head & 31)
if info < 24 {
guard bytes.count == 1 else {
throw DecodeError.trailing
}
return UInt64(info)
}
let width: Int
let minimum: UInt64
switch info {
case 24:
(width, minimum) = (1, 24)
case 25:
(width, minimum) = (2, 256)
case 26:
(width, minimum) = (4, 65_536)
case 27:
(width, minimum) = (8, 4_294_967_296)
default:
throw DecodeError.additional
}
guard bytes.count >= width + 1 else {
throw DecodeError.truncated
}
guard bytes.count == width + 1 else {
throw DecodeError.trailing
}
var value: UInt64 = 0
for byte in bytes.dropFirst() {
value = (value << 8) | UInt64(byte)
}
guard value >= minimum else {
throw DecodeError.nonMinimal
}
return value
}
The accumulation loop runs at most 8 times, and the entire result fits in UInt64. Do not then convert it to Int before passing it to application logic: the unsigned maximum allowed by the protocol exceeds the signed integer maximum. If the field actually represents an array length, also validate application-level limits before allocating any memory.
Test encoding thresholds with fixed bytes
Append the tests to the same file. The valid vectors cover both sides of every encoding-length transition, especially 23 and 24, and 255 and 256. Specify the bytes directly rather than generating the input with your own encoder; otherwise, the encoder and decoder could share the same bug.
func check(_ condition: Bool) {
if !condition {
fatalError("CBOR check failed")
}
}
let valid: [([UInt8], UInt64)] = [
([0x00], 0),
([0x17], 23),
([0x18, 0x18], 24),
([0x18, 0xff], 255),
([0x19, 0x01, 0x00], 256),
([0x19, 0xff, 0xff], 65_535),
([0x1a, 0x00, 0x01, 0x00, 0x00], 65_536),
([0x1a, 0xff, 0xff, 0xff, 0xff], 4_294_967_295),
([0x1b, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00], 4_294_967_296),
([0x1b] + Array(repeating: 0xff, count: 8), UInt64.max)
]
for (bytes, expected) in valid {
check(try decodeUnsigned(Data(bytes)) == expected)
}
The try is at the top level, so an unexpected decoding error causes the program to fail. Compile the file into an executable and run it: a failure produces a nonzero exit status, without relying on someone reading a success message in the terminal.
Assert error categories as well
Invalid-input tests must do more than check that “an error occurred.” For example, a broken implementation that reports every input as truncated could still pass a crude rejection test. Append these assertions for specific error categories:
let invalid: [([UInt8], DecodeError)] = [
([], .length),
([0x20], .type),
([0x1c], .additional),
([0x1f], .additional),
([0x19, 0x01], .truncated),
([0x00, 0x00], .trailing),
([0x18, 0x17], .nonMinimal),
([0x19, 0x00, 0xff], .nonMinimal),
(Array(repeating: 0, count: 10), .length)
]
for (bytes, expected) in invalid {
do {
_ = try decodeUnsigned(Data(bytes))
fatalError("Invalid input accepted")
} catch let error as DecodeError {
check(error == expected)
}
}
Add another systematic check: for each valid multibyte vector, test every prefix from length zero through one byte short of the full length, and verify that none is accepted. The empty prefix is a length error; the other prefixes with missing value bytes are truncation errors. This helps prevent out-of-bounds reads and catches implementations that silently fill missing bytes with zeros.
Run remotely and integrate into the project
Run the following commands from the directory containing the file. Compilation errors and test failures both stop the command chain:
xcrun swiftc -version
xcrun swiftc CBORCheck.swift -o cbor-check &&
./cbor-check
Keep the compiler version, test source file, and execution exit code. There is no need to launch a simulator for these byte-only tests. Next, add the decoding function to the shared source code, move the fixed vectors into the iOS unit test target, and run them through the project's existing test entry point to confirm that compilation also succeeds for the target platform.
Check the consumption boundary
If real messages contain multiple items, do not simply remove the trailing-byte check. Instead, create a separate parsing interface that returns both the value and the number of bytes consumed. Let the caller advance a cursor in a loop, and limit the total number of items. The interface in this article deliberately accepts only a single item, so even two adjacent valid integers must produce an error.
Before committing, check three things one last time: oversized input is rejected before copying; each encoding threshold has independent vectors on both sides; and invalid input never produces a default value that subsequent code can use. Lock down these boundaries before adding other CBOR types, so more complex container parsing does not obscure the underlying faults.
Frequently asked questions
Is a non-shortest CBOR integer always invalid?
No. A general decoder may accept certain longer representations. This fixture rejects them because its application profile explicitly requires the shortest representation.
Do these tests establish deterministic encoding for an entire message?
No. Container lengths, map key ordering, floating-point representations, and other type rules also matter. This fixture checks one standalone unsigned integer only.
Move your next build to a cloud Mac
Rent a dedicated physical Mac and use its macOS desktop in your browser. Choose a daily, weekly, monthly, or quarterly plan; it stops at the end of your term unless you renew.
Get a Mac