aboutsummaryrefslogtreecommitdiff
path: root/internal/iolimit/capped_capture_writer.go
blob: e4a645900fde480325abf5d0128712efe9a991d3 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package iolimit

import (
	"bytes"
	"fmt"

	"lindenii.org/go/lgo/intconv"
)

// 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 uint64
	buf   bytes.Buffer
	full  bool
}

// NewCappedCaptureWriter constructs one capped capture writer.
func NewCappedCaptureWriter(limit uint64) *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
	}

	used, err := intconv.IntToUint64(writer.buf.Len())
	if err != nil {
		return 0, fmt.Errorf("iolimit: %w", err)
	}

	if used >= writer.limit {
		writer.full = true

		return len(src), nil
	}

	room := writer.limit - used
	if uint64(len(src)) > room {
		take, err := intconv.Uint64ToInt(room)
		if err != nil {
			return 0, fmt.Errorf("iolimit: %w", err)
		}

		_, _ = writer.buf.Write(src[:take])
		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()
}