Pitch: Add implementation for `withContiguousStorageIfAvailable()` to `Foundation.ContiguousBytes`-conforming sequence types

Adding a ContiguousBytes protocol is the most logical way to handle containers that can be viewed as contiguous bytes. But there may be some concern about the runtime overhead associated with adding more conformances to generic types. I'm not sure how valid those concerns still are given the current state of runtime optimization. Nonetheless, it's a significant language change.

As of Feb 5, 2022, it is reasonably safe to implement Foundation.Data's withContiguousStorageIfAvailable by using withMemoryRebound: SE-0333 Expand usability of withMemoryRebound

It is now legal to pass a Swift UnsafePointer into a C function taking char *. That solves the problem of calling into (abusive) C APIs that assume char * can alias with anything.

It is extremely important for Swift programmers, whether they are C experts or not, to realize that casting typed pointers is the wrong way to reinterpret types. There is a safe and convenient way to do this using raw pointers. If they see common examples of code converting typed pointers, rather than using raw pointers, then that is actively misleading. It will lead to more undefined behavior in Swift code as they find ways to force the compiler to cast pointers to other types. Special-casing the semantics of Swift's generic unsafe pointer types based on an element type, which is not always known at compile time, would add a bizarre source of complexity to the language.

Remember that it's common for C code to have undefined behavior related to this. People seldom notice this problem because of limited optimization scope across C libraries.

4 Likes