]> Sergey Matveev's repositories - btrtrc.git/blob - storage/bolt.go
5104c68265097ef9fc22968c3e35fe2637de7aef
[btrtrc.git] / storage / bolt.go
1 //go:build !noboltdb
2 // +build !noboltdb
3
4 package storage
5
6 import (
7         "encoding/binary"
8         "path/filepath"
9         "time"
10
11         "github.com/anacrolix/missinggo/expect"
12         "go.etcd.io/bbolt"
13
14         "github.com/anacrolix/torrent/metainfo"
15 )
16
17 const (
18         // Chosen to match the usual chunk size in a torrent client. This way, most chunk writes are to
19         // exactly one full item in bbolt DB.
20         chunkSize = 1 << 14
21 )
22
23 type boltClient struct {
24         db *bbolt.DB
25 }
26
27 type boltTorrent struct {
28         cl *boltClient
29         ih metainfo.Hash
30 }
31
32 func NewBoltDB(filePath string) ClientImplCloser {
33         db, err := bbolt.Open(filepath.Join(filePath, "bolt.db"), 0600, &bbolt.Options{
34                 Timeout: time.Second,
35         })
36         expect.Nil(err)
37         db.NoSync = true
38         return &boltClient{db}
39 }
40
41 func (me *boltClient) Close() error {
42         return me.db.Close()
43 }
44
45 func (me *boltClient) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (TorrentImpl, error) {
46         return &boltTorrent{me, infoHash}, nil
47 }
48
49 func (me *boltTorrent) Piece(p metainfo.Piece) PieceImpl {
50         ret := &boltPiece{
51                 p:  p,
52                 db: me.cl.db,
53                 ih: me.ih,
54         }
55         copy(ret.key[:], me.ih[:])
56         binary.BigEndian.PutUint32(ret.key[20:], uint32(p.Index()))
57         return ret
58 }
59
60 func (boltTorrent) Close() error { return nil }