Skip to content

codec simplification via generics #216

@ubiquitousbyte

Description

@ubiquitousbyte

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions