-
Notifications
You must be signed in to change notification settings - Fork 1
/
write-closer-to-chan-line.go
82 lines (67 loc) · 1.43 KB
/
write-closer-to-chan-line.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
/*
© 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
ISC License
*/
package pio
import (
"io"
"io/fs"
"strings"
"sync"
"github.com/haraldrudell/parl"
"github.com/haraldrudell/parl/perrors"
)
type WriteCloserToChanLine struct {
lock sync.Mutex
s string
ch parl.NBChan[string]
withNewline bool
}
func NewWriteCloserToChanLine(withNewline ...bool) (writeCloser io.WriteCloser) {
var withNewline0 bool
if len(withNewline) > 0 {
withNewline0 = withNewline[0]
}
return &WriteCloserToChanLine{withNewline: withNewline0}
}
func (wc *WriteCloserToChanLine) Write(p []byte) (n int, err error) {
// check for closed write stream
if wc.ch.DidClose() {
err = perrors.ErrorfPF(fs.ErrClosed.Error())
return
}
wc.lock.Lock()
defer wc.lock.Unlock()
// write data to string
s := wc.s + string(p)
n = len(p)
// write buffer line-by-line to channel
for {
index := strings.Index(s, "\n")
if index == -1 {
break // no more newlines
}
var i int
if wc.withNewline {
i = index + 1
} else {
i = index
}
wc.ch.Send(s[:i])
s = s[index+1:]
}
wc.s = s // store remaining string characters
return
}
func (wc *WriteCloserToChanLine) Close() (err error) {
wc.lock.Lock()
defer wc.lock.Unlock()
if wc.s != "" {
wc.ch.Send(wc.s)
}
wc.ch.Close()
return
}
func (wc *WriteCloserToChanLine) Ch() (readCh <-chan string) {
return wc.ch.Ch()
}