Skip to content

Commit

Permalink
feat: add ConsumeVarint
Browse files Browse the repository at this point in the history
Signed-off-by: Christian Stewart <christian@aperture.us>
  • Loading branch information
paralin committed Apr 22, 2024
1 parent 8991137 commit 00f5827
Showing 1 changed file with 104 additions and 0 deletions.
104 changes: 104 additions & 0 deletions protobuf-go-lite.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,110 @@ func AppendVarint(b []byte, v uint64) []byte {
return b
}

// ConsumeVarint parses b as a varint-encoded uint64, reporting its length.
// This returns -1 upon any error, -1 for parse error and -2 for overflow.
func ConsumeVarint(b []byte) (v uint64, n int) {
var y uint64
if len(b) <= 0 {
return 0, -1
}
v = uint64(b[0])
if v < 0x80 {
return v, 1
}
v -= 0x80

if len(b) <= 1 {
return 0, -1
}
y = uint64(b[1])
v += y << 7
if y < 0x80 {
return v, 2
}
v -= 0x80 << 7

if len(b) <= 2 {
return 0, -1
}
y = uint64(b[2])
v += y << 14
if y < 0x80 {
return v, 3
}
v -= 0x80 << 14

if len(b) <= 3 {
return 0, -1
}
y = uint64(b[3])
v += y << 21
if y < 0x80 {
return v, 4
}
v -= 0x80 << 21

if len(b) <= 4 {
return 0, -1
}
y = uint64(b[4])
v += y << 28
if y < 0x80 {
return v, 5
}
v -= 0x80 << 28

if len(b) <= 5 {
return 0, -1
}
y = uint64(b[5])
v += y << 35
if y < 0x80 {
return v, 6
}
v -= 0x80 << 35

if len(b) <= 6 {
return 0, -1
}
y = uint64(b[6])
v += y << 42
if y < 0x80 {
return v, 7
}
v -= 0x80 << 42

if len(b) <= 7 {
return 0, -1
}
y = uint64(b[7])
v += y << 49
if y < 0x80 {
return v, 8
}
v -= 0x80 << 49

if len(b) <= 8 {
return 0, -1
}
y = uint64(b[8])
v += y << 56
if y < 0x80 {
return v, 9
}
v -= 0x80 << 56

if len(b) <= 9 {
return 0, -1
}
y = uint64(b[9])
v += y << 63
if y < 2 {
return v, 10
}
return 0, -2
}

// SizeOfVarint returns the size of the varint-encoded value.
func SizeOfVarint(x uint64) (n int) {
return (bits.Len64(x|1) + 6) / 7
Expand Down

0 comments on commit 00f5827

Please sign in to comment.