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

Dany St-Amant dsa.mls at icloud.com
Fri Mar 25 09:02:51 CDT 2016


> Le 24 mars 2016 à 18:50, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> a écrit :
> 
>> 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.

In the low level world, there is no such thing as an invalid address; both 0x0 and ~0x0 are perfectly valid byte pointers. So using something else than 0x0 for Swift invalid pointer just shuffle the problem around.

Dany

> 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
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list