// Package protohelpers provides helper functions for encoding and decoding protobuf messages. // The spec can be found at https://protobuf.dev/programming-guides/encoding/.
package protohelpers import ( ) var ( // ErrInvalidLength is returned when decoding a negative length. ErrInvalidLength = fmt.Errorf("proto: negative length found during unmarshaling") // ErrIntOverflow is returned when decoding a varint representation of an integer that overflows 64 bits. ErrIntOverflow = fmt.Errorf("proto: integer overflow") // ErrUnexpectedEndOfGroup is returned when decoding a group end without a corresponding group start. ErrUnexpectedEndOfGroup = fmt.Errorf("proto: unexpected end of group") ) // EncodeVarint encodes a uint64 into a varint-encoded byte slice and returns the offset of the encoded value. // The provided offset is the offset after the last byte of the encoded value. func ( []byte, int, uint64) int { -= SizeOfVarint() := for >= 1<<7 { [] = uint8(&0x7f | 0x80) >>= 7 ++ } [] = uint8() return } // SizeOfVarint returns the size of the varint-encoded value. func ( uint64) ( int) { return (bits.Len64(|1) + 6) / 7 } // SizeOfZigzag returns the size of the zigzag-encoded value. func ( uint64) ( int) { return SizeOfVarint(uint64(( << 1) ^ uint64((int64() >> 63)))) } // Skip the first record of the byte slice and return the offset of the next record. func ( []byte) ( int, error) { := len() := 0 := 0 for < { var uint64 for := uint(0); ; += 7 { if >= 64 { return 0, ErrIntOverflow } if >= { return 0, io.ErrUnexpectedEOF } := [] ++ |= (uint64() & 0x7F) << if < 0x80 { break } } := int( & 0x7) switch { case 0: for := uint(0); ; += 7 { if >= 64 { return 0, ErrIntOverflow } if >= { return 0, io.ErrUnexpectedEOF } ++ if [-1] < 0x80 { break } } case 1: += 8 case 2: var int for := uint(0); ; += 7 { if >= 64 { return 0, ErrIntOverflow } if >= { return 0, io.ErrUnexpectedEOF } := [] ++ |= (int() & 0x7F) << if < 0x80 { break } } if < 0 { return 0, ErrInvalidLength } += case 3: ++ case 4: if == 0 { return 0, ErrUnexpectedEndOfGroup } -- case 5: += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", ) } if < 0 { return 0, ErrInvalidLength } if == 0 { return , nil } } return 0, io.ErrUnexpectedEOF }