Skip to content

Instantly share code, notes, and snippets.

@quux00
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quux00/0d75432b898e92200449 to your computer and use it in GitHub Desktop.
Save quux00/0d75432b898e92200449 to your computer and use it in GitHub Desktop.
func ReadVarIntToUint(r io.Reader) (uint64, error) {
var (
varbs []byte
ba [1]byte
u uint64
n int
err error
)
varbs = make([]byte, 0, 10)
/* ---[ read in all varint bytes ]--- */
for {
n, err = r.Read(ba[:])
if err != nil {
return 0, oerror.NewTrace(err)
}
if n != 1 {
return 0, oerror.IncorrectNetworkRead{Expected: 1, Actual: n}
}
varbs = append(varbs, ba[0])
if IsFinalVarIntByte(ba[0]) {
varbs = append(varbs, byte(0x0))
break
}
}
/* ---[ decode ]--- */
var right, left uint
finalbs := make([]byte, 8)
idx := 0
for i := 0; i < len(varbs)-1 && idx < 8; i++ {
right = uint(i) % 8
left = 7 - right
if i == 7 {
continue
}
vbcurr := varbs[i]
vbnext := varbs[i+1]
x := vbcurr & byte(0x7f)
y := x >> right
z := vbnext << left
finalbs[idx] = y | z
idx++
}
u = binary.LittleEndian.Uint64(finalbs)
return u, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment