]> Sergey Matveev's repositories - btrtrc.git/blob - storage/bolt.go
Drop support for go 1.20
[btrtrc.git] / storage / bolt.go
1 //go:build !noboltdb && !wasm
2 // +build !noboltdb,!wasm
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"), 0o600, &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(_ *metainfo.Info, infoHash metainfo.Hash) (TorrentImpl, error) {
46         t := &boltTorrent{me, infoHash}
47         return TorrentImpl{
48                 Piece: t.Piece,
49                 Close: t.Close,
50         }, nil
51 }
52
53 func (me *boltTorrent) Piece(p metainfo.Piece) PieceImpl {
54         ret := &boltPiece{
55                 p:  p,
56                 db: me.cl.db,
57                 ih: me.ih,
58         }
59         copy(ret.key[:], me.ih[:])
60         binary.BigEndian.PutUint32(ret.key[20:], uint32(p.Index()))
61         return ret
62 }
63
64 func (boltTorrent) Close() error { return nil }