mem: simplify Sizeof/Alignof; testx: add ShouldPanic
This commit is contained in:
parent
e2cec86c39
commit
43e07fcbac
2 changed files with 16 additions and 8 deletions
14
mem/mem.go
14
mem/mem.go
|
|
@ -11,18 +11,18 @@ const (
|
||||||
Terabyte
|
Terabyte
|
||||||
)
|
)
|
||||||
|
|
||||||
// SizeOf returns the size (in bytes) of the given type.
|
// Sizeof returns the size (in bytes) of the given type.
|
||||||
//
|
//
|
||||||
// Not to be confused with [unsafe.Sizeof] which returns the size of a type via an expression.
|
// Not to be confused with [unsafe.Sizeof] which returns the size of a type via an expression.
|
||||||
func SizeOf[T any]() uintptr {
|
func Sizeof[T any]() uintptr {
|
||||||
return unsafe.Sizeof(ZeroValue[T]())
|
return unsafe.Sizeof(*(*T)(nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
// AlignOf returns the alignment (in bytes) of the given type.
|
// Alignof returns the alignment (in bytes) of the given type.
|
||||||
//
|
//
|
||||||
// Not to be confused with [unsafe.AlignOf] which returns the alignment of a type via an expression.
|
// Not to be confused with [unsafe.AlignOf] which returns the alignment of a type via an expression.
|
||||||
func AlignOf[T any]() uintptr {
|
func Alignof[T any]() uintptr {
|
||||||
return unsafe.Alignof(ZeroValue[T]())
|
return unsafe.Alignof(*(*T)(nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ZeroValue returns the zero value of a given type.
|
// ZeroValue returns the zero value of a given type.
|
||||||
|
|
@ -34,7 +34,7 @@ func ZeroValue[T any]() (_ T) {
|
||||||
//
|
//
|
||||||
// BitCast panics if the sizes of the types differ.
|
// BitCast panics if the sizes of the types differ.
|
||||||
func BitCast[TOut any, TIn any](value *TIn) TOut {
|
func BitCast[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")
|
||||||
}
|
}
|
||||||
return *((*TOut)(unsafe.Pointer(value)))
|
return *((*TOut)(unsafe.Pointer(value)))
|
||||||
|
|
|
||||||
|
|
@ -7,10 +7,18 @@ func Expect(t *testing.T, cond bool, message ...any) {
|
||||||
|
|
||||||
if !cond {
|
if !cond {
|
||||||
if len(message) == 0 {
|
if len(message) == 0 {
|
||||||
message = append(message, "assertion failed")
|
message = append(message, "expectation failed")
|
||||||
}
|
}
|
||||||
|
|
||||||
str := message[0].(string)
|
str := message[0].(string)
|
||||||
t.Fatalf(str, message[1:]...)
|
t.Fatalf(str, message[1:]...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ShouldPanic(t *testing.T, f func()) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
defer func() { recover() }()
|
||||||
|
f()
|
||||||
|
t.Fatal("expected panic")
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue