From 8576e5f207f9d3b7c6324ed71a3ca6a005f9ae7c Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Mon, 30 May 2022 12:00:39 -0400 Subject: ahhhh --- pkg/binstruct/size.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 pkg/binstruct/size.go (limited to 'pkg/binstruct/size.go') diff --git a/pkg/binstruct/size.go b/pkg/binstruct/size.go new file mode 100644 index 0000000..519c2fe --- /dev/null +++ b/pkg/binstruct/size.go @@ -0,0 +1,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())) + } +} -- cgit v1.2.3-2-g168b