Debian Codegraph @

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

raw
1 #if swift(>=5.8)
2 @_documentation(visibility: private)
3 #endif
4 fileprivate struct FfiConverterString: FfiConverter {
5 typealias SwiftType = String
6 typealias FfiType = RustBuffer
7
8 public static func lift(_ value: RustBuffer) throws -> String {
9 defer {
10 value.deallocate()
11 }
12 if value.data == nil {
13 return String()
14 }
15 let bytes = UnsafeBufferPointer<UInt8>(start: value.data!, count: Int(value.len))
16 return String(bytes: bytes, encoding: String.Encoding.utf8)!
17 }
18
19 public static func lower(_ value: String) -> RustBuffer {
20 return value.utf8CString.withUnsafeBufferPointer { ptr in
21 // The swift string gives us int8_t, we want uint8_t.
22 ptr.withMemoryRebound(to: UInt8.self) { ptr in
23 // The swift string gives us a trailing null byte, we don't want it.
24 let buf = UnsafeBufferPointer(rebasing: ptr.prefix(upTo: ptr.count - 1))
25 return RustBuffer.from(buf)
26 }
27 }
28 }
29
30 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> String {
31 let len: Int32 = try readInt(&buf)
32 return String(bytes: try readBytes(&buf, count: Int(len)), encoding: String.Encoding.utf8)!
33 }
34
35 public static func write(_ value: String, into buf: inout [UInt8]) {
36 let len = Int32(value.utf8.count)
37 writeInt(&buf, len)
38 writeBytes(&buf, value.utf8)
39 }
40 }