[Pitch] Unaligned Loads and Stores from Raw Memory

The UnsafeRawPointer APIs work with imported C unions. You can try it today. This proposal doesn't add anything new in that respect.

Converting from C unions to Swift enums is an unrelated problem. Their layouts are not compatible except in certain single-payload cases dictated by the ABI.

1 Like

Interacting with binary serialization formats that require unaligned accesses (e.g. formats like BSON) has been 100% of my use cases. load looks like exactly the right API for that kind of thing, and when it doesn’t work, you’re left thinking that you’re ”holding it wrong”, because surely the whole withUnsafe… dance can’t be the best way.

I agree with the idea of broadening the current load API to support this, instead of introducing a new one.

The necessity of this workaround (or of others that produce the same outcome) is unsatisfactory for two reasons; firstly it is tremendously non-obvious.

I'm worried that knowing to use loadUnaligned(frombyteOffset:as:) instead would be equally non-obvious.

If loadUnaligned(frombyteOffset:as:) were to exist, would there be any reason to call load(frombyteOffset:as:)? Is there anything I'm overlooking?

For better or worse, there are platforms that don’t support unaligned loads, and on those platforms this would have to be implemented by loading bytes and stitching them together (effectively memcpy). Even on x86 aligned loads are faster but I don’t know how much statically knowing that buys you.

4 Likes

Even on x86 aligned loads are faster but I don’t know how much statically knowing that buys you.

It allows you to prevent performance bugs from creeping in by making it so that unaligned accesses will fail, producing easy-to-diagnose errors immediately instead of performance regressions that may go undetected for months.

1 Like

This proposal is actually in active review, so if you have thoughts about it, please post them there instead of here in the pitch thread.

2 Likes