Avoid duplicate lookup

In C++20 `std::views::transform()` followed by `std::views::filter()` has a nasty effect of
invoking transformation function twice.
Note that there will be a `std::views::cache_latest()` in C++26 to
address this issue.

Ref:
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2760r1.html#cache_last
https://stackoverflow.com/questions/64199664/why-c-ranges-transform-filter-calls-transform-twice-for-values-that-match

PR #23343.
This commit is contained in:
Chocobo1
2025-10-07 02:12:27 +08:00
committed by GitHub
parent d5d690cace
commit 34ad55bb29

View File

@@ -5923,12 +5923,15 @@ TorrentImpl *SessionImpl::getTorrent(const lt::torrent_handle &nativeHandle) con
QList<TorrentImpl *> SessionImpl::getQueuedTorrentsByID(const QList<TorrentID> &torrentIDs) const
{
auto torrents = torrentIDs
| std::views::transform([this](const TorrentID &torrentID) { return m_torrents.value(torrentID); })
| std::views::filter([](const TorrentImpl *torrent) { return torrent && (torrent->queuePosition() >= 0); });
QList<TorrentImpl *> queuedTorrents = {torrents.begin(), torrents.end()};
std::ranges::sort(queuedTorrents, std::less<>(), &TorrentImpl::queuePosition);
QList<TorrentImpl *> queuedTorrents;
queuedTorrents.reserve(torrentIDs.size());
for (const TorrentID &torrentID : torrentIDs)
{
TorrentImpl *torrent = m_torrents.value(torrentID);
if (torrent && (torrent->queuePosition() >= 0))
queuedTorrents.push_back(torrent);
}
std::ranges::sort(queuedTorrents, std::less(), &TorrentImpl::queuePosition);
return queuedTorrents;
}