karmem icon indicating copy to clipboard operation
karmem copied to clipboard

[go] Add a Writable interface to ease the process to encode structs to Writer

Open lburgazzoli opened this issue 1 year ago • 1 comments

I've been experimenting with karmem and I found that it would be useful to have an interface to describe writeable structs, something like:

// Writable writes an encoded representation of the type to the underlying Writer.
type Writable interface {
	WriteAsRoot(*Writer) (uint, error)
}

This would help to create helper method to encode different type of generated structs, i.e. I have something like

func ToPtr(writable Writable, w *karmem.Writer ) (uint32, uint32) {
	if _, err := writable.WriteAsRoot(w); err != nil {
		panic(err)
	}

	buf := w.Bytes()
	ptr := &buf[0]
	unsafePtr := uintptr(unsafe.Pointer(ptr))

	return uint32(unsafePtr), uint32(len(buf))
}

lburgazzoli avatar Mar 03 '23 17:03 lburgazzoli

I can send a PR if it make sense

lburgazzoli avatar Mar 03 '23 17:03 lburgazzoli