go-hep.org/x/hep@v0.38.1/brio/cmd/brio-gen/main.go (about) 1 // Copyright ©2016 The go-hep Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Command brio-gen generates (un)marshaler code for types. 6 // 7 // For each type given to brio-gen, marshaling and unmarshaling code will be 8 // generated so the types implement binary.Binary(Un)Marshaler. 9 // 10 // - values are encoded using binary.LittleEndian, 11 // - int and uint are encoded as (resp.) int64 and uint64, 12 // - booleans are encoded as a single uint8 (0==false, 1==true), 13 // - strings are encoded as a pair(uint64, []byte), 14 // - arrays are encoded as a sequence of Ts, the length is implicit as it is 15 // part of the array type, 16 // - slices are encoded as a pair(uint64, T...) 17 // - pointers are encoded as *T (like encoding/gob) 18 // - interfaces are not supported. 19 // 20 // Usage: brio-gen [options] 21 // 22 // ex: 23 // 24 // $> brio-gen -p image -t Point -o image_brio.go 25 // $> brio-gen -p go-hep.org/x/hep/hbook -t Dist0D,Dist1D,Dist2D -o foo_brio.go 26 // 27 // options: 28 // 29 // -o string 30 // output file name (default "brio_gen.go") 31 // -p string 32 // package import path 33 // -t string 34 // comma-separated list of type names 35 package main 36 37 import ( 38 "flag" 39 "fmt" 40 "io" 41 "log" 42 "os" 43 "strings" 44 45 "go-hep.org/x/hep/brio/cmd/brio-gen/internal/gen" 46 ) 47 48 var ( 49 typeNames = flag.String("t", "", "comma-separated list of type names") 50 pkgPath = flag.String("p", "", "package import path") 51 output = flag.String("o", "brio_gen.go", "output file name") 52 ) 53 54 func main() { 55 flag.Usage = func() { 56 fmt.Fprintf( 57 os.Stderr, 58 `Usage: brio-gen [options] 59 60 ex: 61 $> brio-gen -p image -t Point -o image_brio.go 62 $> brio-gen -p go-hep.org/x/hep/hbook -t Dist0D,Dist1D,Dist2D -o foo_brio.go 63 64 options: 65 `, 66 ) 67 flag.PrintDefaults() 68 } 69 70 flag.Parse() 71 72 log.SetPrefix("brio: ") 73 log.SetFlags(0) 74 75 if *typeNames == "" { 76 flag.Usage() 77 os.Exit(2) 78 } 79 80 types := strings.Split(*typeNames, ",") 81 out, err := os.Create(*output) 82 if err != nil { 83 log.Fatal(err) 84 } 85 defer out.Close() 86 87 err = generate(out, *pkgPath, types) 88 if err != nil { 89 log.Fatal(err) 90 } 91 92 err = out.Close() 93 if err != nil { 94 log.Fatal(err) 95 } 96 } 97 98 func generate(w io.Writer, pkg string, types []string) error { 99 g, err := gen.NewGenerator(pkg) 100 if err != nil { 101 return err 102 } 103 104 for _, t := range types { 105 g.Generate(t) 106 } 107 108 buf, err := g.Format() 109 if err != nil { 110 return err 111 } 112 113 _, err = w.Write(buf) 114 if err != nil { 115 return err 116 } 117 118 return nil 119 }