Validate iOS LZFSE streams on a cloud Mac: termination and output limits

After a project starts compressing offline data with LZFSE, complete files may load correctly while files interrupted during transfer occasionally still display partial content. The problem is usually not the UI: the decoder is treating “some bytes were produced” as “the entire compressed stream succeeded.” Building a standalone validation program on a cloud Mac, then moving the same cases into an iOS test target, catches these errors before the data is stored.

Define the record boundary first

This article uses a single-stream protocol: each record contains one LZFSE stream, with the original byte count stored separately outside it. Neither concatenated streams nor extra bytes after the end of the stream are accepted. Compressed input is limited to 8 MiB, and uncompressed data to 64 MiB. These are example application quotas, not algorithm limits.

Success requires all three conditions to hold: the decoder reports the end of the stream, all compressed input has been consumed, and the output length matches the declared length. The declared original length is untrusted. Check it against the upper limit before using it; do not allocate that much memory directly.

Recovering a valid piece of text proves only that the prefix is decodable. It does not prove that the remaining data is complete or that the content has not been tampered with.

Scope: compression is not authentication. If external data needs tamper protection, use a separate authentication mechanism to protect both the record and its length field.

Build a minimal decoder on a cloud Mac

First, confirm that the development tools are available, then save the following code as LZFSECheck.swift. The program relies only on system frameworks, so there are no dependencies to download. The commands at the end compile and run it.

import Foundation
import Compression

enum DecodeFailure: Error {
    case invalidLength, invalidStream, outputLimit, trailingBytes
}

func decode(_ input: Data, expected: Int) throws -> Data {
    guard !input.isEmpty,
          input.count <= 8 * 1024 * 1024,
          expected >= 0,
          expected <= 64 * 1024 * 1024 else {
        throw DecodeFailure.invalidLength
    }

    var stream = compression_stream()
    guard compression_stream_init(
        &stream, COMPRESSION_STREAM_DECODE, COMPRESSION_LZFSE
    ) == COMPRESSION_STATUS_OK else {
        throw DecodeFailure.invalidStream
    }
    defer { compression_stream_destroy(&stream) }

    let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 4096)
    defer { buffer.deallocate() }

    return try input.withUnsafeBytes { raw in
        stream.src_ptr = raw.bindMemory(to: UInt8.self).baseAddress!
        stream.src_size = input.count
        var result = Data()

        while true {
            let before = stream.src_size
            stream.dst_ptr = buffer
            stream.dst_size = 4096

            let status = compression_stream_process(&stream, 0)
            guard status != COMPRESSION_STATUS_ERROR else {
                throw DecodeFailure.invalidStream
            }

            let produced = 4096 - stream.dst_size
            guard produced <= expected - result.count else {
                throw DecodeFailure.outputLimit
            }
            result.append(buffer, count: produced)

            if status == COMPRESSION_STATUS_END {
                guard stream.src_size == 0 else {
                    throw DecodeFailure.trailingBytes
                }
                guard result.count == expected else {
                    throw DecodeFailure.invalidLength
                }
                return result
            }

            guard status == COMPRESSION_STATUS_OK,
                  produced > 0 || stream.src_size < before else {
                throw DecodeFailure.invalidStream
            }
        }
    }
}

let plain = Data(String(repeating: "构建记录\n", count: 200).utf8)
let packed = try (plain as NSData).compressed(using: .lzfse) as Data
let restored = try decode(packed, expected: plain.count)
precondition(restored == plain)

func mustReject(_ bytes: Data, expected: Int) {
    do {
        _ = try decode(bytes, expected: expected)
    } catch {
        return
    }
    fatalError("Invalid input was accepted")
}

for end in 0..<packed.count {
    mustReject(Data(packed.prefix(end)), expected: plain.count)
}
mustReject(packed + Data([0x7f]), expected: plain.count)
mustReject(packed, expected: plain.count - 1)
mustReject(packed, expected: plain.count + 1)
xcrun swiftc LZFSECheck.swift -o LZFSECheck
./LZFSECheck

A successful run produces no output and exits with code zero. The code keeps the input pointer within the lifetime of withUnsafeBytes and supplies a fixed-size output buffer on each call. If an error occurs, it does not return the prefix already decoded.

Scope: this decoder assumes the entire input has arrived. When decoding network data in chunks, “no input available right now” must not be treated as truncation. That requires an additional distinction between waiting for more data and the upstream source reaching its end.

Verify failure paths with truncated fixtures

Small fixtures let you test every prefix, starting at zero bytes and covering each possible amount of missing data at the end. Every one must be rejected. The code also checks trailing garbage and declared lengths that are too small or too large. This tests both the terminal state and the outer protocol.

Add samples that cross buffer boundaries

Add empty source data, a single byte, an all-zero block, and a repeated sequence containing every possible byte value. Cover source lengths of 4095, 4096, and 4097 bytes to verify that decoding completes both when the output exactly fills the buffer and when it exceeds it by one byte. Empty source data must still be compressed into a valid stream first; do not substitute a zero-byte file.

For large files, there is no need to exhaustively test every truncation point. Instead, check fixed positions in the header, at block boundaries, and near the end, and retain failing samples. Do not rely solely on random byte flips for acceptance testing: some changes may produce another valid compressed stream and therefore may not trigger a decoding error.

Scope: negative tests verify rejection conditions; they do not prove that the algorithm implementation is defect-free. Also, do not require the same error enum case for every kind of corruption.

Integrate with the iOS test target

Once command-line validation passes, add decode and its error type to the app module and move the fixture assertions into XCTest. Build and run the simulator tests to confirm that behavior under the iOS SDK matches the host tests. Do not treat a macOS executable as an iOS acceptance result.

At a minimum, assert that a valid round trip returns exactly the same bytes, every invalid fixture throws an error, and the persistence entry point is never called after a failure. Separate “decode successfully” from “commit the data” rather than modifying the production database while decompression is still in progress.

Scope: this does not validate the UI, network retries, or background execution. Those callers should reuse the same decoding contract rather than relaxing the success criteria independently.

Keep reviewable acceptance results

For each run, record the source commit, development tool version, fixture name, compressed length, declared length, and pass status. Keep small, fixed binary fixtures rather than generating every test case on the fly with the same encoder. Otherwise, shared assumptions in the encoder and decoder may hide problems.

The final checklist is: validate size limits up front and check again before appending output; return only after the end-of-stream status; never silently discard trailing bytes; and leave no partial application data after a failure. Establish these conditions before discussing compression ratios and processing time, so performance optimizations do not change the integrity guarantees.

Frequently asked questions

Must I check termination if the decoded text looks complete?

Yes. Accept the result only after COMPRESSION_STATUS_END, full consumption of the single-stream input and a matching output length.

Does storing the original length prevent excessive memory use?

Not by itself. Validate the declared length against an application limit, then enforce the remaining budget before every append. Never allocate a large buffer directly from an untrusted length.

Get a cloud Mac ready for your next build

Prepare your project on Windows or Linux, then rent a dedicated physical machine and use Xcode in your browser to build and archive your app.

You’ll need to provide the developer account, certificates, and provisioning profiles required for code signing. We don’t submit apps for you.

Rent a cloud Mac

Choose a cloud Mac for your project

Prepare your project on Windows or Linux, then sign in to a dedicated physical machine and use Xcode in your browser to build and archive your app.

You’ll need to provide the developer account, certificates, and provisioning profiles required for code signing. We don’t submit apps for you.