github.com/aclements/go-misc@v0.0.0-20240129233631-2f6ede80790c/varint/varint.go (about) 1 // Copyright 2016 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package varint 6 7 const maxVarintBytes = 10 8 9 // EncodeVarint and DecodeVarint from https://github.com/golang/protobuf 10 11 func EncodeVarint(x uint64) []byte { 12 var buf [maxVarintBytes]byte 13 var n int 14 for n = 0; x > 127; n++ { 15 buf[n] = 0x80 | uint8(x&0x7F) 16 x >>= 7 17 } 18 buf[n] = uint8(x) 19 n++ 20 return buf[0:n] 21 } 22 23 func DecodeVarint(buf []byte) (x uint64, n int) { 24 // x, n already 0 25 for shift := uint(0); shift < 64; shift += 7 { 26 if n >= len(buf) { 27 return 0, 0 28 } 29 b := uint64(buf[n]) 30 n++ 31 x |= (b & 0x7F) << shift 32 if (b & 0x80) == 0 { 33 return x, n 34 } 35 } 36 37 // The number is too large to represent in a 64-bit value. 38 return 0, 0 39 } 40 41 func queryBMI2() bool 42 43 var hasBMI2 = queryBMI2() 44 45 func decodeVarintAsmLoop(buf []byte) (x uint64, n int) 46 func decodeVarintAsmBMI2(buf []byte) (x uint64, n int) 47 func decodeVarintAsm1(buf []byte) (x uint64, n int) 48 func decodeVarintAsm2(buf []byte) (x uint64, n int)