blob: 2e69806a14fac179fa1f97e6c89a229286558bf6 (
about) (
plain) (
blame)
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
|
package iolimit
import "bytes"
// CappedCaptureWriter captures written bytes up to a fixed limit.
//
// Once the total written bytes would exceed the limit, capture is disabled and
// Bytes() returns nil. Write still reports success for the full input length.
type CappedCaptureWriter struct {
limit int64
buf bytes.Buffer
full bool
}
// NewCappedCaptureWriter constructs one capped capture writer.
func NewCappedCaptureWriter(limit int64) *CappedCaptureWriter {
return &CappedCaptureWriter{limit: limit}
}
// Write captures up to the configured limit and always reports len(src) bytes written.
func (writer *CappedCaptureWriter) Write(src []byte) (int, error) {
if writer.full {
return len(src), nil
}
room := writer.limit - int64(writer.buf.Len())
if room <= 0 {
writer.full = true
return len(src), nil
}
if int64(len(src)) > room {
_, _ = writer.buf.Write(src[:room])
writer.full = true
return len(src), nil
}
_, _ = writer.buf.Write(src)
return len(src), nil
}
// Bytes returns captured bytes, or nil when capture exceeded the limit.
func (writer *CappedCaptureWriter) Bytes() []byte {
if writer.full {
return nil
}
return writer.buf.Bytes()
}
|