binary.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package yu_proto
  2. import yu_math "gogs.qqck.cn/s/tools/math"
  3. // MaxVarintLenN is the maximum length of a varint-encoded N-bit integer.
  4. const (
  5. maxVarintLen16 = 3
  6. maxVarintLen32 = 5
  7. maxVarintLen64 = 10
  8. )
  9. func appendInt64(buf []byte, x int64) []byte {
  10. if x >= 0 {
  11. return appendUint64(buf, uint64(x)<<1)
  12. } else {
  13. return appendUint64(buf, ^uint64(x)<<1)
  14. }
  15. }
  16. func appendUint64(buf []byte, x uint64) []byte {
  17. for x >= 0x80 {
  18. buf = append(buf, byte(x)|0x80)
  19. x >>= 7
  20. }
  21. return append(buf, byte(x))
  22. }
  23. func appendFloat32(buf []byte, x float32) []byte {
  24. v := yu_math.Float32bits(x)
  25. buf = append(buf, byte(v))
  26. buf = append(buf, byte(v>>8))
  27. buf = append(buf, byte(v>>16))
  28. return append(buf, byte(v>>24))
  29. }
  30. func appendFloat64(buf []byte, x float64) []byte {
  31. v := yu_math.Float64bits(x)
  32. buf = append(buf, byte(v))
  33. buf = append(buf, byte(v>>8))
  34. buf = append(buf, byte(v>>16))
  35. buf = append(buf, byte(v>>24))
  36. buf = append(buf, byte(v>>32))
  37. buf = append(buf, byte(v>>40))
  38. buf = append(buf, byte(v>>48))
  39. return append(buf, byte(v>>56))
  40. }
  41. // Uvarint decodes a uint64 from buf and returns that value and the
  42. // number of bytes read (> 0). If an error occurred, the value is 0
  43. // and the number of bytes n is <= 0 meaning:
  44. //
  45. // n == 0: buf too small
  46. // n < 0: value larger than 64 bits (overflow)
  47. // and -n is the number of bytes read
  48. func getUint64(buf []byte) (uint64, int) {
  49. var x uint64
  50. var s uint
  51. for i, b := range buf {
  52. if i == maxVarintLen64 {
  53. // Catch byte reads past MaxVarintLen64.
  54. // See issue https://golang.org/issues/41185
  55. return 0, -(i + 1) // overflow
  56. }
  57. if b < 0x80 {
  58. if i == maxVarintLen64-1 && b > 1 {
  59. return 0, -(i + 1) // overflow
  60. }
  61. return x | uint64(b)<<s, i + 1
  62. }
  63. x |= uint64(b&0x7f) << s
  64. s += 7
  65. }
  66. return 0, 0
  67. }