Are Data/NSData bytes guaranteed to be stored in contiguous memory? Looking at the documentation (https://developer.apple.com/reference/foundation/data), I'm under the impression that one can access a contiguous representation of the bytes using withUnsafeBytes()
or withUnsafeMutableBytes()
. However, it is possible that the bytes are copied from non-contiguous storage to a contiguous block when these methods are invoked.
I think it would be somewhat inefficient to copy the bytes when accessing them via those withUnsafe...
methods, and the bytes are evidently stored contiguously when the init(bytesNoCopy: ...)
initializer is used, so I tend to think that they are always stored contiguously, but haven't seen any docs stating so explicitly.
NSData provides methods for atomically saving their contents to a file, which guarantee that the data is either saved in its entirety, or it fails completely. An atomic write first writes the data to a temporary file and then, only if this write succeeds, moves the temporary file to its final location.
Data in Swift 3 is a struct that conforms to collection protocol. It is a collection of bytes ( [UInt8] array of unsigned integer 8 bits 0-255).
No, Data
is not guaranteed to be stored in contiguous memory. If you use withUnsafeBytes
or withUnsafeMutableBytes
, though, it will copy all the buffers to a single contiguous buffer.
If you do not want to incur that overhead, you can access the individual buffers using the regions
property.
The presence of withUnsafeBytes
is a way of documenting that they reserve the right to not store the bytes contiguously, but can provide them that way on demand.
This might be because they imagine NSData would be ported to memory constrained environments and they don't want you to have system dependent code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With