You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

byteorder.go 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 littleEndian on little-endian machines and
  34. // bigEndian on big-endian machines.
  35. func hostByteOrder() byteOrder {
  36. switch runtime.GOARCH {
  37. case "386", "amd64", "amd64p32",
  38. "alpha",
  39. "arm", "arm64",
  40. "mipsle", "mips64le", "mips64p32le",
  41. "nios2",
  42. "ppc64le",
  43. "riscv", "riscv64",
  44. "sh":
  45. return littleEndian{}
  46. case "armbe", "arm64be",
  47. "m68k",
  48. "mips", "mips64", "mips64p32",
  49. "ppc", "ppc64",
  50. "s390", "s390x",
  51. "shbe",
  52. "sparc", "sparc64":
  53. return bigEndian{}
  54. }
  55. panic("unknown architecture")
  56. }