Debian Codegraph @

third_party/rust/uniffi_bindgen/src/bindings/swift/templates/RustBufferTemplate.swift

raw
1 fileprivate extension RustBuffer {
2 // Allocate a new buffer, copying the contents of a `UInt8` array.
3 init(bytes: [UInt8]) {
4 let rbuf = bytes.withUnsafeBufferPointer { ptr in
5 RustBuffer.from(ptr)
6 }
7 self.init(capacity: rbuf.capacity, len: rbuf.len, data: rbuf.data)
8 }
9
10 static func empty() -> RustBuffer {
11 RustBuffer(capacity: 0, len:0, data: nil)
12 }
13
14 static func from(_ ptr: UnsafeBufferPointer<UInt8>) -> RustBuffer {
15 try! rustCall { {{ ci.ffi_rustbuffer_from_bytes().name() }}(ForeignBytes(bufferPointer: ptr), $0) }
16 }
17
18 // Frees the buffer in place.
19 // The buffer must not be used after this is called.
20 func deallocate() {
21 try! rustCall { {{ ci.ffi_rustbuffer_free().name() }}(self, $0) }
22 }
23 }
24
25 fileprivate extension ForeignBytes {
26 init(bufferPointer: UnsafeBufferPointer<UInt8>) {
27 self.init(len: Int32(bufferPointer.count), data: bufferPointer.baseAddress)
28 }
29 }
30
31 // For every type used in the interface, we provide helper methods for conveniently
32 // lifting and lowering that type from C-compatible data, and for reading and writing
33 // values of that type in a buffer.
34
35 // Helper classes/extensions that don't change.
36 // Someday, this will be in a library of its own.
37
38 fileprivate extension Data {
39 init(rustBuffer: RustBuffer) {
40 self.init(
41 bytesNoCopy: rustBuffer.data!,
42 count: Int(rustBuffer.len),
43 deallocator: .none
44 )
45 }
46 }
47
48 // Define reader functionality. Normally this would be defined in a class or
49 // struct, but we use standalone functions instead in order to make external
50 // types work.
51 //
52 // With external types, one swift source file needs to be able to call the read
53 // method on another source file's FfiConverter, but then what visibility
54 // should Reader have?
55 // - If Reader is fileprivate, then this means the read() must also
56 // be fileprivate, which doesn't work with external types.
57 // - If Reader is internal/public, we'll get compile errors since both source
58 // files will try define the same type.
59 //
60 // Instead, the read() method and these helper functions input a tuple of data
61
62 fileprivate func createReader(data: Data) -> (data: Data, offset: Data.Index) {
63 (data: data, offset: 0)
64 }
65
66 // Reads an integer at the current offset, in big-endian order, and advances
67 // the offset on success. Throws if reading the integer would move the
68 // offset past the end of the buffer.
69 fileprivate func readInt<T: FixedWidthInteger>(_ reader: inout (data: Data, offset: Data.Index)) throws -> T {
70 let range = reader.offset..<reader.offset + MemoryLayout<T>.size
71 guard reader.data.count >= range.upperBound else {
72 throw UniffiInternalError.bufferOverflow
73 }
74 if T.self == UInt8.self {
75 let value = reader.data[reader.offset]
76 reader.offset += 1
77 return value as! T
78 }
79 var value: T = 0
80 let _ = withUnsafeMutableBytes(of: &value, { reader.data.copyBytes(to: $0, from: range)})
81 reader.offset = range.upperBound
82 return value.bigEndian
83 }
84
85 // Reads an arbitrary number of bytes, to be used to read
86 // raw bytes, this is useful when lifting strings
87 fileprivate func readBytes(_ reader: inout (data: Data, offset: Data.Index), count: Int) throws -> Array<UInt8> {
88 let range = reader.offset..<(reader.offset+count)
89 guard reader.data.count >= range.upperBound else {
90 throw UniffiInternalError.bufferOverflow
91 }
92 var value = [UInt8](repeating: 0, count: count)
93 value.withUnsafeMutableBufferPointer({ buffer in
94 reader.data.copyBytes(to: buffer, from: range)
95 })
96 reader.offset = range.upperBound
97 return value
98 }
99
100 // Reads a float at the current offset.
101 fileprivate func readFloat(_ reader: inout (data: Data, offset: Data.Index)) throws -> Float {
102 return Float(bitPattern: try readInt(&reader))
103 }
104
105 // Reads a float at the current offset.
106 fileprivate func readDouble(_ reader: inout (data: Data, offset: Data.Index)) throws -> Double {
107 return Double(bitPattern: try readInt(&reader))
108 }
109
110 // Indicates if the offset has reached the end of the buffer.
111 fileprivate func hasRemaining(_ reader: (data: Data, offset: Data.Index)) -> Bool {
112 return reader.offset < reader.data.count
113 }
114
115 // Define writer functionality. Normally this would be defined in a class or
116 // struct, but we use standalone functions instead in order to make external
117 // types work. See the above discussion on Readers for details.
118
119 fileprivate func createWriter() -> [UInt8] {
120 return []
121 }
122
123 fileprivate func writeBytes<S>(_ writer: inout [UInt8], _ byteArr: S) where S: Sequence, S.Element == UInt8 {
124 writer.append(contentsOf: byteArr)
125 }
126
127 // Writes an integer in big-endian order.
128 //
129 // Warning: make sure what you are trying to write
130 // is in the correct type!
131 fileprivate func writeInt<T: FixedWidthInteger>(_ writer: inout [UInt8], _ value: T) {
132 var value = value.bigEndian
133 withUnsafeBytes(of: &value) { writer.append(contentsOf: $0) }
134 }
135
136 fileprivate func writeFloat(_ writer: inout [UInt8], _ value: Float) {
137 writeInt(&writer, value.bitPattern)
138 }
139
140 fileprivate func writeDouble(_ writer: inout [UInt8], _ value: Double) {
141 writeInt(&writer, value.bitPattern)
142 }
143
144 // Protocol for types that transfer other types across the FFI. This is
145 // analogous to the Rust trait of the same name.
146 fileprivate protocol FfiConverter {
147 associatedtype FfiType
148 associatedtype SwiftType
149
150 static func lift(_ value: FfiType) throws -> SwiftType
151 static func lower(_ value: SwiftType) -> FfiType
152 static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType
153 static func write(_ value: SwiftType, into buf: inout [UInt8])
154 }
155
156 // Types conforming to `Primitive` pass themselves directly over the FFI.
157 fileprivate protocol FfiConverterPrimitive: FfiConverter where FfiType == SwiftType { }
158
159 extension FfiConverterPrimitive {
160 #if swift(>=5.8)
161 @_documentation(visibility: private)
162 #endif
163 public static func lift(_ value: FfiType) throws -> SwiftType {
164 return value
165 }
166
167 #if swift(>=5.8)
168 @_documentation(visibility: private)
169 #endif
170 public static func lower(_ value: SwiftType) -> FfiType {
171 return value
172 }
173 }
174
175 // Types conforming to `FfiConverterRustBuffer` lift and lower into a `RustBuffer`.
176 // Used for complex types where it's hard to write a custom lift/lower.
177 fileprivate protocol FfiConverterRustBuffer: FfiConverter where FfiType == RustBuffer {}
178
179 extension FfiConverterRustBuffer {
180 #if swift(>=5.8)
181 @_documentation(visibility: private)
182 #endif
183 public static func lift(_ buf: RustBuffer) throws -> SwiftType {
184 var reader = createReader(data: Data(rustBuffer: buf))
185 let value = try read(from: &reader)
186 if hasRemaining(reader) {
187 throw UniffiInternalError.incompleteData
188 }
189 buf.deallocate()
190 return value
191 }
192
193 #if swift(>=5.8)
194 @_documentation(visibility: private)
195 #endif
196 public static func lower(_ value: SwiftType) -> RustBuffer {
197 var writer = createWriter()
198 write(value, into: &writer)
199 return RustBuffer(bytes: writer)
200 }
201 }