forked from YouROK/TorrServer
/
storage.go
72 lines (62 loc) · 1.38 KB
/
storage.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
package torrstor
import (
"sync"
"github.com/Terisback/TorrServer/server/torr/storage"
"github.com/anacrolix/torrent/metainfo"
ts "github.com/anacrolix/torrent/storage"
)
type Storage struct {
storage.Storage
caches map[metainfo.Hash]*Cache
capacity int64
mu sync.Mutex
}
func NewStorage(capacity int64) *Storage {
stor := new(Storage)
stor.capacity = capacity
stor.caches = make(map[metainfo.Hash]*Cache)
return stor
}
func (s *Storage) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (ts.TorrentImpl, error) {
// capFunc := func() (int64, bool) { // NE
// return s.capacity, true // NE
// } // NE
s.mu.Lock()
defer s.mu.Unlock()
ch := NewCache(s.capacity, s)
ch.Init(info, infoHash)
s.caches[infoHash] = ch
return ch, nil // OE
// return ts.TorrentImpl{ // NE
// Piece: ch.Piece, // NE
// Close: ch.Close, // NE
// Capacity: &capFunc, // NE
// }, nil // NE
}
func (s *Storage) CloseHash(hash metainfo.Hash) {
if s.caches == nil {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if ch, ok := s.caches[hash]; ok {
ch.Close()
delete(s.caches, hash)
}
}
func (s *Storage) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
for _, ch := range s.caches {
ch.Close()
}
return nil
}
func (s *Storage) GetCache(hash metainfo.Hash) *Cache {
s.mu.Lock()
defer s.mu.Unlock()
if cache, ok := s.caches[hash]; ok {
return cache
}
return nil
}