mojo
mojo copied to clipboard
[Feature Request] SIMD bitcasts to different length SIMD types
Similar to #182, when working with the SIMD types, it would be nice to have an easy conversion from something like UI32
to SIMD[DType.ui8, 4]
. Aliases like UI8x4
might make sense if such conversions are allowed (and these would be sensible as they appear in many SIMD libraries).
We made quite a bit of effort not to expose bitcasts in stdlib (at least readily accessible). Bitcasts are super dangerous and can create issues. There is a way to implement what you want above which is via
fn bitcast[target_type : AnyType, src_type : AnyType](src : src_type) -> target_type:
var tmp = src
let addr = Pointer[src_type].address_of(tmp)
return addr.bitcast[target_type]().load()
That makes sense. I would be satisfied with that decision as long as there is a constructor for SIMD[DType.ui8, N]
for other SIMD types. It could potentially take a Endianness
param (as mentioned in #285), there's also the option of just having a from_le_bytes
/from_be_bytes
method like Rust does.
We do not have a Target info to query endieness at the moment, but you can use https://docs.modular.com/mojo/MojoStdlib/Bit.html#bitreverse to reverse bits
I'm going to close this issue. Please file an issue for the Endianness feature
We made quite a bit of effort not to expose bitcasts in stdlib (at least readily accessible). Bitcasts are super dangerous and can create issues. There is a way to implement what you want above which is via
fn bitcast[target_type : AnyType, src_type : AnyType](src : src_type) -> target_type: var tmp = src let addr = Pointer[src_type].address_of(tmp) return src.bitcast[target_type]().load()
@abduld should that read return addr.bitcast[target_type]().load()
at the end(?)
So that would be finally :
fn bitcast[target_type : AnyType, src_type : AnyType](src : src_type) -> target_type:
var tmp = src
let addr = Pointer[src_type].address_of(tmp)
return addr.bitcast[target_type]().load()
FYI: A bitcast functions was added https://docs.modular.com/mojo/stdlib/memory/unsafe.html#bitcast-2