github.com/safing/portbase@v0.19.5/formats/varint/helpers.go (about)

     1  package varint
     2  
     3  import "errors"
     4  
     5  // PrependLength prepends the varint encoded length of the byte slice to itself.
     6  func PrependLength(data []byte) []byte {
     7  	return append(Pack64(uint64(len(data))), data...)
     8  }
     9  
    10  // GetNextBlock extract the integer from the beginning of the given byte slice and returns the remaining bytes, the extracted integer, and whether there was an error.
    11  func GetNextBlock(data []byte) ([]byte, int, error) {
    12  	l, n, err := Unpack64(data)
    13  	if err != nil {
    14  		return nil, 0, err
    15  	}
    16  	length := int(l)
    17  	totalLength := length + n
    18  	if totalLength > len(data) {
    19  		return nil, 0, errors.New("varint: not enough data for given block length")
    20  	}
    21  	return data[n:totalLength], totalLength, nil
    22  }
    23  
    24  // EncodedSize returns the size required to varint-encode an uint.
    25  func EncodedSize(n uint64) (size int) {
    26  	switch {
    27  	case n < 1<<7: // < 128
    28  		return 1
    29  	case n < 1<<14: // < 16384
    30  		return 2
    31  	case n < 1<<21: // < 2097152
    32  		return 3
    33  	case n < 1<<28: // < 268435456
    34  		return 4
    35  	case n < 1<<35: // < 34359738368
    36  		return 5
    37  	case n < 1<<42: // < 4398046511104
    38  		return 6
    39  	case n < 1<<49: // < 562949953421312
    40  		return 7
    41  	case n < 1<<56: // < 72057594037927936
    42  		return 8
    43  	case n < 1<<63: // < 9223372036854775808
    44  		return 9
    45  	default:
    46  		return 10
    47  	}
    48  }