writer.go (1344B)
1 package tpls 2 3 import ( 4 "strconv" 5 6 "go.lair.cx/go-core/net/htmlx" 7 ) 8 9 type Writer interface { 10 Grow(n int) 11 WriteRaw(s string) 12 WriteBytesRaw(z []byte) 13 WriteString(s string) 14 WriteByteString(z []byte) 15 WriteInteger(n int) 16 WriteFloat(n float64, precision int) 17 } 18 19 func NewWriter(buf []byte) *BufferedWriter { 20 return &BufferedWriter{buf: buf} 21 } 22 23 type BufferedWriter struct { 24 buf []byte 25 } 26 27 func (w *BufferedWriter) WriteRaw(s string) { 28 w.grow(len(s)) 29 w.buf = append(w.buf, s...) 30 } 31 32 func (w *BufferedWriter) WriteBytesRaw(z []byte) { 33 w.grow(len(z)) 34 w.buf = append(w.buf, z...) 35 } 36 37 func (w *BufferedWriter) WriteString(s string) { 38 w.WriteRaw(htmlx.EscapeString(s)) 39 } 40 41 func (w *BufferedWriter) WriteByteString(s []byte) { 42 w.WriteBytesRaw(htmlx.Escape(s)) 43 } 44 45 func (w *BufferedWriter) WriteInteger(n int) { 46 formatted := strconv.FormatInt(int64(n), 10) 47 w.WriteRaw(formatted) 48 } 49 50 func (w *BufferedWriter) WriteFloat(n float64, precision int) { 51 formatted := strconv.FormatFloat(n, 'f', precision, 64) 52 w.WriteRaw(formatted) 53 } 54 55 func (w *BufferedWriter) Bytes() []byte { 56 return w.buf 57 } 58 59 func (w *BufferedWriter) Grow(n int) { 60 w.grow(n) 61 } 62 63 func (w *BufferedWriter) grow(n int) { 64 if cap(w.buf) >= len(w.buf)+n { 65 return 66 } 67 68 buf := make([]byte, len(w.buf), len(w.buf)*2+n) 69 copy(buf, w.buf) 70 w.buf = buf 71 } 72 73 var _ Writer = (*BufferedWriter)(nil)