Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is NSData/Data storage contiguous?

Tags:

swift

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.

like image 969
Anatoli P Avatar asked Nov 19 '16 02:11

Anatoli P


People also ask

What is NSData?

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.

What is data () in Swift?

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).


2 Answers

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.

like image 90
Rob Avatar answered Sep 23 '22 01:09

Rob


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.

like image 45
Lou Franco Avatar answered Sep 24 '22 01:09

Lou Franco