Skip to content

Commit dbca2e1

Browse files
authored
Merge pull request #4 from alevinval/master
(posix-writer) test coverage, simplify logic and faster clearLines()
2 parents 19a7db7 + b9d6077 commit dbca2e1

3 files changed

Lines changed: 46 additions & 12 deletions

File tree

cwriter/writer.go

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,19 +26,12 @@ func New(w io.Writer) *Writer {
2626

2727
// Flush flushes the underlying buffer
2828
func (w *Writer) Flush() error {
29-
// do nothing if buffer is empty
30-
if len(w.buf.Bytes()) == 0 {
29+
// Do nothing if buffer is empty
30+
if w.buf.Len() == 0 {
3131
return nil
3232
}
3333
w.clearLines()
34-
35-
lines := 0
36-
for _, b := range w.buf.Bytes() {
37-
if b == '\n' {
38-
lines++
39-
}
40-
}
41-
w.lineCount = lines
34+
w.lineCount = bytes.Count(w.buf.Bytes(), []byte("\n"))
4235
_, err := w.out.Write(w.buf.Bytes())
4336
w.buf.Reset()
4437
return err

cwriter/writer_posix.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,15 @@ import (
88
"unsafe"
99
)
1010

11+
var (
12+
cursorUp = fmt.Sprintf("%c[%dA", ESC, 1)
13+
clearLine = fmt.Sprintf("%c[2K\r", ESC)
14+
clearCursorAndLine = cursorUp + clearLine
15+
)
16+
1117
func (w *Writer) clearLines() {
1218
for i := 0; i < w.lineCount; i++ {
13-
fmt.Fprintf(w.out, "%c[%dA", ESC, 1) // move the cursor up
14-
fmt.Fprintf(w.out, "%c[2K\r", ESC) // clear the line
19+
fmt.Fprint(w.out, clearCursorAndLine)
1520
}
1621
}
1722

cwriter/writer_posix_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// +build !windows
2+
3+
package cwriter_test
4+
5+
import (
6+
"bytes"
7+
"fmt"
8+
"testing"
9+
10+
"github.com/vbauerster/mpb/cwriter"
11+
)
12+
13+
var clearSequence = fmt.Sprintf("%c[%dA%c[2K\r", 27, 1, 27)
14+
15+
// TestWriterPosix by writing and flushing many times. The output buffer
16+
// must contain the clearCursor and clearLine sequences.
17+
func TestWriterPosix(t *testing.T) {
18+
out := new(bytes.Buffer)
19+
w := cwriter.New(out)
20+
21+
testCases := []struct {
22+
input, expectedOutput string
23+
}{
24+
{input: "foo\n", expectedOutput: "foo\n"},
25+
{input: "bar\n", expectedOutput: "foo\n" + clearSequence + "bar\n"},
26+
{input: "fizz\n", expectedOutput: "foo\n" + clearSequence + "bar\n" + clearSequence + "fizz\n"},
27+
}
28+
for _, testCase := range testCases {
29+
w.Write([]byte(testCase.input))
30+
w.Flush()
31+
output := out.String()
32+
if output != testCase.expectedOutput {
33+
t.Fatalf("want %q, got %q", testCase.expectedOutput, output)
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)