github.com/sandwich-go/boost@v1.3.29/misc/xgen/gen.go (about) 1 package xgen 2 3 import ( 4 "bytes" 5 "fmt" 6 "strings" 7 ) 8 9 type Gen struct { 10 *bytes.Buffer 11 indent string 12 cellIndent string 13 indentCount int 14 } 15 16 // In Indents the output one tab stop. 17 func (g *Gen) In() { 18 g.indent += g.cellIndent 19 g.indentCount++ 20 } 21 22 // Out unindents the output one tab stop. 23 func (g *Gen) Out() { 24 if g.indentCount > 0 { 25 g.indent = g.indent[len(g.cellIndent):] 26 g.indentCount-- 27 } 28 } 29 30 func (g *Gen) Indent() string { 31 return g.indent 32 } 33 func (g *Gen) IndentCount() int { 34 return g.indentCount 35 } 36 37 func (g *Gen) SetPrefixIndent(base int) { 38 for i := 0; i < base; i++ { 39 g.In() 40 } 41 } 42 43 func (g *Gen) OutPrefixIndent(base int) { 44 for i := 0; i < base; i++ { 45 g.Out() 46 } 47 } 48 49 func (g *Gen) TrimRight(s string) { 50 ret := bytes.TrimRight(g.Buffer.Bytes(), s) 51 g.Buffer.Reset() 52 g.Buffer.Write(ret) 53 } 54 55 func (g *Gen) PFormat(fmtStr string, str ...interface{}) { 56 g.P(fmt.Sprintf(fmtStr, str...)) 57 } 58 59 // P prints the arguments to the generated output. It handles strings and int32s, plus 60 // handling indirections because they may be *string, etc. 61 func (g *Gen) P(str ...interface{}) { 62 _, _ = g.WriteString(g.indent) 63 for _, v := range str { 64 switch s := v.(type) { 65 case string: 66 _, _ = g.WriteString(s) 67 case *string: 68 _, _ = g.WriteString(*s) 69 case bool: 70 _, _ = fmt.Fprintf(g, "%t", s) 71 case *bool: 72 _, _ = fmt.Fprintf(g, "%t", *s) 73 case int: 74 _, _ = fmt.Fprintf(g, "%d", s) 75 case *int32: 76 _, _ = fmt.Fprintf(g, "%d", *s) 77 case *int64: 78 _, _ = fmt.Fprintf(g, "%d", *s) 79 case float64: 80 _, _ = fmt.Fprintf(g, "%g", s) 81 case *float64: 82 _, _ = fmt.Fprintf(g, "%g", *s) 83 default: 84 g.Fail(fmt.Sprintf("unknown type in printer: %T", v)) 85 } 86 } 87 _ = g.WriteByte('\n') 88 } 89 90 // Fail reports a problem and exits the program. 91 func (g *Gen) Fail(msgs ...string) { 92 panic("ProtoKit: error:" + strings.Join(msgs, " ")) 93 } 94 95 func (g *Gen) StringTrimNewline() string { 96 return strings.TrimRight(g.String(), "\n") 97 } 98 99 func NewGeneratorWithTabIndent() *Gen { 100 return &Gen{Buffer: new(bytes.Buffer), cellIndent: "\t"} 101 } 102 func NewGeneratorWithSpaceIndent(n int) *Gen { 103 return &Gen{Buffer: new(bytes.Buffer), cellIndent: strings.Repeat(" ", n)} 104 }