tlv/internal: add new internal package for generating TLV type structs

In this commit, we add some new code generation to the codebase. As
we'll see in a future commit, this'll allow us to create a new Record[T,
V] type, where T is actually a concrete _struct_ that implements a
special interface that deems it as a valid TLV type.
This commit is contained in:
Olaoluwa Osuntokun 2023-12-06 19:07:11 -08:00
parent f2d48c328b
commit 78d5806555
No known key found for this signature in database
GPG key ID: 3BBD59E99B280306

View file

@ -0,0 +1,59 @@
package main
import (
"bytes"
"flag"
"os"
"text/template"
)
const (
numberOfTypes = 100
defaultOutputFile = "tlv_types_generated.go"
)
const typeCodeTemplate = `// Code generated by tlv/internal/gen; DO NOT EDIT.
package tlv
{{- range $index, $element := . }}
type tlvType{{ $index }} struct{}
func (t *tlvType{{ $index }}) typeVal() Type {
return {{ $index }}
}
type TlvType{{ $index }} = *tlvType{{ $index }}
{{- end }}
`
func main() {
// Create a slice of items that the template can range over.
var items []struct{}
for i := uint16(0); i <= numberOfTypes; i++ {
items = append(items, struct{}{})
}
tpl, err := template.New("tlv").Parse(typeCodeTemplate)
if err != nil {
panic(err)
}
// Execute the template
var out bytes.Buffer
err = tpl.Execute(&out, items)
if err != nil {
panic(err)
}
outputFile := flag.String(
"o", defaultOutputFile, "Output file for generated code",
)
flag.Parse()
err = os.WriteFile(*outputFile, out.Bytes(), 0644)
if err != nil {
panic(err)
}
}