Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

codec simplification via generics #216

Open
ubiquitousbyte opened this issue Jul 18, 2024 · 0 comments
Open

codec simplification via generics #216

ubiquitousbyte opened this issue Jul 18, 2024 · 0 comments

Comments

@ubiquitousbyte
Copy link

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant