diff --git a/cwriter/cuuAndEd_construction_bench_test.go b/cwriter/cuuAndEd_construction_bench_test.go index de87aee..2abbec3 100644 --- a/cwriter/cuuAndEd_construction_bench_test.go +++ b/cwriter/cuuAndEd_construction_bench_test.go @@ -37,7 +37,9 @@ } func BenchmarkWithCurrentImpl(b *testing.B) { + w := New(out) + b.ResetTimer() for i := 0; i < b.N; i++ { - _ = ansiCuuAndEd(out, lines) + _ = w.ew.ansiCuuAndEd(out, lines) } } diff --git a/cwriter/writer.go b/cwriter/writer.go index ad2ac9a..4a7a34a 100644 --- a/cwriter/writer.go +++ b/cwriter/writer.go @@ -6,7 +6,6 @@ "io" "os" "strconv" - "sync" ) // https://github.com/dylanaraps/pure-sh-bible#cursor-movement @@ -15,14 +14,6 @@ cuuAndEd = "A\x1b[J" ) -// used by ansiCuuAndEd func -var escBuf = sync.Pool{ - New: func() interface{} { - b := make([]byte, 8) - return &b - }, -} - // ErrNotTTY not a TeleTYpewriter error. var ErrNotTTY = errors.New("not a terminal") @@ -30,6 +21,7 @@ // contents of writer will be flushed when Flush is called. type Writer struct { *bytes.Buffer + ew escWriter out io.Writer lines int // used by writer_windows only fd int @@ -41,6 +33,7 @@ func New(out io.Writer) *Writer { w := &Writer{ Buffer: new(bytes.Buffer), + ew: escWriter(make([]byte, 8, 16)), out: out, termSize: func(_ int) (int, int, error) { return -1, -1, ErrNotTTY @@ -63,12 +56,10 @@ return w.termSize(w.fd) } -// if n > 99 it will allocate because escBuf.Get returns slice of length 8 -func ansiCuuAndEd(out io.Writer, n int) error { - bufp := escBuf.Get() - buf := *bufp.(*[]byte) - buf = strconv.AppendInt(buf[:copy(buf, escOpen)], int64(n), 10) - _, err := out.Write(append(buf, cuuAndEd...)) - escBuf.Put(bufp) +type escWriter []byte + +func (b escWriter) ansiCuuAndEd(out io.Writer, n int) error { + b = strconv.AppendInt(b[:copy(b, escOpen)], int64(n), 10) + _, err := out.Write(append(b, cuuAndEd...)) return err } diff --git a/cwriter/writer_posix.go b/cwriter/writer_posix.go index a6f904f..a32336f 100644 --- a/cwriter/writer_posix.go +++ b/cwriter/writer_posix.go @@ -11,7 +11,7 @@ _, err := w.WriteTo(w.out) // some terminals interpret 'cursor up 0' as 'cursor up 1' if err == nil && lines > 0 { - err = ansiCuuAndEd(w, lines) + err = w.ew.ansiCuuAndEd(w, lines) } return err } diff --git a/cwriter/writer_windows.go b/cwriter/writer_windows.go index f9447a6..eebd027 100644 --- a/cwriter/writer_windows.go +++ b/cwriter/writer_windows.go @@ -31,7 +31,7 @@ func (w *Writer) clearLines(n int) error { if !w.terminal { // hope it's cygwin or similar - return ansiCuuAndEd(w.out, n) + return w.ew.ansiCuuAndEd(w.out, n) } var info windows.ConsoleScreenBufferInfo