issue97_test.go | 26 ++++++++++++++++++++++++++ torrent.go | 22 +++++++++++++--------- diff --git a/issue97_test.go b/issue97_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3f4e16d2d0d1b89b911d460543a150c8a0b2d437 --- /dev/null +++ b/issue97_test.go @@ -0,0 +1,26 @@ +package torrent + +import ( + "io/ioutil" + "os" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/anacrolix/torrent/internal/testutil" + "github.com/anacrolix/torrent/storage" +) + +func TestHashPieceAfterStorageClosed(t *testing.T) { + td, err := ioutil.TempDir("", "") + require.NoError(t, err) + defer os.RemoveAll(td) + cs := storage.NewFile(td) + tt := &Torrent{} + tt.info = &testutil.GreetingMetaInfo().Info + tt.makePieces() + tt.storage, err = cs.OpenTorrent(tt.info) + require.NoError(t, err) + require.NoError(t, tt.storage.Close()) + tt.hashPiece(0) +} diff --git a/torrent.go b/torrent.go index cb17f49b3b0649b42b88b5b56ae9516f29c3857b..216ebbc1cbb6f1b9dc47df19e1ad2b3a0abd8d30 100644 --- a/torrent.go +++ b/torrent.go @@ -205,6 +205,18 @@ } return } +func (t *Torrent) makePieces() { + hashes := infoPieceHashes(&t.info.Info) + t.pieces = make([]piece, len(hashes)) + for i, hash := range hashes { + piece := &t.pieces[i] + piece.t = t + piece.index = i + piece.noPendingWrites.L = &piece.pendingWritesMutex + missinggo.CopyExact(piece.Hash[:], hash) + } +} + // Called when metadata for a torrent becomes available. func (t *Torrent) setInfoBytes(b []byte) error { if t.haveInfo() { @@ -237,15 +249,7 @@ t.length += f.Length } t.metadataBytes = b t.metadataCompletedChunks = nil - hashes := infoPieceHashes(&t.info.Info) - t.pieces = make([]piece, len(hashes)) - for i, hash := range hashes { - piece := &t.pieces[i] - piece.t = t - piece.index = i - piece.noPendingWrites.L = &piece.pendingWritesMutex - missinggo.CopyExact(piece.Hash[:], hash) - } + t.makePieces() for _, conn := range t.conns { if err := conn.setNumPieces(t.numPieces()); err != nil { log.Printf("closing connection: %s", err)