NSData.data vs Data.withUnsafeBytes

found this thread that sheds more light about it: https://forums.swift.org/t/best-practice-for-parsing-heterogeneous-types-from-data-in-swift-5

you can add an extension:

extension UnsafeRawPointer {
  func loadUnaligned<T>(as: T.Type) -> T {
    assert(_isPOD(T.self)) // relies on the type being POD (no refcounting or other management)
    let buffer = UnsafeMutablePointer<T>.allocate(capacity: 1)
    defer { buffer.deallocate() }
    memcpy(buffer, self, MemoryLayout<T>.size)
    return buffer.pointee
  }
}

with the help of this extension Quinn's example can work even without relying on __attribute__((__packed__)) added to the C struct (in fact it can work on Swift struct if the packed aspect is not needed otherwise):

d.dropFirst().withUnsafeBytes { buf in
    print(buf.baseAddress!.loadUnaligned(as: TwoUInt8sAndAUInt16.self))
}

also this from https://github.com/apple/swift-evolution/blob/master/proposals/0107-unsaferawpointer.md#future-improvements-and-planned-additive-api:

1 Like