2
0
mirror of synced 2025-02-24 14:48:27 +00:00
torrent/storage/sqlite/direct.go

87 lines
1.7 KiB
Go
Raw Normal View History

2021-05-21 14:16:59 +10:00
//go:build cgo
// +build cgo
package sqliteStorage
import (
2021-08-24 18:37:38 +10:00
"io"
"crawshaw.io/sqlite"
2021-08-25 14:37:00 +10:00
"github.com/anacrolix/squirrel"
2021-05-21 14:16:59 +10:00
"github.com/anacrolix/torrent/metainfo"
"github.com/anacrolix/torrent/storage"
)
// A convenience function that creates a connection pool, resource provider, and a pieces storage
// ClientImpl and returns them all with a Close attached.
func NewDirectStorage(opts NewDirectStorageOpts) (_ storage.ClientImplCloser, err error) {
2021-08-25 14:37:00 +10:00
cache, err := squirrel.NewCache(opts)
if err != nil {
return
}
2021-08-25 14:37:00 +10:00
return &client{
cache,
2021-08-26 11:19:39 +10:00
cache.GetCapacity,
}, nil
}
func NewWrappingClient(cache *squirrel.Cache) storage.ClientImpl {
return &client{
cache,
cache.GetCapacity,
}
}
type client struct {
2021-08-25 14:37:00 +10:00
*squirrel.Cache
capacity func() *int64
}
2021-08-25 14:37:00 +10:00
func (c *client) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (storage.TorrentImpl, error) {
t := torrent{c.Cache}
return storage.TorrentImpl{Piece: t.Piece, Close: t.Close, Capacity: &c.capacity}, nil
}
type torrent struct {
2021-08-25 14:37:00 +10:00
c *squirrel.Cache
}
func (t torrent) Piece(p metainfo.Piece) storage.PieceImpl {
ret := piece{
2021-08-26 11:19:39 +10:00
sb: t.c.OpenWithLength(p.Hash().HexString(), p.Length()),
2021-08-24 18:37:38 +10:00
}
ret.ReaderAt = &ret.sb
ret.WriterAt = &ret.sb
return ret
}
func (t torrent) Close() error {
return nil
}
type piece struct {
2021-08-25 14:37:00 +10:00
sb squirrel.Blob
2021-08-24 18:37:38 +10:00
io.ReaderAt
io.WriterAt
}
2021-08-24 18:37:38 +10:00
func (p piece) MarkComplete() error {
return p.sb.SetTag("verified", true)
}
func (p piece) MarkNotComplete() error {
2021-08-24 18:37:38 +10:00
return p.sb.SetTag("verified", false)
}
func (p piece) Completion() (ret storage.Completion) {
2021-08-24 18:37:38 +10:00
err := p.sb.GetTag("verified", func(stmt *sqlite.Stmt) {
ret.Complete = stmt.ColumnInt(0) != 0
2021-08-24 18:37:38 +10:00
})
ret.Ok = err == nil
if err != nil {
panic(err)
}
return
}