summaryrefslogtreecommitdiff
path: root/go/variable-length-quantity/variable_length_quantity.go
blob: 9df99d9df772b9bd09b4c1afef21e31088079d5e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package variablelengthquantity

import (
	"bytes"
	"io"
)

func decodeVarint(r io.ByteReader) (uint32, error) {
	var i uint32
	for {
		b, err := r.ReadByte()
		if err != nil {
			return 0, err
		}
		i = (i << 7) | uint32(b&0x7f)
		if b&0x80 == 0 {
			return i, nil
		}
	}
}

func DecodeVarint(b []byte) ([]uint32, error) {
	var ret []uint32
	r := bytes.NewReader(b)
	for r.Len() > 0 {
		u, err := decodeVarint(r)
		if err != nil {
			return nil, err
		}
		ret = append(ret, u)
	}
	return ret, nil
}

func encodeVarint(w io.ByteWriter, u uint32) {
	if u == 0 {
		w.WriteByte(0)
		return
	}
	var l int
	for i := u; i > 0; i >>= 7 {
		l++
	}
	for i := l - 1; i >= 0; i-- {
		o := byte(u >> uint(i*7) & 0x7f)
		if i != 0 {
			o |= 0x80
		}
		w.WriteByte(o)
	}
}

func EncodeVarint(u []uint32) []byte {
	w := new(bytes.Buffer)
	for _, v := range u {
		encodeVarint(w, v)
	}
	return w.Bytes()
}