Skip to content

Commit

Permalink
provide an implementation example
Browse files Browse the repository at this point in the history
  • Loading branch information
mattetti committed Apr 29, 2016
1 parent 914be72 commit 3464be9
Showing 1 changed file with 45 additions and 4 deletions.
49 changes: 45 additions & 4 deletions exercises/variable-length-quantity/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,55 @@ package variablelengthquantity

// EncodeVarint returns the varint encoding of x.
func EncodeVarint(x uint32) []byte {
// TODO: implement me
return nil
if x>>7 == 0 {
return []byte{
byte(x),
}
}

if x>>14 == 0 {
return []byte{
byte(0x80 | x>>7),
byte(127 & x),
}
}

if x>>21 == 0 {
return []byte{
byte(0x80 | x>>14),
byte(0x80 | x>>7),
byte(127 & x),
}
}

return []byte{
byte(0x80 | x>>21),
byte(0x80 | x>>14),
byte(0x80 | x>>7),
byte(127 & x),
}
}

// DecodeVarint reads a varint-encoded integer from the slice.
// It returns the integer and the number of bytes consumed, or
// zero if there is not enough.
func DecodeVarint(buf []byte) (x uint32, n int) {
// TODO: implement me
return 0, 0
if len(buf) < 1 {
return 0, 0
}

if buf[0] <= 0x80 {
return uint32(buf[0]), 1
}

var b byte
for n, b = range buf {
x = x << 7
x |= uint32(b) & 0x7F
if (b & 0x80) == 0 {
return x, n
}
}

return x, n
}

0 comments on commit 3464be9

Please sign in to comment.