[swift-evolution] [RFC] UnsafeBytePointer API for In-Memory Layout

Joe Groff jgroff at apple.com
Thu May 12 10:41:33 CDT 2016

> Future improvements
> UnsafeBytePointer should eventually support unaligned memory access. I believe that we will eventually have a modifier that allows "packed" struct members. At that time we may also want to add a "packed" flag to UnsafeBytePointer's load and initialize methods.

We should probably call out the fact that `load` and `initialize` require alignment in the meantime.

> When accessing a memory buffer, it is generally convenient to cast to a type with known layout and compute offsets relative to the type's size. This is how UnsafePointer<Pointee> works. A generic UnsafeTypePunnedPointer<Pointee> could be introduced with the same interface as UnsafePointer<Pointer>, but without the strict aliasing requirements. This seems like an overdesign simply to avoid calling strideof() in an rare use case, but nothing prevents adding this type later.

This need could also be addressed with some additional convenience methods on UnsafeBytePointer to load or store at a given index, something like:

	func load<T>(asArrayOf type: T.Type, at index: Int) -> T {
		return (self + strideof(T) * index).load(T)
	func initialize(asArrayOf type: T.Type, initialValue: T, at index: Int) {
		return (self + strideof(T) * index).initialize(initialValue)


More information about the swift-evolution mailing list