github.com/segmentio/kafka-go@v0.4.48-0.20240318174348-3f6244eb34fd/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 sizeofInt16(_ int16) int32 { 32 return 2 33 } 34 35 func sizeofInt32(_ int32) int32 { 36 return 4 37 } 38 39 func sizeofInt64(_ int64) int32 { 40 return 8 41 } 42 43 func sizeofString(s string) int32 { 44 return 2 + int32(len(s)) 45 } 46 47 func sizeofNullableString(s *string) int32 { 48 if s == nil { 49 return 2 50 } 51 return sizeofString(*s) 52 } 53 54 func sizeofBytes(b []byte) int32 { 55 return 4 + int32(len(b)) 56 } 57 58 func sizeofArray(n int, f func(int) int32) int32 { 59 s := int32(4) 60 for i := 0; i != n; i++ { 61 s += f(i) 62 } 63 return s 64 } 65 66 func sizeofInt32Array(a []int32) int32 { 67 return 4 + (4 * int32(len(a))) 68 } 69 70 func sizeofStringArray(a []string) int32 { 71 return sizeofArray(len(a), func(i int) int32 { return sizeofString(a[i]) }) 72 }