github.com/hack0072008/kafka-go@v1.0.1/sizeof.go (about)

     1  package kafka
     2  
     3  import "fmt"
     4  
     5  type sizable interface {
     6  	size() int32
     7  }
     8  
     9  func sizeof(a interface{}) int32 {
    10  	switch v := a.(type) {
    11  	case int8:
    12  		return 1
    13  	case int16:
    14  		return 2
    15  	case int32:
    16  		return 4
    17  	case int64:
    18  		return 8
    19  	case string:
    20  		return sizeofString(v)
    21  	case bool:
    22  		return 1
    23  	case []byte:
    24  		return sizeofBytes(v)
    25  	case sizable:
    26  		return v.size()
    27  	}
    28  	panic(fmt.Sprintf("unsupported type: %T", a))
    29  }
    30  
    31  func sizeofInt8(_ int8) int32 {
    32  	return 1
    33  }
    34  
    35  func sizeofInt16(_ int16) int32 {
    36  	return 2
    37  }
    38  
    39  func sizeofInt32(_ int32) int32 {
    40  	return 4
    41  }
    42  
    43  func sizeofInt64(_ int64) int32 {
    44  	return 8
    45  }
    46  
    47  func sizeofString(s string) int32 {
    48  	return 2 + int32(len(s))
    49  }
    50  
    51  func sizeofNullableString(s *string) int32 {
    52  	if s == nil {
    53  		return 2
    54  	}
    55  	return sizeofString(*s)
    56  }
    57  
    58  func sizeofBool(_ bool) int32 {
    59  	return 1
    60  }
    61  
    62  func sizeofBytes(b []byte) int32 {
    63  	return 4 + int32(len(b))
    64  }
    65  
    66  func sizeofArray(n int, f func(int) int32) int32 {
    67  	s := int32(4)
    68  	for i := 0; i != n; i++ {
    69  		s += f(i)
    70  	}
    71  	return s
    72  }
    73  
    74  func sizeofInt32Array(a []int32) int32 {
    75  	return 4 + (4 * int32(len(a)))
    76  }
    77  
    78  func sizeofStringArray(a []string) int32 {
    79  	return sizeofArray(len(a), func(i int) int32 { return sizeofString(a[i]) })
    80  }