// Package variablelengthquantity is for VLQ manipulations.
package variablelengthquantity
import (
"fmt"
)
// EncodeVarint VLQ encodes input numbers.
func EncodeVarint(input []uint32) []byte {
out := []byte{}
for _, val := range input {
if val == 0 {
out = append(out, 0x0)
}
out = append(out, msb(val)...)
}
return out
}
// msb truncates input to 7-bit long pieces.
// Also set the Most Significant Bit for all bytes except the last one.
func msb(input uint32) []byte {
out := []byte{}
for input > 0 {
out = append([]byte{byte(input) & 0x7f}, out...)
input >>= 7
if len(out) > 1 { // set MSB except for last one
out[0] |= 0x80
}
}
return out
}
// DecodeVarint decondes VLQ encoded input.
func DecodeVarint(input []byte) ([]uint32, error) {
out := []uint32{}
num := 0
for i, bt := range input {
// VSL has 7 useful bit
num <<= 7
// set last 7 bits, truncate MSB
num |= 0x7f & int(bt)
if (bt & 0x80) == 0 { // MSB is 0, this is the last byte of num
out = append(out, uint32(num))
num = 0
}
if i == len(input)-1 && (bt&0x80) != 0 {
return nil, fmt.Errorf("incomplete byte sequence")
}
}
return out, nil
}