varint.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright 2011 The Snappy-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 varint implements a variable-width encoding of unsigned integers.
  5. //
  6. // It is the same format used by protocol buffers. The format is described at
  7. // http://code.google.com/apis/protocolbuffers/docs/encoding.html
  8. package varint
  9. // MaxLen is the maximum encoded length of a uint64.
  10. const MaxLen = 10
  11. // Len returns the number of bytes used to represent v.
  12. func Len(v uint64) (n int) {
  13. for v > 0x7f {
  14. v >>= 7
  15. n++
  16. }
  17. return n + 1
  18. }
  19. // Decode returns the value encoded at the start of src, as well as the number
  20. // of bytes it occupies. It returns n == 0 if given invalid input.
  21. func Decode(src []byte) (v uint64, n int) {
  22. for shift := uint(0); ; shift += 7 {
  23. if n >= len(src) {
  24. return 0, 0
  25. }
  26. b := src[n]
  27. n++
  28. v |= uint64(b&0x7f) << shift
  29. if b&0x80 == 0 {
  30. break
  31. }
  32. }
  33. return v, n
  34. }
  35. // Encode writes the value to the start of dst, and returns the number of bytes
  36. // written. It panics if len(dst) < Len(v).
  37. func Encode(dst []byte, v uint64) (n int) {
  38. for v > 0x7f {
  39. dst[n] = 0x80 | uint8(v&0x7f)
  40. v >>= 7
  41. n++
  42. }
  43. dst[n] = uint8(v)
  44. return n + 1
  45. }