github.com/GeniusesGroup/libgo@v0.0.0-20220929090155-5ff932cb408e/binary/le-in-be-cpu.go (about) 1 // For license and copyright information please see the LEGAL file in the code repository 2 3 //go:build armbe || arm64be || mips || mips64 || mips64p32 || ppc || ppc64 || s390 || s390x || sparc || sparc64 4 5 package binary 6 7 import "unsafe" 8 9 // LittleEndian is the little-endian implementation to get|set from le binary to be cpu 10 var LittleEndian littleEndian 11 12 type littleEndian struct{} 13 14 func (littleEndian) Uint16(b []byte) uint16 { 15 _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808 16 return uint16(b[1]) | uint16(b[0])<<8 } 17 func (littleEndian) Uint32(b []byte) uint32 { 18 _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 19 return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24 20 } 21 func (littleEndian) Uint64(b []byte) uint64 { 22 _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 23 return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | 24 uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56 25 } 26 27 func (littleEndian) PutUint16(b []byte, v uint16) { 28 _ = b[1] // early bounds check to guarantee safety of writes below 29 b[0] = byte(v >> 8) 30 b[1] = byte(v) 31 } 32 func (littleEndian) PutUint32(b []byte, v uint32) { 33 _ = b[3] // early bounds check to guarantee safety of writes below 34 b[0] = byte(v >> 24) 35 b[1] = byte(v >> 16) 36 b[2] = byte(v >> 8) 37 b[3] = byte(v) 38 } 39 func (littleEndian) PutUint64(b []byte, v uint64) { 40 _ = b[7] // early bounds check to guarantee safety of writes below 41 b[0] = byte(v >> 56) 42 b[1] = byte(v >> 48) 43 b[2] = byte(v >> 40) 44 b[3] = byte(v >> 32) 45 b[4] = byte(v >> 24) 46 b[5] = byte(v >> 16) 47 b[6] = byte(v >> 8) 48 b[7] = byte(v) 49 } 50 51 func init() { 52 i := uint32(1) 53 b := (*[4]byte)(unsafe.Pointer(&i)) 54 if b[0] == 1 { 55 panic("Expect BigEndian CPU but have LittleEndian CPU that cause many problem in other packages") 56 } 57 }