blob: 519c2fea10bdb70ee2bee0e288a933b4af7db04a (
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
|
package binstruct
import (
"fmt"
"reflect"
)
type StaticSizer interface {
BinaryStaticSize() int
}
func StaticSize(obj any) int {
return staticSize(reflect.TypeOf(obj))
}
var staticSizerType = reflect.TypeOf((*StaticSizer)(nil)).Elem()
func staticSize(typ reflect.Type) int {
if typ.Implements(staticSizerType) {
return reflect.New(typ).Elem().Interface().(StaticSizer).BinaryStaticSize()
}
if szer, ok := obj.(StaticSizer); ok {
return szer.BinaryStaticSize()
}
switch typ.Kind() {
case reflect.Ptr:
return StaticSize(typ.Elem())
case reflect.Array:
return StaticSize(typ.Elem()) * typ.Len()
case reflect.Struct:
// TODO
default:
panic(fmt.Errorf("type=%v does not implement binfmt.StaticSizer and kind=%v is not a supported statically-sized kind",
typ, typ.Kind()))
}
}
|