Last active
August 29, 2015 14:24
-
-
Save quux00/0d75432b898e92200449 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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