blob: f6b3241cf912cbac17fd19b2923e270ed6009efc (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
package binstruct
import (
"fmt"
"reflect"
)
type StaticSizer interface {
BinaryStaticSize() int
}
func StaticSize(obj any) int {
sz, err := staticSize(reflect.TypeOf(obj))
if err != nil {
panic(err)
}
return sz
}
var staticSizerType = reflect.TypeOf((*StaticSizer)(nil)).Elem()
func staticSize(typ reflect.Type) (int, error) {
if typ.Implements(staticSizerType) {
return reflect.New(typ).Elem().Interface().(StaticSizer).BinaryStaticSize(), nil
}
switch typ.Kind() {
case reflect.Uint8, reflect.Int8:
return 1, nil
case reflect.Ptr:
return staticSize(typ.Elem())
case reflect.Array:
elemSize, err := staticSize(typ.Elem())
if err != nil {
return 0, err
}
return elemSize * typ.Len(), nil
case reflect.Struct:
return getStructHandler(typ).Size, nil
default:
return 0, fmt.Errorf("type=%v does not implement binfmt.StaticSizer and kind=%v is not a supported statically-sized kind",
typ, typ.Kind())
}
}
|