Skip to content

Commit

Permalink
native: add IsBigEndian bool const
Browse files Browse the repository at this point in the history
  • Loading branch information
bradfitz committed Dec 13, 2022
1 parent a938fb1 commit 1f8c40c
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions endian_big.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,10 @@ package native

import "encoding/binary"

// Endian is the encoding/binary.ByteOrder implementation for the
// current CPU's native byte order.
var Endian = binary.BigEndian

// IsBigEndian is whether the current CPU's native byte order is big
// endian.
const IsBigEndian = true
4 changes: 4 additions & 0 deletions endian_generic.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,16 @@ import (

var Endian binary.ByteOrder

var IsBigEndian bool

func init() {
b := uint16(0xff) // one byte
if *(*byte)(unsafe.Pointer(&b)) == 0 {
Endian = binary.BigEndian
IsBigEndian = true
} else {
Endian = binary.LittleEndian
IsBigEndian = false
}
log.Printf("github.com/josharian/native: unrecognized arch %v (%v), please file an issue", runtime.GOARCH, Endian)
}
6 changes: 6 additions & 0 deletions endian_little.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,10 @@ package native

import "encoding/binary"

// Endian is the encoding/binary.ByteOrder implementation for the
// current CPU's native byte order.
var Endian = binary.LittleEndian

// IsBigEndian is whether the current CPU's native byte order is big
// endian.
const IsBigEndian = false
9 changes: 9 additions & 0 deletions endian_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
package native_test

import (
"encoding/binary"
"testing"

"github.com/josharian/native"
)

func TestPrintEndianness(t *testing.T) {
t.Logf("native endianness is %v", native.Endian)

var want binary.ByteOrder = binary.BigEndian
if !native.IsBigEndian {
want = binary.LittleEndian
}
if native.Endian != want {
t.Errorf("IsBigEndian = %v not consistent with native.Endian = %T", native.IsBigEndian, want)
}
}

0 comments on commit 1f8c40c

Please sign in to comment.