byteorder.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2019 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package cpu
  5. import (
  6. "runtime"
  7. )
  8. // byteOrder is a subset of encoding/binary.ByteOrder.
  9. type byteOrder interface {
  10. Uint32([]byte) uint32
  11. Uint64([]byte) uint64
  12. }
  13. type littleEndian struct{}
  14. type bigEndian struct{}
  15. func (littleEndian) Uint32(b []byte) uint32 {
  16. _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808
  17. return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
  18. }
  19. func (littleEndian) Uint64(b []byte) uint64 {
  20. _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808
  21. return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |
  22. uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
  23. }
  24. func (bigEndian) Uint32(b []byte) uint32 {
  25. _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808
  26. return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24
  27. }
  28. func (bigEndian) Uint64(b []byte) uint64 {
  29. _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808
  30. return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 |
  31. uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56
  32. }
  33. // hostByteOrder returns binary.LittleEndian on little-endian machines and
  34. // binary.BigEndian on big-endian machines.
  35. func hostByteOrder() byteOrder {
  36. switch runtime.GOARCH {
  37. case "386", "amd64", "amd64p32",
  38. "arm", "arm64",
  39. "mipsle", "mips64le", "mips64p32le",
  40. "ppc64le",
  41. "riscv", "riscv64":
  42. return littleEndian{}
  43. case "armbe", "arm64be",
  44. "mips", "mips64", "mips64p32",
  45. "ppc", "ppc64",
  46. "s390", "s390x",
  47. "sparc", "sparc64":
  48. return bigEndian{}
  49. }
  50. panic("unknown architecture")
  51. }