Friday, May 13, 2016

Packing Bytes in Swift

Russ Bishop:

I want to do this purely in Swift and mostly analogous to what you’d do in C because it’s relatively quick, doesn’t introduce any dependencies, and the decoder is really simple and could be implemented on any platform.

[…]

We can calculate the appropriate location in the buffer by performing arithmetic on the UnsafeMutablePointer itself. The key is that unsafe pointers in Swift know the size of the type they are working with and all adjustments are made in terms of the size of that type, not in bytes! (A Void pointer does work in terms of bytes since it knows nothing about the size of the type).

[…]

Why pass in a deallocator function? Technically you might be able to get away with NSData(bytesNoCopy:length:freeWhenDone:) but that would just be an accident of implementation. If the Swift runtime did (or does) use a different allocator than the default system malloc/free then You’re Gonna Have a Bad Time.

He doesn’t show them, but Swift numbers actually do have built-in methods for endian conversion.

Comments RSS · Twitter

Leave a Comment