数据中的字符串,无需复制

时间:2017-11-29 02:35:19

标签: swift string

我想从String创建Data而不复制。我一直在尝试使用 String(bytesNoCopy:UnsafeMutableRawPointer, length:Int, encoding:String.Encoding, freeWhenDone:Bool)

无论我如何尝试,它总是返回零。如果我使用String(bytes:..., encoding:...)创建它就会成功。

有没有办法尝试从String对象创建Data而不重复字节。

以下是它的来源和我尝试的内容:

 ...
 // get the data. This succeeds
 guard var data = try? Data(contentsOf: url, options: .mappedIfSafe) else {
        return .failed
 }

 //Tried: 
 let ptr = UnsafeMutableRawPointer(&data)
 let str = String(bytesNoCopy: ptr, length: data.count, encoding: .utf8, freeWhenDone: false)

1 个答案:

答案 0 :(得分:0)

再次尝试,我发现了一种有效的方法:

 ...
 // get the data. This succeeds
 guard var data = try? Data(contentsOf: url, options: .mappedIfSafe) else {
        return .failed
 }


 data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) -> Void in
        let unsafePtr = UnsafeMutableRawPointer(ptr)
        // This is now working
        let str = String(bytesNoCopy: unsafePtr, length: data.count, encoding: .utf8, freeWhenDone: false)
 }