-
Notifications
You must be signed in to change notification settings - Fork 14
/
line_buffer.go
102 lines (78 loc) · 1.55 KB
/
line_buffer.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package tui
import (
"github.com/mitchellh/go-wordwrap"
"strings"
"sync"
)
type LineBuffer struct {
mutex sync.Mutex
width int
messages []string
lines []string
}
func NewLineBuffer(width int) *LineBuffer {
return &LineBuffer{
width: width,
messages: []string{},
lines: []string{},
}
}
func (s *LineBuffer) Write(p []byte) (n int, err error) {
s.mutex.Lock()
defer s.mutex.Unlock()
l := string(p)
s.messages = append(s.messages, l)
wl := s.wrap(l)
s.lines = append(s.lines, wl...)
return len(p), nil
}
func (s *LineBuffer) SetWidth(width int) {
if width < 1 {
return
}
s.mutex.Lock()
defer s.mutex.Unlock()
if width == s.width {
return
}
s.width = width
chunks := make([][]string, len(s.messages))
var wg sync.WaitGroup
wg.Add(len(s.messages))
// parallelize this as it will get really slow the bigger the buffer is
for i, l := range s.messages {
go func(i int, l string) {
defer wg.Done()
wl := s.wrap(l)
chunks[i] = append(chunks[i], wl...)
}(i, l)
}
wg.Wait()
s.lines = []string{}
for _, c := range chunks {
s.lines = append(s.lines, c...)
}
}
func (s *LineBuffer) Lines(from, to int) []string {
s.mutex.Lock()
defer s.mutex.Unlock()
if from < 0 {
from = 0
}
if to < 0 {
to = 0
}
if to > len(s.lines) {
to = len(s.lines)
}
return s.lines[from:to]
}
func (s *LineBuffer) Len() int {
s.mutex.Lock()
defer s.mutex.Unlock()
return len(s.lines)
}
func (s *LineBuffer) wrap(line string) []string {
wl := wordwrap.WrapString(line, uint(s.width))
return strings.Split(wl, "\n")
}