Testing iOS bitmap row stride and buffer boundaries on a cloud Mac
When a client's image filter works on test images but produces diagonal artifacts with camera frames, the cause is often not the algorithm: the code is treating the number of active pixel bytes in each row as the actual row stride. Before handing over an image-processing module, a studio can run a set of deterministic, pure Swift fixtures on a cloud Mac to verify row padding, truncated input and capacity calculations separately, then connect the module to device data.
Define the pixel layout before assuming a row stride
This article handles only normalized, single-plane, interleaved RGBA8 bytes: four bytes per pixel, with channels in red, green, blue, alpha order. It is not a decoder for arbitrary image files and does not perform color-space conversion.
At a width of three pixels, each row contains twelve bytes of active data, but the producer may allocate a row stride of sixteen bytes. The next row starts at offset sixteen, not twelve. Taking one contiguous slice of the input would treat padding bytes as pixels in the second row.
Row stride describes memory layout, not image content. Tests must deliberately include padding; tightly packed images alone cannot establish that row addressing is correct.
Every client project should record the width, height, pixel format, row stride and number of accessible bytes. If any of these is missing, do not start copying based only on a pointer or image dimensions.
Write a row-by-row copier with overflow checks
The copier below produces tightly packed data. It accepts positive dimensions, requires the stride to be at least the number of active bytes per row, and checks for overflow before multiplication and addition. Save it as StrideCheck.swift and append the tests below to the same file.
import Foundation
enum LayoutError: Error {
case invalidSize
case overflow
case shortStride
case truncated
}
func tightRGBA(
_ input: [UInt8],
width: Int,
height: Int,
bytesPerRow: Int
) throws -> [UInt8] {
guard width > 0, height > 0, bytesPerRow > 0 else {
throw LayoutError.invalidSize
}
let (rowBytes, rowOverflow) =
width.multipliedReportingOverflow(by: 4)
guard !rowOverflow else {
throw LayoutError.overflow
}
guard bytesPerRow >= rowBytes else {
throw LayoutError.shortStride
}
let (lastStart, offsetOverflow) =
(height - 1).multipliedReportingOverflow(by: bytesPerRow)
guard !offsetOverflow else {
throw LayoutError.overflow
}
let (required, endOverflow) =
lastStart.addingReportingOverflow(rowBytes)
let (outputCount, countOverflow) =
height.multipliedReportingOverflow(by: rowBytes)
guard !endOverflow, !countOverflow else {
throw LayoutError.overflow
}
guard input.count >= required else {
throw LayoutError.truncated
}
var output = [UInt8]()
output.reserveCapacity(outputCount)
for row in 0..<height {
let start = row * bytesPerRow
output.append(contentsOf: input[start..<(start + rowBytes)])
}
return output
}
The minimum input length here is “the start of the last row plus its active byte count,” not height multiplied by stride. Since the copier never reads padding after the final row, it accepts input without that trailing padding. This contract applies only to this reader; it does not mean the underlying image API can allocate less memory.
Build counterexamples with conspicuous padding values
Start with a fixture containing two rows of two pixels each: eight active bytes per row and a stride of twelve bytes. The four 238 values in the middle mark the padding and must not appear in the expected output. Leave the final row unpadded to verify the minimum-length contract at the same time.
func expectError(
_ expected: LayoutError,
_ operation: () throws -> [UInt8]
) {
do {
_ = try operation()
fatalError("Expected rejection")
} catch let actual as LayoutError {
precondition(actual == expected)
} catch {
fatalError("Unexpected error")
}
}
let first: [UInt8] = [1, 2, 3, 255, 4, 5, 6, 255]
let second: [UInt8] = [7, 8, 9, 255, 10, 11, 12, 255]
let padded = first + [238, 238, 238, 238] + second
let result = try tightRGBA(
padded, width: 2, height: 2, bytesPerRow: 12
)
precondition(result == first + second)
expectError(.truncated) {
try tightRGBA(
Array(padded.dropLast()),
width: 2, height: 2, bytesPerRow: 12
)
}
expectError(.shortStride) {
try tightRGBA(padded, width: 2, height: 2, bytesPerRow: 7)
}
expectError(.overflow) {
try tightRGBA([], width: Int.max, height: 1, bytesPerRow: 8)
}
expectError(.overflow) {
try tightRGBA([], width: 1, height: 2, bytesPerRow: Int.max)
}
expectError(.invalidSize) {
try tightRGBA([], width: 0, height: 1, bytesPerRow: 4)
}
Run xcrun swift StrideCheck.swift in an environment with the Swift toolchain installed. A normal exit means the tests passed; a failed assertion or an unhandled error returns a failure status. Do not compile the tests with -Ounchecked, which disables checks.
These fixtures verify address calculations, not how the image looks. Add four more cases: a single row, a single pixel, a tightly packed stride and extra bytes at the end of the input. Extra bytes should be ignored, and the output length must always equal width multiplied by height multiplied by four.
Keep an adapter layer when connecting real buffers
When integrating with Core Graphics, checking bitsPerPixel alone is not enough. Also verify the bits per component, channel order, byte order and alpha convention. A four-byte pixel may be BGRA rather than the RGBA layout used here. Premultiplied alpha cannot be addressed simply by swapping channels, either.
When working with a pixel buffer, lock its base address as required by the API. Read the format, dimensions and actual stride while it is locked, then unlock it after copying. Do not let the base-address pointer outlive its validity, and do not force a multiplanar format through a single-plane function.
The adapter layer should have just two responsibilities: validate the format contract and provide bounded data. The application algorithm should receive only normalized, tightly packed arrays. If a client changes image sources, failures will then be contained in the format-conversion layer rather than becoming seemingly random out-of-bounds accesses inside the filter.
Hand over memory budgets alongside test evidence
The absence of integer overflow does not mean there is enough memory. Production entry points still need limits on dimensions, input capacity and the output memory budget. Account for the source buffer, destination array and intermediate copies that coexist in memory. Set the budget according to project requirements; do not rely on allocation failure to reject abnormal input.
Whenever the copying logic changes, save the toolchain version, commit ID and deterministic fixture results. Failure records need only the dimensions, stride, capacity and error category—not the client's original image. For misalignment, check each row's starting offset first. For swapped colors, check the channel layout. For artifacts around semitransparent edges, check the premultiplication convention.
The final acceptance criterion is not “the image looks right.” It is that active pixels are correct byte for byte, no padding enters the output, and invalid input is rejected before any read. Establish these three guarantees, and you have a repeatable memory-layout baseline for later integration with camera frames, filters or export pipelines.
Frequently asked questions
Does bytesPerRow always equal width times four?
No. For four-byte pixels, that gives the useful pixel bytes per row. The actual stride may include alignment padding and must come from the buffer producer.
Must the final row include trailing padding?
This reader accesses only useful pixels, so it does not require trailing padding on the final row. An underlying image API may impose a stricter allocation requirement, which must also be satisfied.
Set up a Mac for your next client project
Rent a dedicated physical Mac mini by the day, week, month or quarter. Your Mac is ready on the day you order. Track progress in the console, and submit a support ticket there if you need help.
Rent a cloud Mac