github.com/RomiChan/protobuf@v0.1.1-0.20230204044148-2ed269a2e54d/proto/gen/option/main.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "go/format" 6 "os" 7 "strings" 8 "text/template" 9 ) 10 11 const decodeTmpl = `// Code generated by gen/option/main.go. DO NOT EDIT. 12 13 package proto 14 15 import "unsafe" 16 17 {{range .Decoder}} 18 var {{.Codec}}OptionCodec = codec{ 19 size: sizeOf{{.Name}}Option, 20 encode: encode{{.Name}}Option, 21 decode: decode{{.Name}}Option, 22 } 23 24 func sizeOf{{.Name}}Option(p unsafe.Pointer, f *structField) int { 25 o := (*Option[{{.Type}}])(p) 26 if o.IsSome() { 27 return sizeOf{{.Name}}Required(o.unsafePointer(), f) 28 } 29 return 0 30 } 31 32 func encode{{.Name}}Option(b []byte, p unsafe.Pointer, f *structField) []byte { 33 o := (*Option[{{.Type}}])(p) 34 if o.IsSome() { 35 return encode{{.Name}}Required(b, o.unsafePointer(), f) 36 } 37 return b 38 } 39 40 func decode{{.Name}}Option(b []byte, p unsafe.Pointer) (int, error) { 41 v := (*Option[{{.Type}}])(p) 42 v.some = true 43 return decode{{.Name}}(b, v.unsafePointer()) 44 } 45 46 {{end}} 47 ` 48 49 func main() { 50 type decoder struct { 51 Type string 52 Name string 53 Codec string 54 } 55 56 var decoders = []decoder{ 57 {Type: "bool", Name: "Bool"}, 58 {Type: "string", Name: "String"}, 59 {Type: "int32", Name: "Int32"}, 60 {Type: "uint32", Name: "Uint32"}, 61 {Type: "int64", Name: "Int64"}, 62 {Type: "uint64", Name: "Uint64"}, 63 {Type: "int32", Name: "Zigzag32"}, 64 {Type: "int64", Name: "Zigzag64"}, 65 {Type: "uint32", Name: "Fixed32"}, 66 {Type: "uint64", Name: "Fixed64"}, 67 {Type: "float32", Name: "Float32"}, 68 {Type: "float64", Name: "Float64"}, 69 } 70 71 for i, d := range decoders { 72 decoders[i].Codec = strings.ToLower(d.Name) 73 } 74 75 var out bytes.Buffer 76 tmpl, err := template.New("").Parse(decodeTmpl) 77 if err != nil { 78 panic(err) 79 } 80 tmpl.Execute(&out, &struct { 81 Decoder []decoder 82 }{ 83 Decoder: decoders, 84 }) 85 86 source, err := format.Source(out.Bytes()) 87 if err != nil { 88 panic(err) 89 } 90 f, _ := os.OpenFile("option_codec.go", os.O_WRONLY|os.O_CREATE|os.O_SYNC|os.O_TRUNC, 0o644) 91 f.Write(source) 92 }