blob: 150cad77f8f347c001b39daf90a89f81de7422ae [file] [log] [blame]
Scott Bakerb90c4312020-03-12 21:33:25 -07001// Copyright 2012 Google, Inc. All rights reserved.
2//
3// Use of this source code is governed by a BSD-style license
4// that can be found in the LICENSE file in the root of the source
5// tree.
6
7// +build ignore
8
9// This binary handles creating string constants and function templates for enums.
10//
11// go run gen.go | gofmt > enums_generated.go
12package main
13
14import (
15 "fmt"
16 "log"
17 "os"
18 "text/template"
19 "time"
20)
21
22const fmtString = `// Copyright 2012 Google, Inc. All rights reserved.
23
24package layers
25
26// Created by gen2.go, don't edit manually
27// Generated at %s
28
29import (
30 "fmt"
31
32 "github.com/google/gopacket"
33)
34
35`
36
37var funcsTmpl = template.Must(template.New("foo").Parse(`
38// Decoder calls {{.Name}}Metadata.DecodeWith's decoder.
39func (a {{.Name}}) Decode(data []byte, p gopacket.PacketBuilder) error {
40 return {{.Name}}Metadata[a].DecodeWith.Decode(data, p)
41}
42// String returns {{.Name}}Metadata.Name.
43func (a {{.Name}}) String() string {
44 return {{.Name}}Metadata[a].Name
45}
46// LayerType returns {{.Name}}Metadata.LayerType.
47func (a {{.Name}}) LayerType() gopacket.LayerType {
48 return {{.Name}}Metadata[a].LayerType
49}
50
51type errorDecoderFor{{.Name}} int
52func (a *errorDecoderFor{{.Name}}) Decode(data []byte, p gopacket.PacketBuilder) error {
53 return a
54}
55func (a *errorDecoderFor{{.Name}}) Error() string {
56 return fmt.Sprintf("Unable to decode {{.Name}} %d", int(*a))
57}
58
59var errorDecodersFor{{.Name}} [{{.Num}}]errorDecoderFor{{.Name}}
60var {{.Name}}Metadata [{{.Num}}]EnumMetadata
61
62func initUnknownTypesFor{{.Name}}() {
63 for i := 0; i < {{.Num}}; i++ {
64 errorDecodersFor{{.Name}}[i] = errorDecoderFor{{.Name}}(i)
65 {{.Name}}Metadata[i] = EnumMetadata{
66 DecodeWith: &errorDecodersFor{{.Name}}[i],
67 Name: "Unknown{{.Name}}",
68 }
69 }
70}
71`))
72
73func main() {
74 fmt.Fprintf(os.Stderr, "Writing results to stdout\n")
75 fmt.Printf(fmtString, time.Now())
76 types := []struct {
77 Name string
78 Num int
79 }{
80 {"LinkType", 256},
81 {"EthernetType", 65536},
82 {"PPPType", 65536},
83 {"IPProtocol", 256},
84 {"SCTPChunkType", 256},
85 {"PPPoECode", 256},
86 {"FDDIFrameControl", 256},
87 {"EAPOLType", 256},
88 {"ProtocolFamily", 256},
89 {"Dot11Type", 256},
90 {"USBTransportType", 256},
91 }
92
93 fmt.Println("func init() {")
94 for _, t := range types {
95 fmt.Printf("initUnknownTypesFor%s()\n", t.Name)
96 }
97 fmt.Println("initActualTypeData()")
98 fmt.Println("}")
99 for _, t := range types {
100 if err := funcsTmpl.Execute(os.Stdout, t); err != nil {
101 log.Fatalf("Failed to execute template %s: %v", t.Name, err)
102 }
103 }
104}