torrent/storage/boltdb.go

58 lines
1.1 KiB
Go
Raw Normal View History

2016-08-31 07:48:50 +00:00
package storage
import (
"encoding/binary"
"path/filepath"
"time"
2016-08-31 07:48:50 +00:00
2018-04-12 01:34:24 +00:00
"github.com/anacrolix/missinggo/expect"
2020-03-24 01:54:57 +00:00
"go.etcd.io/bbolt"
2019-08-21 10:58:40 +00:00
"github.com/anacrolix/torrent/metainfo"
2016-08-31 07:48:50 +00:00
)
const (
// Chosen to match the usual chunk size in a torrent client. This way,
2020-03-24 01:54:57 +00:00
// most chunk writes are to exactly one full item in bbolt DB.
chunkSize = 1 << 14
)
2016-08-31 08:04:11 +00:00
2016-08-31 07:48:50 +00:00
type boltDBClient struct {
2020-03-24 01:54:57 +00:00
db *bbolt.DB
2016-08-31 07:48:50 +00:00
}
type boltDBTorrent struct {
cl *boltDBClient
ih metainfo.Hash
}
func NewBoltDB(filePath string) ClientImplCloser {
2020-03-24 01:54:57 +00:00
db, err := bbolt.Open(filepath.Join(filePath, "bolt.db"), 0600, &bbolt.Options{
Timeout: time.Second,
})
2018-04-12 01:34:24 +00:00
expect.Nil(err)
db.NoSync = true
return &boltDBClient{db}
2016-08-31 07:48:50 +00:00
}
func (me *boltDBClient) Close() error {
return me.db.Close()
}
func (me *boltDBClient) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (TorrentImpl, error) {
2016-08-31 07:48:50 +00:00
return &boltDBTorrent{me, infoHash}, nil
}
func (me *boltDBTorrent) Piece(p metainfo.Piece) PieceImpl {
ret := &boltDBPiece{
p: p,
db: me.cl.db,
ih: me.ih,
}
2016-08-31 07:48:50 +00:00
copy(ret.key[:], me.ih[:])
binary.BigEndian.PutUint32(ret.key[20:], uint32(p.Index()))
return ret
}
func (boltDBTorrent) Close() error { return nil }