| 1 |
package proto |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/binary" |
| 5 |
"errors" |
| 6 |
"io" |
| 7 |
"unsafe" |
| 8 |
) |
| 9 |
|
| 10 |
// DecodeTag reverses the encoding applied by EncodeTag. |
| 11 |
func DecodeTag(tag uint64) (FieldNumber, WireType) { |
| 12 |
return FieldNumber(tag >> 3), WireType(tag & 7) |
| 13 |
} |
| 14 |
|
| 15 |
// DecodeZigZag reverses the encoding applied by EncodeZigZag. |
| 16 |
func DecodeZigZag(v uint64) int64 { |
| 17 |
return decodeZigZag64(v) |
| 18 |
} |
| 19 |
|
| 20 |
func decodeZigZag64(v uint64) int64 { |
| 21 |
return int64(v>>1) ^ -(int64(v) & 1) |
| 22 |
} |
| 23 |
|
| 24 |
func decodeZigZag32(v uint32) int32 { |
| 25 |
return int32(v>>1) ^ -(int32(v) & 1) |
| 26 |
} |
| 27 |
|
| 28 |
type decodeFunc = func([]byte, unsafe.Pointer, flags) (int, error) |
| 29 |
|
| 30 |
var errVarintOverflow = errors.New("varint overflowed 64 bits integer") |
| 31 |
|
| 32 |
func decodeVarint(b []byte) (uint64, int, error) { |
| 33 |
if len(b) != 0 && b[0] < 0x80 { |
| 34 |
// Fast-path for decoding the common case of varints that fit on a |
| 35 |
// single byte. |
| 36 |
// |
| 37 |
// This path is ~60% faster than calling binary.Uvarint. |
| 38 |
return uint64(b[0]), 1, nil |
| 39 |
} |
| 40 |
|
| 41 |
var x uint64 |
| 42 |
var s uint |
| 43 |
|
| 44 |
for i, c := range b { |
| 45 |
if c < 0x80 { |
| 46 |
if i > 9 || i == 9 && c > 1 { |
| 47 |
return 0, i, errVarintOverflow |
| 48 |
} |
| 49 |
return x | uint64(c)<<s, i + 1, nil |
| 50 |
} |
| 51 |
x |= uint64(c&0x7f) << s |
| 52 |
s += 7 |
| 53 |
} |
| 54 |
|
| 55 |
return x, len(b), io.ErrUnexpectedEOF |
| 56 |
} |
| 57 |
|
| 58 |
func decodeVarintZigZag(b []byte) (int64, int, error) { |
| 59 |
v, n, err := decodeVarint(b) |
| 60 |
return decodeZigZag64(v), n, err |
| 61 |
} |
| 62 |
|
| 63 |
func decodeLE32(b []byte) (uint32, int, error) { |
| 64 |
if len(b) < 4 { |
| 65 |
return 0, 0, io.ErrUnexpectedEOF |
| 66 |
} |
| 67 |
return binary.LittleEndian.Uint32(b), 4, nil |
| 68 |
} |
| 69 |
|
| 70 |
func decodeLE64(b []byte) (uint64, int, error) { |
| 71 |
if len(b) < 8 { |
| 72 |
return 0, 0, io.ErrUnexpectedEOF |
| 73 |
} |
| 74 |
return binary.LittleEndian.Uint64(b), 8, nil |
| 75 |
} |
| 76 |
|
| 77 |
func decodeTag(b []byte) (f fieldNumber, t wireType, n int, err error) { |
| 78 |
v, n, err := decodeVarint(b) |
| 79 |
return fieldNumber(v >> 3), wireType(v & 7), n, err |
| 80 |
} |
| 81 |
|
| 82 |
func decodeVarlen(b []byte) ([]byte, int, error) { |
| 83 |
v, n, err := decodeVarint(b) |
| 84 |
if err != nil { |
| 85 |
return nil, n, err |
| 86 |
} |
| 87 |
if v > uint64(len(b)-n) { |
| 88 |
return nil, n, io.ErrUnexpectedEOF |
| 89 |
} |
| 90 |
return b[n : n+int(v)], n + int(v), nil |
| 91 |
} |