-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrent_writeseeker.go
52 lines (42 loc) · 935 Bytes
/
concurrent_writeseeker.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
package networkfile
import (
"io"
"sync"
)
type concurrentWriteSeeker struct {
wrtr io.WriteSeeker
lastChange *writeSeeker
mu sync.Mutex
}
func (rs *concurrentWriteSeeker) newWriteSeeker() io.WriteSeeker {
return &writeSeeker{
parent: rs,
}
}
type writeSeeker struct {
parent *concurrentWriteSeeker
offset int64
}
func (rs *writeSeeker) Write(p []byte) (n int, err error) {
rs.parent.mu.Lock()
defer rs.parent.mu.Unlock()
if rs.parent.lastChange != rs {
n, err := rs.parent.wrtr.Seek(rs.offset, io.SeekStart)
rs.offset = n
if err != nil {
return 0, err
}
}
rs.parent.lastChange = rs
n, err = rs.parent.wrtr.Write(p)
rs.offset += int64(n)
return n, err
}
func (rs *writeSeeker) Seek(offset int64, whence int) (int64, error) {
rs.parent.mu.Lock()
defer rs.parent.mu.Unlock()
rs.parent.lastChange = rs
n, err := rs.parent.wrtr.Seek(offset, whence)
rs.offset = n
return n, err
}