-
Notifications
You must be signed in to change notification settings - Fork 105
Open
Description
This package supports the two latest Go versions. With that in mind, interpretation of raw byte buffers as integer types can be simplified with the usage of generics, thereby reducing the verbosity of the nlenc package. This change is backwards-compatible with the currently exposed API. What do you think?
// Int returns the contents of raw as an integer as specified by T
// Int panics if the raw data is not the exact length as the compile-time
// length of T
func Int[T constraints.Integer](raw []byte) (i T) {
rawLen := len(raw)
if compLen := int(unsafe.Sizeof(i)); compLen != rawLen {
panic(fmt.Sprintf(
"unexpected byte slice length when decoding integer: %d",
rawLen,
))
}
return *(*T)(unsafe.Pointer(&raw[0]))
}
// PutInt puts an integer into the contents of raw
// PutInt panics if the byte slice is not the exact length as the compile-time
// length of T
func PutInt[T constraints.Integer](raw []byte, i T) {
rawLen := len(raw)
if compLen := int(unsafe.Sizeof(i)); compLen != rawLen {
panic(fmt.Sprintf(
"unexpected byte slice length when encoding integer: %d",
rawLen,
))
}
*(*T)(unsafe.Pointer(&raw[0])) = i
}Metadata
Metadata
Assignees
Labels
No labels