Skip to content

[cxx-interop] Proper conversions between MutableSpan and C++ span #81097

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions stdlib/public/Cxx/CxxSpan.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
import Builtin

@usableFromInline
internal func unsafeBitCast<T: ~Escapable, U>(
_ x: T, to type: U.Type
internal func unsafeBitCast<T: ~Escapable & ~Copyable, U>(
_ x: consuming T, to type: U.Type
) -> U {
Builtin.reinterpretCast(x)
}
Expand Down Expand Up @@ -139,7 +139,7 @@ public protocol CxxMutableSpan<Element> {
init(_ unsafeMutablePointer : UnsafeMutablePointer<Element>, _ count: Size)

func size() -> Size
func __dataUnsafe() -> UnsafeMutablePointer<Element>
func __dataUnsafe() -> UnsafeMutablePointer<Element>?
}

extension CxxMutableSpan {
Expand All @@ -150,4 +150,14 @@ extension CxxMutableSpan {
"UnsafeMutableBufferPointer should not point to nil")
unsafe self.init(unsafeMutableBufferPointer.baseAddress!, Size(unsafeMutableBufferPointer.count))
}

@available(SwiftStdlib 6.2, *)
@inlinable
@unsafe
public init(_ span: consuming MutableSpan<Element>) {
let (p, c) = unsafe unsafeBitCast(span, to: (UnsafeMutableRawPointer?, Int).self)
unsafe precondition(p != nil, "Span should not point to nil")
let binding = unsafe p!.bindMemory(to: Element.self, capacity: c)
unsafe self.init(binding, Size(c))
}
}
24 changes: 24 additions & 0 deletions test/Interop/Cxx/stdlib/use-std-span.swift
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,30 @@ StdSpanTestSuite.test("Convert between Swift and C++ span types")
expectEqual(cxxSpan[2], 3)
}
}
do {
var arr: [Int32] = [1, 2, 3]
arr.withUnsafeMutableBufferPointer{ ubpointer in
let s = SpanOfInt(ubpointer.baseAddress!, ubpointer.count)
let swiftSpan = MutableSpan(_unsafeCxxSpan: s)
expectEqual(swiftSpan.count, 3)
expectFalse(swiftSpan.isEmpty)
expectEqual(swiftSpan[0], 1)
expectEqual(swiftSpan[1], 2)
expectEqual(swiftSpan[2], 3)
}
}
do {
var arr: [Int32] = [1, 2, 3]
arr.withUnsafeMutableBufferPointer{ ubpointer in
let s = MutableSpan(_unsafeElements: ubpointer)
let cxxSpan = SpanOfInt(s)
expectEqual(cxxSpan.size(), 3)
expectFalse(cxxSpan.empty())
expectEqual(cxxSpan[0], 1)
expectEqual(cxxSpan[1], 2)
expectEqual(cxxSpan[2], 3)
}
}
}

runAllTests()