forked from anacrolix/torrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_handle.go
75 lines (67 loc) · 1.42 KB
/
file_handle.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
package torrentfs
import (
"context"
"io"
"github.com/anacrolix/missinggo"
"github.com/anacrolix/torrent"
"bazil.org/fuse"
"bazil.org/fuse/fs"
)
type fileHandle struct {
fn fileNode
r *torrent.Reader
}
var _ interface {
fs.HandleReader
fs.HandleReleaser
} = fileHandle{}
func (me fileHandle) Read(ctx context.Context, req *fuse.ReadRequest, resp *fuse.ReadResponse) error {
torrentfsReadRequests.Add(1)
if req.Dir {
panic("read on directory")
}
pos, err := me.r.Seek(me.fn.TorrentOffset+req.Offset, io.SeekStart)
if err != nil {
panic(err)
}
if pos != me.fn.TorrentOffset+req.Offset {
panic("seek failed")
}
resp.Data = resp.Data[:req.Size]
readDone := make(chan struct{})
ctx, cancel := context.WithCancel(ctx)
var readErr error
go func() {
defer close(readDone)
me.fn.FS.mu.Lock()
me.fn.FS.blockedReads++
me.fn.FS.event.Broadcast()
me.fn.FS.mu.Unlock()
var n int
r := missinggo.ContextedReader{me.r, ctx}
n, readErr = r.Read(resp.Data)
if readErr == io.EOF {
readErr = nil
}
resp.Data = resp.Data[:n]
}()
defer func() {
<-readDone
me.fn.FS.mu.Lock()
me.fn.FS.blockedReads--
me.fn.FS.event.Broadcast()
me.fn.FS.mu.Unlock()
}()
defer cancel()
select {
case <-readDone:
return readErr
case <-me.fn.FS.destroyed:
return fuse.EIO
case <-ctx.Done():
return fuse.EINTR
}
}
func (me fileHandle) Release(context.Context, *fuse.ReleaseRequest) error {
return me.r.Close()
}