Skip to content

Commit c44a4d9

Browse files
committed
cli/command/container: RunStats: avoid bytes to strings conversions
This code is using a `bytes.Buffer` to render the stats, before writing the results to the CLI's output. Let's try to use bytes where possible instead of converting to a string; - Use the buffer's `Write` (and `Out().Write`) to write directly to the buffer/writer where possible. - Use `io.WriteString` instead of `fmt.Printf` - Use `bytes.SplitSeq` instead of `strings.SplitSeq` Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
1 parent d92d118 commit c44a4d9

1 file changed

Lines changed: 10 additions & 8 deletions

File tree

cli/command/container/stats.go

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,7 @@ import (
77
"bytes"
88
"context"
99
"errors"
10-
"fmt"
1110
"io"
12-
"strings"
1311
"sync"
1412
"time"
1513

@@ -312,7 +310,7 @@ func RunStats(ctx context.Context, dockerCLI command.Cli, options *StatsOptions)
312310
if err := statsFormatWrite(statsCtx, ccStats, daemonOSType, !options.NoTrunc); err != nil {
313311
return err
314312
}
315-
_, _ = fmt.Fprint(dockerCLI.Out(), renderBuf.String())
313+
_, _ = dockerCLI.Out().Write(renderBuf.Bytes())
316314
return nil
317315
}
318316

@@ -339,16 +337,20 @@ func RunStats(ctx context.Context, dockerCLI command.Cli, options *StatsOptions)
339337
}
340338

341339
// Start by moving the cursor to the top-left
342-
_, _ = fmt.Fprint(&frameBuf, "\033[H")
340+
_, _ = io.WriteString(&frameBuf, "\033[H")
343341

344-
for line := range strings.SplitSeq(renderBuf.String(), "\n") {
342+
// TODO(thaJeztah): consider wrapping the writer to inject ANSI (line-clearing) during formatting.
343+
// instead of post-processing the results.
344+
for line := range bytes.SplitSeq(renderBuf.Bytes(), []byte{'\n'}) {
345345
// In case the new text is shorter than the one we are writing over,
346346
// we'll append the "erase line" escape sequence to clear the remaining text.
347-
_, _ = fmt.Fprintln(&frameBuf, line, "\033[K")
347+
_, _ = frameBuf.Write(line)
348+
_, _ = io.WriteString(&frameBuf, "\033[K")
349+
_ = frameBuf.WriteByte('\n')
348350
}
349351
// We might have fewer containers than before, so let's clear the remaining text
350-
_, _ = fmt.Fprint(&frameBuf, "\033[J")
351-
_, _ = fmt.Fprint(dockerCLI.Out(), frameBuf.String())
352+
_, _ = io.WriteString(&frameBuf, "\033[J")
353+
_, _ = dockerCLI.Out().Write(frameBuf.Bytes())
352354
case err, ok := <-closeChan:
353355
if !ok || err == nil || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
354356
// Suppress "unexpected EOF" errors in the CLI so that

0 commit comments

Comments
 (0)