Skip to content

Commit 7fc3d3c

Browse files
authored
Document the ToRustStr protocol (#266)
This commit adds documentation that explains the `ToRustStr` protocol.
1 parent 04e6abf commit 7fc3d3c

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

crates/swift-bridge-build/src/generate_core/string.swift

+13-4
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,6 @@ public protocol IntoRustString {
3535
func intoRustString() -> RustString;
3636
}
3737

38-
public protocol ToRustStr {
39-
func toRustStr<T> (_ withUnsafeRustStr: (RustStr) -> T) -> T;
40-
}
41-
4238
extension String: IntoRustString {
4339
public func intoRustString() -> RustString {
4440
// TODO: When passing an owned Swift std String to Rust we've being wasteful here in that
@@ -72,6 +68,19 @@ func optionalStringIntoRustString<S: IntoRustString>(_ string: Optional<S>) -> R
7268
}
7369
}
7470

71+
/// Used to safely get a pointer to a sequence of utf8 bytes, represented as a `RustStr`.
72+
///
73+
/// For example, the Swift `String` implementation of the `ToRustStr` protocol does the following:
74+
/// 1. Use Swift's `String.utf8.withUnsafeBufferPointer` to get a pointer to the strings underlying
75+
/// utf8 bytes.
76+
/// 2. Construct a `RustStr` that points to these utf8 bytes. This is safe because `withUnsafeBufferPointer`
77+
/// guarantees that the buffer pointer will be valid for the duration of the `withUnsafeBufferPointer`
78+
/// callback.
79+
/// 3. Pass the `RustStr` to the closure that was passed into `RustStr.toRustStr`.
80+
public protocol ToRustStr {
81+
func toRustStr<T> (_ withUnsafeRustStr: (RustStr) -> T) -> T;
82+
}
83+
7584
extension String: ToRustStr {
7685
/// Safely get a scoped pointer to the String and then call the callback with a RustStr
7786
/// that uses that pointer.

0 commit comments

Comments
 (0)