DEV Community

Cover image for OutputSpan and UTF8Span in Practice: Building and Parsing Without Copies in Swift 6.2
Dheerendra Chaturvedi
Dheerendra Chaturvedi

Posted on AI-assisted

OutputSpan and UTF8Span in Practice: Building and Parsing Without Copies in Swift 6.2

This is a follow-up to my earlier post, Span, InlineArray and ~Escapable in Practice. Same setup as before: I'm an iOS developer who ported real code onto these types, I built a small package first and wrote this from it, and I'll be honest about where the shipped toolchain and the proposals don't line up yet.

Last time I looked at reading contiguous storage without copies. The two halves I kept hitting after that were the other direction — building a buffer, and parsing text. Building a byte buffer by hand meant Array(unsafeUninitializedCapacity:initializingWith:) with an inout count I had to remember to advance, or a pre-zeroed [UInt8] and an index cursor that nothing checked. Parsing text meant one of two bad choices: copy the String into [UInt8] so I could index bytes, or iterate Characters and pay for grapheme breaking on every byte even when I was looking for an ASCII colon.

OutputSpan (SE-0485) and UTF8Span (SE-0464) are the stdlib's answers. This post is what actually compiled and what didn't, on the toolchain below.

Toolchain: Apple Swift 6.2.4 (swiftlang-6.2.4.1.4), Xcode 26.3 (17C529), Swift 6 language mode, building against the macOS 26 SDK. Every snippet is copied from a package that builds warning-free.

OutputSpan

OutputSpan<Element> is a ~Escapable view over a region of partially initialized storage. It tracks how many elements you've initialized, gives you an append / removeLast API, and the type system guarantees you can never read an element you haven't written and never leave the buffer partly initialized when it's finalized.

The first surprise: in 6.2.4 the only standard-library type that vends a safe OutputSpan initializer is InlineArray, via init(initializingWith:). The Array(capacity:initializingWith:) and String convenience initializers described around SE-0485 did not ship in this toolchain — I grepped the Swift.swiftinterface, and the only init(initializingWith: (inout OutputSpan<Element>) -> Void) is on InlineArray.

So my worked example writes a fixed 10-byte packet header into an InlineArray<10, UInt8>:

public static func encode(_ header: PacketHeader) -> InlineArray<10, UInt8> {
  InlineArray<10, UInt8> { (out: inout OutputSpan<UInt8>) in
    appendBigEndian(&out, PacketHeader.magic)   // UInt16, 0xC0DE
    out.append(header.version)
    out.append(header.flags)
    appendBigEndian(&out, header.length)        // UInt32
    appendBigEndian(&out, header.checksum)      // UInt16
  }
}
Enter fullscreen mode Exit fullscreen mode

OutputSpan mid-encode over InlineArray<10, UInt8>: bytes 0–3 (C0 DE 01 00) initialized, bytes 4–9 uninitialized; count is 4, freeCapacity is 6

appendBigEndian is just a loop of out.append(...):

static func appendBigEndian<T: FixedWidthInteger>(
  _ out: inout OutputSpan<UInt8>, _ value: T
) {
  let width = T.bitWidth / 8
  for shift in stride(from: (width - 1) * 8, through: 0, by: -8) {
    out.append(UInt8(truncatingIfNeeded: value >> shift))
  }
}
Enter fullscreen mode Exit fullscreen mode

The initializer only finalizes once the span's initialized count equals the array's size; if I appended nine bytes instead of ten it would trap rather than hand back a half-built value. Compare the old version, where the storage is zero-filled first and a stray index is a silent logic bug:

public static func encodeOld(_ header: PacketHeader) -> [UInt8] {
  var bytes = [UInt8](repeating: 0, count: PacketHeader.byteCount)
  var i = 0
  func put<T: FixedWidthInteger>(_ value: T) {
    var be = value.bigEndian
    withUnsafeBytes(of: &be) { raw in
      for b in raw { bytes[i] = b; i += 1 }
    }
  }
  put(PacketHeader.magic); bytes[i] = header.version; i += 1
  bytes[i] = header.flags; i += 1
  put(header.length); put(header.checksum)
  return bytes
}
Enter fullscreen mode Exit fullscreen mode

