github.com/rbisecke/kafka-go@v0.4.27/protocol/size.go (about)

     1  package protocol
     2  
     3  import (
     4  	"math/bits"
     5  	"reflect"
     6  )
     7  
     8  func sizeOf(typ reflect.Type) int {
     9  	switch typ.Kind() {
    10  	case reflect.Bool, reflect.Int8:
    11  		return 1
    12  	case reflect.Int16:
    13  		return 2
    14  	case reflect.Int32:
    15  		return 4
    16  	case reflect.Int64:
    17  		return 8
    18  	default:
    19  		return 0
    20  	}
    21  }
    22  
    23  func sizeOfString(s string) int {
    24  	return 2 + len(s)
    25  }
    26  
    27  func sizeOfBytes(b []byte) int {
    28  	return 4 + len(b)
    29  }
    30  
    31  func sizeOfVarString(s string) int {
    32  	return sizeOfVarInt(int64(len(s))) + len(s)
    33  }
    34  
    35  func sizeOfCompactString(s string) int {
    36  	return sizeOfUnsignedVarInt(uint64(len(s)+1)) + len(s)
    37  }
    38  
    39  func sizeOfVarBytes(b []byte) int {
    40  	return sizeOfVarInt(int64(len(b))) + len(b)
    41  }
    42  
    43  func sizeOfCompactBytes(b []byte) int {
    44  	return sizeOfUnsignedVarInt(uint64(len(b)+1)) + len(b)
    45  }
    46  
    47  func sizeOfVarNullString(s string) int {
    48  	n := len(s)
    49  	if n == 0 {
    50  		return sizeOfVarInt(-1)
    51  	}
    52  	return sizeOfVarInt(int64(n)) + n
    53  }
    54  
    55  func sizeOfCompactNullString(s string) int {
    56  	n := len(s)
    57  	if n == 0 {
    58  		return sizeOfUnsignedVarInt(0)
    59  	}
    60  	return sizeOfUnsignedVarInt(uint64(n)+1) + n
    61  }
    62  
    63  func sizeOfVarNullBytes(b []byte) int {
    64  	if b == nil {
    65  		return sizeOfVarInt(-1)
    66  	}
    67  	n := len(b)
    68  	return sizeOfVarInt(int64(n)) + n
    69  }
    70  
    71  func sizeOfVarNullBytesIface(b Bytes) int {
    72  	if b == nil {
    73  		return sizeOfVarInt(-1)
    74  	}
    75  	n := b.Len()
    76  	return sizeOfVarInt(int64(n)) + n
    77  }
    78  
    79  func sizeOfCompactNullBytes(b []byte) int {
    80  	if b == nil {
    81  		return sizeOfUnsignedVarInt(0)
    82  	}
    83  	n := len(b)
    84  	return sizeOfUnsignedVarInt(uint64(n)+1) + n
    85  }
    86  
    87  func sizeOfVarInt(i int64) int {
    88  	return sizeOfUnsignedVarInt(uint64((i << 1) ^ (i >> 63))) // zig-zag encoding
    89  }
    90  
    91  func sizeOfUnsignedVarInt(i uint64) int {
    92  	return (bits.Len64(i|1) + 6) / 7
    93  }