How to convert `RawSpan` to `Span<UInt8>`?

Until SE-525 lands, is there any way at all (in Swift 6.3) to convert a RawSpan to a Span<UInt8>? I’m struggling and failing. Even the BinaryParsing package doesn’t offer a way to get a typed Span from its ParserSpan.

The closest I got was first this:

extension RawSpan {
    var byteSpan: Span<UInt8> {
        @_lifetime(copy self)
        get {
            self.withUnsafeBytes { buffer in   // ERROR: Instance method 'withUnsafeBytes' requires that 'Span<UInt8>' conform to 'Escapable'
                buffer.bindMemory(to: UInt8.self).span
            }
        }
    }
}

Then this:

extension RawSpan {
    var byteSpan: Span<UInt8> {
        @_lifetime(copy self)
        get {
            let buf = self.withUnsafeBytes { buffer in
                buffer.bindMemory(to: UInt8.self)
            }
            return buf.span  // ERROR: Lifetime-dependent value escapes its scope
        }
    }
}

I’m out of ideas.

…as usual, the rubber-duck approach comes through. After I posted that, it occurred to me that SwiftParsing has a method ParserSpan.sliceUTF8Span() that returns a UTF8Span. I can’t use that because it requires macOS 26, but how does it manage to create a typed span?

Looking at the source, I found it calls the undocumented Span<UInt8>(_bytes: rawSpan) Bingo!

2 Likes