github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/fvm/environment/generate-wrappers/file_content.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "io" 6 ) 7 8 var ( 9 indent = []byte("\t") 10 newline = []byte("\n") 11 ) 12 13 type Chunk struct { 14 indentLevel int 15 format string 16 args []interface{} 17 } 18 19 func (chunk *Chunk) WriteTo(writer io.Writer) (int64, error) { 20 total := int64(0) 21 22 if chunk.format != "" { 23 for i := 0; i < chunk.indentLevel; i++ { 24 n, err := writer.Write(indent) 25 total += int64(n) 26 27 if err != nil { 28 return total, err 29 } 30 } 31 32 n, err := fmt.Fprintf(writer, chunk.format, chunk.args...) 33 total += int64(n) 34 35 if err != nil { 36 return total, err 37 } 38 } 39 40 n, err := writer.Write(newline) 41 total += int64(n) 42 if err != nil { 43 return total, err 44 } 45 46 return total, nil 47 } 48 49 type FileContent struct { 50 indentLevel int 51 chunks []io.WriterTo 52 } 53 54 func NewFileContent() *FileContent { 55 return &FileContent{ 56 indentLevel: 0, 57 chunks: nil, 58 } 59 } 60 61 func (content *FileContent) PushIndent() { 62 content.indentLevel += 1 63 } 64 65 func (content *FileContent) PopIndent() { 66 if content.indentLevel > 0 { 67 content.indentLevel -= 1 68 } 69 } 70 71 func (content *FileContent) Line(format string, args ...interface{}) { 72 content.chunks = append( 73 content.chunks, 74 &Chunk{content.indentLevel, format, args}) 75 } 76 77 func (content *FileContent) Section(format string, args ...interface{}) { 78 content.chunks = append(content.chunks, &Chunk{0, format, args}) 79 } 80 81 func (content *FileContent) WriteTo(output io.Writer) (int64, error) { 82 total := int64(0) 83 for _, chunk := range content.chunks { 84 n, err := chunk.WriteTo(output) 85 total += n 86 87 if err != nil { 88 return total, err 89 } 90 } 91 92 return total, nil 93 }