About Data alignment

Data is its own subsequence type, which means that a function

func foo(data: Data) { }

cannot assume that data.startIndex is zero. Therefore – if I understand it correctly – the following can invoke undefined behavior if the data is not properly aligned:

func foo(data: Data) {
    if data.count >= 4 {
        let val: UInt32 = data.withUnsafeBytes { $0.pointee }
        print(val)
    }
}

My questions is: According to the documentation, subdata(in:) creates a copy of the data. Can I assume that the underlying storage of the copy has some minimum alignment (e.g. 8 bytes), so that this is a safe variant:

let subdata = data.subdata(in: 0..<4)
let val: UInt32 = subdata.withUnsafeBytes { $0.pointee }

Or to put it differently: Does data.startIndex == 0 imply that the underlying storage is (at least) 8 byte aligned?

1 Like

No, it does not. Data has an initializer for "adopting" existing memory, and there's no guarantee that that memory is aligned.

This is a separate question. I believe the answer is also "no", but I'll defer to @millenomi or @Philippe_Hausler to give a definitive answer (and to say how to guarantee alignment when it is needed).

1 Like

I see. An example would be init(bytesNoCopy:count:deallocator:) ?

Some definite answer on when data alignment is guaranteed, or how it can be achieved, would be appreciated.

1 Like
Terms of Service

Privacy Policy

Cookie Policy