|
| 1 | +// |
| 2 | +// Copyright 2025 Signal Messenger, LLC. |
| 3 | +// SPDX-License-Identifier: AGPL-3.0-only |
| 4 | +// |
| 5 | + |
| 6 | +import Foundation |
| 7 | +import SignalFfi |
| 8 | + |
| 9 | +/// Represents a type that can be "borrowed" into an FFI-compatible form using a scope-based callback. |
| 10 | +internal protocol BorrowForFfi { |
| 11 | + associatedtype Borrowed |
| 12 | + func withBorrowed<Result>(_ callback: (Borrowed) throws -> Result) throws -> Result |
| 13 | +} |
| 14 | + |
| 15 | +/// Invokes `callback` with the borrowed form of each `input` |
| 16 | +internal func withAllBorrowed<Result, each Input: BorrowForFfi>( |
| 17 | + _ input: repeat each Input, |
| 18 | + in callback: (repeat (each Input).Borrowed) throws -> Result |
| 19 | +) throws -> Result { |
| 20 | + return try withoutActuallyEscaping(callback) { callback in |
| 21 | + // Optimization: allocate the correct-sized array up front. |
| 22 | + var count = 0 |
| 23 | + for _ in repeat (each Input).self { |
| 24 | + count += 1 |
| 25 | + } |
| 26 | + |
| 27 | + // Make space for each of the "borrowed" values. |
| 28 | + // If we had first-class references like Rust we could do: |
| 29 | + // var borrows: (repeat (each Input)?) = (repeat nil) |
| 30 | + // var places = (repeat &mut (each borrows)) |
| 31 | + // and then iterate over `inputs` and `places` together. |
| 32 | + // But we don't, so we instead build up an array of pointers |
| 33 | + // to stack locations and read them all out at the end. |
| 34 | + // And we use a stack array instead of a full Array as a microoptimization. |
| 35 | + // (We could put the values directly in the array instead using Any, |
| 36 | + // but then we have to downcast them to get them out.) |
| 37 | + return try withUnsafeTemporaryAllocation(of: UnsafeRawPointer.self, capacity: count) { borrows in |
| 38 | + var nextIndex = count - 1 |
| 39 | + |
| 40 | + // Because the "borrow" operations have to be nested to work correctly, |
| 41 | + // we build up a compound operation whose final (innermost) step is |
| 42 | + // "actually invoke the callback". The wrapping layers are described in the loop below. |
| 43 | + var operation = { |
| 44 | + // The "innermost" operation reads out all the values from the pointers in `borrows` |
| 45 | + // and invokes the user's callback. |
| 46 | + var pointerIter = borrows.makeIterator() |
| 47 | + let borrows = (repeat pointerIter.next()!.load(as: (each Input).Borrowed.self)) |
| 48 | + return try callback(repeat each borrows) |
| 49 | + } |
| 50 | + |
| 51 | + for next in repeat each input { |
| 52 | + // For each input, we wrap `operation` ("the rest of the work") in "borrow this input, |
| 53 | + // store it for later, and invoke the rest of the work". |
| 54 | + // Note that this only works because we're promising not to use the array after the |
| 55 | + // operation is complete. |
| 56 | + operation = { [operation] in |
| 57 | + return try next.withBorrowed { borrowed in |
| 58 | + try withUnsafePointer(to: borrowed) { pointer in |
| 59 | + borrows[nextIndex] = UnsafeRawPointer(pointer) |
| 60 | + nextIndex -= 1 |
| 61 | + return try operation() |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + // Finally, we can invoke our stacked operation, which looks something like this: |
| 68 | + // - Borrow input3, then... |
| 69 | + // - Borrow input2, then... |
| 70 | + // - Borrow input1, then... |
| 71 | + // - Read out (input1, input2, input3) and invoke the original callback. |
| 72 | + return try operation() |
| 73 | + } |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +// Overloads for the short cases, to help with optimization. |
| 78 | + |
| 79 | +internal func withAllBorrowed<Result, Input1: BorrowForFfi>( |
| 80 | + _ input1: Input1, |
| 81 | + in callback: (Input1.Borrowed) throws -> Result |
| 82 | +) throws -> Result { |
| 83 | + return try input1.withBorrowed(callback) |
| 84 | +} |
| 85 | + |
| 86 | +internal func withAllBorrowed<Result, Input1: BorrowForFfi, Input2: BorrowForFfi>( |
| 87 | + _ input1: Input1, |
| 88 | + _ input2: Input2, |
| 89 | + in callback: (Input1.Borrowed, Input2.Borrowed) throws -> Result |
| 90 | +) throws -> Result { |
| 91 | + // Borrow in reverse order, like the variadic one does. |
| 92 | + return try input2.withBorrowed { input2 in |
| 93 | + try input1.withBorrowed { input1 in |
| 94 | + try callback(input1, input2) |
| 95 | + } |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +internal func withAllBorrowed<Result, Input1: BorrowForFfi, Input2: BorrowForFfi, Input3: BorrowForFfi>( |
| 100 | + _ input1: Input1, |
| 101 | + _ input2: Input2, |
| 102 | + _ input3: Input3, |
| 103 | + in callback: (Input1.Borrowed, Input2.Borrowed, Input3.Borrowed) throws -> Result |
| 104 | +) throws -> Result { |
| 105 | + // Borrow in reverse order, like the variadic one does. |
| 106 | + return try input3.withBorrowed { input3 in |
| 107 | + try input2.withBorrowed { input2 in |
| 108 | + try input1.withBorrowed { input1 in |
| 109 | + try callback(input1, input2, input3) |
| 110 | + } |
| 111 | + } |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +extension NativeHandleOwner: BorrowForFfi { |
| 116 | + typealias Borrowed = PointerType |
| 117 | + func withBorrowed<Result>(_ callback: (Borrowed) throws -> Result) rethrows -> Result { |
| 118 | + return try self.withNativeHandle(callback) |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +extension ByteArray: BorrowForFfi { |
| 123 | + typealias Borrowed = SignalBorrowedBuffer |
| 124 | + func withBorrowed<Result>(_ callback: (Borrowed) throws -> Result) rethrows -> Result { |
| 125 | + return try self.withUnsafeBorrowedBuffer(callback) |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +extension ServiceId: BorrowForFfi { |
| 130 | + typealias Borrowed = UnsafePointer<ServiceIdStorage> |
| 131 | + func withBorrowed<Result>(_ callback: (Borrowed) throws -> Result) rethrows -> Result { |
| 132 | + return try self.withPointerToFixedWidthBinary(callback) |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +extension Randomness: BorrowForFfi { |
| 137 | + typealias Borrowed = UnsafePointer<SignalRandomnessBytes> |
| 138 | + func withBorrowed<Result>(_ callback: (Borrowed) throws -> Result) rethrows -> Result { |
| 139 | + return try self.withUnsafePointerToBytes(callback) |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +extension Data: BorrowForFfi { |
| 144 | + typealias Borrowed = SignalBorrowedBuffer |
| 145 | + func withBorrowed<Result>(_ callback: (SignalBorrowedBuffer) throws -> Result) rethrows -> Result { |
| 146 | + return try self.withUnsafeBorrowedBuffer(callback) |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +extension Optional: BorrowForFfi where Wrapped: BorrowForFfi, Wrapped.Borrowed == SignalBorrowedBuffer { |
| 151 | + typealias Borrowed = SignalOptionalBorrowedSliceOfc_uchar |
| 152 | + func withBorrowed<Result>(_ callback: (SignalOptionalBorrowedSliceOfc_uchar) throws -> Result) throws -> Result { |
| 153 | + guard let self else { |
| 154 | + return try callback(.init()) |
| 155 | + } |
| 156 | + return try self.withBorrowed { buffer in |
| 157 | + try callback(.init(present: true, value: buffer)) |
| 158 | + } |
| 159 | + } |
| 160 | +} |
| 161 | + |
| 162 | +internal struct ContiguousBytesWrapper<Inner: ContiguousBytes>: BorrowForFfi { |
| 163 | + var inner: Inner |
| 164 | + |
| 165 | + typealias Borrowed = SignalBorrowedBuffer |
| 166 | + func withBorrowed<Result>(_ callback: (SignalBorrowedBuffer) throws -> Result) rethrows -> Result { |
| 167 | + return try self.inner.withUnsafeBorrowedBuffer(callback) |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +extension BorrowForFfi { |
| 172 | + // A trick to expose a contextual shortcut where a BorrowForFfi instance is expected. |
| 173 | + // See <https://github.com/swiftlang/swift-evolution/blob/main/proposals/0299-extend-generic-static-member-lookup.md>. |
| 174 | + static func bytes<Bytes: ContiguousBytes>(_ bytes: Bytes) -> Self where Self == ContiguousBytesWrapper<Bytes> { |
| 175 | + .init(inner: bytes) |
| 176 | + } |
| 177 | +} |
| 178 | + |
| 179 | +extension UUID: BorrowForFfi { |
| 180 | + typealias Borrowed = UnsafePointer<uuid_t> |
| 181 | + func withBorrowed<Result>(_ callback: (Borrowed) throws -> Result) rethrows -> Result { |
| 182 | + return try withUnsafePointer(to: self.uuid, callback) |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +internal struct FixedLengthWrapper<FixedLengthRepr>: BorrowForFfi { |
| 187 | + var inner: ByteArray |
| 188 | + |
| 189 | + typealias Borrowed = UnsafePointer<FixedLengthRepr> |
| 190 | + func withBorrowed<Result>(_ callback: (Borrowed) throws -> Result) throws -> Result { |
| 191 | + return try self.inner.withUnsafePointerToSerialized(callback) |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +extension BorrowForFfi { |
| 196 | + static func fixed<FixedLengthRepr>(_ serialized: ByteArray) -> Self where Self == FixedLengthWrapper<FixedLengthRepr> { |
| 197 | + .init(inner: serialized) |
| 198 | + } |
| 199 | +} |
| 200 | + |
| 201 | +protocol FfiBorrowedSlice { |
| 202 | + associatedtype Element |
| 203 | + // We ought to be able to make the requirement init(base:length:), like the one that gets synthesized, |
| 204 | + // but that doesn't seem to work. |
| 205 | + init(_ buffer: UnsafeBufferPointer<Element>) |
| 206 | +} |
| 207 | + |
| 208 | +extension SignalBorrowedSliceOfConstPointerSessionRecord: FfiBorrowedSlice { |
| 209 | + init(_ buffer: UnsafeBufferPointer<SignalConstPointerSessionRecord>) { |
| 210 | + self.init(base: buffer.baseAddress, length: buffer.count) |
| 211 | + } |
| 212 | +} |
| 213 | + |
| 214 | +extension SignalBorrowedSliceOfConstPointerProtocolAddress: FfiBorrowedSlice { |
| 215 | + init(_ buffer: UnsafeBufferPointer<SignalConstPointerProtocolAddress>) { |
| 216 | + self.init(base: buffer.baseAddress, length: buffer.count) |
| 217 | + } |
| 218 | +} |
| 219 | + |
| 220 | +internal struct ElementsWrapper<FfiType: FfiBorrowedSlice>: BorrowForFfi { |
| 221 | + var inner: [FfiType.Element] |
| 222 | + |
| 223 | + typealias Borrowed = FfiType |
| 224 | + func withBorrowed<Result>(_ callback: (Borrowed) throws -> Result) throws -> Result { |
| 225 | + return try self.inner.withUnsafeBufferPointer { |
| 226 | + try callback(.init($0)) |
| 227 | + } |
| 228 | + } |
| 229 | +} |
| 230 | + |
| 231 | +extension BorrowForFfi { |
| 232 | + static func slice<FfiType: FfiBorrowedSlice>(_ input: [FfiType.Element]) -> Self where Self == ElementsWrapper<FfiType> { |
| 233 | + .init(inner: input) |
| 234 | + } |
| 235 | +} |
0 commit comments