summaryrefslogtreecommitdiff
path: root/pkg/binstruct/size.go
diff options
context:
space:
mode:
authorLuke Shumaker <lukeshu@lukeshu.com>2022-05-30 12:00:39 -0400
committerLuke Shumaker <lukeshu@lukeshu.com>2022-05-30 12:00:39 -0400
commit8576e5f207f9d3b7c6324ed71a3ca6a005f9ae7c (patch)
tree1ff3001f73011a96aa603ec2eda7d29ce4885d47 /pkg/binstruct/size.go
parent04d6677e52352a7e3ec791e3e817cfe3865e7d6d (diff)
ahhhh
Diffstat (limited to 'pkg/binstruct/size.go')
-rw-r--r--pkg/binstruct/size.go36
1 files changed, 36 insertions, 0 deletions
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()))
+ }
+}