Skip to content

Commit

Permalink
Document the ToRustStr protocol (#266)
Browse files Browse the repository at this point in the history
This commit adds documentation that explains the `ToRustStr` protocol.
  • Loading branch information
chinedufn authored Apr 9, 2024
1 parent 04e6abf commit 7fc3d3c
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions crates/swift-bridge-build/src/generate_core/string.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,6 @@ public protocol IntoRustString {
func intoRustString() -> RustString;
}

public protocol ToRustStr {
func toRustStr<T> (_ withUnsafeRustStr: (RustStr) -> T) -> T;
}

extension String: IntoRustString {
public func intoRustString() -> RustString {
// TODO: When passing an owned Swift std String to Rust we've being wasteful here in that
Expand Down Expand Up @@ -72,6 +68,19 @@ func optionalStringIntoRustString<S: IntoRustString>(_ string: Optional<S>) -> R
}
}

/// Used to safely get a pointer to a sequence of utf8 bytes, represented as a `RustStr`.
///
/// For example, the Swift `String` implementation of the `ToRustStr` protocol does the following:
/// 1. Use Swift's `String.utf8.withUnsafeBufferPointer` to get a pointer to the strings underlying
/// utf8 bytes.
/// 2. Construct a `RustStr` that points to these utf8 bytes. This is safe because `withUnsafeBufferPointer`
/// guarantees that the buffer pointer will be valid for the duration of the `withUnsafeBufferPointer`
/// callback.
/// 3. Pass the `RustStr` to the closure that was passed into `RustStr.toRustStr`.
public protocol ToRustStr {
func toRustStr<T> (_ withUnsafeRustStr: (RustStr) -> T) -> T;
}

extension String: ToRustStr {
/// Safely get a scoped pointer to the String and then call the callback with a RustStr
/// that uses that pointer.
Expand Down

0 comments on commit 7fc3d3c

Please sign in to comment.