[swift-evolution] [Review] SE-0055 Make unsafe pointer nullability explicit using Optional

Brent Royal-Gordon brent at architechies.com
Thu Mar 24 17:50:46 CDT 2016


> Thirdly, as mentioned in the prior discussion it's certainly possible on some platforms to remap the memory page at address 0x0 and make it usable to userland code. Even if we don't currently support any such platforms, we shouldn't lock ourselves into a situation where we need to be able to do this.

I don't think this is mentioned in the proposal itself, but it came up in the discussion.

The C standard requires that there be a "null" pointer address which can be stored into any pointer but which can never actually be valid. It does *not* require that the null pointer address be 0x0. Most platforms do use 0x0, and clang doesn't support a non-0x0 null pointer, but this is not required by the C standard.

I believe Swift should mimic this behavior. On platforms where 0x0 is a valid address, Swift should not use 0x0 as the null pointer, but rather use some other address which isn't valid (perhaps ~0x0). Pointer types should treat this address as an unused value, which the enum machinery will then exploit to represent Optional.none.

For now, this design should probably just be documented somewhere, perhaps in a porting guide; actually implementing it is not really a priority.

> Finally, having nullable UnsafePointers currently is the only way from swift code to convert an UnsafePointer to an Int of its raw address, short of using another level of indirection:
> 
> let rawAddress: Int = UnsafePointer<UInt8>(nil).distanceTo(myPointer)

Given what I discussed about `nil` not necessarily being 0x0, this construct is not necessarily valid anyway.

Besides, we *do* have a construct which converts between pointers and integers without any semantic confusion about `nil`—and it even expresses what it's doing more clearly than your `distanceTo` trick:

	unsafeBitCast(pointer, Int.self)

> I'm actually unsure of any other languages that have explicit nullability on a raw pointer type. (Maybe rust has it? I'm not very familiar with rust).

Apple variants of C, C++, and Objective-C now do. Actually, I believe they had some nullability control even before the recent keywords through __attribute__.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list