endian

package
v0.0.0-...-73ec345 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 20, 2026 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

Package endian provides type-safe helpers for reading and writing fixed-width unsigned integers with explicit byte order.

Using generics it collapses what would otherwise be twelve separate functions (four types × three byte orders) into four.

User-defined types built on unsigned integer bases satisfy the Unsigned constraint and work without explicit casting:

type SessionID uint32
endian.PutBE(buf, SessionID(42))

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func PutBE

func PutBE[T Unsigned](dst []byte, v T)

PutBE encodes v into dst in big-endian byte order. dst must be at least as long as the byte size of T.

Example
package main

import (
	"fmt"

	"lowbit.dev/wireframe/endian"
)

func main() {
	buf := make([]byte, 4)
	endian.PutBE(buf, uint32(0xDEADBEEF))
	fmt.Printf("%X\n", buf)
}
Output:
DEADBEEF
Example (UserDefinedType)
package main

import (
	"fmt"

	"lowbit.dev/wireframe/endian"
)

// SessionID is a user-defined type with an unsigned integer base.
// It satisfies the Unsigned constraint without any explicit casting.
type SessionID uint32

func main() {
	buf := make([]byte, 4)
	endian.PutBE(buf, SessionID(42))
	got := endian.ReadBE[SessionID](buf)
	fmt.Println(got)
}
Output:
42

func PutLE

func PutLE[T Unsigned](dst []byte, v T)

PutLE encodes v into dst in little-endian byte order. dst must be at least as long as the byte size of T.

Example
package main

import (
	"fmt"

	"lowbit.dev/wireframe/endian"
)

func main() {
	buf := make([]byte, 2)
	endian.PutLE(buf, uint16(0x0102))
	// Little-endian stores the low byte first.
	fmt.Printf("%02X %02X\n", buf[0], buf[1])
}
Output:
02 01

func ReadBE

func ReadBE[T Unsigned](src []byte) T

ReadBE decodes a value of type T from src in big-endian byte order. src must be at least as long as the byte size of T.

Example
package main

import (
	"fmt"

	"lowbit.dev/wireframe/endian"
)

func main() {
	buf := []byte{0xDE, 0xAD, 0xBE, 0xEF}
	v := endian.ReadBE[uint32](buf)
	fmt.Printf("%X\n", v)
}
Output:
DEADBEEF

func ReadLE

func ReadLE[T Unsigned](src []byte) T

ReadLE decodes a value of type T from src in little-endian byte order. src must be at least as long as the byte size of T.

Example
package main

import (
	"fmt"

	"lowbit.dev/wireframe/endian"
)

func main() {
	buf := []byte{0x02, 0x01}
	v := endian.ReadLE[uint16](buf)
	fmt.Printf("%04X\n", v)
}
Output:
0102

Types

type Unsigned

type Unsigned interface {
	~uint8 | ~uint16 | ~uint32 | ~uint64
}

Unsigned is the constraint satisfied by all unsigned integer types as well as user-defined types with an unsigned integer base.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL