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

native: add IsBigEndian bool const #3

Merged
merged 1 commit into from
Dec 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}