Here’s a simple problem involving unsafe pointers, presented as a puzzle to be solved for the “best” solution that Swift has to offer. Consider a function with the following signature:
func fill<T>(_ buffer: UnsafeMutableRawPointer, with array: [T]) { … }
The rules of the game are:
-
The semantics of the function are that it copies the contents of the array into the given buffer.
-
You can assume that
bufferpoints to memory that has been allocated at a suitable size, and has a lifetime longer than the call tofill(_:with:). If you wish, you can further assume that the buffer has been initialized to all 0 bits. -
Tis a trivial type. It can be a simple integer or float type, or a struct with trivial members, or a SIMD generic over a trivial numeric type. -
The
bufferparameter is passed in as an immutable variable. You aren’t allowed to make itinout(in case that matters to the solution). -
APIs used in the implementation are limited to the Swift language and the standard library.
The game is:
— Complete the function by writing the “best” implementation.
Obviously, “best” is going to be somewhat subjective (so the planned $1,000,000 cash prize isn’t going to be awarded, for ethical reasons), but here are some criteria:
• Swifty-est. A casual reader of the implementation should tend to think, “Oh, I didn’t realize Swift could handle that so neatly.” The reader should ideally learn something about Swift from this.
• Proper-est. The implementation shouldn’t abuse Swift features designed for other purposes, but can be opinionated about what features are relevant here. For example, “binding” of unsafe pointers doesn’t really do anything for trivial types (AFAIK). A solution will have to take a stand on whether to avoid APIs that mention bind or assumingBound because it’s a distraction for trivial types, or to embrace binding because it’s formally required even if it doesn’t do anything here.
• Un-hacky-est. The more directly the solution expresses what is actually going on, the better.
The judges will be a panel of international semioticists and impartial language lawyers — blindfolded, of course, and prepared by 3 days of immersion in sensory deprivation tanks. The judges’ decision will be final and cannot be overridden.