/
boltpc.go
130 lines (114 loc) · 2.61 KB
/
boltpc.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package store
import (
"encoding/binary"
"os"
"path/filepath"
"sync"
"time"
"github.com/anacrolix/torrent/metainfo"
"github.com/anacrolix/torrent/storage"
"github.com/boltdb/bolt"
)
const (
boltDbCompleteValue = "c"
boltDbIncompleteValue = "i"
)
var (
completionBucketKey = []byte("completion")
)
type boltPieceCompletion struct {
db *bolt.DB
}
var _ PieceCompletion = (*boltPieceCompletion)(nil)
func NewBoltPieceCompletion(dir string) (ret PieceCompletion, err error) {
var pwd string
pwd, err = os.Getwd()
if err != nil {
return
}
ddir := filepath.Join(pwd, dir)
os.MkdirAll(ddir, 0770)
p := filepath.Join(ddir, ".torrent.bolt.db")
db, err := bolt.Open(p, 0660, &bolt.Options{
Timeout: time.Second,
})
if err != nil {
return
}
db.NoSync = true
ret = &boltPieceCompletion{db}
return
}
func (me boltPieceCompletion) Get(pk metainfo.PieceKey) (cn storage.Completion, err error) {
err = me.db.View(func(tx *bolt.Tx) error {
cb := tx.Bucket(completionBucketKey)
if cb == nil {
return nil
}
ih := cb.Bucket(pk.InfoHash[:])
if ih == nil {
return nil
}
var key [4]byte
binary.BigEndian.PutUint32(key[:], uint32(pk.Index))
cn.Ok = true
switch string(ih.Get(key[:])) {
case boltDbCompleteValue:
cn.Complete = true
case boltDbIncompleteValue:
cn.Complete = false
default:
cn.Ok = false
}
return nil
})
return
}
func (me boltPieceCompletion) Set(pk metainfo.PieceKey, b bool) error {
return me.db.Update(func(tx *bolt.Tx) error {
c, err := tx.CreateBucketIfNotExists(completionBucketKey)
if err != nil {
return err
}
ih, err := c.CreateBucketIfNotExists(pk.InfoHash[:])
if err != nil {
return err
}
var key [4]byte
binary.BigEndian.PutUint32(key[:], uint32(pk.Index))
return ih.Put(key[:], []byte(func() string {
if b {
return boltDbCompleteValue
} else {
return boltDbIncompleteValue
}
}()))
})
}
func (me *boltPieceCompletion) Close() error {
return me.db.Close()
}
type mapPieceCompletion struct {
mu sync.Mutex
m map[metainfo.PieceKey]bool
}
var _ PieceCompletion = (*mapPieceCompletion)(nil)
func NewMapPieceCompletion() PieceCompletion {
return &mapPieceCompletion{m: make(map[metainfo.PieceKey]bool)}
}
func (*mapPieceCompletion) Close() error { return nil }
func (me *mapPieceCompletion) Get(pk metainfo.PieceKey) (c storage.Completion, err error) {
me.mu.Lock()
defer me.mu.Unlock()
c.Complete, c.Ok = me.m[pk]
return
}
func (me *mapPieceCompletion) Set(pk metainfo.PieceKey, b bool) error {
me.mu.Lock()
defer me.mu.Unlock()
if me.m == nil {
me.m = make(map[metainfo.PieceKey]bool)
}
me.m[pk] = b
return nil
}