forked from apache/beam
/
varint.go
98 lines (83 loc) · 2.6 KB
/
varint.go
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package coder
import (
"errors"
"io"
)
// ErrVarIntTooLong indicates a data corruption issue that needs special
// handling by callers of decode. TODO(herohde): have callers perform
// this special handling.
var ErrVarIntTooLong = errors.New("varint too long")
// EncodeVarUint64 encodes an uint64.
func EncodeVarUint64(value uint64, w io.Writer) error {
var ret []byte
for {
// Encode next 7 bits + terminator bit
bits := value & 0x7f
value >>= 7
var mask uint64
if value != 0 {
mask = 0x80
}
ret = append(ret, (byte)(bits|mask))
if value == 0 {
_, err := w.Write(ret)
return err
}
}
}
// Variable-length encoding for integers.
//
// Takes between 1 and 10 bytes. Less efficient for negative or large numbers.
// All negative ints are encoded using 5 bytes, longs take 10 bytes. We use
// uint64 (over int64) as the primitive form to get logical bit shifts.
// TODO(herohde) 5/16/2017: figure out whether it's too slow to read one byte
// at a time here. If not, we may need a more sophisticated reader than
// io.Reader with lookahead, say.
// DecodeVarUint64 decodes an uint64.
func DecodeVarUint64(r io.Reader) (uint64, error) {
var ret uint64
var shift uint
data := make([]byte, 1)
for {
// Get 7 bits from next byte
if n, err := r.Read(data); n < 1 {
return 0, err
}
b := data[0]
bits := (uint64)(b & 0x7f)
if shift >= 64 || (shift == 63 && bits > 1) {
return 0, ErrVarIntTooLong
}
ret |= bits << shift
shift += 7
if (b & 0x80) == 0 {
return ret, nil
}
}
}
// EncodeVarInt encodes an int32.
func EncodeVarInt(value int32, w io.Writer) error {
return EncodeVarUint64((uint64)(value)&0xffffffff, w)
}
// DecodeVarInt decodes an int32.
func DecodeVarInt(r io.Reader) (int32, error) {
ret, err := DecodeVarUint64(r)
if err != nil {
return 0, err
}
return (int32)(ret), nil
}