summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadRustRuntime/String+UnsafePointer.swift
blob: 996052c456ba3ae6069befe8dc649c68c1b44778 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//
//  String+UnsafePointer.swift
//  MullvadVPN
//
//  Created by Mojgan on 2025-04-02.
//  Copyright © 2026 Mullvad VPN AB. All rights reserved.
//

import Foundation

extension String {
    // Ensure the string is converted to a null-terminated C string
    // UnsafePointer provides no automated memory management or alignment guarantees.
    // The caller is responsible to manage the memory
    func toCStringPointer() -> UnsafePointer<CChar>? {
        // Convert the Swift string to a null-terminated UTF-8 C string
        guard let cString = cString(using: .utf8) else { return nil }

        // Allocate memory for characters + null terminator
        let pointer = UnsafeMutablePointer<CChar>.allocate(capacity: cString.count)

        // Copy the characters (including the null terminator)
        pointer.initialize(from: cString, count: cString.count)

        return UnsafePointer(pointer)
    }
}