From a804e107fb4f9df28491cf15795c2f86bba133fb Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 17:18:17 -0800 Subject: [PATCH 01/13] chore(quest): claim quest/m1/ffi-export/swift-span.md Quest-Claim: 3b29d7fc31003a13 From 088f13c26bc06ae43284d67a56bce3303a3a3779 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 17:52:00 -0800 Subject: [PATCH 02/13] wip: swift spans --- ffi/README.md | 9 ++- ffi/fixtures/api/src/lib.rs | 20 +++++ ffi/moq/bench/export.swift | 14 ++-- ffi/runtime/rt.swift | 48 +++++++++++- ffi/src/swift.rs | 63 +++++++++++++-- ffi/surface/api/c.h | 12 ++- ffi/surface/api/cpp.hpp | 7 ++ ffi/surface/api/dart.dart | 6 ++ ffi/surface/api/go.txt | 6 ++ ffi/surface/api/kotlin.kt | 5 ++ ffi/surface/api/python.pyi | 7 ++ ffi/surface/api/swift.swift | 35 +++++---- ffi/surface/api/web.d.ts | 15 ++++ ffi/surface/moq/swift.swift | 146 +++++++++++++++++------------------ ffi/tests/api.swift | 86 +++++++++++++++++---- ffi/tests/fixtures.rs | 1 + ffi/tests/fixtures/shapes.rs | 33 ++++++-- 17 files changed, 384 insertions(+), 129 deletions(-) diff --git a/ffi/README.md b/ffi/README.md index 2e9a3cd0a..e20a337b6 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -927,7 +927,14 @@ value of a Rust type crosses as one Swift type that holds it exactly, and back u as an array's items or behind a pointer, which Rust only reads and so copies. Swift's own, made with `Bytes(data)` or from any sequence of bytes, Rust copies once where it keeps them. `bytes.data` is a `Data`: Swift's as they are, and Rust's copied, so nothing - writes into a buffer Rust shares. + writes into a buffer Rust shares, and `bytes.withSpan` lends them in place as a + `Span`. +- **Slices** a call borrows, `&[u8]` and `&[T]` of a fixed-width integer or float, are + `borrowing Swift.Span`, which Rust reads in place: an array's `span`, or before + Apple's 26 releases its slice's (`array[...]`), or `Bytes` lent by `withSpan`. Bytes Rust lends a closure or trait + method are a `Span` of Rust's own memory, which the compiler keeps from outliving + the call. A `span` property on `Bytes` waits on Swift's lifetime dependencies, still + experimental, and on `Data` keeping short bytes inline. Strings are `String`, copied, `char` `Unicode.Scalar`, `usize` `UInt`, `Option` `T?`, a tuple a Swift tuple, though a tuple of one is its element, `u128` a `U128` of its `high` and `low` halves until the deployment target allows `UInt128`, and `Duration` the diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index b9f325e25..36c8149f8 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -4141,6 +4141,26 @@ pub fn doubled_i64(items: &[i64]) -> Vec { items.iter().map(|v| v.wrapping_mul(2)).collect() } +/// What `visit` returns for each chunk of `payload` of up to `size` bytes, which is not 0, +/// each lent in place, then for none. +pub fn visit_chunks(payload: &[u8], size: usize, mut visit: impl FnMut(Option<&[u8]>) -> u64) -> Vec { + let mut seen: Vec = payload.chunks(size).map(|chunk| visit(Some(chunk))).collect(); + seen.push(visit(None)); + seen +} + +/// A reader of lent bytes: a callback interface, implemented in C. +pub trait Scan { + /// A digest of `payload` and `rest`, if any, each lent for the call. + fn scan(&self, payload: &[u8], rest: Option<&[u8]>) -> u64; +} + +/// What `scan` returns for each half of `payload`, each lent in place, then for none. +pub fn scanned(scan: impl Scan, payload: Vec) -> u64 { + let (head, tail) = payload.split_at(payload.len() / 2); + scan.scan(head, Some(tail)) + scan.scan(&[], None) +} + /// `items` back as Rust took them, boxed. pub fn boxed_floats(items: Box<[f64]>) -> Box<[f64]> { items diff --git a/ffi/moq/bench/export.swift b/ffi/moq/bench/export.swift index cd89f92b9..7063e92f9 100644 --- a/ffi/moq/bench/export.swift +++ b/ffi/moq/bench/export.swift @@ -164,7 +164,7 @@ func throughput(_ track: TrackProducer, _ subscriber: inout TrackSubscriber, _ m var group = try track.appendGroup(at) var reader = try await subscriber.recvGroup()! for _ in 0.. ([(String, Span)], Int) { for _ in 0.. ([(String, Span)], Int) { micros += 1 var group = try track.appendGroup(at) for _ in 0.. ([(String, Span)], Int) { var group = try track.appendGroup(at) var reader = try await subscriber.recvGroup()! for _ in 0.. ([(String, Span)], Int) { for _ in 0.. ([(String, Span)], Int) { for _ in 0.. ([(String, Span)], Int) { queue.drain() for f in 0..(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { - try storage.withUnsafeBytes(body) + /// Run `body` with the bytes in place, as a span the compiler keeps it from keeping. + public func withSpan(_ body: (Swift.Span) throws -> R) rethrows -> R { + var result: R? = nil + try storage.withUnsafeBytes { raw in + result = try body(Swift.Span(_unsafeElements: raw.assumingMemoryBound(to: Swift.UInt8.self))) + } + return result.take()! } /// Whether `a` and `b` hold the same bytes, wherever each keeps them. @@ -505,6 +509,44 @@ extension Native { return try view(bytes, body) } + /// `span` as a view C reads during `body`, without a copy. + @inline(__always) + static func view(_ span: borrowing Swift.Span, _ body: (Buf) throws -> R) rethrows -> R { + try span.withUnsafeBytes { raw in try body(view(raw)) } + } + + @inline(__always) + static func view(_ span: borrowing Swift.Span?, _ body: (Buf) throws -> R) rethrows -> R { + switch span { + case .some(let span): return try view(span, body) + case .none: return try body(none) + } + } + + /// `span` as the array `make` makes of its items, which C reads during `body` without a + /// copy: never null, so no items read as present. + @inline(__always) + static func view( + _ span: borrowing Swift.Span, _ make: (UnsafePointer?, Int, UnsafeMutableRawPointer?) -> L, + _ body: (L) throws -> R + ) rethrows -> R { + try span.withUnsafeBufferPointer { items in + let ptr = items.baseAddress ?? UnsafePointer(bitPattern: MemoryLayout.alignment)! + return try body(make(ptr, items.count, nil)) + } + } + + @inline(__always) + static func view( + _ span: borrowing Swift.Span?, _ make: (UnsafePointer?, Int, UnsafeMutableRawPointer?) -> L, + _ body: (L) throws -> R + ) rethrows -> R { + switch span { + case .some(let span): return try view(span, make, body) + case .none: return try body(make(nil, 0, nil)) + } + } + /// `text`'s UTF-8 as a view C reads during `body`, without a copy for a native string. @inline(__always) static func view(_ text: Swift.String, _ body: (Buf) throws -> R) rethrows -> R { diff --git a/ffi/src/swift.rs b/ffi/src/swift.rs index 0a3087c92..2628d38b9 100644 --- a/ffi/src/swift.rs +++ b/ffi/src/swift.rs @@ -20,13 +20,16 @@ //! Bytes are the runtime's `Bytes`: those Rust returned lend its buffer, and pass back to //! Rust as a second owner of it, so neither way copies them. Swift's own bytes and text //! pass as views of Swift's memory at a call's top level, which Rust copies once where it -//! keeps them; nested in another value, they are copied once into a buffer Rust takes. +//! keeps them; nested in another value, they are copied once into a buffer Rust takes. A +//! slice Rust borrows, of bytes or a block's numbers, is a `Span` either way: a parameter +//! Rust reads in place, and bytes Rust lends a closure or callback, which Swift's compiler +//! keeps from escaping the call. use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::fmt::Write; use crate::abi::{self, Abi, Ty, pascal}; -use crate::ir::{Access, Closure, Family, Function, Int, Literal, Mutability, On, Param, Receiver, Type}; +use crate::ir::{Access, Closure, Collection, Family, Function, Int, Literal, Mutability, On, Param, Receiver, Type}; const RUNTIME: &str = include_str!("../runtime/rt.swift"); @@ -328,6 +331,29 @@ impl<'a> Gen<'a> { unique(&self.structs, ty) } + /// The element of the span Swift borrows a shared slice of bytes or of a block's numbers + /// as, in place, which the compiler keeps from escaping the call. + fn spanned(&self, ty: &Type) -> Option { + match ty { + Type::Ref(Mutability::Not, inner) => match &**inner { + Type::Slice => Some("Swift.UInt8".to_string()), + list @ Type::List(Collection::Slice, elem) if list.block().is_some() => Some(self.sw(elem)), + _ => None, + }, + _ => None, + } + } + + /// The Swift type of a parameter of type `ty`, which Rust takes or lends: a slice it + /// borrows is a span, and any other type as [`Self::sw`] has it. + fn param(&self, ty: &Type) -> String { + match (ty, self.spanned(unoption(ty))) { + (Type::Option(_), Some(elem)) => format!("Swift.Span<{elem}>?"), + (_, Some(elem)) => format!("Swift.Span<{elem}>"), + (_, None) => self.sw(ty), + } + } + /// The ownership a parameter of type `ty` declares, which Swift requires of a /// noncopyable one: `&T` borrows it, `&mut T` is `inout`, and a value moves in. fn ownership(&self, ty: &Type) -> &'static str { @@ -400,7 +426,7 @@ impl<'a> Gen<'a> { Type::Closure(closure_) => { let (params, ret) = (&closure_.params, &closure_.ok); let params: Vec = (params.iter()) - .map(|p| format!("{}{}", self.ownership(p), self.sw(p))) + .map(|p| format!("{}{}", self.ownership(p), self.param(p))) .collect(); let throws = match closure_.err { Some(_) => " throws", @@ -680,9 +706,13 @@ impl<'a> Gen<'a> { } /// The Swift value of the C value `e` of type `ty`, which C lends a callback or closure - /// for its call: bytes and text copied, and a scalar as it is. + /// for its call: a slice as a span of it in place, other bytes and text copied, and a + /// scalar as it is. fn lift_lent(&mut self, ty: &Type, e: &str) -> String { + let span = |e: &str| format!("Swift.Span(_unsafeElements: Swift.UnsafeBufferPointer(start: {e}.ptr, count: {e}.len))"); match ty { + _ if self.spanned(ty).is_some() => span(e), + Type::Option(inner) if self.spanned(inner).is_some() => format!("({e}.ptr == nil ? nil : {})", span(e)), Type::Str | Type::String => format!("Native.string(lent: {e})"), Type::Path | Type::PathBuf => format!("Native.path(lent: {e})"), Type::Slice | Type::Vec | Type::Bytes => format!("Native.bytes(lent: {e})"), @@ -1363,7 +1393,7 @@ impl<'a> Gen<'a> { crate::lock::function(&mut self.locked, method, &member); members.push(full(false, &member, method.params.iter().map(|_| "_".to_string()))); let params: Vec = (method.params.iter().zip(locals(&method.params))) - .map(|(p, name)| format!("_ {name}: {}", self.sw(&p.ty))) + .map(|(p, name)| format!("_ {name}: {}", self.param(&p.ty))) .collect(); let ret = match method.ok { Type::Unit => String::new(), @@ -1497,6 +1527,18 @@ impl<'a> Gen<'a> { arg.exprs.push(format!("Native.future({e})")); arg.gives = true; } + // A span is a view of Swift's memory, which Rust borrows in place. + (ty, _) if self.spanned(unoption(ty)).is_some() => { + let b = format!("b{k}_"); + let make = match unoption(ty) { + Type::Ref(_, list) if let Type::List(_, elem) = &**list => { + format!(", {}.init(ptr:len:owner:)", abi.list(elem)) + } + _ => String::new(), + }; + arg.open = Some((format!("{tr}Native.view({e}{make}) {{ {b} in"), "}".to_string())); + arg.exprs.push(b); + } (ty, Ty::Buf) if Abi::is_buf(ty) || matches!(ty.base(), Type::Option(inner) if Abi::is_buf(inner)) => { let b = format!("b{k}_"); arg.open = Some((format!("{tr}Native.take({e}) {{ {b} in"), "}".to_string())); @@ -1797,9 +1839,10 @@ impl<'a> Gen<'a> { (false, Type::Closure(closure_)) if closure_.kept => "@escaping ", // Rust reads and seeks the reader in place. (false, Type::Ref(_, inner)) if **inner == Type::Reader => "inout ", + (false, ty) if self.spanned(unoption(ty)).is_some() => "borrowing ", (false, _) => self.ownership(¶m.ty), }; - params.push(format!("_ {name}: {ownership}{}", self.sw(¶m.ty))); + params.push(format!("_ {name}: {ownership}{}", self.param(¶m.ty))); let (arg, needs) = self.arg(¶m.ty, c, name, k, tr, &what); arena |= needs; args.push(arg); @@ -2303,6 +2346,14 @@ fn unique(structs: &BTreeSet, ty: &Type) -> bool { } } +/// `ty`, or what it holds if an `Option`. +fn unoption(ty: &Type) -> &Type { + match ty { + Type::Option(inner) => inner, + ty => ty, + } +} + /// Whether `ty` is an `Option<&T>` of one of `structs`. fn lent_option(structs: &BTreeSet, ty: &Type) -> bool { matches!(ty, Type::Option(inner) if matches!(&**inner, Type::Ref(Mutability::Not, object) if unique(structs, object))) diff --git a/ffi/surface/api/c.h b/ffi/surface/api/c.h index 0a5137410..f3760f560 100644 --- a/ffi/surface/api/c.h +++ b/ffi/surface/api/c.h @@ -7,7 +7,7 @@ #ifdef __cplusplus extern "C" { #endif -#define API_CONTRACT ((uint64_t)0xdcf4774fd2b0babdULL) +#define API_CONTRACT ((uint64_t)0x4a5c46273fe1db16ULL) uint64_t api_contract(void); uint32_t api_target(void); typedef int32_t api_status; @@ -1063,6 +1063,14 @@ typedef struct api_Log { const api_Log_vtable *vtable; void *data; } api_Log; +typedef struct api_Scan_vtable { + void (*free)(void *data); + uint64_t (*scan)(void *data, api_buf payload, api_buf rest); +} api_Scan_vtable; +typedef struct api_Scan { + const api_Scan_vtable *vtable; + void *data; +} api_Scan; typedef struct api_Beat_vtable { void (*free)(void *data); uint32_t (*beat)(void *data); @@ -2195,6 +2203,8 @@ api_vec_vec_u32 api_least(api_vec_vec_u32 sets); void api_split_last(api_vec_i32 items, api_vec_i32 *out0, uint32_t *out1); uint64_t api_sum_u32(api_vec_u32 items); api_vec_i64 api_doubled_i64(api_vec_i64 items); +api_vec_u64 api_visit_chunks(api_buf payload, size_t size, uint64_t (*visit)(void *data, api_buf), void *visit_data); +uint64_t api_scanned(api_Scan scan, api_buf payload); api_vec_f64 api_boxed_floats(api_vec_f64 items); api_Point api_summed(api_vec_Point points); api_duration api_breadth(api_Limits_duration limits); diff --git a/ffi/surface/api/cpp.hpp b/ffi/surface/api/cpp.hpp index 7717f7551..ee1fd5b46 100644 --- a/ffi/surface/api/cpp.hpp +++ b/ffi/surface/api/cpp.hpp @@ -618,6 +618,10 @@ namespace api { virtual ~Log() = default; virtual bool log(::std::uint8_t level, ::api::view line) const = 0; }; + class Scan { + virtual ~Scan() = default; + virtual ::std::uint64_t scan(::api::view payload, ::std::optional<::api::view> rest) const = 0; + }; class Beat { virtual ~Beat() = default; virtual ::std::uint32_t beat() const = 0; @@ -1495,6 +1499,8 @@ namespace api { inline ::std::tuple<::std::vector<::std::int32_t>, ::std::uint32_t> split_last(const ::std::vector<::std::int32_t> &items_); inline ::std::uint64_t sum_u32(const ::std::vector<::std::uint32_t> &items_); inline ::std::vector<::std::int64_t> doubled_i64(const ::std::vector<::std::int64_t> &items_); + template inline ::std::vector<::std::uint64_t> visit_chunks(::api::input payload, ::std::size_t size, F0 &&visit); + inline ::std::uint64_t scanned(::std::unique_ptr<::api::Scan> scan, ::api::input payload); inline ::std::vector boxed_floats(const ::std::vector &items_); inline ::api::Point summed(const ::std::vector<::api::Point> &points); inline ::api::duration breadth(const ::api::Limits_duration &limits); @@ -1957,6 +1963,7 @@ namespace api { class Forged; class Part; class Log; + class Scan; class Beat; struct Choice_Empty; struct Choice_Picked; diff --git a/ffi/surface/api/dart.dart b/ffi/surface/api/dart.dart index 3cde662a5..b8911d877 100644 --- a/ffi/surface/api/dart.dart +++ b/ffi/surface/api/dart.dart @@ -1433,6 +1433,10 @@ abstract class Log { bool log(int level, String line); void close(); } +abstract class Scan { + U64 scan(typed.Uint8List payload, typed.Uint8List? rest); + void close(); +} abstract class Beat { int beat(); void close(); @@ -1650,6 +1654,8 @@ List> least(List> sets); (typed.Int32List, int) splitLast(typed.Int32List items); U64 sumU32(typed.Uint32List items); typed.Int64List doubledI64(typed.Int64List items); +List visitChunks(typed.Uint8List payload, U64 size, U64 Function(typed.Uint8List?) visit); +U64 scanned(Scan scan, typed.Uint8List payload); typed.Float64List boxedFloats(typed.Float64List items); Point summed(List points); RustDuration breadth(LimitsDuration limits); diff --git a/ffi/surface/api/go.txt b/ffi/surface/api/go.txt index eec351aa7..b19094338 100644 --- a/ffi/surface/api/go.txt +++ b/ffi/surface/api/go.txt @@ -184,6 +184,8 @@ func SameU64(v uint64) uint64 func SameUsize(v uint) uint func SampleHex(sample p_rt.Bytes) string func Scaled(v p_rt.U128, by uint64) *p_rt.U128 +func ScanVtable_() unsafe.Pointer +func Scanned(scan Scan, payload p_rt.Bytes) uint64 func SecondLater(w235 p_rt.Duration) p_rt.Duration func Sections(entries []p_rt.Tuple2[string, *p_serdejson.Json]) ([]p_rt.Tuple2[string, *p_serdejson.Json], error) func Secure(alpn string) (*p_tls.Config, error) @@ -230,6 +232,7 @@ func TokenSlice(id uint32, len_ uint32, of uint32) p_rt.Bytes func Total(range_ p_rt.RangeU64) uint64 func Unhook() error func Verify(cert *p_tls.Cert) (uint32, error) +func VisitChunks(payload p_rt.Bytes, size uint, visit func(*[]byte) uint64) []uint64 func VisitStray(visit func(string)) func WaiterPollFuture(ctx context.Context, future func(context.Context)) error func Walk(steps uint64, visit func(*Cursor) uint64) uint64 @@ -1430,6 +1433,9 @@ type RightU8 struct { } func (self RightU8) Equal(other RightU8) bool func (self RightU8) GoString() string +type Scan interface { + Scan(payload []byte, rest *[]byte) uint64 +} type Score struct { Bytes_ [1]uint64 Made_ bool diff --git a/ffi/surface/api/kotlin.kt b/ffi/surface/api/kotlin.kt index 280423217..be0f99bca 100644 --- a/ffi/surface/api/kotlin.kt +++ b/ffi/surface/api/kotlin.kt @@ -1215,6 +1215,9 @@ class Part internal constructor(raw: Long, lent: Boolean = false) : AutoCloseabl interface Log { fun log(level: kotlin.UByte, line: kotlin.String): kotlin.Boolean } +interface Scan { + fun scan(payload: api.Bytes, rest: api.Bytes?): kotlin.ULong +} interface Beat { fun beat(): kotlin.UInt } @@ -1446,6 +1449,8 @@ fun least(sets: kotlin.collections.List>): fun splitLast(items: kotlin.IntArray): api.Tuple2 fun sumU32(items: kotlin.UIntArray): kotlin.ULong fun doubledI64(items: kotlin.LongArray): kotlin.LongArray +fun visitChunks(payload: api.Bytes, size: kotlin.ULong, visit: (api.Bytes?) -> kotlin.ULong): kotlin.ULongArray +fun scanned(scan: api.Scan, payload: api.Bytes): kotlin.ULong fun boxedFloats(items: kotlin.DoubleArray): kotlin.DoubleArray fun summed(points: kotlin.collections.List): api.Point fun breadth(limits: api.LimitsDuration): api.Duration diff --git a/ffi/surface/api/python.pyi b/ffi/surface/api/python.pyi index 1a31c83bb..57d85e7e9 100644 --- a/ffi/surface/api/python.pyi +++ b/ffi/surface/api/python.pyi @@ -1170,6 +1170,9 @@ class Part(_n.Object): class Log(_abc.ABC): @_abc.abstractmethod def log(self, level: _int, line: _str) -> _bool: ... +class Scan(_abc.ABC): + @_abc.abstractmethod + def scan(self, payload: _bytes, rest: _bytes | None) -> _int: ... class Beat(_abc.ABC): @_abc.abstractmethod def beat(self) -> _int: ... @@ -1385,6 +1388,8 @@ def least(sets: _typing.Iterable[_typing.Iterable[_int]]) -> _list[_list[_int]]: def split_last(items: _array.array[_int] | _memoryview) -> _tuple[_array.array[_int], _int]: ... def sum_u32(items: _array.array[_int] | _memoryview) -> _int: ... def doubled_i64(items: _array.array[_int] | _memoryview) -> _array.array[_int]: ... +def visit_chunks(payload: _bytes | _bytearray | _memoryview, size: _int, visit: _typing.Callable[[_bytes | None], _int]) -> _array.array[_int]: ... +def scanned(scan: Scan, payload: _bytes | _bytearray | _memoryview) -> _int: ... def boxed_floats(items: _array.array[_float] | _memoryview) -> _array.array[_float]: ... def summed(points: _typing.Iterable[Point]) -> Point: ... def breadth(limits: LimitsDuration) -> Duration: ... @@ -1641,6 +1646,8 @@ least = _n.least split_last = _n.split_last sum_u32 = _n.sum_u32 doubled_i64 = _n.doubled_i64 +visit_chunks = _n.visit_chunks +scanned = _n.scanned boxed_floats = _n.boxed_floats summed = _n.summed breadth = _n.breadth diff --git a/ffi/surface/api/swift.swift b/ffi/surface/api/swift.swift index cc6d70a84..7a3915648 100644 --- a/ffi/surface/api/swift.swift +++ b/ffi/surface/api/swift.swift @@ -63,7 +63,7 @@ public struct Bytes: Hashable, Sendable, RandomAccessCollection { @inlinable public var endIndex: Swift.Int { get } @inlinable public subscript(i: Swift.Int) -> Swift.UInt8 { get } @inlinable public subscript(bounds: Swift.Range) -> Bytes { get } - @inlinable public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R + @inlinable public func withSpan(_ body: (Swift.Span) throws -> R) rethrows -> R @inlinable public static func == (a: Bytes, b: Bytes) -> Swift.Bool @inlinable public func hash(into hasher: inout Swift.Hasher) } @@ -686,7 +686,7 @@ public enum Clash: Sendable, CustomDebugStringConvertible, Equatable { @inlinable public func reading(_ kotlin: Swift.UInt32) -> Reading @inlinable public static func listed(_ java: [Swift.UInt32], _ kotlin: inout Swift.UInt32) -> [[Swift.UInt32]] @inlinable nonisolated(nonsending) public static func after(_ first: @escaping @Sendable () async -> Void, _ kotlin: Swift.Double) async throws -> Clash - @inlinable public func joined(_ lent: Bytes, _ owned: Bytes, _ maybe: Bytes?) -> Bytes + @inlinable public func joined(_ lent: borrowing Swift.Span, _ owned: Bytes, _ maybe: Bytes?) -> Bytes @inlinable nonisolated(nonsending) public func tagged(_ tag: Swift.String) async throws -> Swift.String @inlinable public func stamp(_ kotlin: Swift.UInt64) -> Stamp @inlinable public func moment(_ kotlin: Swift.UInt64) -> Moment @@ -891,7 +891,7 @@ public struct Codecs: ~Copyable, @unchecked Sendable { @inlinable public mutating func ids() throws -> Swift.UInt32 } public struct Der: ~Copyable, @unchecked Sendable { - @inlinable public static func fromSlice(_ bytes: Bytes) -> Der + @inlinable public static func fromSlice(_ bytes: borrowing Swift.Span) -> Der @inlinable public func bytes() -> Bytes } public struct Verbosity: ~Copyable, @unchecked Sendable { @@ -1040,7 +1040,7 @@ public struct Channel: ~Copyable, @unchecked Sendable { @inlinable public func notify(_ waker: @escaping @Sendable () -> Void) throws @inlinable nonisolated(nonsending) public func sendLater(_ payload: Bytes) async throws @inlinable nonisolated(nonsending) public func tagged(_ tag: Swift.String) async throws -> Swift.String - @inlinable nonisolated(nonsending) public func itemized(_ items: [Swift.UInt32]?) async throws -> Swift.UInt + @inlinable nonisolated(nonsending) public func itemized(_ items: borrowing Swift.Span?) async throws -> Swift.UInt @inlinable nonisolated(nonsending) public func pollTake() async throws -> Bytes @inlinable nonisolated(nonsending) public mutating func pollMeasure(_ extra: Swift.UInt) async throws -> Swift.UInt @inlinable public func listen(_ cx: @escaping @Sendable () -> Void) throws @@ -1259,6 +1259,9 @@ public struct Part: ~Copyable, @unchecked Sendable { public protocol Log: Sendable { func log(_ level: Swift.UInt8, _ line: Swift.String) -> Swift.Bool } +public protocol Scan: Sendable { + func scan(_ payload: Swift.Span, _ rest: Swift.Span?) -> Swift.UInt64 +} public protocol Beat: Sendable { func beat() -> Swift.UInt32 } @@ -1294,7 +1297,7 @@ public let FAR: Swift.Int64 @inlinable public func corner(_ unit: Swift.Bool) throws -> (Swift.UInt32, Swift.UInt32) @inlinable nonisolated(nonsending) public func cornerLater() async throws -> (Swift.UInt32, Swift.UInt32) @inlinable public func spread(_ n: Swift.UInt64) -> (Swift.UInt8, Swift.Int16, Swift.UInt32, Swift.UInt64)? -@inlinable public func find(_ haystack: Bytes, _ needle: Bytes) -> (Swift.UInt, Swift.UInt)? +@inlinable public func find(_ haystack: borrowing Swift.Span, _ needle: borrowing Swift.Span) -> (Swift.UInt, Swift.UInt)? @inlinable public func rows(_ points: [Point]) -> [(Swift.String, Shape, Point)] @inlinable public func port(_ text: Swift.String) throws -> Swift.UInt16 @inlinable public func span(_ start: Swift.UInt32, _ end: Swift.UInt32) -> Swift.UInt32 @@ -1380,11 +1383,11 @@ public let FAR: Swift.Int64 @inlinable public func walk(_ steps: Swift.UInt64, _ visit: @Sendable (borrowing Cursor) -> Swift.UInt64) -> Swift.UInt64 @inlinable public func each(_ steps: Swift.UInt32, _ visit: @Sendable (Swift.UInt32) -> Void) -> Swift.UInt32 @inlinable public func peek(_ tally: borrowing Tally, _ peek: @Sendable (borrowing Tally) -> Swift.UInt32) throws -> Swift.UInt32 -@inlinable public func len(_ payload: Bytes) -> Swift.UInt +@inlinable public func len(_ payload: borrowing Swift.Span) -> Swift.UInt @inlinable public func hex(_ payload: Bytes) -> Swift.String @inlinable public func timedHex(_ payload: Bytes) -> Swift.String @inlinable public func timedText(_ value: borrowing Json) throws -> Swift.String -@inlinable public func sampleHex(_ sample: Bytes) -> Swift.String +@inlinable public func sampleHex(_ sample: borrowing Swift.Span) -> Swift.String @inlinable public func queuedHex(_ queued: Bytes) -> Swift.String @inlinable public func tickName(_ tick: Label) -> Swift.String @inlinable public func rootedName(_ rooted: Label) -> Swift.String @@ -1445,8 +1448,8 @@ public let FAR: Swift.Int64 @inlinable public func secure(_ alpn: Swift.String) -> TlsConfig @inlinable public func alpn(_ config: consuming TlsConfig) throws -> Swift.String @inlinable public func alpnLent(_ config: borrowing TlsConfig) throws -> Swift.String -@inlinable public func certify(_ der: Bytes) -> TlsCert -@inlinable nonisolated(nonsending) public func byteLen(_ bytes: Bytes) async throws -> Swift.UInt +@inlinable public func certify(_ der: borrowing Swift.Span) -> TlsCert +@inlinable nonisolated(nonsending) public func byteLen(_ bytes: borrowing Swift.Span) async throws -> Swift.UInt @inlinable public func certLen(_ cert: borrowing TlsCert) throws -> Swift.UInt @inlinable public func certDer(_ cert: consuming TlsCert) throws -> Bytes @inlinable public func chainLen(_ chain: consuming UniqueArray) throws -> Swift.UInt @@ -1465,10 +1468,10 @@ public let FAR: Swift.Int64 @inlinable public func resume(_ alpn: Swift.String, _ seconds: Swift.UInt32) throws -> TlsSession @inlinable public func either(_ text: Swift.String?) -> Swift.UInt @inlinable nonisolated(nonsending) public func eitherLater(_ text: Swift.String?) async throws -> Swift.UInt -@inlinable public func prefixed(_ payload: Bytes, _ prefix: Bytes?) -> Bytes -@inlinable public func sumLists(_ a: [Swift.Int32], _ b: [Swift.Int32]?, _ c: [Swift.Int32]?) -> Swift.Int32 +@inlinable public func prefixed(_ payload: borrowing Swift.Span, _ prefix: borrowing Swift.Span?) -> Bytes +@inlinable public func sumLists(_ a: [Swift.Int32], _ b: borrowing Swift.Span?, _ c: [Swift.Int32]?) -> Swift.Int32 @inlinable public func coordinates(_ point: Point?) -> Swift.Int32 -@inlinable public func chunks(_ bytes: Bytes, _ size: Swift.UInt) -> [Bytes] +@inlinable public func chunks(_ bytes: borrowing Swift.Span, _ size: Swift.UInt) -> [Bytes] @inlinable public func counters(_ names: [Swift.String]) -> UniqueArray @inlinable public func worth(_ some: consuming UniqueArray?, _ boxed: consuming UniqueArray) throws -> Swift.UInt64 @inlinable public func heldCount(_ held: consuming Counter?) throws -> Swift.UInt64? @@ -1478,15 +1481,17 @@ public let FAR: Swift.Int64 @inlinable public func sums(_ rows: [[Swift.UInt32]]) -> [Swift.UInt32] @inlinable public func least(_ sets: [[Swift.UInt32]]) -> [[Swift.UInt32]] @inlinable public func splitLast(_ items: [Swift.Int32]) -> ([Swift.Int32], Swift.UInt32) -@inlinable public func sumU32(_ items: [Swift.UInt32]) -> Swift.UInt64 -@inlinable public func doubledI64(_ items: [Swift.Int64]) -> [Swift.Int64] +@inlinable public func sumU32(_ items: borrowing Swift.Span) -> Swift.UInt64 +@inlinable public func doubledI64(_ items: borrowing Swift.Span) -> [Swift.Int64] +@inlinable public func visitChunks(_ payload: borrowing Swift.Span, _ size: Swift.UInt, _ visit: @Sendable (Swift.Span?) -> Swift.UInt64) -> [Swift.UInt64] +@inlinable public func scanned(_ scan: any Scan, _ payload: Bytes) -> Swift.UInt64 @inlinable public func boxedFloats(_ items: [Swift.Double]) -> [Swift.Double] @inlinable public func summed(_ points: [Point]) -> Point @inlinable public func breadth(_ limits: LimitsDuration) -> RustDuration @inlinable public func byteLimits(_ low: Bytes, _ high: Bytes) -> LimitsBytes @inlinable public func joined(_ parts: [Bytes]) -> Bytes @inlinable public func firstOf(_ items: [Swift.String]) -> Swift.String? -@inlinable public func readLen(_ reader: Bytes) -> Swift.UInt64 +@inlinable public func readLen(_ reader: borrowing Swift.Span) -> Swift.UInt64 @inlinable public func longest(_ words: [Swift.String]) -> Swift.UInt @inlinable public func encode(_ value: borrowing Json) throws -> Swift.String @inlinable public func tagged(_ doc: consuming Json, _ tag: Swift.String) throws -> Json diff --git a/ffi/surface/api/web.d.ts b/ffi/surface/api/web.d.ts index 19c475741..35819849e 100644 --- a/ffi/surface/api/web.d.ts +++ b/ffi/surface/api/web.d.ts @@ -1138,6 +1138,13 @@ export type RightU8 = { export declare function debug(self: RightU8): string; export declare function eq(a: RightU8, b: RightU8): boolean; +// Scan.ts +import * as rt from "./rt.ts"; +export interface Scan { + scan(payload: Uint8Array, rest: Uint8Array | undefined): rt.u64; + close?(): void; +} + // Score.ts import * as rt from "./rt.ts"; import type { Mark } from "./Mark.ts"; @@ -1584,6 +1591,7 @@ export declare function f12(): number; export declare function f13(): number; export declare function f14(): number; export declare function f15(): number; +export declare function f16(): number; export declare function f2(): number; export declare function f3(): number; export declare function f4(): number; @@ -1850,6 +1858,7 @@ export declare function t13(f: (a0: Tally) => number, p0: number): number; export declare function t14(f: (a0: number) => number, p0: number): number; export declare function t15(f: (a0: number) => number, p0: number): number; export declare function t16(f: (a0: rt.PathBuf) => void, p0: number): void; +export declare function t17(f: (a0: Uint8Array | undefined) => rt.u64, p0: number): bigint; export declare function t2(f: (a0: Counter) => boolean, p0: number): number; export declare function t3(f: (a0: Moment, a1: Waiter) => rt.Result, p0: number, p1: number, p2: number, p3: number): number; export declare function t4(f: (a0: number) => string, r$: number, p0: number): void; @@ -1863,6 +1872,7 @@ export declare function t_Ticket(p: number, v: Ticket): void; export declare function t_option_Moment(p: number, v: Moment | undefined): void; export declare function vt_Beat(): number; export declare function vt_Log(): number; +export declare function vt_Scan(): number; export declare function w_Atlas(p: number, v: Atlas): void; export declare function w_Booth(p: number, v: Booth): void; export declare function w_Boxed_u16(p: number, v: BoxedU16): void; @@ -2041,6 +2051,7 @@ export declare function w_vec_vec_u32_2(p: number, v: number[][] | undefined): v export declare const imports: { api_web_cb_Beat_beat: (data: number) => number; api_web_cb_Log_log: (data: number, p0: number, p1: number) => number; + api_web_cb_Scan_scan: (data: number, p0: number, p1: number) => bigint; api_web_i_fn_0: (data: number, p0: bigint) => void; api_web_i_fn_1: (data: number) => number; api_web_i_fn_10: (data: number, p0: number) => bigint; @@ -2049,6 +2060,7 @@ export declare const imports: { api_web_i_fn_13: (data: number, p0: number) => number; api_web_i_fn_14: (data: number, p0: number) => number; api_web_i_fn_15: (data: number, p0: number) => void; + api_web_i_fn_16: (data: number, p0: number) => bigint; api_web_i_fn_2: (data: number, p0: number) => number; api_web_i_fn_3: (data: number, p0: number, p1: number, p2: number, p3: number) => number; api_web_i_fn_4: (r$: number, data: number, p0: number) => void; @@ -2115,6 +2127,7 @@ import type { Reading } from "./Reading.ts"; import type { Receipt } from "./Receipt.ts"; import type { Refusal } from "./Refusal.ts"; import type { RightLeftU8 } from "./RightLeftU8.ts"; +import type { Scan } from "./Scan.ts"; import type { Seat } from "./Seat.ts"; import type { Shape } from "./Shape.ts"; import type { Size } from "./Size.ts"; @@ -2403,6 +2416,8 @@ export declare function least(sets: number[][]): number[][]; export declare function splitLast(items: Int32Array): [Int32Array, number]; export declare function sumU32(items: Uint32Array): rt.u64; export declare function doubledI64(items: BigInt64Array): BigInt64Array; +export declare function visitChunks(payload: Uint8Array | rt.Bytes, size: number, visit: (a0: Uint8Array | undefined) => rt.u64): BigUint64Array; +export declare function scanned(scan: Scan, payload: Uint8Array | rt.Bytes): rt.u64; export declare function boxedFloats(items: Float64Array): Float64Array; export declare function summed(points: Point[]): Point; export declare function breadth(limits: LimitsDuration): rt.Duration; diff --git a/ffi/surface/moq/swift.swift b/ffi/surface/moq/swift.swift index 3c524d1db..63f5874d2 100644 --- a/ffi/surface/moq/swift.swift +++ b/ffi/surface/moq/swift.swift @@ -63,7 +63,7 @@ public struct Bytes: Hashable, Sendable, RandomAccessCollection { @inlinable public var endIndex: Swift.Int { get } @inlinable public subscript(i: Swift.Int) -> Swift.UInt8 { get } @inlinable public subscript(bounds: Swift.Range) -> Bytes { get } - @inlinable public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R + @inlinable public func withSpan(_ body: (Swift.Span) throws -> R) rethrows -> R @inlinable public static func == (a: Bytes, b: Bytes) -> Swift.Bool @inlinable public func hash(into hasher: inout Swift.Hasher) } @@ -786,7 +786,7 @@ public struct MuxCodecH264Sps: Sendable, CustomDebugStringConvertible { public var codedHeight: Swift.UInt32 @inlinable public init(profile: Swift.UInt8, constraints: Swift.UInt8, level: Swift.UInt8, codedWidth: Swift.UInt32, codedHeight: Swift.UInt32) @inlinable public var debugDescription: Swift.String { get } - @inlinable public static func parse(_ nal: Bytes) throws -> MuxCodecH264Sps + @inlinable public static func parse(_ nal: borrowing Swift.Span) throws -> MuxCodecH264Sps } public struct MuxCodecH265VideoSignal: Sendable, CustomDebugStringConvertible, Equatable { public var primaries: Swift.UInt8 @@ -801,7 +801,7 @@ public struct MuxCodecMp3Config: Sendable { public var sampleRate: Swift.UInt32 public var channelCount: Swift.UInt32 @inlinable public init(sampleRate: Swift.UInt32, channelCount: Swift.UInt32) - @inlinable public static func parse(_ data: Bytes) throws -> MuxCodecMp3Config + @inlinable public static func parse(_ data: borrowing Swift.Span) throws -> MuxCodecMp3Config } public struct MuxCodecOpusMapping: Sendable, CustomDebugStringConvertible, Equatable { @inlinable public var debugDescription: Swift.String { get } @@ -1922,8 +1922,8 @@ public struct HangCatalog: ~Copyable, @unchecked Sendable { @inlinable public static func defaultSubscription() -> TrackSubscription @inlinable public func checkRenditions() throws @inlinable public func withoutExt() throws -> HangCatalog - @inlinable public static func fromSlice(_ v: Bytes) throws -> HangCatalog - @inlinable public static func fromReader(_ reader: Bytes) throws -> HangCatalog + @inlinable public static func fromSlice(_ v: borrowing Swift.Span) throws -> HangCatalog + @inlinable public static func fromReader(_ reader: borrowing Swift.Span) throws -> HangCatalog @inlinable public func toJson() throws -> Swift.String @inlinable public func toVec() throws -> Bytes @inlinable public func toWriter(_ writer: Bytes) throws @@ -1957,8 +1957,8 @@ public struct HangCatalogExtra: ~Copyable, @unchecked Sendable { @inlinable public mutating func skippedSet(_ value: consuming HangCatalogSkipped) throws @inlinable public func checkRenditions() throws @inlinable public func withoutExt() throws -> HangCatalog - @inlinable public static func fromSlice(_ v: Bytes) throws -> HangCatalogExtra - @inlinable public static func fromReader(_ reader: Bytes) throws -> HangCatalogExtra + @inlinable public static func fromSlice(_ v: borrowing Swift.Span) throws -> HangCatalogExtra + @inlinable public static func fromReader(_ reader: borrowing Swift.Span) throws -> HangCatalogExtra @inlinable public func toJson() throws -> Swift.String @inlinable public func toVec() throws -> Bytes @inlinable public func toWriter(_ writer: Bytes) throws @@ -1992,8 +1992,8 @@ public struct HangCatalogExt: ~Copyable, @unchecked Sendable { @inlinable public mutating func skippedSet(_ value: consuming HangCatalogSkipped) throws @inlinable public func checkRenditions() throws @inlinable public func withoutExt() throws -> HangCatalog - @inlinable public static func fromSlice(_ v: Bytes) throws -> HangCatalogExt - @inlinable public static func fromReader(_ reader: Bytes) throws -> HangCatalogExt + @inlinable public static func fromSlice(_ v: borrowing Swift.Span) throws -> HangCatalogExt + @inlinable public static func fromReader(_ reader: borrowing Swift.Span) throws -> HangCatalogExt @inlinable public func toJson() throws -> Swift.String @inlinable public func toVec() throws -> Bytes @inlinable public func toWriter(_ writer: Bytes) throws @@ -2696,7 +2696,7 @@ public struct DatagramProducer: ~Copyable, @unchecked Sendable { @inlinable public func clone() throws -> DatagramProducer @inlinable public func name() throws -> Swift.String @inlinable public func info() throws -> DatagramInfo - @inlinable public mutating func append(_ timestamp: Timestamp, _ payload: Bytes) throws -> Swift.UInt64 + @inlinable public mutating func append(_ timestamp: Timestamp, _ payload: borrowing Swift.Span) throws -> Swift.UInt64 @inlinable public mutating func insert(_ datagram: DatagramDatagram) throws @inlinable public func consume() throws -> DatagramConsumer @inlinable public consuming func finish() throws @@ -2734,7 +2734,7 @@ public final class DatagramInfo: @unchecked Sendable { public struct FrameProducer: ~Copyable, @unchecked Sendable { @inlinable public func group() throws -> GroupProducer @inlinable public func remaining() throws -> Swift.UInt - @inlinable public mutating func write(_ chunk: Bytes) throws + @inlinable public mutating func write(_ chunk: borrowing Swift.Span) throws @inlinable public consuming func finish() throws -> GroupProducer @inlinable public consuming func abort(_ err: Error) throws @inlinable public var sizeGet: Swift.UInt64 { get } @@ -2747,7 +2747,7 @@ public struct FrameFrame: ~Copyable, @unchecked Sendable { @inlinable public mutating func timestampSet(_ value: Timestamp) throws @inlinable public var payloadGet: Bytes { get } @inlinable public mutating func payloadSet(_ value: Bytes) throws - @inlinable public static func new(_ timestamp: Timestamp, _ payload: Bytes) throws -> FrameFrame + @inlinable public static func new(_ timestamp: Timestamp, _ payload: borrowing Swift.Span) throws -> FrameFrame @inlinable public func arrived() throws -> ClockInstant } public struct FrameConsumer: ~Copyable, @unchecked Sendable { @@ -2760,7 +2760,7 @@ public struct FrameConsumer: ~Copyable, @unchecked Sendable { public struct GroupProducer: ~Copyable, @unchecked Sendable { @inlinable public func timescale() throws -> Timescale? @inlinable public mutating func startAt(_ index: Swift.UInt64) throws - @inlinable public mutating func writeFrame(_ timestamp: Timestamp, _ data: Bytes) throws + @inlinable public mutating func writeFrame(_ timestamp: Timestamp, _ data: borrowing Swift.Span) throws @inlinable public consuming func createFrame(_ frame: FrameInfo) throws -> FrameProducer @inlinable public consuming func finishAt(_ end: Swift.UInt64) throws -> GroupFinished @inlinable public consuming func finish() throws -> GroupFinished @@ -2925,7 +2925,7 @@ public final class TrackProducer: @unchecked Sendable { @inlinable public func info() throws -> TrackInfo @inlinable public func createGroup(_ group: GroupInfo) throws -> GroupProducer @inlinable public func appendGroup(_ start: Timestamp) throws -> GroupProducer - @inlinable public func writeFrame(_ timestamp: Timestamp, _ frame: Bytes) throws + @inlinable public func writeFrame(_ timestamp: Timestamp, _ frame: borrowing Swift.Span) throws @inlinable public func finish() throws -> TrackFinished @inlinable public func fail(_ err: Error) throws -> TrackFinished @inlinable public func finishAt(_ end: TrackPosition) throws @@ -5426,7 +5426,7 @@ public struct MuxFollowInstances: ~Copyable, @unchecked Sendable { } public struct MuxImportContainer: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReserved, _ `init`: borrowing MuxImportContainerInit) throws -> MuxImportContainer - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public consuming func finish() throws -> MuxImportContainerFinished @inlinable public consuming func abort(_ err: Error) throws @inlinable public mutating func cut() throws @@ -5434,7 +5434,7 @@ public struct MuxImportContainer: ~Copyable, @unchecked Sendable { } public struct MuxImportContainerExtra: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReservedExtra, _ `init`: borrowing MuxImportContainerInit) throws -> MuxImportContainerExtra - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public consuming func finish() throws -> MuxImportContainerFinishedExtra @inlinable public consuming func abort(_ err: Error) throws @inlinable public mutating func cut() throws @@ -5442,7 +5442,7 @@ public struct MuxImportContainerExtra: ~Copyable, @unchecked Sendable { } public struct MuxImportContainerExt: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReservedExt, _ `init`: borrowing MuxImportContainerInit) throws -> MuxImportContainerExt - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public consuming func finish() throws -> MuxImportContainerFinishedExt @inlinable public consuming func abort(_ err: Error) throws @inlinable public mutating func cut() throws @@ -5497,7 +5497,7 @@ public final class MuxImportTrack { @inlinable public static func videoExtra(_ request: consuming TrackRequest, _ reserved: consuming MuxCatalogReservedExtra, _ `init`: consuming MuxImportVideoInit) throws -> MuxImportTrack @inlinable public static func videoExt(_ request: consuming TrackRequest, _ reserved: consuming MuxCatalogReservedExt, _ `init`: consuming MuxImportVideoInit) throws -> MuxImportTrack @inlinable public static func videoUnit(_ request: consuming TrackRequest, _ reserved: consuming MuxCatalogReserved, _ `init`: consuming MuxImportVideoInit) throws -> MuxImportTrack - @inlinable public func decode(_ frame: Bytes, _ pts: Timestamp?) throws + @inlinable public func decode(_ frame: borrowing Swift.Span, _ pts: Timestamp?) throws @inlinable public func finish() throws -> MuxImportTrackFinished @inlinable public func abort(_ err: Error) throws @inlinable public func abortUnwanted(_ err: Error) throws @@ -5512,8 +5512,8 @@ public final class MuxImportTrackStream { @inlinable public static func videoExtra(_ request: consuming TrackRequest, _ reserved: consuming MuxCatalogReservedExtra, _ `init`: consuming MuxImportVideoInit) throws -> MuxImportTrackStream @inlinable public static func videoExt(_ request: consuming TrackRequest, _ reserved: consuming MuxCatalogReservedExt, _ `init`: consuming MuxImportVideoInit) throws -> MuxImportTrackStream @inlinable public static func videoUnit(_ request: consuming TrackRequest, _ reserved: consuming MuxCatalogReserved, _ `init`: consuming MuxImportVideoInit) throws -> MuxImportTrackStream - @inlinable public func initialize(_ data: Bytes) throws - @inlinable public func decode(_ data: Bytes) throws + @inlinable public func initialize(_ data: borrowing Swift.Span) throws + @inlinable public func decode(_ data: borrowing Swift.Span) throws @inlinable public func finish() throws -> MuxImportTrackFinished @inlinable public func setEnabled(_ enabled: Swift.Bool) throws @inlinable public func abort(_ err: Error) throws @@ -5720,7 +5720,7 @@ public struct TokioTlsPeerIdentity: ~Copyable, @unchecked Sendable { public struct TokioTlsCertificates: ~Copyable, @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } @inlinable public func clone() -> TokioTlsCertificates - @inlinable public static func fromPem(_ chain: Bytes) throws -> TokioTlsCertificates + @inlinable public static func fromPem(_ chain: borrowing Swift.Span) throws -> TokioTlsCertificates @inlinable public func fingerprints() -> [Swift.String] } public struct TokioTlsKeyLog: ~Copyable, @unchecked Sendable { @@ -6002,7 +6002,7 @@ public final class MuxCodecAacImport { @inlinable public func cut(_ end: Timestamp?) throws @inlinable public func discontinuity() throws @inlinable public func seek(_ start: Swift.UInt64) throws - @inlinable public func decode(_ frame: Bytes, _ pts: Timestamp?) throws + @inlinable public func decode(_ frame: borrowing Swift.Span, _ pts: Timestamp?) throws } public final class MuxCodecAnnexbError: @unchecked Sendable, CustomStringConvertible, CustomDebugStringConvertible { @inlinable public var description: Swift.String { get } @@ -6013,7 +6013,7 @@ public final class MuxCodecAv1Import { @inlinable public static func newExtra(_ track: TrackProducer, _ reserved: consuming MuxCatalogReservedExtra, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecAv1Import @inlinable public static func newExt(_ track: TrackProducer, _ reserved: consuming MuxCatalogReservedExt, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecAv1Import @inlinable public static func newUnit(_ track: TrackProducer, _ reserved: consuming MuxCatalogReserved, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecAv1Import - @inlinable public func initialize(_ buf: Bytes) throws + @inlinable public func initialize(_ buf: borrowing Swift.Span) throws @inlinable public func demand() throws -> TrackDemand @inlinable public func finish() throws -> MuxContainerFinishedContainerVideoConfig @inlinable public func abort(_ err: Error) throws @@ -6027,7 +6027,7 @@ public final class MuxCodecAv1Import { public struct MuxCodecAv1Split: ~Copyable, @unchecked Sendable { @inlinable public static func `default`() -> MuxCodecAv1Split @inlinable public static func new() -> MuxCodecAv1Split - @inlinable public mutating func decode(_ data: Bytes, _ pts: Timestamp?) throws -> [MuxContainerFrame] + @inlinable public mutating func decode(_ data: borrowing Swift.Span, _ pts: Timestamp?) throws -> [MuxContainerFrame] @inlinable public mutating func flush(_ pts: Timestamp?) throws -> [MuxContainerFrame] @inlinable public mutating func reset() throws } @@ -6042,7 +6042,7 @@ public final class MuxCodecFlacImport { @inlinable public func cut(_ end: Timestamp?) throws @inlinable public func discontinuity() throws @inlinable public func seek(_ start: Swift.UInt64) throws - @inlinable public func decode(_ frame: Bytes, _ pts: Timestamp?) throws + @inlinable public func decode(_ frame: borrowing Swift.Span, _ pts: Timestamp?) throws } public struct MuxCodecH264Avc1: ~Copyable, @unchecked Sendable { @inlinable public static func `default`() -> MuxCodecH264Avc1 @@ -6074,13 +6074,13 @@ public struct MuxCodecH264Avcc: ~Copyable, @unchecked Sendable { @inlinable public mutating func codedWidthSet(_ value: Swift.UInt32?) throws @inlinable public var codedHeightGet: Swift.UInt32? { get } @inlinable public mutating func codedHeightSet(_ value: Swift.UInt32?) throws - @inlinable public static func parse(_ avcc: Bytes) throws -> MuxCodecH264Avcc + @inlinable public static func parse(_ avcc: borrowing Swift.Span) throws -> MuxCodecH264Avcc } public final class MuxCodecH264Import { @inlinable public static func newExtra(_ track: TrackProducer, _ reserved: consuming MuxCatalogReservedExtra, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecH264Import @inlinable public static func newExt(_ track: TrackProducer, _ reserved: consuming MuxCatalogReservedExt, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecH264Import @inlinable public static func newUnit(_ track: TrackProducer, _ reserved: consuming MuxCatalogReserved, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecH264Import - @inlinable public func initialize(_ buf: Bytes) throws + @inlinable public func initialize(_ buf: borrowing Swift.Span) throws @inlinable public func name() throws -> Swift.String @inlinable public func demand() throws -> TrackDemand @inlinable public func track() throws -> TrackProducer @@ -6099,7 +6099,7 @@ public final class MuxCodecH264Import { public struct MuxCodecH264Split: ~Copyable, @unchecked Sendable { @inlinable public static func `default`() -> MuxCodecH264Split @inlinable public static func new() -> MuxCodecH264Split - @inlinable public mutating func decode(_ data: Bytes, _ pts: Timestamp?) throws -> [MuxContainerFrame] + @inlinable public mutating func decode(_ data: borrowing Swift.Span, _ pts: Timestamp?) throws -> [MuxContainerFrame] @inlinable public mutating func flush(_ pts: Timestamp?) throws -> [MuxContainerFrame] @inlinable public mutating func reset() throws } @@ -6125,12 +6125,12 @@ public struct MuxCodecH265Hvcc: ~Copyable, @unchecked Sendable { @inlinable public mutating func spsSet(_ value: [Bytes]) throws @inlinable public var ppsGet: [Bytes] { get } @inlinable public mutating func ppsSet(_ value: [Bytes]) throws - @inlinable public static func parse(_ hvcc: Bytes) throws -> MuxCodecH265Hvcc + @inlinable public static func parse(_ hvcc: borrowing Swift.Span) throws -> MuxCodecH265Hvcc } public struct MuxCodecH265Sps: ~Copyable, @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } @inlinable public func clone() -> MuxCodecH265Sps - @inlinable public static func parse(_ nal: Bytes) throws -> MuxCodecH265Sps + @inlinable public static func parse(_ nal: borrowing Swift.Span) throws -> MuxCodecH265Sps @inlinable public func size() -> (Swift.UInt32, Swift.UInt32) @inlinable public func videoSignal() -> MuxCodecH265VideoSignal? } @@ -6138,7 +6138,7 @@ public final class MuxCodecH265Import { @inlinable public static func newExtra(_ track: TrackProducer, _ reserved: consuming MuxCatalogReservedExtra, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecH265Import @inlinable public static func newExt(_ track: TrackProducer, _ reserved: consuming MuxCatalogReservedExt, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecH265Import @inlinable public static func newUnit(_ track: TrackProducer, _ reserved: consuming MuxCatalogReserved, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecH265Import - @inlinable public func initialize(_ buf: Bytes) throws + @inlinable public func initialize(_ buf: borrowing Swift.Span) throws @inlinable public func name() throws -> Swift.String @inlinable public func demand() throws -> TrackDemand @inlinable public func track() throws -> TrackProducer @@ -6157,7 +6157,7 @@ public final class MuxCodecH265Import { public struct MuxCodecH265Split: ~Copyable, @unchecked Sendable { @inlinable public static func `default`() -> MuxCodecH265Split @inlinable public static func new() -> MuxCodecH265Split - @inlinable public mutating func decode(_ data: Bytes, _ pts: Timestamp?) throws -> [MuxContainerFrame] + @inlinable public mutating func decode(_ data: borrowing Swift.Span, _ pts: Timestamp?) throws -> [MuxContainerFrame] @inlinable public mutating func flush(_ pts: Timestamp?) throws -> [MuxContainerFrame] @inlinable public mutating func reset() throws } @@ -6172,7 +6172,7 @@ public final class MuxCodecMp3Import { @inlinable public func cut(_ end: Timestamp?) throws @inlinable public func discontinuity() throws @inlinable public func seek(_ start: Swift.UInt64) throws - @inlinable public func decode(_ frame: Bytes, _ pts: Timestamp?) throws + @inlinable public func decode(_ frame: borrowing Swift.Span, _ pts: Timestamp?) throws } public final class MuxCodecOpusConfig: @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } @@ -6205,14 +6205,14 @@ public final class MuxCodecOpusImport { @inlinable public func cut(_ end: Timestamp?) throws @inlinable public func discontinuity() throws @inlinable public func seek(_ start: Swift.UInt64) throws - @inlinable public func decode(_ frame: Bytes, _ pts: Timestamp?) throws + @inlinable public func decode(_ frame: borrowing Swift.Span, _ pts: Timestamp?) throws } public final class MuxCodecVp8Import { @inlinable public static func newExtra(_ track: TrackProducer, _ reserved: consuming MuxCatalogReservedExtra, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecVp8Import @inlinable public static func newExt(_ track: TrackProducer, _ reserved: consuming MuxCatalogReservedExt, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecVp8Import @inlinable public static func newUnit(_ track: TrackProducer, _ reserved: consuming MuxCatalogReserved, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecVp8Import - @inlinable public func initialize(_ buf: Bytes) throws - @inlinable public func decode(_ frame: Bytes, _ pts: Timestamp?) throws + @inlinable public func initialize(_ buf: borrowing Swift.Span) throws + @inlinable public func decode(_ frame: borrowing Swift.Span, _ pts: Timestamp?) throws @inlinable public func demand() throws -> TrackDemand @inlinable public func finish() throws -> MuxContainerFinishedContainerVideoConfig @inlinable public func abort(_ err: Error) throws @@ -6226,8 +6226,8 @@ public final class MuxCodecVp9Import { @inlinable public static func newExtra(_ track: TrackProducer, _ reserved: consuming MuxCatalogReservedExtra, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecVp9Import @inlinable public static func newExt(_ track: TrackProducer, _ reserved: consuming MuxCatalogReservedExt, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecVp9Import @inlinable public static func newUnit(_ track: TrackProducer, _ reserved: consuming MuxCatalogReserved, _ hint: consuming MuxCatalogVideoHint) throws -> MuxCodecVp9Import - @inlinable public func initialize(_ buf: Bytes) throws - @inlinable public func decode(_ frame: Bytes, _ pts: Timestamp?) throws + @inlinable public func initialize(_ buf: borrowing Swift.Span) throws + @inlinable public func decode(_ frame: borrowing Swift.Span, _ pts: Timestamp?) throws @inlinable public func demand() throws -> TrackDemand @inlinable public func finish() throws -> MuxContainerFinishedContainerVideoConfig @inlinable public func abort(_ err: Error) throws @@ -6240,7 +6240,7 @@ public final class MuxCodecVp9Import { public struct MuxContainerFlvImport: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReserved) throws -> MuxContainerFlvImport @inlinable public consuming func withContainer(_ container: consuming HangCatalogContainer) throws -> MuxContainerFlvImport - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public mutating func seek(_ start: Swift.UInt64) throws @inlinable public consuming func finish() throws -> MuxContainerFlvFinished @inlinable public consuming func abort(_ err: Error) throws @@ -6248,7 +6248,7 @@ public struct MuxContainerFlvImport: ~Copyable, @unchecked Sendable { public struct MuxContainerFlvImportExtra: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReservedExtra) throws -> MuxContainerFlvImportExtra @inlinable public consuming func withContainer(_ container: consuming HangCatalogContainer) throws -> MuxContainerFlvImportExtra - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public mutating func seek(_ start: Swift.UInt64) throws @inlinable public consuming func finish() throws -> MuxContainerFlvFinishedExtra @inlinable public consuming func abort(_ err: Error) throws @@ -6256,7 +6256,7 @@ public struct MuxContainerFlvImportExtra: ~Copyable, @unchecked Sendable { public struct MuxContainerFlvImportExt: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReservedExt) throws -> MuxContainerFlvImportExt @inlinable public consuming func withContainer(_ container: consuming HangCatalogContainer) throws -> MuxContainerFlvImportExt - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public mutating func seek(_ start: Swift.UInt64) throws @inlinable public consuming func finish() throws -> MuxContainerFlvFinishedExt @inlinable public consuming func abort(_ err: Error) throws @@ -6271,7 +6271,7 @@ public struct MuxContainerFlvFinishedExt: ~Copyable, @unchecked Sendable { @inlinable public consuming func abort(_ err: Error) throws } public struct MuxContainerFmp4Wire: ~Copyable, @unchecked Sendable { - @inlinable public static func fromInit(_ initData: Bytes) throws -> MuxContainerFmp4Wire + @inlinable public static func fromInit(_ initData: borrowing Swift.Span) throws -> MuxContainerFmp4Wire } public final class MuxContainerFmp4Error: @unchecked Sendable, CustomStringConvertible, CustomDebugStringConvertible { @inlinable public var description: Swift.String { get } @@ -6283,7 +6283,7 @@ public struct MuxContainerFmp4Import: ~Copyable, @unchecked Sendable { @inlinable public mutating func cut() throws @inlinable public consuming func withSelect(_ select: consuming MuxSelectBroadcast) throws -> MuxContainerFmp4Import @inlinable public consuming func withCmaf(_ cmaf: Swift.Bool) throws -> MuxContainerFmp4Import - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public consuming func finish() throws -> MuxContainerFmp4Finished @inlinable public consuming func abort(_ err: Error) throws @inlinable public mutating func seek(_ start: Swift.UInt64) throws @@ -6295,7 +6295,7 @@ public struct MuxContainerFmp4ImportExtra: ~Copyable, @unchecked Sendable { @inlinable public mutating func cut() throws @inlinable public consuming func withSelect(_ select: consuming MuxSelectBroadcast) throws -> MuxContainerFmp4ImportExtra @inlinable public consuming func withCmaf(_ cmaf: Swift.Bool) throws -> MuxContainerFmp4ImportExtra - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public consuming func finish() throws -> MuxContainerFmp4FinishedExtra @inlinable public consuming func abort(_ err: Error) throws @inlinable public mutating func seek(_ start: Swift.UInt64) throws @@ -6307,7 +6307,7 @@ public struct MuxContainerFmp4ImportExt: ~Copyable, @unchecked Sendable { @inlinable public mutating func cut() throws @inlinable public consuming func withSelect(_ select: consuming MuxSelectBroadcast) throws -> MuxContainerFmp4ImportExt @inlinable public consuming func withCmaf(_ cmaf: Swift.Bool) throws -> MuxContainerFmp4ImportExt - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public consuming func finish() throws -> MuxContainerFmp4FinishedExt @inlinable public consuming func abort(_ err: Error) throws @inlinable public mutating func seek(_ start: Swift.UInt64) throws @@ -6338,12 +6338,12 @@ public final class MuxContainerLegacyAudio: @unchecked Sendable, CustomDebugStri @inlinable public func clone() -> MuxContainerLegacyAudio @inlinable public static func == (a: MuxContainerLegacyAudio, b: MuxContainerLegacyAudio) -> Swift.Bool @inlinable public static func new(_ config: borrowing HangCatalogAudioConfig) throws -> MuxContainerLegacyAudio? - @inlinable public func duration(_ payload: Bytes) -> Timestamp? + @inlinable public func duration(_ payload: borrowing Swift.Span) -> Timestamp? } public struct MuxContainerMkvImport: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReserved) throws -> MuxContainerMkvImport @inlinable public consuming func withContainer(_ container: consuming HangCatalogContainer) throws -> MuxContainerMkvImport - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public mutating func seek(_ start: Swift.UInt64) throws @inlinable public consuming func finish() throws -> MuxContainerMkvFinished @inlinable public consuming func abort(_ err: Error) throws @@ -6351,7 +6351,7 @@ public struct MuxContainerMkvImport: ~Copyable, @unchecked Sendable { public struct MuxContainerMkvImportExtra: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReservedExtra) throws -> MuxContainerMkvImportExtra @inlinable public consuming func withContainer(_ container: consuming HangCatalogContainer) throws -> MuxContainerMkvImportExtra - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public mutating func seek(_ start: Swift.UInt64) throws @inlinable public consuming func finish() throws -> MuxContainerMkvFinishedExtra @inlinable public consuming func abort(_ err: Error) throws @@ -6359,7 +6359,7 @@ public struct MuxContainerMkvImportExtra: ~Copyable, @unchecked Sendable { public struct MuxContainerMkvImportExt: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReservedExt) throws -> MuxContainerMkvImportExt @inlinable public consuming func withContainer(_ container: consuming HangCatalogContainer) throws -> MuxContainerMkvImportExt - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public mutating func seek(_ start: Swift.UInt64) throws @inlinable public consuming func finish() throws -> MuxContainerMkvFinishedExt @inlinable public consuming func abort(_ err: Error) throws @@ -6525,7 +6525,7 @@ public struct MuxContainerTsPassthrough: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReservedExt) throws -> MuxContainerTsPassthrough @inlinable public consuming func withPcrPid(_ pid: Swift.UInt16) throws -> MuxContainerTsPassthrough @inlinable public func track() throws -> Swift.String - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public consuming func finish() throws -> MuxContainerTsPassthroughFinished @inlinable public consuming func abort(_ err: Error) throws } @@ -6533,7 +6533,7 @@ public struct MuxContainerTsPassthroughUnit: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReserved) throws -> MuxContainerTsPassthroughUnit @inlinable public consuming func withPcrPid(_ pid: Swift.UInt16) throws -> MuxContainerTsPassthroughUnit @inlinable public func track() throws -> Swift.String - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public consuming func finish() throws -> MuxContainerTsPassthroughFinishedUnit @inlinable public consuming func abort(_ err: Error) throws } @@ -6541,13 +6541,13 @@ public struct MuxContainerTsPassthroughExtra: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReservedExtra) throws -> MuxContainerTsPassthroughExtra @inlinable public consuming func withPcrPid(_ pid: Swift.UInt16) throws -> MuxContainerTsPassthroughExtra @inlinable public func track() throws -> Swift.String - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public consuming func finish() throws -> MuxContainerTsPassthroughFinishedExtra @inlinable public consuming func abort(_ err: Error) throws } public struct MuxContainerTsPrograms: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ origin: consuming OriginProducer, _ name: consuming Path, _ config: consuming MuxCatalogConfig) throws -> MuxContainerTsPrograms - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public func stats() throws -> MuxContainerTsStatsSnapshot @inlinable public consuming func finish() throws -> MuxContainerTsProgramsFinished @inlinable public consuming func abort(_ err: Error) throws @@ -6566,7 +6566,7 @@ public struct MuxContainerTsRepublish: ~Copyable, @unchecked Sendable { @inlinable public func broadcast() throws -> BroadcastProducer @inlinable public func catalog() throws -> MuxCatalogProducerExt @inlinable public func instance() throws -> Instance - @inlinable public mutating func decode(_ data: Bytes) throws -> MuxContainerTsRepublished? + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws -> MuxContainerTsRepublished? @inlinable public func stats() throws -> MuxContainerTsStatsSnapshot @inlinable public consuming func finish() throws -> MuxContainerTsRepublishFinished @inlinable public consuming func abort(_ err: Error) throws @@ -6583,7 +6583,7 @@ public struct MuxContainerTsImport: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReserved) throws -> MuxContainerTsImport @inlinable public consuming func withProgram(_ program: Swift.UInt16) throws -> MuxContainerTsImport @inlinable public consuming func withContainer(_ container: consuming HangCatalogContainer) throws -> MuxContainerTsImport - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public mutating func seek(_ sequence: Swift.UInt64) throws @inlinable public consuming func finish() throws -> MuxContainerTsFinished @inlinable public func stats() throws -> MuxContainerTsStatsSnapshot @@ -6593,7 +6593,7 @@ public struct MuxContainerTsImportExtra: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReservedExtra) throws -> MuxContainerTsImportExtra @inlinable public consuming func withProgram(_ program: Swift.UInt16) throws -> MuxContainerTsImportExtra @inlinable public consuming func withContainer(_ container: consuming HangCatalogContainer) throws -> MuxContainerTsImportExtra - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public mutating func seek(_ sequence: Swift.UInt64) throws @inlinable public consuming func finish() throws -> MuxContainerTsFinishedExtra @inlinable public func stats() throws -> MuxContainerTsStatsSnapshot @@ -6603,7 +6603,7 @@ public struct MuxContainerTsImportExt: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ broadcast: consuming BroadcastProducer, _ reserved: consuming MuxCatalogReservedExt) throws -> MuxContainerTsImportExt @inlinable public consuming func withProgram(_ program: Swift.UInt16) throws -> MuxContainerTsImportExt @inlinable public consuming func withContainer(_ container: consuming HangCatalogContainer) throws -> MuxContainerTsImportExt - @inlinable public mutating func decode(_ data: Bytes) throws + @inlinable public mutating func decode(_ data: borrowing Swift.Span) throws @inlinable public mutating func seek(_ sequence: Swift.UInt64) throws @inlinable public consuming func finish() throws -> MuxContainerTsFinishedExt @inlinable public func stats() throws -> MuxContainerTsStatsSnapshot @@ -6645,8 +6645,8 @@ public final class MuxCodecAacAdtsHeader: @unchecked Sendable { @inlinable public func channelConfigSet(_ value: Swift.UInt8) throws @inlinable public var blocksGet: Swift.UInt8 { get } @inlinable public func blocksSet(_ value: Swift.UInt8) throws - @inlinable public static func parse(_ data: Bytes) throws -> MuxCodecAacAdtsHeader - @inlinable public func payload(_ packet: Bytes) throws -> Bytes + @inlinable public static func parse(_ data: borrowing Swift.Span) throws -> MuxCodecAacAdtsHeader + @inlinable public func payload(_ packet: borrowing Swift.Span) throws -> Bytes } public struct MuxContainerTsPassthroughFinished: ~Copyable, @unchecked Sendable { @inlinable public func track() throws -> Swift.String @@ -6894,7 +6894,7 @@ public struct RustlsPkiTypesCertificateDer: ~Copyable, @unchecked Sendable { @inlinable public func clone() throws -> RustlsPkiTypesCertificateDer @inlinable public static func == (a: borrowing RustlsPkiTypesCertificateDer, b: borrowing RustlsPkiTypesCertificateDer) throws -> Swift.Bool @inlinable public func hash(into hasher: inout Swift.Hasher) throws - @inlinable public static func fromSlice(_ bytes: Bytes) -> RustlsPkiTypesCertificateDer + @inlinable public static func fromSlice(_ bytes: borrowing Swift.Span) -> RustlsPkiTypesCertificateDer @inlinable public consuming func intoOwned() throws -> RustlsPkiTypesCertificateDer } public struct MoqTokioConnectResolved: ~Copyable, @unchecked Sendable { @@ -7133,7 +7133,7 @@ public struct RustlsClientResumption: ~Copyable, @unchecked Sendable { public struct RustlsDistinguishedName: ~Copyable, @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } @inlinable public func clone() -> RustlsDistinguishedName - @inlinable public static func inSequence(_ bytes: Bytes) -> RustlsDistinguishedName + @inlinable public static func inSequence(_ bytes: borrowing Swift.Span) -> RustlsDistinguishedName } public struct MoqTokioWebsocketResolved: ~Copyable, @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } @@ -7184,7 +7184,7 @@ public struct RustlsPkiTypesDer: ~Copyable, @unchecked Sendable { @inlinable public func clone() throws -> RustlsPkiTypesDer @inlinable public static func == (a: borrowing RustlsPkiTypesDer, b: borrowing RustlsPkiTypesDer) throws -> Swift.Bool @inlinable public func hash(into hasher: inout Swift.Hasher) throws - @inlinable public static func fromSlice(_ der: Bytes) -> RustlsPkiTypesDer + @inlinable public static func fromSlice(_ der: borrowing Swift.Span) -> RustlsPkiTypesDer } public struct MoqTokioQuicDemuxDatagram: ~Copyable, @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } @@ -7346,18 +7346,18 @@ public let HANG_CATALOG_MAX_SAFE_INTEGER: Swift.UInt64 @inlinable public func tokioTlsParseFingerprint(_ value: Swift.String) throws -> ArrayU8x32 @inlinable public func tokioOriginSpawn() -> OriginProducer @inlinable public func transportMemoryPair(_ config: consuming TransportMemoryConfig) throws -> TupleTransportMemorySessionTransportMemorySession -@inlinable public func muxCodecAacConfig(_ `init`: Bytes) throws -> HangCatalogAudioConfig +@inlinable public func muxCodecAacConfig(_ `init`: borrowing Swift.Span) throws -> HangCatalogAudioConfig @inlinable public var MUXCODECANNEXBSTARTCODE: Bytes { get } -@inlinable public func muxCodecAnnexbFromLengthPrefixed(_ payload: Bytes, _ lengthSize: Swift.UInt, _ prefix: Bytes?) throws -> Bytes +@inlinable public func muxCodecAnnexbFromLengthPrefixed(_ payload: borrowing Swift.Span, _ lengthSize: Swift.UInt, _ prefix: borrowing Swift.Span?) throws -> Bytes @inlinable public func muxCodecAnnexbBuildPrefix(_ nals: [Bytes]) -> Bytes -@inlinable public func muxCodecAnnexbLengthPrefixedToAnnexb(_ data: Bytes, _ lengthSize: Swift.UInt, _ out: inout Bytes) throws -@inlinable public func muxCodecAnnexbAfterStartCode(_ b: Bytes) throws -> Swift.UInt? -@inlinable public func muxCodecAnnexbFindStartCode(_ b: Bytes) -> (Swift.UInt, Swift.UInt)? -@inlinable public func muxCodecFlacConfig(_ `init`: Bytes) throws -> HangCatalogAudioConfig -@inlinable public func muxCodecH264Config(_ buf: Bytes) throws -> HangCatalogVideoConfig -@inlinable public func muxCodecH265Config(_ buf: Bytes) throws -> HangCatalogVideoConfig -@inlinable public func muxCodecMp3Config(_ `init`: Bytes) throws -> HangCatalogAudioConfig +@inlinable public func muxCodecAnnexbLengthPrefixedToAnnexb(_ data: borrowing Swift.Span, _ lengthSize: Swift.UInt, _ out: inout Bytes) throws +@inlinable public func muxCodecAnnexbAfterStartCode(_ b: borrowing Swift.Span) throws -> Swift.UInt? +@inlinable public func muxCodecAnnexbFindStartCode(_ b: borrowing Swift.Span) -> (Swift.UInt, Swift.UInt)? +@inlinable public func muxCodecFlacConfig(_ `init`: borrowing Swift.Span) throws -> HangCatalogAudioConfig +@inlinable public func muxCodecH264Config(_ buf: borrowing Swift.Span) throws -> HangCatalogVideoConfig +@inlinable public func muxCodecH265Config(_ buf: borrowing Swift.Span) throws -> HangCatalogVideoConfig +@inlinable public func muxCodecMp3Config(_ `init`: borrowing Swift.Span) throws -> HangCatalogAudioConfig @inlinable public var MUXCODECOPUSWARMUP: RustDuration { get } -@inlinable public func muxCodecOpusPacketSamples(_ packet: Bytes) -> Swift.UInt32? -@inlinable public func muxCodecOpusConfig(_ `init`: Bytes) throws -> HangCatalogAudioConfig +@inlinable public func muxCodecOpusPacketSamples(_ packet: borrowing Swift.Span) -> Swift.UInt32? +@inlinable public func muxCodecOpusConfig(_ `init`: borrowing Swift.Span) throws -> HangCatalogAudioConfig @inlinable public func muxContainerMp4Repair(_ file: inout some SeekableReader) throws -> MuxContainerMp4Finish? diff --git a/ffi/tests/api.swift b/ffi/tests/api.swift index 2e680c490..184dab902 100644 --- a/ffi/tests/api.swift +++ b/ffi/tests/api.swift @@ -73,6 +73,17 @@ func text(_ data: Bytes) -> String { String(decoding: data, as: UTF8.self) } +/// `text`'s UTF-8, lent to `body` as a span. +func lend(_ text: String, _ body: (Swift.Span) throws -> R) rethrows -> R { + try Bytes(text.utf8).withSpan(body) +} + +/// `items`, lent to `body` as a span: an array's own `span` needs macOS 26, its slice's none. +func lend(_ items: [T], _ body: (Swift.Span) throws -> R) rethrows -> R { + let slice = items[...] + return try body(slice.span) +} + /// Check that `body` throws for the call `function` of a Refusal a move closed. func closed(_ function: String, _ body: () throws -> Void) { do { @@ -313,7 +324,7 @@ func script() { } } for needle in ["lo", "x"] { - if let found = find(Bytes("hello".utf8), Bytes(needle.utf8)) { + if let found = lend("hello", { haystack in lend(needle) { find(haystack, $0) } }) { print("find \(found.0) \(found.1)") } else { print("find none") @@ -453,11 +464,11 @@ func script() { print("window \(window.contains(4)) \(window.contains(6)) \(debug(window))") print(greet("x", .square)) - print("len \(len(Bytes("abc".utf8)))") + print("len \(lend("abc") { len($0) })") let binary = Bytes([0xff, 0, 0x61]) print("hex \(hex(binary))") print("timed hex \(timedHex(binary))") - print("sample hex \(sampleHex(binary))") + print("sample hex \(binary.withSpan { sampleHex($0) })") print("queued hex \(queuedHex(binary))") print("tick \(tickName(Label(name: "tick", at: nil, ttl: nil)))") print("rooted \(rootedName(Label(name: "rooted", at: nil, ttl: nil)))") @@ -592,8 +603,10 @@ func script() { print("recv \(text(try await channel.recv()))") // The send happens at the call, and the future borrows the channel and the tag. print("tagged \(try await channel.tagged("tag"))") - print("itemized \(try await channel.itemized([1, 2, 3]))") - print("byte_len \(try await byteLen(Bytes("abc".utf8)))") + let items: ArraySlice = [1, 2, 3] + print("itemized \(try await channel.itemized(items.span))") + let abc = Array("abc".utf8)[...] + print("byte_len \(try await byteLen(abc.span))") try! channel.send(Bytes("sized".utf8)) let (payload, size) = try await channel.recvSized() print("sized \(text(payload)) \(size)") @@ -740,7 +753,7 @@ func script() { print("sentence \(sentence(words)) \(sentence(nil))") print("sentence \(sentence([]))|") print("either \(either("abc")) \(either(nil))") - print("prefixed \(String(decoding: prefixed(Bytes("cd".utf8), Bytes("ab".utf8)), as: UTF8.self)) \(String(decoding: prefixed(Bytes("cd".utf8), nil), as: UTF8.self))") + print("prefixed \(String(decoding: lend("cd", { cd in lend("ab") { prefixed(cd, $0) } }), as: UTF8.self)) \(String(decoding: lend("cd") { prefixed($0, nil) }, as: UTF8.self))") print("coordinates \(coordinates(Point(x: 2, y: 3))) \(coordinates(nil))") do { // An optional borrowed handle is an overload with it and one without; one borrowed @@ -828,12 +841,12 @@ func script() { do { let config = secure("h3") print("secure \(try! alpnLent(config)) \(try! alpn(config.clone()))") - let cert = certify(Bytes("der".utf8)) + let cert = lend("der") { certify($0) } let certLength = try! certLen(cert) let der = text(try! certDer(cert)) var chain = UniqueArray() - chain.append(certify(Bytes("a".utf8))) - chain.append(certify(Bytes("bc".utf8))) + chain.append(lend("a") { certify($0) }) + chain.append(lend("bc") { certify($0) }) print("cert \(certLength) \(der) \(try! chainLen(chain))") // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. print("resolver \(try! resolved(resolver("r1")))") @@ -857,8 +870,8 @@ func script() { print("offered_len \(offeredLen([Bytes("h3".utf8), Bytes("moq-00".utf8)]))") print("join_words \(joinWords(["a", "b", "c"]))") // Bytes that must be `'static`, interned. - print("der \(text(Der.fromSlice(Bytes("der".utf8)).bytes()))") - print("der again \(text(Der.fromSlice(Bytes("der".utf8)).bytes()))") + print("der \(text(lend("der") { Der.fromSlice($0) }.bytes()))") + print("der again \(text(lend("der") { Der.fromSlice($0) }.bytes()))") let session = try! resume("h3", 60) print("resume \(session.alpn()) \(session.lifetime().seconds)") do { @@ -936,7 +949,7 @@ func script() { check(false, "a sealed ledger throws an Error") } } - print("chunks \(chunks(Bytes("abcde".utf8), 2).map { Array($0) })") + print("chunks \(lend("abcde") { chunks($0, 2) }.map { Array($0) })") var counters = counters(["x", "y"]) print("counters \(listed(counters) { "\(try! $0.name()) \(try! $0.get())" })") // Each counter moves in. @@ -955,8 +968,8 @@ func script() { let edges = Numbers.edges() let nan = Measure.new(Double.nan, false) print("float equal \(edges == edges) \(edges == Numbers.edges()) \(Numbers.zero(true) == Numbers.zero(false)) \(nan == nan) \(Measure.new(-0.0, true) == Measure.new(0.0, false))") - print("sum u32 \(sumU32([])) \(sumU32([UInt32.max, UInt32.max, 2]))") - print("doubled i64 \(doubledI64([Int64.min, -1, 0, Int64.max]))") + print("sum u32 \(lend([UInt32]()) { sumU32($0) }) \(lend([UInt32.max, UInt32.max, 2]) { sumU32($0) })") + print("doubled i64 \(lend([Int64.min, -1, 0, Int64.max]) { doubledI64($0) })") print("boxed floats \(boxedFloats([-0.0, Double(bitPattern: 0x7ff8_0000_0000_0001)]).map(\.bitPattern))") let sum = summed([Point(x: 1, y: 2), Point(x: -4, y: 6)]) let noneSum = summed([]) @@ -969,7 +982,7 @@ func script() { let high = String(decoding: limits.high, as: UTF8.self) print("limits \(low) \(high) breadth \(waits.secs * 1000 + UInt64(waits.nanos) / 1_000_000)") let parts = String(decoding: Api.joined([Bytes("ab".utf8), Bytes(), Bytes("c".utf8)]), as: UTF8.self) - print("joined \(parts) \(Api.joined([]).count) read \(readLen(Bytes("hello".utf8)))") + print("joined \(parts) \(Api.joined([]).count) read \(lend("hello") { readLen($0) })") let doc = try! Json.parse(#"{"b": [1, 2.5, null], "a": "é"}"#) print("json \(try! encode(doc))") print("timed text \(try! timedText(doc))") @@ -1544,7 +1557,7 @@ func owned() { /// Where `bytes` start. func address(_ bytes: Bytes) -> UnsafeRawPointer? { - bytes.withUnsafeBytes { $0.baseAddress } + bytes.withSpan { $0.withUnsafeBufferPointer { UnsafeRawPointer($0.baseAddress) } } } // A payload Rust returned, read and written back, whole and in a record: Rust takes a @@ -1570,6 +1583,21 @@ func forward() { // Each breaks a contract Swift's compiler checks, so it fails to compile, built alone with // its flag. +/// A digest of the bytes Rust lends, read in place. +struct ScanDigest: Scan { + func scan(_ payload: Swift.Span, _ rest: Swift.Span?) -> UInt64 { + var sum = UInt64(payload.count) << 32 + for i in payload.indices { + sum += UInt64(payload[i]) + } + guard let rest else { return sum + (1 << 48) } + for i in rest.indices { + sum += UInt64(rest[i]) * 256 + } + return sum + } +} + #if MOVED func moved() { let c = Counter.new("c", 0) @@ -1596,6 +1624,20 @@ func lentMoved() { } #endif +#if SPAN_KEPT +/// Keeps a span Rust lent past the call it was lent for. +func spanKept() { + lend("ab") { whole in + nonisolated(unsafe) var kept: Swift.Span? = nil + _ = visitChunks(whole, 1) { chunk in + kept = chunk + return 0 + } + print(kept?.count ?? 0) + } +} +#endif + #if LENT_KEPT /// Holds a lent tally past the call it was lent for. final class Kept: @unchecked Sendable { @@ -1687,6 +1729,18 @@ func lossless() { print("lossless path \(hexBytes(samePath("a/é").bytes)) \(hexBytes(samePath(strayPath).bytes))") check(samePath(strayPath) == strayPath, "a path that is not UTF-8 crosses back") visitStray { path in check(path == strayPath, "a lent path that is not UTF-8 keeps its bytes") } + // Rust borrows a caller's span in place, and lends a closure each chunk of it in place. + lend("abcde") { whole in + let base = UInt64(UInt(bitPattern: whole.withUnsafeBufferPointer { $0.baseAddress })) + let seen = visitChunks(whole, 2) { chunk in + guard let chunk else { return 7 } + let at = chunk.withUnsafeBufferPointer { UInt64(UInt(bitPattern: $0.baseAddress)) } + return (at - base) * 1000 + UInt64(chunk[chunk.count - 1]) + } + check(seen == [98, 2100, 4101, 7], "a closure reads each chunk of a caller's bytes in place") + } + let digest = scanned(ScanDigest(), Bytes("abcd".utf8)) + check(digest == (2 << 32) + 97 + 98 + (99 + 100) * 256 + (1 << 48), "a callback reads lent bytes and none") check(samePath(PathBuf(bytes: Bytes([0xff]))) == strayPath, "a caller's bytes make a path") let v4 = sameSocketAddrV4(SocketAddrV4(ip: Ipv4Addr(bits: .max), port: .max)) let ip6 = Ipv6Addr(bits: U128(high: 1 << 48, low: 2)) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index d9a4a360f..f312fe677 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1417,6 +1417,7 @@ fn api_swift() { "missing reinitialization of inout parameter 'counter' after consume", ), ("LENT_KEPT", "implicit conversion to 'Tally?' is consuming"), + ("SPAN_KEPT", "lifetime-dependent variable 'kept' escapes its scope"), ] { let step = Step { stamp: &dir.join(format!("{case}.stamp")), diff --git a/ffi/tests/fixtures/shapes.rs b/ffi/tests/fixtures/shapes.rs index 8b6e2fe64..2e1dd0d93 100644 --- a/ffi/tests/fixtures/shapes.rs +++ b/ffi/tests/fixtures/shapes.rs @@ -1201,7 +1201,8 @@ fn python(built: &Built, calls: &[Call]) -> String { /// The Swift driver, in the generated module's `main.swift`: each shape's calls in a /// function of its own, since type-checking them as one body of top-level code takes -/// tens of gigabytes. +/// tens of gigabytes, and `lend`, which lends bytes or an array to a `digest_N` borrowing +/// a slice as the span it takes. fn swift(calls: &[Call], source: &str) -> String { // Whether the generated `func` throws, as one taking a checked handle does. let throws = |function: &str| { @@ -1219,17 +1220,32 @@ fn swift(calls: &[Call], source: &str) -> String { true => "try! ", false => "", }; + // `digest_N` of the value `v`, lent as a span where it borrows a slice. + let digest = |n: usize, v: String| { + match source.contains(&format!("public func digest{n}(_ v: borrowing Swift.Span<")) { + true => { + let t = match throws(&format!("digest{n}")) { + true => "try ", + false => "", + }; + format!("lend({v}) {{ {t}digest{n}($0) }}") + } + false => format!("digest{n}({v})"), + } + }; let shapes = by_shape(calls, |call| { let value = match call { Call::Echo(n, seed) => format!( - "{}digest{n}(echo{n}(make{n}({seed})))", - tr(&[format!("digest{n}"), format!("echo{n}"), format!("make{n}")]) + "{}{}", + tr(&[format!("digest{n}"), format!("echo{n}"), format!("make{n}")]), + digest(n, format!("echo{n}(make{n}({seed}))")) ), Call::Lent(n, seed) => { format!( - "{}lent{n}({seed}) {{ {}digest{n}($0) }}", + "{}lent{n}({seed}) {{ {}{} }}", tr(&[format!("lent{n}")]), - closed(format!("digest{n}")) + closed(format!("digest{n}")), + digest(n, "$0".to_string()) ) } Call::Peek(n, seed) => { @@ -1247,11 +1263,14 @@ fn swift(calls: &[Call], source: &str) -> String { ) } // The future throws, so `try` always marks the call. - Call::Later(n, seed) => format!("try await digest{n}(later{n}(make{n}({seed})))"), + Call::Later(n, seed) => format!("try await {}", digest(n, format!("later{n}(make{n}({seed}))"))), }; format!("\tprint(\"{} \\({value})\")", call.label()) }); - let mut out = String::new(); + let mut out = String::from( + "func lend(_ bytes: Bytes, _ body: (Swift.Span) throws -> R) rethrows -> R {\n\ttry bytes.withSpan(body)\n}\n\n\ + func lend(_ items: [T], _ body: (Swift.Span) throws -> R) rethrows -> R {\n\tlet slice = items[...]\n\treturn try body(slice.span)\n}\n\n", + ); for (n, lines) in &shapes { let _ = writeln!(out, "func shape{n}() async throws {{\n{lines}}}\n"); } From 1b7ebdd03d5a21d2e18cc83657cde84ffd08c5d4 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 18:16:21 -0800 Subject: [PATCH 03/13] wip: quest --- quest/m1/ffi-export/README.md | 2 +- quest/m1/ffi-export/ship.md | 1 - quest/m1/ffi-export/swift-span.md | 26 -------------------------- quest/m1/ffi-speed/README.md | 2 +- quest/m3/swift-bytes-span.md | 29 +++++++++++++++++++++++++++++ 5 files changed, 31 insertions(+), 29 deletions(-) delete mode 100644 quest/m1/ffi-export/swift-span.md create mode 100644 quest/m3/swift-bytes-span.md diff --git a/quest/m1/ffi-export/README.md b/quest/m1/ffi-export/README.md index 3c29f909f..a3b63ed8c 100644 --- a/quest/m1/ffi-export/README.md +++ b/quest/m1/ffi-export/README.md @@ -97,7 +97,7 @@ Decided with the maintainer on 2026-11-18, in the per-language audit: - ✅ Breaking changes to a generated API that the audit found are children here, and land as soon as possible: "You're allowed to break the API absolutely. Do it sooner." They are the API surface lock (`ffi/surface/`), which landed first, - [C and C++](/quest/m1/ffi-export/cpp-idioms.md), [Swift](/quest/m1/ffi-export/swift-span.md), + [C and C++](/quest/m1/ffi-export/cpp-idioms.md), Swift, [Kotlin](/quest/m1/ffi-export/kotlin-idioms.md), [Python](/quest/m1/ffi-export/python-idioms.md), [Dart](/quest/m1/ffi-export/dart-analyze.md), and [docs](/quest/m1/ffi-export/docs.md). Rejected: only the surface lock holding the pin; all of them after the pin. diff --git a/quest/m1/ffi-export/ship.md b/quest/m1/ffi-export/ship.md index 48e5d7073..241bf43ff 100644 --- a/quest/m1/ffi-export/ship.md +++ b/quest/m1/ffi-export/ship.md @@ -21,7 +21,6 @@ then see change. A sibling planned later adds itself to `Required` here. - [Refusals](/quest/m1/ffi-refusals/README.md) - the census lists no refusals at the moq pin, and `ffi.toml` is gone - [C and C++ idioms](/quest/m1/ffi-export/cpp-idioms.md) - numeric slice views and must-use returns change the C++ API -- [Swift spans](/quest/m1/ffi-export/swift-span.md) - lent bytes and slices change the Swift API - [Kotlin idioms](/quest/m1/ffi-export/kotlin-idioms.md) - direct buffers and Java annotations change the Kotlin API - [Python idioms](/quest/m1/ffi-export/python-idioms.md) - the exception hierarchy changes the Python API - [Dart analysis](/quest/m1/ffi-export/dart-analyze.md) - lint fixes may rename generated Dart diff --git a/quest/m1/ffi-export/swift-span.md b/quest/m1/ffi-export/swift-span.md deleted file mode 100644 index 58276f896..000000000 --- a/quest/m1/ffi-export/swift-span.md +++ /dev/null @@ -1,26 +0,0 @@ -# [M] Swift: lend bytes and numeric slices as Span - -## Goal - -The Swift binding lends bytes and numeric slices to closures as `Span`/`RawSpan` with -no copy, takes `&[u8]` and numeric `&[T]` parameters as `borrowing Span`, and gives -`Bytes` a `span` accessor, so a frame's payload crosses into Swift without the copy -`lift_lent` makes today (`ffi/src/swift.rs:683-688`). The compiler, not a run-time check, -keeps a lent span from escaping. - -## Plan - -Found by the 2026-11-18 language audit. Swift 6.2's `Span` back-deploys to iOS 12.2 and -macOS 10.14.4 ([SE-0456](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0456-stdlib-span-properties.md), -[back-deployment](https://forums.swift.org/t/using-span-on-pre-26-apple-os-versions/80513)); -`Array.span` needs OS 26, so building spans must not rely on it. - -Decided with the maintainer on 2026-11-18: ✅ breaking changes land in this epic before -moq pins, as soon as possible (rejected: after the pin). - -First check that generated code can build a span without the experimental Lifetimes -flags; if it cannot, report what it would take and stop. Measure the lent-bytes cases on -[the binding benchmark](/bench/ffi/README.md) before and after. - -Public API: breaking for Swift callers of closures that receive lent bytes, and of -functions taking byte or numeric slices. diff --git a/quest/m1/ffi-speed/README.md b/quest/m1/ffi-speed/README.md index 223159851..02dc03014 100644 --- a/quest/m1/ffi-speed/README.md +++ b/quest/m1/ffi-speed/README.md @@ -11,7 +11,7 @@ every child has merged. Decided with the maintainer on 2026-11-18, in the per-language audit: ✅ all of the speed findings are kept (rejected: any subset). The zero-copy buffer findings change generated APIs, so they are children of [the exporter epic](/quest/m1/ffi-export/README.md) instead: -[C++](/quest/m1/ffi-export/cpp-idioms.md), [Swift](/quest/m1/ffi-export/swift-span.md), and +[C++](/quest/m1/ffi-export/cpp-idioms.md), Swift, and [Kotlin](/quest/m1/ffi-export/kotlin-idioms.md). This epic changes no generated API and does not hold moq's pin. diff --git a/quest/m3/swift-bytes-span.md b/quest/m3/swift-bytes-span.md new file mode 100644 index 000000000..4ae64ada4 --- /dev/null +++ b/quest/m3/swift-bytes-span.md @@ -0,0 +1,29 @@ +# [S] Swift: a span property on Bytes + +## Goal + +`Bytes` has a `span` property, so a caller passes Rust's own bytes to a call borrowing a +slice as `f(payload.span)` rather than `payload.withSpan { f($0) }`, with no experimental +compiler feature asked of a consumer's build. + +## Plan + +Found by [Swift spans](https://github.com/kixel-ai/rust2/pull/902), which takes slices as +`Span` and gave `Bytes` the scoped `withSpan`. A property returning a `Span` needs +`@_lifetime(borrow self)`, which Swift 6.4 builds only under +`-enable-experimental-feature Lifetimes`. It also needs `Bytes` addressable for its +dependents (`AddressableTypes`, as Foundation's `Data.span` has), since `Data` keeps up to +14 bytes inline in the value, where a borrow may copy them. + +Recommended: wait for both to leave experimental, since a consumer would otherwise add +two experimental flags to its build of the generated file, whose spelling has already +changed once (`@lifetime` to `@_lifetime` in 6.2). Rejected: those flags now. + +Public API: adds `Bytes.span`; nothing breaks. + +## Waiting + +- swiftlang/swift-evolution: lifetime dependencies and addressable types accepted, so a + release toolchain builds `@_lifetime` and `@_addressableForDependencies` without + `-enable-experimental-feature`; check by compiling a getter that returns + `_overrideLifetime(span, borrowing: self)` with plain `swiftc`. From 078431ae6699bb50b35ae571485d2047b457eb4e Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 18:17:33 -0800 Subject: [PATCH 04/13] wip: fmt --- ffi/src/swift.rs | 3 ++- ffi/tests/fixtures/shapes.rs | 7 +++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/ffi/src/swift.rs b/ffi/src/swift.rs index 2628d38b9..d12555b66 100644 --- a/ffi/src/swift.rs +++ b/ffi/src/swift.rs @@ -709,7 +709,8 @@ impl<'a> Gen<'a> { /// for its call: a slice as a span of it in place, other bytes and text copied, and a /// scalar as it is. fn lift_lent(&mut self, ty: &Type, e: &str) -> String { - let span = |e: &str| format!("Swift.Span(_unsafeElements: Swift.UnsafeBufferPointer(start: {e}.ptr, count: {e}.len))"); + let span = + |e: &str| format!("Swift.Span(_unsafeElements: Swift.UnsafeBufferPointer(start: {e}.ptr, count: {e}.len))"); match ty { _ if self.spanned(ty).is_some() => span(e), Type::Option(inner) if self.spanned(inner).is_some() => format!("({e}.ptr == nil ? nil : {})", span(e)), diff --git a/ffi/tests/fixtures/shapes.rs b/ffi/tests/fixtures/shapes.rs index 2e1dd0d93..985d27441 100644 --- a/ffi/tests/fixtures/shapes.rs +++ b/ffi/tests/fixtures/shapes.rs @@ -1221,8 +1221,8 @@ fn swift(calls: &[Call], source: &str) -> String { false => "", }; // `digest_N` of the value `v`, lent as a span where it borrows a slice. - let digest = |n: usize, v: String| { - match source.contains(&format!("public func digest{n}(_ v: borrowing Swift.Span<")) { + let digest = + |n: usize, v: String| match source.contains(&format!("public func digest{n}(_ v: borrowing Swift.Span<")) { true => { let t = match throws(&format!("digest{n}")) { true => "try ", @@ -1231,8 +1231,7 @@ fn swift(calls: &[Call], source: &str) -> String { format!("lend({v}) {{ {t}digest{n}($0) }}") } false => format!("digest{n}({v})"), - } - }; + }; let shapes = by_shape(calls, |call| { let value = match call { Call::Echo(n, seed) => format!( From 3ade9f66a28dd522530947d605c9bfc9290e6b4f Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 18:50:29 -0800 Subject: [PATCH 05/13] ffi(swift): Bytes copies a lent span, as a closure keeps it --- ffi/runtime/rt.swift | 5 +++++ ffi/surface/api/swift.swift | 1 + ffi/surface/moq/swift.swift | 1 + ffi/tests/api.swift | 8 ++++++++ 4 files changed, 15 insertions(+) diff --git a/ffi/runtime/rt.swift b/ffi/runtime/rt.swift index 7bf1d8818..bd1cea723 100644 --- a/ffi/runtime/rt.swift +++ b/ffi/runtime/rt.swift @@ -259,6 +259,11 @@ public struct Bytes: Hashable, Sendable, RandomAccessCollection { self.init(Data(bytes)) } + /// `span`'s bytes, copied, as a closure keeps bytes Rust lent it. + public init(_ span: borrowing Swift.Span) { + self.init(span.withUnsafeBufferPointer { Data(buffer: $0) }) + } + /// The bytes as a `Data`: Swift's as they are, and Rust's copied. public var data: Data { owner == nil ? storage : Data(storage) diff --git a/ffi/surface/api/swift.swift b/ffi/surface/api/swift.swift index 7a3915648..fe7786402 100644 --- a/ffi/surface/api/swift.swift +++ b/ffi/surface/api/swift.swift @@ -58,6 +58,7 @@ public struct Bytes: Hashable, Sendable, RandomAccessCollection { @inlinable public init() @inlinable public init(_ data: Data) @inlinable public init(_ bytes: some Swift.Sequence) + @inlinable public init(_ span: borrowing Swift.Span) @inlinable public var data: Data { get } @inlinable public var startIndex: Swift.Int { get } @inlinable public var endIndex: Swift.Int { get } diff --git a/ffi/surface/moq/swift.swift b/ffi/surface/moq/swift.swift index 63f5874d2..3622eb68f 100644 --- a/ffi/surface/moq/swift.swift +++ b/ffi/surface/moq/swift.swift @@ -58,6 +58,7 @@ public struct Bytes: Hashable, Sendable, RandomAccessCollection { @inlinable public init() @inlinable public init(_ data: Data) @inlinable public init(_ bytes: some Swift.Sequence) + @inlinable public init(_ span: borrowing Swift.Span) @inlinable public var data: Data { get } @inlinable public var startIndex: Swift.Int { get } @inlinable public var endIndex: Swift.Int { get } diff --git a/ffi/tests/api.swift b/ffi/tests/api.swift index 091b9213a..1031192ee 100644 --- a/ffi/tests/api.swift +++ b/ffi/tests/api.swift @@ -1124,6 +1124,14 @@ func lossless() { } check(seen == [98, 2100, 4101, 7], "a closure reads each chunk of a caller's bytes in place") } + nonisolated(unsafe) var kept: [Bytes] = [] + _ = lend("abc") { visitChunks($0, 2) { chunk in + if let chunk { + kept.append(Bytes(chunk)) + } + return 0 + } } + check(kept == [Bytes("ab".utf8), Bytes("c".utf8)], "a closure keeps lent bytes by copying them") let digest = scanned(ScanDigest(), Bytes("abcd".utf8)) check(digest == (2 << 32) + 97 + 98 + (99 + 100) * 256 + (1 << 48), "a callback reads lent bytes and none") check(samePath(PathBuf(bytes: Bytes([0xff]))) == strayPath, "a caller's bytes make a path") From ad03b945c01a9df3c341cf3b25fe8eb7ca9aba53 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 19:08:18 -0800 Subject: [PATCH 06/13] ffi(moq): the Swift smoke script lends its frames and head as spans --- ffi/moq/moq.swift | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ffi/moq/moq.swift b/ffi/moq/moq.swift index 2a8e344c7..1c1ac213c 100644 --- a/ffi/moq/moq.swift +++ b/ffi/moq/moq.swift @@ -243,7 +243,7 @@ func script() throws { } q.drain() expect(frame.isEmpty, "a read waits for a frame") - try writer.writeFrame(Timestamp.unscaled(0), Bytes("hello".utf8)) + try Bytes("hello".utf8).withSpan { try writer.writeFrame(Timestamp.unscaled(0), $0) } expect(q.size == 1, "a frame's arrival wakes the read") q.drain() let hello = frame.take()! @@ -257,7 +257,7 @@ func script() throws { let at = try Timestamp.fromMillis(1500) expect(try at.asSecs() == 1, "1500 ms is 1 s") do { - try writer.writeFrame(at, Bytes("late".utf8)) + try Bytes("late".utf8).withSpan { try writer.writeFrame(at, $0) } expect(false, "a timed frame on an untimed track is an error") } catch let e as Moq.Error { expect(try e.description == "frame timestamp doesn't fit its track", "the late frame's error is Rust's") @@ -266,7 +266,7 @@ func script() throws { // The last frame, bytes that are not UTF-8, then the group's end, which reads as nil. let world = Bytes(Data([0xff]) + Data("world".utf8)) - try writer.writeFrame(Timestamp.unscaled(0), world) + try world.withSpan { try writer.writeFrame(Timestamp.unscaled(0), $0) } _ = try writer.finish() try block { let last = try await first.value.readFrame() @@ -293,14 +293,14 @@ func script() throws { // moq-mux reads an OpusHead into hang's catalog config: 44.1 kHz in, stereo, which the // catalog lists at the decoder's 48 kHz, keeping the head as its description. let head = Bytes(Data("OpusHead".utf8) + Data([1, 2, 0x38, 0x01, 0x44, 0xac, 0, 0, 0, 0, 0])) - let audio = try muxCodecOpusConfig(head) + let audio = try head.withSpan { try muxCodecOpusConfig($0) } expect(try audio.sampleRateGet == 48000, "Opus decodes at 48 kHz") expect(try audio.channelCountGet == 2, "the head is stereo") expect(try audio.codecGet == .opus, "the codec is Opus") expect(try audio.descriptionGet == head, "the head is the description") // A truncated head is moq-mux's error. do { - _ = try muxCodecOpusConfig(head.prefix(8)) + _ = try head.prefix(8).withSpan { try muxCodecOpusConfig($0) } expect(false, "a truncated head is an error") } catch let e as MuxError { expect(!"\(e)".isEmpty, "a truncated head's error has a message") @@ -429,7 +429,7 @@ func script() throws { let live = try served.route("live", OriginRouteOptions.default()) let liveTrack = try live.broadcast().createTrack("video", nil) var liveGroup = try liveTrack.appendGroup(Timestamp.unscaled(0)) - try liveGroup.writeFrame(Timestamp.unscaled(0), Bytes("hello".utf8)) + try Bytes("hello".utf8).withSpan { try liveGroup.writeFrame(Timestamp.unscaled(0), $0) } _ = try liveGroup.finish() var serverConfig = TokioServerConfig.default() From 0ca4c486867d67e460217a134e0b82248225f65f Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 20:06:58 -0800 Subject: [PATCH 07/13] quest: record the maintainer's follow-up answers Co-Authored-By: Claude Opus 5.5 --- quest/m3/swift-bytes-span.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/quest/m3/swift-bytes-span.md b/quest/m3/swift-bytes-span.md index 4ae64ada4..87b321026 100644 --- a/quest/m3/swift-bytes-span.md +++ b/quest/m3/swift-bytes-span.md @@ -8,6 +8,8 @@ compiler feature asked of a consumer's build. ## Plan +Decided with the maintainer on 2026-11-19, in the pick of [#902](https://github.com/kixel-ai/rust2/pull/902): ✅ kept, waiting on Swift stabilizing `Lifetimes` and `AddressableTypes` (rejected: adopting the experimental flags now, which puts config in every consumer's build; dropping it). + Found by [Swift spans](https://github.com/kixel-ai/rust2/pull/902), which takes slices as `Span` and gave `Bytes` the scoped `withSpan`. A property returning a `Span` needs `@_lifetime(borrow self)`, which Swift 6.4 builds only under From 38b7bdfb9f226b06542aaf1ed5f6e30f20782042 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 20:50:44 -0800 Subject: [PATCH 08/13] ffi(swift): span locals fit closure bodies and keep their try! The transcript's span argument hoists an ArraySlice local, which an is_err, unwrap_err, join, or map_or body refused, and which lost the try! of a throwing argument. Bytes.withSpan binds raw bytes with Span(_unsafeBytes:), and the runtime qualifies MemoryLayout. Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/examples/transcript.rs | 11 ++++++ ffi/runtime/rt.swift | 4 +-- ffi/tests/fixtures/transcript/swift.rs | 48 +++++++++++++++---------- 3 files changed, 42 insertions(+), 21 deletions(-) diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 9368cddd7..7c6669c0d 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -732,6 +732,17 @@ fn main() { ledger.seal(); println!("sealed {}", ledger.edit().err().unwrap()); println!("chunks {:?}", api::chunks(b"abcde", 2)); + println!( + "chunk lens {} {} {} {}", + api::chunks(b"abcde", 2) + .iter() + .map(|c| format!("{}", api::len(c))) + .collect::>() + .join(" "), + api::scaled(3, 1).map_or("none".to_string(), |v| format!("{v} {}", api::len(b"ab"))), + api::fingerprint(&format!("{}", api::len(b"abc"))).is_err(), + api::len(&api::fingerprint("deadbeef").unwrap()) + ); let counters = api::counters(vec!["x".to_string(), "y".to_string()]); println!( "counters {}", diff --git a/ffi/runtime/rt.swift b/ffi/runtime/rt.swift index bd1cea723..3a0d9533f 100644 --- a/ffi/runtime/rt.swift +++ b/ffi/runtime/rt.swift @@ -288,7 +288,7 @@ public struct Bytes: Hashable, Sendable, RandomAccessCollection { public func withSpan(_ body: (Swift.Span) throws -> R) rethrows -> R { var result: R? = nil try storage.withUnsafeBytes { raw in - result = try body(Swift.Span(_unsafeElements: raw.assumingMemoryBound(to: Swift.UInt8.self))) + result = try body(Swift.Span(_unsafeBytes: raw)) } return result.take()! } @@ -536,7 +536,7 @@ extension Native { _ body: (L) throws -> R ) rethrows -> R { try span.withUnsafeBufferPointer { items in - let ptr = items.baseAddress ?? UnsafePointer(bitPattern: MemoryLayout.alignment)! + let ptr = items.baseAddress ?? UnsafePointer(bitPattern: Swift.MemoryLayout.alignment)! return try body(make(ptr, items.count, nil)) } } diff --git a/ffi/tests/fixtures/transcript/swift.rs b/ffi/tests/fixtures/transcript/swift.rs index 837e08191..dc6ab06fd 100644 --- a/ffi/tests/fixtures/transcript/swift.rs +++ b/ffi/tests/fixtures/transcript/swift.rs @@ -1175,8 +1175,8 @@ impl Emitter<'_> { let (exception, wrapped) = self.exception(err); let call = self.attempt(inner); match wrapped { - true => format!("_err({exception}.self) {{ {call} }}.error"), - false => format!("_err({exception}.self) {{ {call} }}"), + true => format!("_err({exception}.self) {{{call}}}.error"), + false => format!("_err({exception}.self) {{{call}}}"), } } Kind::IsErr(inner) => { @@ -1185,7 +1185,7 @@ impl Emitter<'_> { }; let (exception, _) = self.exception(err); let call = self.attempt(inner); - format!("_fails({exception}.self) {{ {call} }}") + format!("_fails({exception}.self) {{{call}}}") } Kind::IsSome(inner) => format!("({} != nil)", self.expr(inner, out)), Kind::IsNone(inner) => format!("({} == nil)", self.expr(inner, out)), @@ -1228,9 +1228,9 @@ impl Emitter<'_> { let x = self.param(pat); let body = self.closure_value(body); match self.model.unique(&item) { - true => format!("_each({v}) {{ {x} in {body} }}.joined(separator: \"{}\")", escape(sep)), + true => format!("_each({v}) {{ {x} in{body}}}.joined(separator: \"{}\")", escape(sep)), false => format!( - "{}.map {{ {x} in {body} }}.joined(separator: \"{}\")", + "{}.map {{ {x} in{body}}}.joined(separator: \"{}\")", postfix(&v), escape(sep) ), @@ -1246,7 +1246,7 @@ impl Emitter<'_> { let none = self.expr(none, out); let x = self.param(pat); let some = self.closure_value(some); - format!("({}.map {{ {x} in {some} }} ?? {none})", postfix(&option)) + format!("({}.map {{ {x} in{some}}} ?? {none})", postfix(&option)) } Kind::Utf8(inner) => format!("String(decoding: {}, as: UTF8.self)", self.expr(inner, out)), Kind::Len(inner) => { @@ -1275,12 +1275,25 @@ impl Emitter<'_> { } } - /// The call `inner` makes, which throws its error, for a closure that catches it. + /// The body of a closure that catches the error the call `inner` throws. fn attempt(&mut self, inner: &Expr) -> String { - let mut pre = String::new(); - let call = self.rooted("try ", &mut pre, |this, pre| this.expr(inner, pre)); - assert!(pre.is_empty(), "a failing call needing statements first"); - call + self.inline(|this, pre| this.rooted("try ", pre, |this, pre| this.expr(inner, pre))) + } + + /// The body of a closure returning `write`'s expression: the expression alone, or after + /// the statements it needs first, such as a span's local. + fn inline(&mut self, write: impl FnOnce(&mut Self, &mut String) -> String) -> String { + self.depth += 1; + let mut body = String::new(); + let v = write(self, &mut body); + if !body.is_empty() { + self.line(&mut body, &format!("return {v}")); + } + self.depth -= 1; + match body.is_empty() { + true => format!(" {v} "), + false => format!("\n{body}{}", self.indent()), + } } /// Arguments labelled as `labels` say, each passed where its type is taken. @@ -1350,12 +1363,9 @@ impl Emitter<'_> { list } - /// A closure's value, as its own root. + /// The body of a closure returning `value`, as its own root. fn closure_value(&mut self, value: &Expr) -> String { - let mut pre = String::new(); - let v = self.root(value, &value.ty, &mut pre); - assert!(pre.is_empty(), "a closure's value needing statements first"); - v + self.inline(|this, pre| this.root(value, &value.ty, pre)) } fn closure(&mut self, params: &[Pat], steps: &[Step], value: &Expr) -> String { @@ -1488,7 +1498,7 @@ impl Emitter<'_> { match (ty, &arg.kind) { (Type::Option(_), Kind::None) => "nil".to_string(), (Type::Option(inner), Kind::Some(value)) => { - let v = self.value(value, inner, out); + let v = self.root(value, inner, out); self.line( out, &format!("let {tmp}: ArraySlice<{elem}>? = ArraySlice<{elem}>({v})"), @@ -1496,12 +1506,12 @@ impl Emitter<'_> { format!("{tmp}?.span") } (Type::Option(_), _) => { - let v = self.value(arg, ty, out); + let v = self.root(arg, ty, out); self.line(out, &format!("let {tmp} = {v}.map {{ ArraySlice<{elem}>($0) }}")); format!("{tmp}?.span") } _ => { - let v = self.value(arg, ty, out); + let v = self.root(arg, ty, out); self.line(out, &format!("let {tmp} = ArraySlice<{elem}>({v})")); format!("{tmp}.span") } From fe79d457a70fb78dcb2d56de179beadd99a2398a Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 20:59:21 -0800 Subject: [PATCH 09/13] ffi(api): the transcript passes spans in closure bodies, an is_err, and a throwing argument Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/examples/transcript.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 7c6669c0d..85f263145 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -739,9 +739,9 @@ fn main() { .map(|c| format!("{}", api::len(c))) .collect::>() .join(" "), - api::scaled(3, 1).map_or("none".to_string(), |v| format!("{v} {}", api::len(b"ab"))), + api::held_count(Some((Counter::new("h", 4),))).map_or("none".to_string(), |v| format!("{v} {}", api::len(b"ab"))), api::fingerprint(&format!("{}", api::len(b"abc"))).is_err(), - api::len(&api::fingerprint("deadbeef").unwrap()) + api::sum_u32(&[ledger.published(), 1]) ); let counters = api::counters(vec!["x".to_string(), "y".to_string()]); println!( From bfbb841613ed37942d226230c2b7e811c60c0073 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 20:59:49 -0800 Subject: [PATCH 10/13] ffi(api): fmt the transcript Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/examples/transcript.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 85f263145..bceb9fd20 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -739,7 +739,8 @@ fn main() { .map(|c| format!("{}", api::len(c))) .collect::>() .join(" "), - api::held_count(Some((Counter::new("h", 4),))).map_or("none".to_string(), |v| format!("{v} {}", api::len(b"ab"))), + api::held_count(Some((Counter::new("h", 4),))) + .map_or("none".to_string(), |v| format!("{v} {}", api::len(b"ab"))), api::fingerprint(&format!("{}", api::len(b"abc"))).is_err(), api::sum_u32(&[ledger.published(), 1]) ); From 8221b85bb9e81df38d1dc23ed374c19c6dec8e67 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 21:37:44 -0800 Subject: [PATCH 11/13] ffi(shapes): the Swift driver lends pair_N and maybe_N their borrowed slice as a span Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures/shapes.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/ffi/tests/fixtures/shapes.rs b/ffi/tests/fixtures/shapes.rs index 22f84278f..212f4a206 100644 --- a/ffi/tests/fixtures/shapes.rs +++ b/ffi/tests/fixtures/shapes.rs @@ -2120,7 +2120,12 @@ fn swift(calls: &[Call], source: &str) -> String { let label = call.label(); let make = |seed: u64| format!("{}make{n}({seed})", tr(&[format!("make{n}")])); // `digest_N` of `v`, lent as a span where it borrows a slice. - let lent = source.contains(&format!("public func digest{n}(_ v: borrowing Swift.Span<")); + // Whether `function` borrows its last argument, a slice, as a span. + let spans = |function: &str| { + let at = source.find(&format!("public func {function}(")).unwrap(); + source[at..].lines().next().unwrap().contains("borrowing Swift.Span<") + }; + let lent = spans(&format!("digest{n}")); let digested = |v: &str| match lent { true => format!("lend({v}) {{ {}digest{n}($0) }}", tr(&[format!("digest{n}")])), false => format!("digest{n}({v})"), @@ -2160,6 +2165,13 @@ fn swift(calls: &[Call], source: &str) -> String { digest("v") ); } + Kind::Pair if spans(&format!("pair{n}")) => format!( + "{}lend({}) {{ {}pair{n}({}, {seed}, $0) }}", + tr(&[format!("pair{n}"), format!("make{n}")]), + make(other), + tr(&[format!("pair{n}")]), + make(seed) + ), Kind::Pair => format!( "{}pair{n}({}, {seed}, {})", tr(&[format!("pair{n}")]), @@ -2168,6 +2180,12 @@ fn swift(calls: &[Call], source: &str) -> String { ), Kind::Maybe => match seed % 2 { 0 => format!("{}maybe{n}(nil)", tr(&[format!("maybe{n}")])), + _ if spans(&format!("maybe{n}")) => format!( + "{}lend({}) {{ {}maybe{n}($0) }}", + tr(&[format!("maybe{n}"), format!("make{n}")]), + make(seed), + tr(&[format!("maybe{n}")]) + ), _ => format!("{}maybe{n}({})", tr(&[format!("maybe{n}")]), make(seed)), }, Kind::Held => { From db919865065d2e9f01b504b169730ffd7cf4d7d0 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 22:04:30 -0800 Subject: [PATCH 12/13] ffi(swift): document async calls borrowing Bytes as a span Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ffi/README.md b/ffi/README.md index 377e3383e..fdfe43682 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -961,9 +961,11 @@ value of a Rust type crosses as one Swift type that holds it exactly, and back u `Span`. - **Slices** a call borrows, `&[u8]` and `&[T]` of a fixed-width integer or float, are `borrowing Swift.Span`, which Rust reads in place: an array's `span`, or before - Apple's 26 releases its slice's (`array[...]`), or `Bytes` lent by `withSpan`. Bytes Rust lends a closure or trait - method are a `Span` of Rust's own memory, which the compiler keeps from outliving - the call. A `span` property on `Bytes` waits on Swift's lifetime dependencies, still + Apple's 26 releases its slice's (`array[...]`), or `Bytes` lent by `withSpan`, whose + closure is synchronous. An `async` call takes `Bytes` copied to a slice that lives + across the `await`, as `let s = Array(bytes)[...]` and then `try await f(s.span)`. + Bytes Rust lends a closure or trait method are a `Span` of Rust's own memory, + which the compiler keeps from outliving the call. A `span` property on `Bytes` waits on Swift's lifetime dependencies, still experimental, and on `Data` keeping short bytes inline. Strings are `String`, copied, `char` `Unicode.Scalar`, `usize` `UInt`, `Option` `T?`, a tuple a Swift tuple, though a tuple of one is its element, `u128` a `U128` of its From b74719e32c130e0b395b867964f364aa9a4079c6 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 22:09:35 -0800 Subject: [PATCH 13/13] ffi(shapes): each closure of the Swift driver under its own comment Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures/shapes.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ffi/tests/fixtures/shapes.rs b/ffi/tests/fixtures/shapes.rs index 212f4a206..1ba155e2f 100644 --- a/ffi/tests/fixtures/shapes.rs +++ b/ffi/tests/fixtures/shapes.rs @@ -2119,13 +2119,13 @@ fn swift(calls: &[Call], source: &str) -> String { let other = call.other(); let label = call.label(); let make = |seed: u64| format!("{}make{n}({seed})", tr(&[format!("make{n}")])); - // `digest_N` of `v`, lent as a span where it borrows a slice. // Whether `function` borrows its last argument, a slice, as a span. let spans = |function: &str| { let at = source.find(&format!("public func {function}(")).unwrap(); source[at..].lines().next().unwrap().contains("borrowing Swift.Span<") }; let lent = spans(&format!("digest{n}")); + // `digest_N` of `v`, lent as a span where it borrows a slice. let digested = |v: &str| match lent { true => format!("lend({v}) {{ {}digest{n}($0) }}", tr(&[format!("digest{n}")])), false => format!("digest{n}({v})"),