github.com/elves/elvish@v0.15.0/pkg/eval/vals/repr_helpers.go (about) 1 package vals 2 3 import ( 4 "bytes" 5 "strings" 6 ) 7 8 // ListReprBuilder helps to build Repr of list-like Values. 9 type ListReprBuilder struct { 10 indent int 11 buf bytes.Buffer 12 } 13 14 // NewListReprBuilder makes a new ListReprBuilder. 15 func NewListReprBuilder(indent int) *ListReprBuilder { 16 return &ListReprBuilder{indent: indent} 17 } 18 19 // WriteElem writes a new element. 20 func (b *ListReprBuilder) WriteElem(v string) { 21 if b.buf.Len() == 0 { 22 b.buf.WriteByte('[') 23 } 24 if b.indent >= 0 { 25 // Pretty-printing: Add a newline and indent+1 spaces. 26 b.buf.WriteString("\n" + strings.Repeat(" ", b.indent+1)) 27 } else if b.buf.Len() > 1 { 28 b.buf.WriteByte(' ') 29 } 30 b.buf.WriteString(v) 31 } 32 33 // String returns the representation that has been built. After it is called, 34 // the ListReprBuilder may no longer be used. 35 func (b *ListReprBuilder) String() string { 36 if b.buf.Len() == 0 { 37 return "[]" 38 } 39 if b.indent >= 0 { 40 b.buf.WriteString("\n" + strings.Repeat(" ", b.indent)) 41 } 42 b.buf.WriteByte(']') 43 return b.buf.String() 44 } 45 46 // MapReprBuilder helps building the Repr of a Map. It is also useful for 47 // implementing other Map-like values. The zero value of a MapReprBuilder is 48 // ready to use. 49 type MapReprBuilder struct { 50 inner ListReprBuilder 51 } 52 53 // NewMapReprBuilder makes a new MapReprBuilder. 54 func NewMapReprBuilder(indent int) *MapReprBuilder { 55 return &MapReprBuilder{ListReprBuilder{indent: indent}} 56 } 57 58 // WritePair writes a new pair. 59 func (b *MapReprBuilder) WritePair(k string, indent int, v string) { 60 if indent > 0 { 61 b.inner.WriteElem("&" + k + "=\t" + v) 62 } else { 63 b.inner.WriteElem("&" + k + "=" + v) 64 } 65 } 66 67 // String returns the representation that has been built. After it is called, 68 // the MapReprBuilder should no longer be used. 69 func (b *MapReprBuilder) String() string { 70 s := b.inner.String() 71 if s == "[]" { 72 return "[&]" 73 } 74 return s 75 }