An example of using simdutf in Swift.
simdutf is written in C++, so this is only possible through Swift's C++ interoperability.
Furthermore, you can call simdutf functions via Swift's Span type instead of the unsafe UnsafePointers.
- Make sure you have Swift 6.3 (nightlies) or better installed.
- Clone this project.
cdto the project directory.- Run
swift run.
After swift run, you'll see a message like this:
$ swift run
Building for debugging...
[1/1] Write swift-version-7E01106DFC2086DF.txt
Build of product 'SIMDUTF_Swift_Example' complete! (0.11s)
Welcome to the SIMDUTF Swift Example!
Enter a line to validate for ASCII:Then you can enter some text to check for being ASCII, via simdutf.
For example you can enter "🙂":
...
Enter a line to validate for ASCII:
🙂
simdutf.validate_ascii says "🙂" is not ASCII!Currently this is the whole code:
import Foundation
import simdutf
@main
struct SIMDUTF_Swift_Example {
static func main() {
print("Welcome to the SIMDUTF Swift Example!")
print("Enter a line to validate for ASCII:")
guard let line = readLine(), !line.isEmpty else {
print("Empty line entered, please enter a non-empty line!")
return
}
/// Pass a swift `Span` to `simdutf`'s C++ functions.
let isASCII = simdutf.validate_ascii(line.utf8Span.span)
print("simdutf.validate_ascii says \(line.debugDescription) is \(isASCII ? "ASCII" : "NOT ASCII")!")
}
}To support Swift, simdutf required these adjustements:
-
- Add an appropriate
Package.swift.
- Add an appropriate
-
- Add an appropriate
module.modulemap.
- Add an appropriate
-
- Add
__noescape(via a customsimd_noescapeattribute) tostd::spanparameters in functions.
- Add
-
- Declare and use a "type alias" instead of just spelling out the type name, for
std::spans.
- For example:
using uint8_span = std::span<const std::uint8_t>;. - Then use it in function parameters:
bool validate_ascii(uint8_span input simdutf_noescape) - This is currently also a requirement of the Swift compiler, and is not optional.
- Declare and use a "type alias" instead of just spelling out the type name, for
On the Swift side, you'd need:
- Swift 6.3.
- Swift 6.2 contains some blocking bugs that are fixed in 6.3.
- Depend on
simdutflike any other Swift package:.package(url: "https://github.com/MahdiBM/simdutf.git", branch: "mmbm-swift-take-2")- Currently this points to my branch. I'll update that when the changes are available in simdutf.
- Depend on
simdutfin your targets:.product(name: "simdutf", package: "simdutf")
- For targets that depend on
simdutf, add the followingswiftSettings:- .interoperabilityMode(.Cxx)
- .enableExperimentalFeature("SafeInteropWrappers")
- Set the cxx langauge standard of the package to
cxx20or better for thestd::spansupport:cxxLanguageStandard: .cxx20
In the end you'll have a Package.swift like this.