Skip to content
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

Remove an extra string copy while constructing HString #157

Merged
merged 4 commits into from
Apr 9, 2024
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
8 changes: 4 additions & 4 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@
"type": "swift-lldb",
"request": "launch",
"name": "test_app",
"program": "${workspaceFolder:swiftwinrt}\\out\\${command:cmake.activeBuildPresetName}\\bin\\test_app.exe",
"program": "${workspaceFolder}\\out\\${command:cmake.activeBuildPresetName}\\bin\\test_app.exe",
"args": [],
"cwd": "${workspaceFolder:swiftwinrt}/tests",
"cwd": "${workspaceFolder}/tests",
"preLaunchTask": "Install"
},
{
"type": "cppvsdbg",
"request": "launch",
"name": "test_app (pdb)",
"program": "${workspaceFolder:swiftwinrt}\\out\\${command:cmake.activeBuildPresetName}\\bin\\test_app",
"program": "${workspaceFolder}\\out\\${command:cmake.activeBuildPresetName}\\bin\\test_app",
"args": [],
"cwd": "${workspaceFolder:swiftwinrt}/tests",
"cwd": "${workspaceFolder}/tests",
"preLaunchTask": "Install"
}
]
Expand Down
22 changes: 18 additions & 4 deletions swiftwinrt/Resources/Support/HString.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,24 @@ final public class HString {
internal private(set) var hString: HSTRING?

public init(_ string: String) throws {
self.hString = try string.withCString(encodedAs: UTF16.self) {
var result: HSTRING?
try CHECKED(WindowsCreateString($0, UINT32(wcslen($0)), &result))
return result
let codeUnitCount = string.utf16.count
var pointer: UnsafeMutablePointer<UInt16>? = nil
var hStringBuffer: HSTRING_BUFFER? = nil

// Note: Methods like String.withCString are not used here because they do a copy to create a null
// terminated string, and requires an additional copy to create an HSTRING. Instead, a single copy is
// done by using WindowsPreallocateStringBuffer to allocate a buffer and directly copying the string into it.
try CHECKED(WindowsPreallocateStringBuffer(UInt32(codeUnitCount), &pointer, &hStringBuffer));
guard let pointer else { throw Error(hr: E_FAIL) }
_ = UnsafeMutableBufferPointer(start: pointer, count: codeUnitCount).initialize(from: string.utf16)

do {
var hString: HSTRING? = nil
try CHECKED(WindowsPromoteStringBuffer(hStringBuffer, &hString));
self.hString = hString
} catch {
WindowsDeleteStringBuffer(hStringBuffer)
throw error
}
}

Expand Down
Loading