Edit: Please note that as discussion progresses the main focus of this topic is about Validatable (pseudo) protocol and the related runtime validation checks, done in debug mode only or in debug/release modes, perhaps controllable similar to how other diagnostic / sanitising checks are controlled).
Currently this code results in a warning:
let intValue = 12345
unsafeBitCast(intValue, to: Unsafe[Mutablle][Raw]Pointer[<Type>].self)
// πΆ Warning: unsafeBitCast' from 'Int' to 'UnsafeRawPointer' can be replaced with 'bitPattern:' initializer on 'UnsafeRawPointer'
I believe this warning must be promoted to an error (with appropriate fix-it).
Normally users won't have an issue changing their exiting code from unsafeBitCast(intValue β pointer)
to pointer.init(bitPattern:)
, unless they are creating a null pointer:
unsafeBitCast(0, Unsafe[Mutablle][Raw]Pointer[<Type>].self)
Which crafts an invalid value and invokes an undefined behaviour making the app invalid. Note that creating an invalid null pointer with the init + bitPattern is impossible:
UnsafeRawPointer(bitPattern: intValue)! // crashes if intValue == 0
The "workaround" fix to the user code that wants it would be something like this:
let pointer = integer != 0 ? UnsafeRawPointer(bitPattern: integer) : nil
Note that it would no longer be possible to create a null pointer to pass to a C-API that was annotated incorrectly:
void foo(uint8_t * dst_buffer, size_t dst_size) // known to accept null but not annotated
foo(UnsafePointer<UInt8>(bitPattern: intValue), ...)
// π Value of optional type 'UnsafePointer<UInt8>?' must be unwrapped to a value of type 'UnsafePointer<UInt8>'
The fix could be fixing the annotation (preferred), or using a wrapper C api:
void bar(uint8_t * _Nullable dst_buffer, size_t dst_size) {
foo(dst_buffer, dstSize);
}
bar(UnsafePointer<UInt8>(bitPattern: intValue), ...) // β
See the relevant recent discussion.