-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
io.go
86 lines (70 loc) · 1.59 KB
/
io.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package restic
import (
"fmt"
"io"
)
// headWriter keeps the first 'limit' bytes in memory.
type headWriter struct {
buf []byte
limit int
}
var _ io.Writer = &headWriter{}
func (w *headWriter) Write(p []byte) (n int, err error) {
if len(w.buf) >= w.limit {
return len(p), nil
}
w.buf = append(w.buf, p...)
if len(w.buf) > w.limit {
w.buf = w.buf[:w.limit]
}
return len(p), nil
}
func (w *headWriter) Bytes() []byte {
return w.buf
}
// tailWriter keeps the last 'limit' bytes in memory.
type tailWriter struct {
buf []byte
limit int
}
var _ io.Writer = &tailWriter{}
func (w *tailWriter) Write(p []byte) (n int, err error) {
w.buf = append(w.buf, p...)
if len(w.buf) > w.limit {
w.buf = w.buf[len(w.buf)-w.limit:]
}
return len(p), nil
}
func (w *tailWriter) Bytes() []byte {
return w.buf
}
type outputCapturer struct {
headWriter
tailWriter
limit int
totalBytes int
}
var _ io.Writer = &outputCapturer{}
func newOutputCapturer(limit int) *outputCapturer {
return &outputCapturer{
headWriter: headWriter{limit: limit},
tailWriter: tailWriter{limit: limit},
limit: limit,
}
}
func (w *outputCapturer) Write(p []byte) (n int, err error) {
w.headWriter.Write(p)
w.tailWriter.Write(p)
w.totalBytes += len(p)
return len(p), nil
}
func (w *outputCapturer) String() string {
head := w.headWriter.Bytes()
tail := w.tailWriter.Bytes()
if w.totalBytes <= w.limit {
return string(head)
}
head = head[:w.limit/2]
tail = tail[len(tail)-w.limit/2:]
return fmt.Sprintf("%s...[%v bytes dropped]...%s", string(head), w.totalBytes-len(head)-len(tail), string(tail))
}