Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/supervisor/pkg/terminal/ring-buffer.go
2500 views
1
// Copyright (c) 2020 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package terminal
6
7
import "golang.org/x/xerrors"
8
9
// RingBuffer implements a ring buffer. It is a fixed size,
10
// and new writes overwrite older data, such that for a buffer
11
// of size N, for any amount of writes, only the last N bytes
12
// are retained.
13
type RingBuffer struct {
14
data []byte
15
size int64
16
writeCursor int64
17
written int64
18
}
19
20
// NewRingBuffer creates a new buffer of a given size. The size
21
// must be greater than 0.
22
func NewRingBuffer(size int64) (*RingBuffer, error) {
23
if size <= 0 {
24
return nil, xerrors.Errorf("Size must be positive")
25
}
26
27
b := &RingBuffer{
28
size: size,
29
data: make([]byte, size),
30
}
31
return b, nil
32
}
33
34
// Write writes up to len(buf) bytes to the internal ring,
35
// overriding older data if necessary.
36
func (b *RingBuffer) Write(buf []byte) (int, error) {
37
// Account for total bytes written
38
n := len(buf)
39
b.written += int64(n)
40
41
// If the buffer is larger than ours, then we only care
42
// about the last size bytes anyways
43
if int64(n) > b.size {
44
buf = buf[int64(n)-b.size:]
45
}
46
47
// Copy in place
48
remain := b.size - b.writeCursor
49
copy(b.data[b.writeCursor:], buf)
50
if int64(len(buf)) > remain {
51
copy(b.data, buf[remain:])
52
}
53
54
// Update location of the cursor
55
b.writeCursor = ((b.writeCursor + int64(len(buf))) % b.size)
56
return n, nil
57
}
58
59
// Size returns the size of the buffer.
60
func (b *RingBuffer) Size() int64 {
61
return b.size
62
}
63
64
// TotalWritten provides the total number of bytes written.
65
func (b *RingBuffer) TotalWritten() int64 {
66
return b.written
67
}
68
69
// Bytes provides a slice of the bytes written. This
70
// slice should not be written to.
71
func (b *RingBuffer) Bytes() []byte {
72
switch {
73
case b.written >= b.size && b.writeCursor == 0:
74
return b.data
75
case b.written > b.size:
76
out := make([]byte, b.size)
77
copy(out, b.data[b.writeCursor:])
78
copy(out[b.size-b.writeCursor:], b.data[:b.writeCursor])
79
return out
80
default:
81
return b.data[:b.writeCursor]
82
}
83
}
84
85
// Reset resets the buffer so it has no content.
86
func (b *RingBuffer) Reset() {
87
b.writeCursor = 0
88
b.written = 0
89
}
90
91
// String returns the contents of the buffer as a string.
92
func (b *RingBuffer) String() string {
93
return string(b.Bytes())
94
}
95
96