mem: add BitCast, BitCastValue, UnsafeCast, UnsafeCastValue

This commit is contained in:
judah 2026-01-11 23:10:09 -07:00
parent e64c06c964
commit 2dd74ce660

View file

@ -40,6 +40,9 @@ func BitCast[TOut any, TIn any](value *TIn) TOut {
return *((*TOut)(unsafe.Pointer(value))) return *((*TOut)(unsafe.Pointer(value)))
} }
// BitCastValue performs a bit conversion between two types of the same size.
//
// BitCastValue panics if the sizes of the types differ.
func BitCastValue[TOut any, TIn any](value TIn) TOut { func BitCastValue[TOut any, TIn any](value TIn) TOut {
if Sizeof[TOut]() != Sizeof[TIn]() { if Sizeof[TOut]() != Sizeof[TIn]() {
panic("bitcast: sizes of types must match") panic("bitcast: sizes of types must match")
@ -47,6 +50,16 @@ func BitCastValue[TOut any, TIn any](value TIn) TOut {
return *((*TOut)(unsafe.Pointer(&value))) return *((*TOut)(unsafe.Pointer(&value)))
} }
// UnsafeCast performs a bit conversion between two types without checking if their sizes match.
func UnsafeCast[TOut any, TIn any](value *TIn) TOut {
return *((*TOut)(unsafe.Pointer(value)))
}
// UnsafeCastValue performs a bit conversion between two types without checking if their sizes match.
func UnsafeCastValue[TOut any, TIn any](value TIn) TOut {
return *((*TOut)(unsafe.Pointer(&value)))
}
// Copy copies size number of bytes from src into dst. // Copy copies size number of bytes from src into dst.
// //
// Returns dst. // Returns dst.