From ea71bf770c0c3c5a3adc537b299227609a2c74bf Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Thu, 27 Feb 2020 16:42:33 +1100 Subject: [PATCH] Expose PieceStateRun formatting --- t.go | 17 +++++++++++++---- torrent.go | 10 +++------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/t.go b/t.go index fcaec919..ccd30096 100644 --- a/t.go +++ b/t.go @@ -41,10 +41,19 @@ func (t *Torrent) NewReader() Reader { return &r } -// Returns the state of pieces of the torrent. They are grouped into runs of -// same state. The sum of the state run lengths is the number of pieces -// in the torrent. -func (t *Torrent) PieceStateRuns() []PieceStateRun { +type PieceStateRuns []PieceStateRun + +func (me PieceStateRuns) String() string { + ss := make([]string, 0, len(me)) + for _, psr := range me { + ss = append(ss, psr.String()) + } + return strings.Join(ss, " ") +} + +// Returns the state of pieces of the torrent. They are grouped into runs of same state. The sum of +// the state run-lengths is the number of pieces in the torrent. +func (t *Torrent) PieceStateRuns() PieceStateRuns { t.cl.rLock() defer t.cl.rUnlock() return t.pieceStateRuns() diff --git a/torrent.go b/torrent.go index cd136523..f6627b2f 100644 --- a/torrent.go +++ b/torrent.go @@ -503,7 +503,7 @@ func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType int, piece in } } -func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) { +func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) { rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) { ret = append(ret, PieceStateRun{ PieceState: el.(PieceState), @@ -518,7 +518,7 @@ func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) { } // Produces a small string representing a PieceStateRun. -func pieceStateRunStatusChars(psr PieceStateRun) (ret string) { +func (psr PieceStateRun) String() (ret string) { ret = fmt.Sprintf("%d", psr.Length) ret += func() string { switch psr.Priority { @@ -576,11 +576,7 @@ func (t *Torrent) writeStatus(w io.Writer) { }()) if t.info != nil { fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted()) - fmt.Fprint(w, "Piece States:") - for _, psr := range t.pieceStateRuns() { - w.Write([]byte(" ")) - w.Write([]byte(pieceStateRunStatusChars(psr))) - } + fmt.Fprintf(w, "Piece States: %s", t.pieceStateRuns()) fmt.Fprintln(w) } fmt.Fprintf(w, "Reader Pieces:") -- 2.44.0