-
Notifications
You must be signed in to change notification settings - Fork 288
/
bufsync.go
55 lines (45 loc) · 961 Bytes
/
bufsync.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
package bufsync
import (
"bytes"
"fmt"
"io"
"strings"
"sync"
"time"
)
type ThreadSafeBuffer struct {
buf *bytes.Buffer
mu sync.Mutex
}
func NewThreadSafeBuffer() *ThreadSafeBuffer {
return &ThreadSafeBuffer{
buf: bytes.NewBuffer(nil),
}
}
func (b *ThreadSafeBuffer) Write(bs []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(bs)
}
func (b *ThreadSafeBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
func (b *ThreadSafeBuffer) WaitUntilContains(expected string, timeout time.Duration) error {
start := time.Now()
for time.Since(start) < timeout {
result := b.String()
if strings.Contains(result, expected) {
return nil
}
time.Sleep(10 * time.Millisecond)
}
return fmt.Errorf("Timeout. Expected %q. Actual: %s", expected, b.String())
}
func (b *ThreadSafeBuffer) Reset() {
b.mu.Lock()
defer b.mu.Unlock()
b.buf.Reset()
}
var _ io.Writer = &ThreadSafeBuffer{}