It should be safe to use pointers from a read-only Span for as long as the span stays alive, so long as you don't violate the usual rules about the Span's memory (particularly that it can't be mutated while the Span is alive). You should be able to write this a bit more straightforwardly though by sinking the withUnsafeBytes into the continuation block:
func write(_ span: Span<UInt8>) async {
defer { extendLifetime(span) } // Pointer must stay valid until after the suspension point.
await withUnsafeContinuation { continuation in
span.withUnsafeBytes {
// Pointer will be used in different thread until continuation is resumed.
scheduleWrite($0, continuation)
}
}
}
(While not immediately relevant to your use case, in case someone finds this thread in a more general context: this is less true for MutableSpan, since its withUnsafe* accessors also assert exclusivity over the span while the pointer is in use. Since there can only be one active exclusive access to a memory location at a time, the MutableSpan itself would be unsafe to use while any pointers into it are potentially active.)