/
writer.go
67 lines (54 loc) · 1.04 KB
/
writer.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
package statos
import (
"io"
"sync"
"syscall"
)
// WriterStatos implements io.Writer
var _ io.Writer = &WriterStatos{}
type WriterStatos struct {
sync.RWMutex
iterator io.Writer
commChan chan int
commClosed bool
commOnce sync.Once
}
func (w *WriterStatos) closeCommChan() bool {
alreadyClosed := w.wasCommClosed()
if !alreadyClosed {
w.commOnce.Do(func() {
w.Lock()
defer w.Unlock()
close(w.commChan)
w.commClosed = true
alreadyClosed = w.commClosed
})
}
return w.commClosed
}
func NewWriter(w io.Writer) *WriterStatos {
return &WriterStatos{
commChan: make(chan int),
iterator: w,
commClosed: false,
}
}
func (w *WriterStatos) Write(p []byte) (n int, err error) {
n, err = w.iterator.Write(p)
if err != nil && err != syscall.EINTR {
w.closeCommChan()
return
}
if n >= 0 && !w.wasCommClosed() {
w.commChan <- n
}
return
}
func (ws *WriterStatos) wasCommClosed() bool {
ws.RLock()
defer ws.RUnlock()
return ws.commClosed
}
func (w *WriterStatos) ProgressChan() chan int {
return w.commChan
}