From 4ff08ff6919578ebd58777e1fb5e1a290e129e1e Mon Sep 17 00:00:00 2001 From: Ivan Sorokin Date: Sun, 2 Nov 2014 19:27:46 +0300 Subject: [PATCH] New improved Sample in TorrentSpeedMonitor --- src/qtlibtorrent/torrentspeedmonitor.cpp | 76 ++++++++++++++++++++---- 1 file changed, 65 insertions(+), 11 deletions(-) diff --git a/src/qtlibtorrent/torrentspeedmonitor.cpp b/src/qtlibtorrent/torrentspeedmonitor.cpp index 6eed6642e..87d63a2f6 100644 --- a/src/qtlibtorrent/torrentspeedmonitor.cpp +++ b/src/qtlibtorrent/torrentspeedmonitor.cpp @@ -36,11 +36,68 @@ using namespace libtorrent; -template struct Sample { - Sample(const T down = 0, const T up = 0) : download(down), upload(up) {} - T download; - T upload; -}; +namespace { + + template struct Sample { + Sample() + : download() + , upload() + {} + + Sample(T download, T upload) + : download(download) + , upload(upload) + {} + + template + explicit Sample(Sample other) + : download(static_cast(other.download)) + , upload(static_cast(other.upload)) + {} + + T download; + T upload; + }; + + template + Sample& operator+=(Sample& lhs, Sample const& rhs) { + lhs.download += rhs.download; + lhs.upload += rhs.upload; + return lhs; + } + + template + Sample& operator-=(Sample& lhs, Sample const& rhs) { + lhs.download -= rhs.download; + lhs.upload -= rhs.upload; + return lhs; + } + + template + Sample operator+(Sample const& lhs, Sample const& rhs) { + return Sample(lhs.download + rhs.download, lhs.upload + rhs.upload); + } + + template + Sample operator-(Sample const& lhs, Sample const& rhs) { + return Sample(lhs.download - rhs.download, lhs.upload - rhs.upload); + } + + template + Sample operator*(Sample const& lhs, T rhs) { + return Sample(lhs.download * rhs, lhs.upload * rhs); + } + + template + Sample operator*(T lhs,Sample const& rhs) { + return Sample(lhs * rhs.download, lhs * rhs.upload); + } + + template + Sample operator/(Sample const& lhs, T rhs) { + return Sample(lhs.download / rhs, lhs.upload / rhs); + } +} class SpeedSample { @@ -79,16 +136,13 @@ Sample SpeedSample::average() const if (m_speedSamples.empty()) return Sample(); - qlonglong sumDL = 0; - qlonglong sumUL = 0; + Sample sum; foreach (const Sample& s, m_speedSamples) { - sumDL += s.download; - sumUL += s.upload; + sum += Sample(s); } - const qreal numSamples = m_speedSamples.size(); - return Sample(sumDL/numSamples, sumUL/numSamples); + return Sample(sum) * (1. / m_speedSamples.size()); } void TorrentSpeedMonitor::removeSamples(const QString &hash)