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.
 
 
 

63 lines
1.5 KiB

  1. // Copyright 2017 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 catmsg
  5. // This file implements varint encoding analogous to the one in encoding/binary.
  6. // We need a string version of this function, so we add that here and then add
  7. // the rest for consistency.
  8. import "errors"
  9. var (
  10. errIllegalVarint = errors.New("catmsg: illegal varint")
  11. errVarintTooLarge = errors.New("catmsg: varint too large for uint64")
  12. )
  13. const maxVarintBytes = 10 // maximum length of a varint
  14. // encodeUint encodes x as a variable-sized integer into buf and returns the
  15. // number of bytes written. buf must be at least maxVarintBytes long
  16. func encodeUint(buf []byte, x uint64) (n int) {
  17. for ; x > 127; n++ {
  18. buf[n] = 0x80 | uint8(x&0x7F)
  19. x >>= 7
  20. }
  21. buf[n] = uint8(x)
  22. n++
  23. return n
  24. }
  25. func decodeUintString(s string) (x uint64, size int, err error) {
  26. i := 0
  27. for shift := uint(0); shift < 64; shift += 7 {
  28. if i >= len(s) {
  29. return 0, i, errIllegalVarint
  30. }
  31. b := uint64(s[i])
  32. i++
  33. x |= (b & 0x7F) << shift
  34. if b&0x80 == 0 {
  35. return x, i, nil
  36. }
  37. }
  38. return 0, i, errVarintTooLarge
  39. }
  40. func decodeUint(b []byte) (x uint64, size int, err error) {
  41. i := 0
  42. for shift := uint(0); shift < 64; shift += 7 {
  43. if i >= len(b) {
  44. return 0, i, errIllegalVarint
  45. }
  46. c := uint64(b[i])
  47. i++
  48. x |= (c & 0x7F) << shift
  49. if c&0x80 == 0 {
  50. return x, i, nil
  51. }
  52. }
  53. return 0, i, errVarintTooLarge
  54. }