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 ¶
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 ¶
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 ¶
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 ¶
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