Revert "fix: sonarcloud (#2558)" (#2562)

This reverts commit 8b9483f7fb.
This commit is contained in:
Charles Kerr 2022-02-01 11:30:51 -06:00 committed by GitHub
parent 329c4d80e1
commit 878405f862
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
58 changed files with 288 additions and 158 deletions

View File

@ -26,7 +26,7 @@ namespace
Session* myCore = nullptr; Session* myCore = nullptr;
void action_cb(Gio::SimpleAction const& action, gpointer user_data) void action_cb(Gio::SimpleAction& action, gpointer user_data)
{ {
gtr_actions_handler(action.get_name(), user_data); gtr_actions_handler(action.get_name(), user_data);
} }

View File

@ -301,7 +301,9 @@ bool getSelectedFilesForeach(
Glib::RefPtr<Gtk::TreeSelection> const& sel, Glib::RefPtr<Gtk::TreeSelection> const& sel,
std::vector<tr_file_index_t>& indexBuf) std::vector<tr_file_index_t>& indexBuf)
{ {
if (bool const is_file = iter->children().empty(); is_file) bool const is_file = iter->children().empty();
if (is_file)
{ {
/* active means: if it's selected or any ancestor is selected */ /* active means: if it's selected or any ancestor is selected */
bool is_active = sel->is_selected(iter); bool is_active = sel->is_selected(iter);
@ -343,7 +345,9 @@ bool getSubtreeForeach(
Gtk::TreeModel::Path const& subtree_path, Gtk::TreeModel::Path const& subtree_path,
std::vector<tr_file_index_t>& indexBuf) std::vector<tr_file_index_t>& indexBuf)
{ {
if (bool const is_file = iter->children().empty(); is_file) bool const is_file = iter->children().empty();
if (is_file)
{ {
if (path == subtree_path || path.is_descendant(subtree_path)) if (path == subtree_path || path.is_descendant(subtree_path))
{ {
@ -475,7 +479,8 @@ void FileList::Impl::set_torrent(int torrentId)
torrent_id_ = torrentId; torrent_id_ = torrentId;
/* populate the model */ /* populate the model */
if (auto* const tor = torrent_id_ > 0 ? core_->find_torrent(torrent_id_) : nullptr; tor != nullptr) auto* const tor = torrent_id_ > 0 ? core_->find_torrent(torrent_id_) : nullptr;
if (tor != nullptr)
{ {
// build a GNode tree of the files // build a GNode tree of the files
FileRowNode root; FileRowNode root;
@ -685,7 +690,9 @@ bool FileList::Impl::getAndSelectEventPath(GdkEventButton const* event, Gtk::Tre
if (view_->get_path_at_pos(event->x, event->y, path, col, cell_x, cell_y)) if (view_->get_path_at_pos(event->x, event->y, path, col, cell_x, cell_y))
{ {
if (auto const sel = view_->get_selection(); !sel->is_selected(path)) auto const sel = view_->get_selection();
if (!sel->is_selected(path))
{ {
sel->unselect_all(); sel->unselect_all();
sel->select(path); sel->select(path);

View File

@ -80,7 +80,7 @@ std::string _icon_cache_get_icon_key(Glib::RefPtr<Gio::Icon> const& icon)
return key; return key;
} }
Glib::RefPtr<Gdk::Pixbuf> get_themed_icon_pixbuf(Gio::ThemedIcon const& icon, int size, Gtk::IconTheme& icon_theme) Glib::RefPtr<Gdk::Pixbuf> get_themed_icon_pixbuf(Gio::ThemedIcon& icon, int size, Gtk::IconTheme& icon_theme)
{ {
auto const icon_names = icon.get_names(); auto const icon_names = icon.get_names();

View File

@ -376,7 +376,9 @@ bool MessageLogWindow::Impl::onRefresh()
if (!isPaused_) if (!isPaused_)
{ {
if (auto* msgs = tr_logGetQueue(); msgs != nullptr) auto* msgs = tr_logGetQueue();
if (msgs != nullptr)
{ {
/* add the new messages and append them to the end of /* add the new messages and append them to the end of
* our persistent list */ * our persistent list */

View File

@ -174,7 +174,8 @@ std::vector<std::string> gtr_pref_strv_get(tr_quark const key)
{ {
std::vector<std::string> ret; std::vector<std::string> ret;
if (tr_variant* list = nullptr; tr_variantDictFindList(getPrefs(), key, &list)) tr_variant* list = nullptr;
if (tr_variantDictFindList(getPrefs(), key, &list))
{ {
size_t const n = tr_variantListSize(list); size_t const n = tr_variantListSize(list);
ret.reserve(n); ret.reserve(n);

View File

@ -3,7 +3,6 @@
// or any future license endorsed by Mnemosyne LLC. // or any future license endorsed by Mnemosyne LLC.
// License text can be found in the licenses/ folder. // License text can be found in the licenses/ folder.
#include <array>
#include <climits> /* USHRT_MAX, INT_MAX */ #include <climits> /* USHRT_MAX, INT_MAX */
#include <sstream> #include <sstream>
#include <string> #include <string>
@ -1098,7 +1097,7 @@ PrefsDialog::Impl::Impl(PrefsDialog& dialog, Glib::RefPtr<Session> const& core)
: dialog_(dialog) : dialog_(dialog)
, core_(core) , core_(core)
{ {
auto constexpr PrefsQuarks = std::array<tr_quark, 2>{ TR_KEY_peer_port, TR_KEY_download_dir }; static tr_quark const prefs_quarks[] = { TR_KEY_peer_port, TR_KEY_download_dir };
core_prefs_tag_ = core_->signal_prefs_changed().connect(sigc::mem_fun(*this, &Impl::on_core_prefs_changed)); core_prefs_tag_ = core_->signal_prefs_changed().connect(sigc::mem_fun(*this, &Impl::on_core_prefs_changed));
@ -1119,7 +1118,7 @@ PrefsDialog::Impl::Impl(PrefsDialog& dialog, Glib::RefPtr<Session> const& core)
n->append_page(*remotePage(), _("Remote")); n->append_page(*remotePage(), _("Remote"));
/* init from prefs keys */ /* init from prefs keys */
for (auto const key : PrefsQuarks) for (auto const key : prefs_quarks)
{ {
on_core_prefs_changed(key); on_core_prefs_changed(key);
} }

View File

@ -145,7 +145,7 @@ private:
void on_pref_changed(tr_quark key); void on_pref_changed(tr_quark key);
void on_torrent_completeness_changed(tr_torrent* tor, tr_completeness completeness, bool was_running); void on_torrent_completeness_changed(tr_torrent* tor, tr_completeness completeness, bool was_running);
void on_torrent_metadata_changed(tr_torrent const* tor); void on_torrent_metadata_changed(tr_torrent* tor);
private: private:
Session& core_; Session& core_;
@ -896,7 +896,7 @@ Gtk::TreeModel::iterator find_row_from_torrent_id(Glib::RefPtr<Gtk::TreeModel> c
/* this is called in the libtransmission thread, *NOT* the GTK+ thread, /* this is called in the libtransmission thread, *NOT* the GTK+ thread,
so delegate to the GTK+ thread before changing our list store... */ so delegate to the GTK+ thread before changing our list store... */
void Session::Impl::on_torrent_metadata_changed(tr_torrent const* tor) void Session::Impl::on_torrent_metadata_changed(tr_torrent* tor)
{ {
Glib::signal_idle().connect( Glib::signal_idle().connect(
[this, core = get_core_ptr(), torrent_id = tr_torrentId(tor)]() [this, core = get_core_ptr(), torrent_id = tr_torrentId(tor)]()
@ -925,7 +925,7 @@ void Session::Impl::on_torrent_metadata_changed(tr_torrent const* tor)
namespace namespace
{ {
unsigned int build_torrent_trackers_hash(tr_torrent const* tor) unsigned int build_torrent_trackers_hash(tr_torrent* tor)
{ {
auto hash = uint64_t{}; auto hash = uint64_t{};
@ -1135,8 +1135,9 @@ void Session::Impl::add_file_async_callback(
bool Session::Impl::add_file(Glib::RefPtr<Gio::File> const& file, bool do_start, bool do_prompt, bool do_notify) bool Session::Impl::add_file(Glib::RefPtr<Gio::File> const& file, bool do_start, bool do_prompt, bool do_notify)
{ {
bool handled = false; bool handled = false;
auto const* const session = get_session();
if (auto const* const session = get_session(); session != nullptr) if (session != nullptr)
{ {
tr_ctor* ctor; tr_ctor* ctor;
bool tried = false; bool tried = false;

View File

@ -134,9 +134,11 @@ Glib::ustring getIconName()
{ {
Glib::ustring icon_name; Glib::ustring icon_name;
auto theme = Gtk::IconTheme::get_default();
// if the tray's icon is a 48x48 file, use it. // if the tray's icon is a 48x48 file, use it.
// otherwise, use the fallback builtin icon. // otherwise, use the fallback builtin icon.
if (auto theme = Gtk::IconTheme::get_default(); !theme->has_icon(TrayIconName)) if (!theme->has_icon(TrayIconName))
{ {
icon_name = AppIconName; icon_name = AppIconName;
} }

View File

@ -272,7 +272,9 @@ bool on_tree_view_button_pressed(
* clear all the selections. */ * clear all the selections. */
bool on_tree_view_button_released(Gtk::TreeView* view, GdkEventButton* event) bool on_tree_view_button_released(Gtk::TreeView* view, GdkEventButton* event)
{ {
if (Gtk::TreeModel::Path path; !view->get_path_at_pos((int)event->x, (int)event->y, path)) Gtk::TreeModel::Path path;
if (!view->get_path_at_pos((int)event->x, (int)event->y, path))
{ {
view->get_selection()->unselect_all(); view->get_selection()->unselect_all();
} }

View File

@ -56,7 +56,8 @@ bool tr_announce_list::remove(tr_tracker_id_t id)
bool tr_announce_list::replace(tr_tracker_id_t id, std::string_view announce_url_sv) bool tr_announce_list::replace(tr_tracker_id_t id, std::string_view announce_url_sv)
{ {
if (auto const announce = tr_urlParseTracker(announce_url_sv); !announce || !canAdd(*announce)) auto const announce = tr_urlParseTracker(announce_url_sv);
if (!announce || !canAdd(*announce))
{ {
return false; return false;
} }
@ -87,7 +88,8 @@ bool tr_announce_list::add(std::string_view announce_url_sv, tr_tracker_tier_t t
tracker.id = nextUniqueId(); tracker.id = nextUniqueId();
tracker.host = tr_strvJoin(tracker.announce.host, ":"sv, tracker.announce.portstr); tracker.host = tr_strvJoin(tracker.announce.host, ":"sv, tracker.announce.portstr);
if (auto const scrape_str = announceToScrape(announce_url_sv); scrape_str) auto const scrape_str = announceToScrape(announce_url_sv);
if (scrape_str)
{ {
tracker.scrape_str = *scrape_str; tracker.scrape_str = *scrape_str;
tracker.scrape = *tr_urlParseTracker(tracker.scrape_str.sv()); tracker.scrape = *tr_urlParseTracker(tracker.scrape_str.sv());
@ -125,7 +127,8 @@ std::optional<std::string> tr_announce_list::announceToScrape(std::string_view a
tr_quark tr_announce_list::announceToScrape(tr_quark announce) tr_quark tr_announce_list::announceToScrape(tr_quark announce)
{ {
if (auto const scrape_str = announceToScrape(tr_quark_get_string_view(announce)); scrape_str) auto const scrape_str = announceToScrape(tr_quark_get_string_view(announce));
if (scrape_str)
{ {
return tr_quark_new(*scrape_str); return tr_quark_new(*scrape_str);
} }

View File

@ -110,7 +110,8 @@ static std::string announce_url_new(tr_session const* session, tr_announce_reque
announce twice. At any rate, we're already computing our IPv6 announce twice. At any rate, we're already computing our IPv6
address (for the LTEP handshake), so this comes for free. */ address (for the LTEP handshake), so this comes for free. */
if (auto const* const ipv6 = tr_globalIPv6(session); ipv6 != nullptr) unsigned char const* const ipv6 = tr_globalIPv6(session);
if (ipv6 != nullptr)
{ {
auto ipv6_readable = std::array<char, INET6_ADDRSTRLEN>{}; auto ipv6_readable = std::array<char, INET6_ADDRSTRLEN>{};
evutil_inet_ntop(AF_INET6, ipv6, std::data(ipv6_readable), std::size(ipv6_readable)); evutil_inet_ntop(AF_INET6, ipv6, std::data(ipv6_readable), std::size(ipv6_readable));
@ -417,7 +418,9 @@ void tr_announcerParseHttpScrapeResponse(tr_scrape_response& response, std::stri
bool Int64(int64_t value, Context const& context) override bool Int64(int64_t value, Context const& context) override
{ {
if (auto const key = currentKey(); row_ && key == "complete"sv) auto const key = currentKey();
if (row_ && key == "complete"sv)
{ {
response_.rows[*row_].seeders = value; response_.rows[*row_].seeders = value;
} }
@ -440,7 +443,9 @@ void tr_announcerParseHttpScrapeResponse(tr_scrape_response& response, std::stri
bool String(std::string_view value, Context const& context) override bool String(std::string_view value, Context const& context) override
{ {
if (auto const key = currentKey(); depth() == 1 && key == "failure reason"sv) auto const key = currentKey();
if (depth() == 1 && key == "failure reason"sv)
{ {
response_.errmsg = value; response_.errmsg = value;
} }

View File

@ -1322,7 +1322,8 @@ static void on_scrape_done(tr_scrape_response const* response, void* vsession)
tier->scheduleNextScrape(); tier->scheduleNextScrape();
tr_logAddTorDbg(tier->tor, "Scrape successful. Rescraping in %d seconds.", tier->scrapeIntervalSec); tr_logAddTorDbg(tier->tor, "Scrape successful. Rescraping in %d seconds.", tier->scrapeIntervalSec);
if (auto* const tracker = tier->currentTracker(); tracker != nullptr) tr_tracker* const tracker = tier->currentTracker();
if (tracker != nullptr)
{ {
if (row.seeders >= 0) if (row.seeders >= 0)
{ {

View File

@ -165,7 +165,7 @@ int tr_blocklistFileGetRuleCount(tr_blocklistFile const* b)
return b->ruleCount; return b->ruleCount;
} }
bool tr_blocklistFileIsEnabled(tr_blocklistFile const* b) bool tr_blocklistFileIsEnabled(tr_blocklistFile* b)
{ {
return b->isEnabled; return b->isEnabled;
} }

View File

@ -22,7 +22,7 @@ int tr_blocklistFileGetRuleCount(tr_blocklistFile const* b);
void tr_blocklistFileFree(tr_blocklistFile* b); void tr_blocklistFileFree(tr_blocklistFile* b);
bool tr_blocklistFileIsEnabled(tr_blocklistFile const* b); bool tr_blocklistFileIsEnabled(tr_blocklistFile* b);
void tr_blocklistFileSetEnabled(tr_blocklistFile* b, bool isEnabled); void tr_blocklistFileSetEnabled(tr_blocklistFile* b, bool isEnabled);

View File

@ -356,8 +356,9 @@ int tr_cacheReadBlock(
uint8_t* setme) uint8_t* setme)
{ {
int err = 0; int err = 0;
struct cache_block* cb = findBlock(cache, torrent, piece, offset);
if (auto* cb = findBlock(cache, torrent, piece, offset); cb != nullptr) if (cb != nullptr)
{ {
evbuffer_copyout(cb->evbuf, setme, len); evbuffer_copyout(cb->evbuf, setme, len);
} }
@ -372,8 +373,9 @@ int tr_cacheReadBlock(
int tr_cachePrefetchBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t piece, uint32_t offset, uint32_t len) int tr_cachePrefetchBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t piece, uint32_t offset, uint32_t len)
{ {
int err = 0; int err = 0;
struct cache_block const* const cb = findBlock(cache, torrent, piece, offset);
if (auto const* const cb = findBlock(cache, torrent, piece, offset); cb == nullptr) if (cb == nullptr)
{ {
err = tr_ioPrefetch(torrent, piece, offset, len); err = tr_ioPrefetch(torrent, piece, offset, len);
} }
@ -452,7 +454,9 @@ int tr_cacheFlushTorrent(tr_cache* cache, tr_torrent* torrent)
/* flush out all the blocks in that torrent */ /* flush out all the blocks in that torrent */
while (err == 0 && pos < tr_ptrArraySize(&cache->blocks)) while (err == 0 && pos < tr_ptrArraySize(&cache->blocks))
{ {
if (auto const* b = static_cast<struct cache_block const*>(tr_ptrArrayNth(&cache->blocks, pos)); b->tor != torrent) auto const* b = static_cast<struct cache_block const*>(tr_ptrArrayNth(&cache->blocks, pos));
if (b->tor != torrent)
{ {
break; break;
} }

View File

@ -917,7 +917,9 @@ bool tr_sys_file_advise(
TR_ASSERT(native_advice != POSIX_FADV_NORMAL); TR_ASSERT(native_advice != POSIX_FADV_NORMAL);
if (int const code = posix_fadvise(handle, offset, size, native_advice); code != 0) int const code = posix_fadvise(handle, offset, size, native_advice);
if (code != 0)
{ {
set_system_error(error, code); set_system_error(error, code);
ret = false; ret = false;
@ -1050,7 +1052,8 @@ bool tr_sys_file_preallocate(tr_sys_file_t handle, uint64_t size, int flags, tr_
{ {
errno = 0; errno = 0;
if (auto const success = approach(handle, size); success) auto const success = approach(handle, size);
if (success)
{ {
return success; return success;
} }
@ -1312,8 +1315,9 @@ char const* tr_sys_dir_read_name(tr_sys_dir_t handle, tr_error** error)
char const* ret = nullptr; char const* ret = nullptr;
errno = 0; errno = 0;
struct dirent const* const entry = readdir((DIR*)handle);
if (auto const* const entry = readdir((DIR*)handle); entry != nullptr) if (entry != nullptr)
{ {
ret = entry->d_name; ret = entry->d_name;
} }

View File

@ -769,7 +769,8 @@ static ReadState readPadA(tr_handshake* handshake, struct evbuffer* inbuf)
return READ_NOW; return READ_NOW;
} }
if (size_t const len = evbuffer_get_length(inbuf); len > SHA_DIGEST_LENGTH) size_t const len = evbuffer_get_length(inbuf);
if (len > SHA_DIGEST_LENGTH)
{ {
evbuffer_drain(inbuf, len - SHA_DIGEST_LENGTH); evbuffer_drain(inbuf, len - SHA_DIGEST_LENGTH);
} }

View File

@ -598,7 +598,9 @@ static int tr_globalAddress(int af, void* addr, int* addr_len)
return -1; return -1;
} }
if (int const rc = get_source_address(sa, salen, (struct sockaddr*)&ss, &sslen); rc < 0) int const rc = get_source_address(sa, salen, (struct sockaddr*)&ss, &sslen);
if (rc < 0)
{ {
return -1; return -1;
} }

View File

@ -668,7 +668,7 @@ static void refillUpkeep(evutil_socket_t /*fd*/, short /*what*/, void* vmgr)
tr_timerAddMsec(mgr->refillUpkeepTimer, RefillUpkeepPeriodMsec); tr_timerAddMsec(mgr->refillUpkeepTimer, RefillUpkeepPeriodMsec);
} }
static void addStrike(tr_swarm const* s, tr_peer* peer) static void addStrike(tr_swarm* s, tr_peer* peer)
{ {
tordbg(s, "increasing peer %s strike count to %d", tr_atomAddrStr(peer->atom), peer->strikes + 1); tordbg(s, "increasing peer %s strike count to %d", tr_atomAddrStr(peer->atom), peer->strikes + 1);
@ -681,11 +681,7 @@ static void addStrike(tr_swarm const* s, tr_peer* peer)
} }
} }
static void peerSuggestedPiece( static void peerSuggestedPiece(tr_swarm* /*s*/, tr_peer* /*peer*/, tr_piece_index_t /*pieceIndex*/, int /*isFastAllowed*/)
tr_swarm const* /*s*/,
tr_peer const* /*peer*/,
tr_piece_index_t /*pieceIndex*/,
int /*isFastAllowed*/)
{ {
#if 0 #if 0
@ -1830,7 +1826,7 @@ void tr_peerMgrClearInterest(tr_torrent* tor)
} }
/* does this peer have any pieces that we want? */ /* does this peer have any pieces that we want? */
static bool isPeerInteresting(tr_torrent const* const tor, bool const* const piece_is_interesting, tr_peer const* const peer) static bool isPeerInteresting(tr_torrent* const tor, bool const* const piece_is_interesting, tr_peer const* const peer)
{ {
/* these cases should have already been handled by the calling code... */ /* these cases should have already been handled by the calling code... */
TR_ASSERT(!tor->isDone()); TR_ASSERT(!tor->isDone());
@ -2405,11 +2401,12 @@ static void closePeer(tr_peer* peer)
{ {
TR_ASSERT(peer != nullptr); TR_ASSERT(peer != nullptr);
auto* const s = peer->swarm; auto* const s = peer->swarm;
peer_atom* const atom = peer->atom;
/* if we transferred piece data, then they might be good peers, /* if we transferred piece data, then they might be good peers,
so reset their `numFails' weight to zero. otherwise we connected so reset their `numFails' weight to zero. otherwise we connected
to them fruitlessly, so mark it as another fail */ to them fruitlessly, so mark it as another fail */
if (auto* const atom = peer->atom; atom->piece_data_time != 0) if (atom->piece_data_time != 0)
{ {
tordbg(s, "resetting atom %s numFails to 0", tr_atomAddrStr(atom)); tordbg(s, "resetting atom %s numFails to 0", tr_atomAddrStr(atom));
atom->numFails = 0; atom->numFails = 0;
@ -2943,7 +2940,7 @@ static bool swarmIsAllSeeds(tr_swarm* swarm)
} }
/** @return an array of all the atoms we might want to connect to */ /** @return an array of all the atoms we might want to connect to */
static std::vector<peer_candidate> getPeerCandidates(tr_session const* session, size_t max) static std::vector<peer_candidate> getPeerCandidates(tr_session* session, size_t max)
{ {
time_t const now = tr_time(); time_t const now = tr_time();
uint64_t const now_msec = tr_time_msec(); uint64_t const now_msec = tr_time_msec();

View File

@ -707,7 +707,7 @@ static void pokeBatchPeriod(tr_peerMsgsImpl* msgs, int interval)
} }
} }
static void dbgOutMessageLen(tr_peerMsgsImpl const* msgs) static void dbgOutMessageLen(tr_peerMsgsImpl* msgs)
{ {
dbgmsg(msgs, "outMessage size is now %zu", evbuffer_get_length(msgs->outMessages)); dbgmsg(msgs, "outMessage size is now %zu", evbuffer_get_length(msgs->outMessages));
} }
@ -1156,7 +1156,8 @@ static void parseLtepHandshake(tr_peerMsgsImpl* msgs, uint32_t len, struct evbuf
msgs->peerSupportsPex = false; msgs->peerSupportsPex = false;
msgs->peerSupportsMetadataXfer = false; msgs->peerSupportsMetadataXfer = false;
if (tr_variant* sub = nullptr; tr_variantDictFindDict(&val, TR_KEY_m, &sub)) tr_variant* sub = nullptr;
if (tr_variantDictFindDict(&val, TR_KEY_m, &sub))
{ {
if (tr_variantDictFindInt(sub, TR_KEY_ut_pex, &i)) if (tr_variantDictFindInt(sub, TR_KEY_ut_pex, &i))
{ {
@ -1913,7 +1914,8 @@ static int clientGotBlock(tr_peerMsgsImpl* msgs, struct evbuffer* data, struct p
*** Save the block *** Save the block
**/ **/
if (int const err = tr_cacheWriteBlock(msgs->session->cache, tor, req->index, req->offset, req->length, data); err != 0) int const err = tr_cacheWriteBlock(msgs->session->cache, tor, req->index, req->offset, req->length, data);
if (err != 0)
{ {
return err; return err;
} }

View File

@ -28,7 +28,7 @@ struct tr_torrent;
class tr_peerMsgs : public tr_peer class tr_peerMsgs : public tr_peer
{ {
public: public:
tr_peerMsgs(tr_torrent const* torrent, peer_atom* atom_in) tr_peerMsgs(tr_torrent* torrent, peer_atom* atom_in)
: tr_peer{ torrent, atom_in } : tr_peer{ torrent, atom_in }
{ {
} }

View File

@ -436,7 +436,8 @@ std::optional<tr_quark> tr_quark_lookup(std::string_view key)
/* was it added during runtime? */ /* was it added during runtime? */
auto const rbegin = std::begin(my_runtime); auto const rbegin = std::begin(my_runtime);
auto const rend = std::end(my_runtime); auto const rend = std::end(my_runtime);
if (auto const rit = std::find(rbegin, rend, key); rit != rend) auto const rit = std::find(rbegin, rend, key);
if (rit != rend)
{ {
return TR_N_KEYS + std::distance(rbegin, rit); return TR_N_KEYS + std::distance(rbegin, rit);
} }

View File

@ -228,7 +228,7 @@ static uint64_t loadFilePriorities(tr_variant* dict, tr_torrent* tor)
**** ****
***/ ***/
static void saveSingleSpeedLimit(tr_variant* d, tr_torrent const* tor, tr_direction dir) static void saveSingleSpeedLimit(tr_variant* d, tr_torrent* tor, tr_direction dir)
{ {
tr_variantDictReserve(d, 3); tr_variantDictReserve(d, 3);
tr_variantDictAddInt(d, TR_KEY_speed_Bps, tor->speedLimitBps(dir)); tr_variantDictAddInt(d, TR_KEY_speed_Bps, tor->speedLimitBps(dir));
@ -236,20 +236,20 @@ static void saveSingleSpeedLimit(tr_variant* d, tr_torrent const* tor, tr_direct
tr_variantDictAddBool(d, TR_KEY_use_speed_limit, tr_torrentUsesSpeedLimit(tor, dir)); tr_variantDictAddBool(d, TR_KEY_use_speed_limit, tr_torrentUsesSpeedLimit(tor, dir));
} }
static void saveSpeedLimits(tr_variant* dict, tr_torrent const* tor) static void saveSpeedLimits(tr_variant* dict, tr_torrent* tor)
{ {
saveSingleSpeedLimit(tr_variantDictAddDict(dict, TR_KEY_speed_limit_down, 0), tor, TR_DOWN); saveSingleSpeedLimit(tr_variantDictAddDict(dict, TR_KEY_speed_limit_down, 0), tor, TR_DOWN);
saveSingleSpeedLimit(tr_variantDictAddDict(dict, TR_KEY_speed_limit_up, 0), tor, TR_UP); saveSingleSpeedLimit(tr_variantDictAddDict(dict, TR_KEY_speed_limit_up, 0), tor, TR_UP);
} }
static void saveRatioLimits(tr_variant* dict, tr_torrent const* tor) static void saveRatioLimits(tr_variant* dict, tr_torrent* tor)
{ {
tr_variant* d = tr_variantDictAddDict(dict, TR_KEY_ratio_limit, 2); tr_variant* d = tr_variantDictAddDict(dict, TR_KEY_ratio_limit, 2);
tr_variantDictAddReal(d, TR_KEY_ratio_limit, tr_torrentGetRatioLimit(tor)); tr_variantDictAddReal(d, TR_KEY_ratio_limit, tr_torrentGetRatioLimit(tor));
tr_variantDictAddInt(d, TR_KEY_ratio_mode, tr_torrentGetRatioMode(tor)); tr_variantDictAddInt(d, TR_KEY_ratio_mode, tr_torrentGetRatioMode(tor));
} }
static void saveIdleLimits(tr_variant* dict, tr_torrent const* tor) static void saveIdleLimits(tr_variant* dict, tr_torrent* tor)
{ {
tr_variant* d = tr_variantDictAddDict(dict, TR_KEY_idle_limit, 2); tr_variant* d = tr_variantDictAddDict(dict, TR_KEY_idle_limit, 2);
tr_variantDictAddInt(d, TR_KEY_idle_limit, tr_torrentGetIdleLimit(tor)); tr_variantDictAddInt(d, TR_KEY_idle_limit, tr_torrentGetIdleLimit(tor));
@ -305,14 +305,17 @@ static uint64_t loadRatioLimits(tr_variant* dict, tr_torrent* tor)
{ {
auto ret = uint64_t{}; auto ret = uint64_t{};
if (tr_variant* d = nullptr; tr_variantDictFindDict(dict, TR_KEY_ratio_limit, &d)) tr_variant* d = nullptr;
if (tr_variantDictFindDict(dict, TR_KEY_ratio_limit, &d))
{ {
if (auto dratio = double{}; tr_variantDictFindReal(d, TR_KEY_ratio_limit, &dratio)) auto dratio = double{};
if (tr_variantDictFindReal(d, TR_KEY_ratio_limit, &dratio))
{ {
tr_torrentSetRatioLimit(tor, dratio); tr_torrentSetRatioLimit(tor, dratio);
} }
if (auto i = int64_t{}; tr_variantDictFindInt(d, TR_KEY_ratio_mode, &i)) auto i = int64_t{};
if (tr_variantDictFindInt(d, TR_KEY_ratio_mode, &i))
{ {
tr_torrentSetRatioMode(tor, tr_ratiolimit(i)); tr_torrentSetRatioMode(tor, tr_ratiolimit(i));
} }
@ -327,14 +330,17 @@ static uint64_t loadIdleLimits(tr_variant* dict, tr_torrent* tor)
{ {
auto ret = uint64_t{}; auto ret = uint64_t{};
if (tr_variant* d = nullptr; tr_variantDictFindDict(dict, TR_KEY_idle_limit, &d)) tr_variant* d = nullptr;
if (tr_variantDictFindDict(dict, TR_KEY_idle_limit, &d))
{ {
if (auto imin = int64_t{}; tr_variantDictFindInt(d, TR_KEY_idle_limit, &imin)) auto imin = int64_t{};
if (tr_variantDictFindInt(d, TR_KEY_idle_limit, &imin))
{ {
tr_torrentSetIdleLimit(tor, imin); tr_torrentSetIdleLimit(tor, imin);
} }
if (auto i = int64_t{}; tr_variantDictFindInt(d, TR_KEY_idle_mode, &i)) auto i = int64_t{};
if (tr_variantDictFindInt(d, TR_KEY_idle_mode, &i))
{ {
tr_torrentSetIdleMode(tor, tr_idlelimit(i)); tr_torrentSetIdleMode(tor, tr_idlelimit(i));
} }
@ -574,7 +580,8 @@ static uint64_t loadProgress(tr_variant* dict, tr_torrent* tor)
auto blocks = tr_bitfield{ tor->blockCount() }; auto blocks = tr_bitfield{ tor->blockCount() };
char const* err = nullptr; char const* err = nullptr;
auto sv = std::string_view{}; auto sv = std::string_view{};
if (auto const* const b = tr_variantDictFind(prog, TR_KEY_blocks); b != nullptr) tr_variant const* const b = tr_variantDictFind(prog, TR_KEY_blocks);
if (b != nullptr)
{ {
uint8_t const* buf = nullptr; uint8_t const* buf = nullptr;
auto buflen = size_t{}; auto buflen = size_t{};
@ -671,7 +678,8 @@ void tr_torrentSaveResume(tr_torrent* tor)
saveName(&top, tor); saveName(&top, tor);
saveLabels(&top, tor); saveLabels(&top, tor);
if (auto const err = tr_variantToFile(&top, TR_VARIANT_FMT_BENC, tor->resumeFile()); err != 0) auto const err = tr_variantToFile(&top, TR_VARIANT_FMT_BENC, tor->resumeFile());
if (err != 0)
{ {
tor->setLocalError(tr_strvJoin("Unable to save resume file: ", tr_strerror(err))); tor->setLocalError(tr_strvJoin("Unable to save resume file: ", tr_strerror(err)));
} }

View File

@ -342,7 +342,7 @@ static bool isIPAddressWithOptionalPort(char const* host)
return evutil_parse_sockaddr_port(host, (struct sockaddr*)&address, &address_len) != -1; return evutil_parse_sockaddr_port(host, (struct sockaddr*)&address, &address_len) != -1;
} }
static bool isHostnameAllowed(tr_rpc_server const* server, evhttp_request const* req) static bool isHostnameAllowed(tr_rpc_server const* server, struct evhttp_request* req)
{ {
/* If password auth is enabled, any hostname is permitted. */ /* If password auth is enabled, any hostname is permitted. */
if (server->isPasswordEnabled) if (server->isPasswordEnabled)

View File

@ -1305,7 +1305,8 @@ static char const* torrentRenamePath(
auto newname = std::string_view{}; auto newname = std::string_view{};
(void)tr_variantDictFindStrView(args_in, TR_KEY_name, &newname); (void)tr_variantDictFindStrView(args_in, TR_KEY_name, &newname);
if (auto const torrents = getTorrents(session, args_in); std::size(torrents) == 1) auto const torrents = getTorrents(session, args_in);
if (std::size(torrents) == 1)
{ {
torrents[0]->renamePath(oldpath, newname, torrentRenamePathDone, idle_data); torrents[0]->renamePath(oldpath, newname, torrentRenamePathDone, idle_data);
} }
@ -2404,7 +2405,8 @@ void tr_rpc_request_exec_json(
tr_variantDictAddDict(&response, TR_KEY_arguments, 0); tr_variantDictAddDict(&response, TR_KEY_arguments, 0);
tr_variantDictAddStr(&response, TR_KEY_result, result); tr_variantDictAddStr(&response, TR_KEY_result, result);
if (auto tag = int64_t{}; tr_variantDictFindInt(mutable_request, TR_KEY_tag, &tag)) auto tag = int64_t{};
if (tr_variantDictFindInt(mutable_request, TR_KEY_tag, &tag))
{ {
tr_variantDictAddInt(&response, TR_KEY_tag, tag); tr_variantDictAddInt(&response, TR_KEY_tag, tag);
} }
@ -2427,7 +2429,8 @@ void tr_rpc_request_exec_json(
tr_variantDictAddStr(&response, TR_KEY_result, result); tr_variantDictAddStr(&response, TR_KEY_result, result);
if (auto tag = int64_t{}; tr_variantDictFindInt(mutable_request, TR_KEY_tag, &tag)) auto tag = int64_t{};
if (tr_variantDictFindInt(mutable_request, TR_KEY_tag, &tag))
{ {
tr_variantDictAddInt(&response, TR_KEY_tag, tag); tr_variantDictAddInt(&response, TR_KEY_tag, tag);
} }
@ -2443,7 +2446,8 @@ void tr_rpc_request_exec_json(
data->response = tr_new0(tr_variant, 1); data->response = tr_new0(tr_variant, 1);
tr_variantInitDict(data->response, 3); tr_variantInitDict(data->response, 3);
if (auto tag = int64_t{}; tr_variantDictFindInt(mutable_request, TR_KEY_tag, &tag)) auto tag = int64_t{};
if (tr_variantDictFindInt(mutable_request, TR_KEY_tag, &tag))
{ {
tr_variantDictAddInt(data->response, TR_KEY_tag, tag); tr_variantDictAddInt(data->response, TR_KEY_tag, tag);
} }

View File

@ -118,7 +118,7 @@ tr_peer_id_t tr_peerIdInit()
**** ****
***/ ***/
tr_encryption_mode tr_sessionGetEncryption(tr_session const* session) tr_encryption_mode tr_sessionGetEncryption(tr_session* session)
{ {
TR_ASSERT(session != nullptr); TR_ASSERT(session != nullptr);
@ -600,7 +600,8 @@ tr_session* tr_sessionInit(char const* config_dir, bool messageQueuingEnabled, t
session->removed_torrents.clear(); session->removed_torrents.clear();
/* nice to start logging at the very beginning */ /* nice to start logging at the very beginning */
if (auto i = int64_t{}; tr_variantDictFindInt(clientSettings, TR_KEY_message_level, &i)) auto i = int64_t{};
if (tr_variantDictFindInt(clientSettings, TR_KEY_message_level, &i))
{ {
tr_logSetLevel(tr_log_level(i)); tr_logSetLevel(tr_log_level(i));
} }
@ -2306,8 +2307,9 @@ static void loadBlocklists(tr_session* session)
if (!tr_sys_path_get_info(binname.c_str(), 0, &binname_info, nullptr)) /* create it */ if (!tr_sys_path_get_info(binname.c_str(), 0, &binname_info, nullptr)) /* create it */
{ {
tr_blocklistFile* b = tr_blocklistFileNew(binname.c_str(), isEnabled); tr_blocklistFile* b = tr_blocklistFileNew(binname.c_str(), isEnabled);
int const n = tr_blocklistFileSetContent(b, path.c_str());
if (int const n = tr_blocklistFileSetContent(b, path.c_str()); n > 0) if (n > 0)
{ {
load = binname; load = binname;
} }

View File

@ -274,7 +274,8 @@ static bool useNewMetainfo(tr_torrent* tor, tr_incomplete_metadata const* m, tr_
} }
// save it // save it
if (auto const filename = tor->torrentFile(); !tr_saveFile(filename, benc, error)) auto const filename = tor->torrentFile();
if (!tr_saveFile(filename, benc, error))
{ {
return false; return false;
} }
@ -369,9 +370,9 @@ bool tr_torrentGetNextMetadataRequest(tr_torrent* tor, time_t now, int* setme_pi
TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(tr_isTorrent(tor));
bool have_request = false; bool have_request = false;
struct tr_incomplete_metadata* m = tor->incompleteMetadata;
if (auto* m = tor->incompleteMetadata; if (m != nullptr && m->piecesNeededCount > 0 && m->piecesNeeded[0].requestedAt + MinRepeatIntervalSecs < now)
m != nullptr && m->piecesNeededCount > 0 && m->piecesNeeded[0].requestedAt + MinRepeatIntervalSecs < now)
{ {
int const piece = m->piecesNeeded[0].piece; int const piece = m->piecesNeeded[0].piece;
tr_removeElementFromArray(m->piecesNeeded, 0, sizeof(struct metadata_node), m->piecesNeededCount); tr_removeElementFromArray(m->piecesNeeded, 0, sizeof(struct metadata_node), m->piecesNeededCount);

View File

@ -336,7 +336,8 @@ static bool tr_torrentGetSeedRatioBytes(tr_torrent const* tor, uint64_t* setme_l
TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(tr_isTorrent(tor));
if (auto seed_ratio = double{}; tr_torrentGetSeedRatio(tor, &seed_ratio)) auto seed_ratio = double{};
if (tr_torrentGetSeedRatio(tor, &seed_ratio))
{ {
auto const uploaded = tor->uploadedCur + tor->uploadedPrev; auto const uploaded = tor->uploadedCur + tor->uploadedPrev;
auto const baseline = tor->totalSize(); auto const baseline = tor->totalSize();
@ -2339,8 +2340,8 @@ static void setLocationImpl(void* vdata)
auto const file_size = tor->fileSize(i); auto const file_size = tor->fileSize(i);
char const* oldbase = nullptr; char const* oldbase = nullptr;
char* sub = nullptr;
if (char* sub = nullptr; tr_torrentFindFile2(tor, i, &oldbase, &sub, nullptr)) if (tr_torrentFindFile2(tor, i, &oldbase, &sub, nullptr))
{ {
auto const oldpath = tr_strvPath(oldbase, sub); auto const oldpath = tr_strvPath(oldbase, sub);
auto const newpath = tr_strvPath(location, sub); auto const newpath = tr_strvPath(location, sub);

View File

@ -104,8 +104,8 @@ static void bootstrap_from_name(char const* name, tr_port port, int af)
tr_snprintf(pp, sizeof(pp), "%d", (int)port); tr_snprintf(pp, sizeof(pp), "%d", (int)port);
addrinfo* info = nullptr; addrinfo* info = nullptr;
int const rc = getaddrinfo(name, pp, &hints, &info);
if (int const rc = getaddrinfo(name, pp, &hints, &info); rc != 0) if (rc != 0)
{ {
tr_logAddNamedError("DHT", "%s:%s: %s", name, pp, gai_strerror(rc)); tr_logAddNamedError("DHT", "%s:%s: %s", name, pp, gai_strerror(rc));
return; return;
@ -527,7 +527,7 @@ int tr_dhtStatus(tr_session* session, int af, int* nodes_return)
return closure.status; return closure.status;
} }
tr_port tr_dhtPort(tr_session const* ss) tr_port tr_dhtPort(tr_session* ss)
{ {
return tr_dhtEnabled(ss) ? ss->udp_port : 0; return tr_dhtEnabled(ss) ? ss->udp_port : 0;
} }
@ -738,8 +738,9 @@ void tr_dhtCallback(unsigned char* buf, int buflen, struct sockaddr* from, sockl
} }
time_t tosleep = 0; time_t tosleep = 0;
int rc = dht_periodic(buf, buflen, from, fromlen, &tosleep, callback, nullptr);
if (int rc = dht_periodic(buf, buflen, from, fromlen, &tosleep, callback, nullptr); rc < 0) if (rc < 0)
{ {
if (errno == EINTR) if (errno == EINTR)
{ {

View File

@ -20,7 +20,7 @@ enum
int tr_dhtInit(tr_session*); int tr_dhtInit(tr_session*);
void tr_dhtUninit(tr_session*); void tr_dhtUninit(tr_session*);
bool tr_dhtEnabled(tr_session const*); bool tr_dhtEnabled(tr_session const*);
tr_port tr_dhtPort(tr_session const*); tr_port tr_dhtPort(tr_session*);
int tr_dhtStatus(tr_session*, int af, int* setme_nodeCount); int tr_dhtStatus(tr_session*, int af, int* setme_nodeCount);
char const* tr_dhtPrintableStatus(int status); char const* tr_dhtPrintableStatus(int status);
bool tr_dhtAddNode(tr_session*, tr_address const*, tr_port, bool bootstrap); bool tr_dhtAddNode(tr_session*, tr_address const*, tr_port, bool bootstrap);

View File

@ -62,7 +62,8 @@ static void getopts_usage_line(tr_option const* opt, int longWidth, int shortWid
auto const strip_leading_whitespace = [](std::string_view text) auto const strip_leading_whitespace = [](std::string_view text)
{ {
if (auto pos = text.find_first_not_of(' '); pos != std::string_view::npos) auto pos = text.find_first_not_of(' ');
if (pos != std::string_view::npos)
{ {
text.remove_prefix(pos); text.remove_prefix(pos);
} }

View File

@ -138,9 +138,10 @@ static char const* lpd_extractHeader(char const* s, struct lpd_protocolVersion*
int major = -1; int major = -1;
int minor = -1; int minor = -1;
size_t len = strlen(s);
/* something might be rotten with this chunk of data */ /* something might be rotten with this chunk of data */
if (auto len = strlen(s); len == 0 || len > lpd_maxDatagramLength) if (len == 0 || len > lpd_maxDatagramLength)
{ {
return nullptr; return nullptr;
} }

View File

@ -478,7 +478,7 @@ void tr_sessionSetLPDEnabled(tr_session* session, bool enabled);
void tr_sessionSetCacheLimit_MB(tr_session* session, int mb); void tr_sessionSetCacheLimit_MB(tr_session* session, int mb);
int tr_sessionGetCacheLimit_MB(tr_session const* session); int tr_sessionGetCacheLimit_MB(tr_session const* session);
tr_encryption_mode tr_sessionGetEncryption(tr_session const* session); tr_encryption_mode tr_sessionGetEncryption(tr_session* session);
void tr_sessionSetEncryption(tr_session* session, tr_encryption_mode mode); void tr_sessionSetEncryption(tr_session* session, tr_encryption_mode mode);
/*********************************************************************** /***********************************************************************

View File

@ -83,7 +83,8 @@ template<typename... T, typename std::enable_if_t<(std::is_convertible_v<T, std:
std::string& tr_buildBuf(std::string& setme, T... args) std::string& tr_buildBuf(std::string& setme, T... args)
{ {
setme.clear(); setme.clear();
if (auto const n = (std::size(std::string_view{ args }) + ...); setme.capacity() < n) auto const n = (std::size(std::string_view{ args }) + ...);
if (setme.capacity() < n)
{ {
setme.reserve(n); setme.reserve(n);
} }
@ -300,8 +301,8 @@ std::string tr_strvPath(T... args)
{ {
auto setme = std::string{}; auto setme = std::string{};
auto const n_args = sizeof...(args); auto const n_args = sizeof...(args);
auto const n = n_args + (std::size(std::string_view{ args }) + ...);
if (auto const n = n_args + (std::size(std::string_view{ args }) + ...); setme.capacity() < n) if (setme.capacity() < n)
{ {
setme.reserve(n); setme.reserve(n);
} }
@ -320,12 +321,11 @@ template<typename... T, typename std::enable_if_t<(std::is_convertible_v<T, std:
std::string tr_strvJoin(T... args) std::string tr_strvJoin(T... args)
{ {
auto setme = std::string{}; auto setme = std::string{};
auto const n = (std::size(std::string_view{ args }) + ...);
if (auto const n = (std::size(std::string_view{ args }) + ...); setme.capacity() < n) if (setme.capacity() < n)
{ {
setme.reserve(n); setme.reserve(n);
} }
((setme += args), ...); ((setme += args), ...);
return setme; return setme;
} }

View File

@ -59,7 +59,8 @@ std::optional<int64_t> ParseInt(std::string_view* benc)
// find the ending delimiter // find the ending delimiter
walk.remove_prefix(std::size(Prefix)); walk.remove_prefix(std::size(Prefix));
if (auto const pos = walk.find(Suffix); pos == std::string_view::npos) auto const pos = walk.find(Suffix);
if (pos == std::string_view::npos)
{ {
return {}; return {};
} }

View File

@ -448,13 +448,17 @@ static void jsonChildFunc(struct jsonWalk* data)
} }
case TR_VARIANT_TYPE_LIST: case TR_VARIANT_TYPE_LIST:
++pstate.childIndex;
if (bool const is_last = pstate.childIndex == pstate.childCount; !is_last)
{ {
evbuffer_add(data->out, ",", 1); ++pstate.childIndex;
jsonIndent(data); bool const is_last = pstate.childIndex == pstate.childCount;
if (!is_last)
{
evbuffer_add(data->out, ",", 1);
jsonIndent(data);
}
break;
} }
break;
default: default:
break; break;

View File

@ -354,7 +354,8 @@ bool tr_variantGetBool(tr_variant const* v, bool* setme)
return true; return true;
} }
if (auto sv = std::string_view{}; tr_variantGetStrView(v, &sv)) auto sv = std::string_view{};
if (tr_variantGetStrView(v, &sv))
{ {
if (sv == "true"sv) if (sv == "true"sv)
{ {
@ -503,7 +504,9 @@ static tr_variant* containerReserve(tr_variant* v, size_t count)
{ {
TR_ASSERT(tr_variantIsContainer(v)); TR_ASSERT(tr_variantIsContainer(v));
if (size_t const needed = v->val.l.count + count; needed > v->val.l.alloc) size_t const needed = v->val.l.count + count;
if (needed > v->val.l.alloc)
{ {
/* scale the alloc size in powers-of-2 */ /* scale the alloc size in powers-of-2 */
size_t n = v->val.l.alloc != 0 ? v->val.l.alloc : 8; size_t n = v->val.l.alloc != 0 ? v->val.l.alloc : 8;
@ -728,8 +731,9 @@ tr_variant* tr_variantDictSteal(tr_variant* dict, tr_quark const key, tr_variant
bool tr_variantDictRemove(tr_variant* dict, tr_quark const key) bool tr_variantDictRemove(tr_variant* dict, tr_quark const key)
{ {
bool removed = false; bool removed = false;
int const i = dictIndexOf(dict, key);
if (int const i = dictIndexOf(dict, key); i >= 0) if (i >= 0)
{ {
int const last = (int)dict->val.l.count - 1; int const last = (int)dict->val.l.count - 1;

View File

@ -304,7 +304,8 @@ std::optional<tr_url_parsed_t> tr_urlParse(std::string_view url)
// So many magnet links are malformed, e.g. not escaping text // So many magnet links are malformed, e.g. not escaping text
// in the display name, that we're better off handling magnets // in the display name, that we're better off handling magnets
// as a special case before even scanning for invalid chars. // as a special case before even scanning for invalid chars.
if (auto constexpr MagnetStart = "magnet:?"sv; tr_strvStartsWith(url, MagnetStart)) auto constexpr MagnetStart = "magnet:?"sv;
if (tr_strvStartsWith(url, MagnetStart))
{ {
parsed.scheme = "magnet"sv; parsed.scheme = "magnet"sv;
parsed.query = url.substr(std::size(MagnetStart)); parsed.query = url.substr(std::size(MagnetStart));

View File

@ -422,7 +422,8 @@ static void tr_webThreadFunc(void* vsession)
tr_logAddNamedInfo("web", "NB: invalid certs will show up as 'Could not connect to tracker' like many other errors"); tr_logAddNamedInfo("web", "NB: invalid certs will show up as 'Could not connect to tracker' like many other errors");
} }
if (auto const str = tr_strvPath(session->config_dir, "cookies.txt"); tr_sys_path_exists(str.c_str(), nullptr)) auto const str = tr_strvPath(session->config_dir, "cookies.txt");
if (tr_sys_path_exists(str.c_str(), nullptr))
{ {
web->cookie_filename = tr_strvDup(str); web->cookie_filename = tr_strvDup(str);
} }

View File

@ -213,7 +213,8 @@ static void write_block_func(void* vdata)
struct tr_webseed* const w = data->webseed; struct tr_webseed* const w = data->webseed;
struct evbuffer* const buf = data->content; struct evbuffer* const buf = data->content;
if (auto* const tor = tr_torrentFindFromId(data->session, data->torrent_id); tor != nullptr) auto* const tor = tr_torrentFindFromId(data->session, data->torrent_id);
if (tor != nullptr)
{ {
uint32_t const block_size = tor->blockSize(); uint32_t const block_size = tor->blockSize();
uint32_t len = evbuffer_get_length(buf); uint32_t len = evbuffer_get_length(buf);

View File

@ -175,7 +175,9 @@ Application::Application(int& argc, char** argv)
// try to delegate the work to an existing copy of Transmission // try to delegate the work to an existing copy of Transmission
// before starting ourselves... // before starting ourselves...
if (InteropHelper interop_client; interop_client.isConnected()) InteropHelper interop_client;
if (interop_client.isConnected())
{ {
bool delegated = false; bool delegated = false;
@ -603,7 +605,9 @@ void Application::raise() const
bool Application::notifyApp(QString const& title, QString const& body, QStringList const& actions) const bool Application::notifyApp(QString const& title, QString const& body, QStringList const& actions) const
{ {
#ifdef QT_DBUS_LIB #ifdef QT_DBUS_LIB
if (auto bus = QDBusConnection::sessionBus(); bus.isConnected()) QDBusConnection bus = QDBusConnection::sessionBus();
if (bus.isConnected())
{ {
QDBusMessage m = QDBusMessage::createMethodCall( QDBusMessage m = QDBusMessage::createMethodCall(
fdo_notifications_service_name_, fdo_notifications_service_name_,
@ -629,6 +633,7 @@ bool Application::notifyApp(QString const& title, QString const& body, QStringLi
return true; return true;
} }
} }
#endif #endif
window_->trayIcon().showMessage(title, body); window_->trayIcon().showMessage(title, body);

View File

@ -39,7 +39,8 @@ void DBusInteropHelper::registerObject(QObject* parent)
return; return;
} }
if (auto const service_name = QStringLiteral("com.transmissionbt.Transmission"); !bus.registerService(service_name)) auto const service_name = QStringLiteral("com.transmissionbt.Transmission");
if (!bus.registerService(service_name))
{ {
qWarning() << "couldn't register" << qPrintable(service_name); qWarning() << "couldn't register" << qPrintable(service_name);
} }

View File

@ -84,7 +84,8 @@ QString collateAddress(QString const& address)
{ {
QString collated; QString collated;
if (QHostAddress ip_address; ip_address.setAddress(address)) QHostAddress ip_address;
if (ip_address.setAddress(address))
{ {
if (ip_address.protocol() == QAbstractSocket::IPv4Protocol) if (ip_address.protocol() == QAbstractSocket::IPv4Protocol)
{ {

View File

@ -108,7 +108,8 @@ void FaviconCache::ensureCacheDirHasBeenScanned()
// remember which hosts we've asked for a favicon so that we // remember which hosts we've asked for a favicon so that we
// don't re-ask them every time we start a new session // don't re-ask them every time we start a new session
if (auto skip_file = QFile(getScrapedFile()); skip_file.open(QIODevice::ReadOnly | QIODevice::Text)) auto skip_file = QFile(getScrapedFile());
if (skip_file.open(QIODevice::ReadOnly | QIODevice::Text))
{ {
while (!skip_file.atEnd()) while (!skip_file.atEnd())
{ {
@ -182,7 +183,8 @@ FaviconCache::Key FaviconCache::add(QString const& url_str)
ensureCacheDirHasBeenScanned(); ensureCacheDirHasBeenScanned();
// find or add this url's key // find or add this url's key
if (auto k_it = keys_.find(url_str); k_it != keys_.end()) auto k_it = keys_.find(url_str);
if (k_it != keys_.end())
{ {
return k_it->second; return k_it->second;
} }

View File

@ -57,7 +57,9 @@ FileTreeItem* FileTreeItem::child(QString const& filename)
{ {
FileTreeItem* item(nullptr); FileTreeItem* item(nullptr);
if (int const row = getMyChildRows().value(filename, -1); row != -1) int const row = getMyChildRows().value(filename, -1);
if (row != -1)
{ {
item = child(row); item = child(row);
assert(filename == item->name()); assert(filename == item->name());

View File

@ -173,7 +173,9 @@ void FileTreeView::mouseDoubleClickEvent(QMouseEvent* event)
void FileTreeView::contextMenuEvent(QContextMenuEvent* event) void FileTreeView::contextMenuEvent(QContextMenuEvent* event)
{ {
if (auto const root_index = model_->index(0, 0); !root_index.isValid()) QModelIndex const root_index = model_->index(0, 0);
if (!root_index.isValid())
{ {
return; return;
} }

View File

@ -83,7 +83,9 @@ void FilterBarComboBox::paintEvent(QPaintEvent* e)
painter.drawComplexControl(QStyle::CC_ComboBox, opt); painter.drawComplexControl(QStyle::CC_ComboBox, opt);
// draw the icon and text // draw the icon and text
if (auto const model_index = model()->index(currentIndex(), 0, rootModelIndex()); model_index.isValid()) QModelIndex const model_index = model()->index(currentIndex(), 0, rootModelIndex());
if (model_index.isValid())
{ {
QStyle* s = style(); QStyle* s = style();
int const hmargin = getHSpacing(this); int const hmargin = getHSpacing(this);

View File

@ -76,7 +76,8 @@ void FreeSpaceLabel::onTimer()
[this](RpcResponse const& r) [this](RpcResponse const& r)
{ {
// update the label // update the label
if (auto const bytes = dictFind<int64_t>(r.args.get(), TR_KEY_size_bytes); bytes && *bytes > 1) auto const bytes = dictFind<int64_t>(r.args.get(), TR_KEY_size_bytes);
if (bytes && *bytes > 1)
{ {
setText(tr("%1 free").arg(Formatter::get().sizeToString(*bytes))); setText(tr("%1 free").arg(Formatter::get().sizeToString(*bytes)));
} }

View File

@ -22,7 +22,9 @@ bool InteropObject::PresentWindow() const
// NOLINTNEXTLINE(readability-identifier-naming) // NOLINTNEXTLINE(readability-identifier-naming)
bool InteropObject::AddMetainfo(QString const& metainfo) const bool InteropObject::AddMetainfo(QString const& metainfo) const
{ {
if (AddData addme(metainfo); addme.type != addme.NONE) AddData addme(metainfo);
if (addme.type != addme.NONE)
{ {
trApp->addTorrent(addme); trApp->addTorrent(addme);
} }

View File

@ -658,8 +658,9 @@ void MainWindow::openFolder()
} }
QString const first_file = files.at(0).filename; QString const first_file = files.at(0).filename;
int slash_index = first_file.indexOf(QLatin1Char('/'));
if (int slash_index = first_file.indexOf(QLatin1Char('/')); slash_index > -1) if (slash_index > -1)
{ {
path = path + QLatin1Char('/') + first_file.left(slash_index); path = path + QLatin1Char('/') + first_file.left(slash_index);
} }

View File

@ -216,7 +216,9 @@ void MakeDialog::onSourceChanged()
{ {
builder_.reset(); builder_.reset();
if (auto const filename = getSource(); !filename.isEmpty()) QString const filename = getSource();
if (!filename.isEmpty())
{ {
builder_.reset(tr_metaInfoBuilderCreate(filename.toUtf8().constData())); builder_.reset(tr_metaInfoBuilderCreate(filename.toUtf8().constData()));
} }

View File

@ -112,7 +112,9 @@ void PathButton::onClicked() const
dialog->setNameFilter(name_filter_); dialog->setNameFilter(name_filter_);
} }
if (QFileInfo const path_info(path_); !path_.isEmpty() && path_info.exists()) QFileInfo const path_info(path_);
if (!path_.isEmpty() && path_info.exists())
{ {
if (path_info.isDir()) if (path_info.isDir())
{ {

View File

@ -38,8 +38,8 @@ namespace
void ensureSoundCommandIsAList(tr_variant* dict) void ensureSoundCommandIsAList(tr_variant* dict)
{ {
tr_quark key = TR_KEY_torrent_complete_sound_command; tr_quark key = TR_KEY_torrent_complete_sound_command;
tr_variant* list = nullptr;
if (tr_variant* list = nullptr; tr_variantDictFindList(dict, key, &list)) if (tr_variantDictFindList(dict, key, &list))
{ {
return; return;
} }
@ -507,8 +507,9 @@ bool Prefs::getBool(int key) const
QString Prefs::getString(int key) const QString Prefs::getString(int key) const
{ {
assert(Items[key].type == QVariant::String); assert(Items[key].type == QVariant::String);
QByteArray const b = values_[key].toByteArray();
if (auto const b = values_[key].toByteArray(); isValidUtf8(b.constData())) if (isValidUtf8(b.constData()))
{ {
values_[key].setValue(QString::fromUtf8(b.constData())); values_[key].setValue(QString::fromUtf8(b.constData()));
} }

View File

@ -206,31 +206,36 @@ void PrefsDialog::linkWidgetToPref(QWidget* widget, int pref_key)
updateWidgetValue(widget, pref_key); updateWidgetValue(widget, pref_key);
widgets_.insert(pref_key, widget); widgets_.insert(pref_key, widget);
if (auto const* check_box = qobject_cast<QCheckBox*>(widget); check_box != nullptr) auto const* check_box = qobject_cast<QCheckBox*>(widget);
if (check_box != nullptr)
{ {
connect(check_box, &QAbstractButton::toggled, this, &PrefsDialog::checkBoxToggled); connect(check_box, &QAbstractButton::toggled, this, &PrefsDialog::checkBoxToggled);
return; return;
} }
if (auto const* time_edit = qobject_cast<QTimeEdit*>(widget); time_edit != nullptr) auto const* time_edit = qobject_cast<QTimeEdit*>(widget);
if (time_edit != nullptr)
{ {
connect(time_edit, &QAbstractSpinBox::editingFinished, this, &PrefsDialog::timeEditingFinished); connect(time_edit, &QAbstractSpinBox::editingFinished, this, &PrefsDialog::timeEditingFinished);
return; return;
} }
if (auto const* line_edit = qobject_cast<QLineEdit*>(widget); line_edit != nullptr) auto const* line_edit = qobject_cast<QLineEdit*>(widget);
if (line_edit != nullptr)
{ {
connect(line_edit, &QLineEdit::editingFinished, this, &PrefsDialog::lineEditingFinished); connect(line_edit, &QLineEdit::editingFinished, this, &PrefsDialog::lineEditingFinished);
return; return;
} }
if (auto const* path_button = qobject_cast<PathButton*>(widget); path_button != nullptr) auto const* path_button = qobject_cast<PathButton*>(widget);
if (path_button != nullptr)
{ {
connect(path_button, &PathButton::pathChanged, this, &PrefsDialog::pathChanged); connect(path_button, &PathButton::pathChanged, this, &PrefsDialog::pathChanged);
return; return;
} }
if (auto const* spin_box = qobject_cast<QAbstractSpinBox*>(widget); spin_box != nullptr) auto const* spin_box = qobject_cast<QAbstractSpinBox*>(widget);
if (spin_box != nullptr)
{ {
connect(spin_box, &QAbstractSpinBox::editingFinished, this, &PrefsDialog::spinBoxEditingFinished); connect(spin_box, &QAbstractSpinBox::editingFinished, this, &PrefsDialog::spinBoxEditingFinished);
} }
@ -276,7 +281,9 @@ void PrefsDialog::lineEditingFinished()
if (pref_widget.is<QLineEdit>()) if (pref_widget.is<QLineEdit>())
{ {
if (auto const* const line_edit = pref_widget.as<QLineEdit>(); line_edit->isModified()) auto const* const line_edit = pref_widget.as<QLineEdit>();
if (line_edit->isModified())
{ {
setPref(pref_widget.getPrefKey(), line_edit->text()); setPref(pref_widget.getPrefKey(), line_edit->text());
} }
@ -674,7 +681,9 @@ void PrefsDialog::setPref(int key, QVariant const& v)
void PrefsDialog::sessionUpdated() void PrefsDialog::sessionUpdated()
{ {
if (bool const is_local = session_.isLocal(); is_local_ != is_local) bool const is_local = session_.isLocal();
if (is_local_ != is_local)
{ {
is_local_ = is_local; is_local_ = is_local;
updateDownloadingWidgetsLocality(); updateDownloadingWidgetsLocality();

View File

@ -301,13 +301,16 @@ RpcResponse RpcClient::parseResponseData(tr_variant& json) const
{ {
RpcResponse ret; RpcResponse ret;
if (auto const result = dictFind<QString>(&json, TR_KEY_result); result) auto const result = dictFind<QString>(&json, TR_KEY_result);
if (result)
{ {
ret.result = *result; ret.result = *result;
ret.success = *result == QStringLiteral("success"); ret.success = *result == QStringLiteral("success");
} }
if (tr_variant * args; tr_variantDictFindDict(&json, TR_KEY_arguments, &args)) tr_variant* args;
if (tr_variantDictFindDict(&json, TR_KEY_arguments, &args))
{ {
ret.args = createVariant(); ret.args = createVariant();
*ret.args = *args; *ret.args = *args;

View File

@ -199,21 +199,26 @@ void Session::updatePref(int key)
break; break;
case Prefs::ENCRYPTION: case Prefs::ENCRYPTION:
switch (int const i = prefs_.variant(key).toInt(); i)
{ {
case 0: int const i = prefs_.variant(key).toInt();
sessionSet(prefs_.getKey(key), QStringLiteral("tolerated"));
break;
case 1: switch (i)
sessionSet(prefs_.getKey(key), QStringLiteral("preferred")); {
break; case 0:
sessionSet(prefs_.getKey(key), QStringLiteral("tolerated"));
break;
case 1:
sessionSet(prefs_.getKey(key), QStringLiteral("preferred"));
break;
case 2:
sessionSet(prefs_.getKey(key), QStringLiteral("required"));
break;
}
case 2:
sessionSet(prefs_.getKey(key), QStringLiteral("required"));
break; break;
} }
break;
case Prefs::RPC_AUTH_REQUIRED: case Prefs::RPC_AUTH_REQUIRED:
if (session_ != nullptr) if (session_ != nullptr)
@ -902,46 +907,68 @@ void Session::updateInfo(tr_variant* d)
switch (prefs_.type(i)) switch (prefs_.type(i))
{ {
case QVariant::Int: case QVariant::Int:
if (auto const value = getValue<int>(b); value)
{ {
prefs_.set(i, *value); auto const value = getValue<int>(b);
if (value)
{
prefs_.set(i, *value);
}
break;
} }
break;
case QVariant::Double: case QVariant::Double:
if (auto const value = getValue<double>(b); value)
{ {
prefs_.set(i, *value); auto const value = getValue<double>(b);
if (value)
{
prefs_.set(i, *value);
}
break;
} }
break;
case QVariant::Bool: case QVariant::Bool:
if (auto const value = getValue<bool>(b); value)
{ {
prefs_.set(i, *value); auto const value = getValue<bool>(b);
if (value)
{
prefs_.set(i, *value);
}
break;
} }
break;
case CustomVariantType::FilterModeType: case CustomVariantType::FilterModeType:
case CustomVariantType::SortModeType: case CustomVariantType::SortModeType:
case QVariant::String: case QVariant::String:
if (auto const value = getValue<QString>(b); value)
{ {
prefs_.set(i, *value); auto const value = getValue<QString>(b);
if (value)
{
prefs_.set(i, *value);
}
break;
} }
break;
default: default:
break; break;
} }
} }
if (auto const b = dictFind<bool>(d, TR_KEY_seedRatioLimited); b) auto const b = dictFind<bool>(d, TR_KEY_seedRatioLimited);
if (b)
{ {
prefs_.set(Prefs::RATIO_ENABLED, *b); prefs_.set(Prefs::RATIO_ENABLED, *b);
} }
if (auto const x = dictFind<double>(d, TR_KEY_seedRatioLimit); x) auto const x = dictFind<double>(d, TR_KEY_seedRatioLimit);
if (x)
{ {
prefs_.set(Prefs::RATIO, *x); prefs_.set(Prefs::RATIO, *x);
} }

View File

@ -32,8 +32,8 @@ template<typename T, typename std::enable_if_t<std::is_same_v<T, bool>>* = nullp
auto getValue(tr_variant const* variant) auto getValue(tr_variant const* variant)
{ {
std::optional<T> ret; std::optional<T> ret;
auto value = T{};
if (auto value = T{}; tr_variantGetBool(variant, &value)) if (tr_variantGetBool(variant, &value))
{ {
ret = value; ret = value;
} }
@ -49,8 +49,8 @@ template<
auto getValue(tr_variant const* variant) auto getValue(tr_variant const* variant)
{ {
std::optional<T> ret; std::optional<T> ret;
auto value = int64_t{};
if (auto value = int64_t{}; tr_variantGetInt(variant, &value)) if (tr_variantGetInt(variant, &value))
{ {
ret = value; ret = value;
} }
@ -62,8 +62,8 @@ template<typename T, typename std::enable_if_t<std::is_same_v<T, double>>* = nul
auto getValue(tr_variant const* variant) auto getValue(tr_variant const* variant)
{ {
std::optional<T> ret; std::optional<T> ret;
auto value = T{};
if (auto value = T{}; tr_variantGetReal(variant, &value)) if (tr_variantGetReal(variant, &value))
{ {
ret = value; ret = value;
} }

View File

@ -544,7 +544,8 @@ static bool UseSSL = false;
static std::string getEncodedMetainfo(char const* filename) static std::string getEncodedMetainfo(char const* filename)
{ {
if (auto contents = std::vector<char>{}; tr_loadFile(contents, filename)) auto contents = std::vector<char>{};
if (tr_loadFile(contents, filename))
{ {
return tr_base64_encode({ std::data(contents), std::size(contents) }); return tr_base64_encode({ std::data(contents), std::size(contents) });
} }
@ -2157,7 +2158,8 @@ static int flush(char const* rpcurl, tr_variant** benc)
fprintf(stderr, "posting:\n--------\n%s\n--------\n", json.c_str()); fprintf(stderr, "posting:\n--------\n%s\n--------\n", json.c_str());
} }
if (auto const res = curl_easy_perform(curl); res != CURLE_OK) auto const res = curl_easy_perform(curl);
if (res != CURLE_OK)
{ {
tr_logAddNamedError(MyName, " (%s) %s", rpcurl_http.c_str(), curl_easy_strerror(res)); tr_logAddNamedError(MyName, " (%s) %s", rpcurl_http.c_str(), curl_easy_strerror(res));
status |= EXIT_FAILURE; status |= EXIT_FAILURE;