github.com/cloudwego/frugal@v0.1.15/internal/binary/defs/sizes.go (about) 1 /* 2 * Copyright 2022 ByteDance Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package defs 18 19 import ( 20 `reflect` 21 ) 22 23 const ( 24 IntSize = 4 << (^uint(0) >> 63) 25 StackSize = 1024 26 ) 27 28 func GetSize(vt reflect.Type) int { 29 switch vt.Kind() { 30 case reflect.Bool : return 1 31 case reflect.Int : return IntSize 32 case reflect.Int8 : return 1 33 case reflect.Int16 : return 2 34 case reflect.Int32 : return 4 35 case reflect.Int64 : return measureInt64(vt) 36 case reflect.Float64 : return 8 37 case reflect.Map : return -1 38 case reflect.Ptr : return -1 39 case reflect.Slice : return -1 40 case reflect.String : return -1 41 case reflect.Struct : return measureStruct(vt) 42 default : panic("unsupported type by Thrift") 43 } 44 } 45 46 func measureInt64(vt reflect.Type) int { 47 if vt == i64type { 48 return 8 49 } else { 50 return 4 51 } 52 } 53 54 func measureStruct(vt reflect.Type) int { 55 var fs int 56 var rs int 57 58 /* measure each field, plus the 3-byte field header */ 59 for i := 0; i < vt.NumField(); i++ { 60 if fs = GetSize(vt.Field(i).Type); fs > 0 { 61 rs += fs + 3 62 } else { 63 return -1 64 } 65 } 66 67 /* all fields have fixed size, plus the STOP field */ 68 return rs + 1 69 }