0

How do you convert an UnsafeMutablePointer to a Data object?

let bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: 20)
let data: Data = ...?
Berry Blue
  • 15,330
  • 18
  • 62
  • 113

1 Answers1

1

You can use:

let data = Data(bytes: bytes, count: 20)
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • This accomplishes what was asked, but it does copy the buffer. Depending on the size of the buffer it might make a difference! Use Data(bytesNoCopy: bytes, count: 20, deallocator: .custom({ (ptr, size) in ptr.deallocate() })) – gekart Nov 11 '22 at 18:34
  • Agreed. IMHO, copying the buffer is generally safer and 20 bytes is not remotely close to where I’d consider the “no copy” pattern, but your point is well taken. Also [note](https://developer.apple.com/documentation/foundation/data/1780455-init), “If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed.” – Rob Nov 11 '22 at 19:02
  • You are absolutely right: One has to be careful about optimization (always understand the implications). Apply when copying MBs / GBs of data or millions of Data structs. – gekart Nov 14 '22 at 10:55