From 9e37c6af0208f1ab092108fe922e1128a7822e30 Mon Sep 17 00:00:00 2001 From: Jimmy Zelinskie Date: Wed, 25 Jun 2014 21:34:21 -0400 Subject: [PATCH] NewPeer now handles nil --- models/models.go | 47 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/models/models.go b/models/models.go index 840f91e..9647272 100644 --- a/models/models.go +++ b/models/models.go @@ -38,6 +38,38 @@ type Peer struct { LastAnnounce int64 `json:"last_announce"` } +// NewPeer returns the Peer representation of an Announce. When provided nil +// for the announce parameter, it panics. When provided nil for the user or +// torrent parameter, it returns a Peer{UserID: 0} or Peer{TorrentID: 0} +// respectively. +func NewPeer(a *Announce, u *User, t *Torrent) *Peer { + if a == nil { + panic("models: announce cannot equal nil") + } + + var userID uint64 + if u == nil { + userID = u.ID + } + + var torrentID uint64 + if t == nil { + torrentID = u.ID + } + + return &Peer{ + ID: a.PeerID, + UserID: userID, + TorrentID: torrentID, + IP: a.IP, + Port: a.Port, + Uploaded: a.Uploaded, + Downloaded: a.Downloaded, + Left: a.Left, + LastAnnounce: time.Now().Unix(), + } +} + // Key returns the unique key used to look-up a peer in a swarm (i.e // Torrent.Seeders & Torrent.Leechers). func (p Peer) Key() string { @@ -71,21 +103,6 @@ func (t *Torrent) InLeecherPool(p *Peer) bool { return exists } -// NewPeer returns the Peer representation of an Announce. -func NewPeer(a *Announce, u *User, t *Torrent) *Peer { - return &Peer{ - ID: a.PeerID, - UserID: u.ID, - TorrentID: t.ID, - IP: a.IP, - Port: a.Port, - Uploaded: a.Uploaded, - Downloaded: a.Downloaded, - Left: a.Left, - LastAnnounce: time.Now().Unix(), - } -} - // User is a registered user for private trackers. type User struct { ID uint64 `json:"id"`