The useful members I reached for: append(_:), append(repeating:count:), removeLast(), count, freeCapacity, isFull, and span / mutableSpan to read back what you've written so far. For a fixed-width text encoding the same pattern works — here's lowercase hex for a UInt32, output length known at compile time so InlineArray<8, UInt8> fits:

public static func hex(_ value: UInt32) -> InlineArray<8, UInt8> {
  InlineArray<8, UInt8> { (out: inout OutputSpan<UInt8>) in
    for shift in stride(from: 28, through: 0, by: -4) {
      let nibble = UInt8((value >> UInt32(shift)) & 0xF)
      out.append(nibbleToHex(nibble))
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The limitation this runs into: a dynamically sized output (hex of N bytes, N known only at runtime) can't use InlineArray, whose size is a compile-time value. In 6.2.4 the only way I found to drive an OutputSpan over heap storage is the @unsafe OutputSpan(buffer:initializedCount:) plus finalize(for:) — which is exactly the unsafe buffer bookkeeping OutputSpan was meant to replace. So for variable-length building, the safe, ergonomic story isn't fully here yet.

UTF8Span

UTF8Span is a ~Escapable, non-owning view over validated UTF-8. You get one from String.utf8Span or Substring.utf8Span — and because a String was already validated when it was built, that's cheap — or by validating a Span<UInt8> yourself:

public init(validating codeUnits: consuming Span<UInt8>) throws(UTF8.ValidationError)
Enter fullscreen mode Exit fullscreen mode

Being ~Escapable is the whole point: you scan inside a scope, you don't stash it in a property or return it. The payoff is scanning bytes without first copying the text into [UInt8]. My favourite example is a zero-allocation field-name check — compare bytes straight out of two validated views:

public static func hasFieldName(_ line: String, _ name: String) -> Bool {
  let lineBytes = line.utf8Span.span
  let nameBytes = name.utf8Span.span
  guard nameBytes.count < lineBytes.count else { return false }
  for i in 0..<nameBytes.count where lineBytes[i] != nameBytes[i] {
    return false
  }
  return lineBytes[nameBytes.count] == UInt8(ascii: ":")
}
Enter fullscreen mode Exit fullscreen mode

"Content-Length: 42" viewed as Span<UInt8> through utf8Span: bytes 0–13 match the field name, byte 14 is the colon, no copy into [UInt8]

utf8Span.span hands you a Span<UInt8> (SE-0447) to index directly. For iteration you ask the view for an iterator. There are two, and the distinction is the honest cost model:

public static func scalarCount(_ s: String) -> Int {
  var iterator = s.utf8Span.makeUnicodeScalarIterator()
  var count = 0
  while iterator.next() != nil { count += 1 }
  return count
}
Enter fullscreen mode Exit fullscreen mode

makeUnicodeScalarIterator() walks Unicode.Scalars; makeCharacterIterator() walks grapheme clusters and is the expensive, Unicode-correct traversal. Both iterators expose currentCodeUnitOffset, previous(), prefix() and suffix(), so you can stop mid-stream and ask where you are without having built any intermediate collection.

Two more things a validated view gives you for free. isKnownASCII lets a length check skip grapheme breaking entirely. And comparison is built in — isCanonicallyEquivalent(to:) treats composed and decomposed forms as equal without normalizing into new Strings:

public static func canonicallyEqual(_ a: String, _ b: String) -> Bool {
  a.utf8Span.isCanonicallyEquivalent(to: b.utf8Span)
}
Enter fullscreen mode Exit fullscreen mode

There's also bytesEqual(to:), unicodeScalarsEqual(to:), charactersEqual(to:) and isCanonicallyLessThan(_:). One gap: there's no String(decoding: Span) or String(_: UTF8Span) convenience in this toolchain, so when you do need to materialize a result String you still copy (which is correct — a String owns its storage). The win is that the scan is copy-free, not the final allocation.

Putting both together

A full round trip: parse a Content-Length request line with UTF8Span, then emit a binary ack packet with OutputSpan.

public static func ackFor(requestLine line: String) -> InlineArray<10, UInt8>? {
  guard HeaderParser.hasFieldName(line, "Content-Length"),
        let (_, value) = HeaderParser.parse(line),
        let length = parseUInt32(value)
  else { return nil }

  let header = PacketHeader(
    version: 1, flags: 0, length: length, checksum: checksum(of: length))
  return PacketEncoder.encode(header)
}
Enter fullscreen mode Exit fullscreen mode

parseUInt32 iterates scalars and never round-trips through Int(String):

static func parseUInt32(_ s: String) -> UInt32? {
  var iterator = s.utf8Span.makeUnicodeScalarIterator()
  var result: UInt32 = 0
  var sawDigit = false
  while let scalar = iterator.next() {
    guard let digit = scalar.asciiDigitValue else { return nil }
    result = result &* 10 &+ UInt32(digit)
    sawDigit = true
  }
  return sawDigit ? result : nil
}
Enter fullscreen mode Exit fullscreen mode

Performance

I have to be straight here: I could not run the benchmarks on the machine I wrote this on. The package targets macOS 26 / iOS 26, and these types live in the macOS 26 standard library and are not back-deployed. On my macOS 15.7.4 box the compiled test and benchmark binaries fail to launch:

dyld: Symbol not found: _$sSS8utf8Spans04UTF8B0Vvg
  (built for macOS 26.0 which is newer than running OS)
Enter fullscreen mode Exit fullscreen mode

That's the getter for String.utf8Span. The benchmark harness is in the package (Benchmarks/, old vs. new for encode, parse and field-name match), it compiles in -c release, and it prints a table. I just don't have a macOS 26 machine to run it on, so rather than invent numbers I'm leaving this section as a placeholder. If you're on macOS 26, swift run -c release SpanBenchmarks will fill it in, and I'd genuinely like to see your output. My expectation is that hasFieldName beats hasPrefix/split by avoiding allocation, and that encode is roughly par with the unsafe cursor since both end up writing the same bytes, but I have not measured it.

How they compare

Comparison of unsafe pointers, OutputSpan and UTF8Span across safety, allocation, escapability, availability and main pitfall

Pitfalls and limitations

  • Availability. Everything here is macOS 26 / iOS 26 and up, not back-deployed. If you ship to older OSes you need if #available and a fallback path, which undercuts a lot of the appeal for another year or two.
  • Safe producers are thin. OutputSpan's only safe stdlib entry point in 6.2.4 is InlineArray.init(initializingWith:). Fixed-size building is lovely; dynamic-size building still means unsafe buffers.
  • No free String materialization. Scanning is copy-free; producing a result String from a view is not, because there's no String-from-Span initializer in this toolchain.
  • ~Escapable ergonomics. You can't return a UTF8Span/OutputSpan, store it, or capture it in an escaping closure. All the real work happens in one scope, which sometimes forces a slightly awkward shape (do the scan, return plain values).
  • They don't compose with everything yet. Lots of stdlib and Foundation APIs still speak [UInt8] / String, so you end up at a copy boundary at the edges regardless.

Migration tips

  • Start with fixed-size building: anywhere you have Array(unsafeUninitializedCapacity: K) with a constant K, try InlineArray<K, _>(initializingWith:).
  • Reach for UTF8Span at hot parsing paths that currently copy to [UInt8] or scan Characters to find ASCII delimiters.
  • Use isKnownASCII as an explicit fast path before any grapheme work.
  • Keep all span work inside one function; return plain values (Int, Bool, a freshly built String), never the view.
  • Gate behind #available and keep the old path until your deployment target reaches 26.

Open questions for the thread

  1. Is the absence of Array/String OutputSpan convenience initializers in 6.2.4 just staging, and what's the intended safe path for dynamically sized OutputSpan output before then?
  2. For building a String from validated bytes, is there a blessed zero-extra-copy path I'm missing (something like String(_: UTF8Span)), or is the final copy simply expected?
  3. Has anyone benchmarked UTF8Span scanning against withUTF8 / utf8 views on a real macOS 26 build? I'd like to know whether the iterator overhead shows up for short lines.

Top comments (0)