refactor: sonarcloud "use if init" statements (#2587)

This commit is contained in:
Charles Kerr 2022-02-07 23:44:31 -06:00 committed by GitHub
parent 8afbfecadb
commit ba14ffa74c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 126 additions and 163 deletions

View File

@ -475,52 +475,51 @@ void FileList::Impl::set_torrent(int torrentId)
torrent_id_ = torrentId;
/* populate the model */
auto* const tor = torrent_id_ > 0 ? core_->find_torrent(torrent_id_) : nullptr;
if (tor != nullptr)
{
// build a GNode tree of the files
FileRowNode root;
auto& root_data = root.data();
root_data.name = tr_torrentName(tor);
root_data.index = -1;
root_data.length = 0;
for (tr_file_index_t i = 0, n_files = tr_torrentFileCount(tor); i < n_files; ++i)
{
auto* parent = &root;
auto const file = tr_torrentFile(tor, i);
for (char const *last = file.name, *next = strchr(last, '/'); last != nullptr;
last = next != nullptr ? next + 1 : nullptr, next = last != nullptr ? strchr(last, '/') : nullptr)
{
bool const isLeaf = next == nullptr;
auto name = Glib::ustring(isLeaf ? last : std::string(last, next - last));
auto* node = find_child(parent, name);
if (node == nullptr)
{
node = new FileRowNode();
auto& row = node->data();
row.name = std::move(name);
row.index = isLeaf ? (int)i : -1;
row.length = isLeaf ? file.length : 0;
parent->append(*node);
}
parent = node;
}
}
// now, add them to the model
struct build_data build;
build.w = &widget_;
build.tor = tor;
build.store = store_;
root.foreach ([&build](auto& child_node) { buildTree(child_node, build); }, FileRowNode::TRAVERSE_ALL);
}
if (torrent_id_ > 0)
{
if (auto* const tor = core_->find_torrent(torrent_id_); tor != nullptr)
{
// build a GNode tree of the files
FileRowNode root;
auto& root_data = root.data();
root_data.name = tr_torrentName(tor);
root_data.index = -1;
root_data.length = 0;
for (tr_file_index_t i = 0, n_files = tr_torrentFileCount(tor); i < n_files; ++i)
{
auto* parent = &root;
auto const file = tr_torrentFile(tor, i);
for (char const *last = file.name, *next = strchr(last, '/'); last != nullptr;
last = next != nullptr ? next + 1 : nullptr, next = last != nullptr ? strchr(last, '/') : nullptr)
{
bool const isLeaf = next == nullptr;
auto name = Glib::ustring(isLeaf ? last : std::string(last, next - last));
auto* node = find_child(parent, name);
if (node == nullptr)
{
node = new FileRowNode();
auto& row = node->data();
row.name = std::move(name);
row.index = isLeaf ? (int)i : -1;
row.length = isLeaf ? file.length : 0;
parent->append(*node);
}
parent = node;
}
}
// now, add them to the model
struct build_data build;
build.w = &widget_;
build.tor = tor;
build.store = store_;
root.foreach ([&build](auto& child_node) { buildTree(child_node, build); }, FileRowNode::TRAVERSE_ALL);
}
refresh();
timeout_tag_ = Glib::signal_timeout().connect_seconds(
[this]() { return refresh(), true; },
@ -593,9 +592,8 @@ std::string buildFilename(tr_torrent const* tor, Gtk::TreeModel::iterator const&
void FileList::Impl::onRowActivated(Gtk::TreeModel::Path const& path, Gtk::TreeViewColumn* /*col*/)
{
bool handled = false;
auto const* tor = core_->find_torrent(torrent_id_);
if (tor != nullptr)
if (auto const* tor = core_->find_torrent(torrent_id_); tor != nullptr)
{
if (auto const iter = store_->get_iter(path); iter)
{

View File

@ -95,10 +95,9 @@ auto const IdleDataKey = Glib::Quark("idle-data");
bool spun_cb_idle(Gtk::SpinButton* spin, tr_quark const key, Glib::RefPtr<Session> const& core, bool isDouble)
{
bool keep_waiting = true;
auto* last_change = static_cast<Glib::Timer*>(spin->get_data(IdleDataKey));
/* has the user stopped making changes? */
if (last_change->elapsed() > 0.33)
if (auto* last_change = static_cast<Glib::Timer*>(spin->get_data(IdleDataKey)); last_change->elapsed() > 0.33)
{
/* update the core */
if (isDouble)

View File

@ -271,29 +271,25 @@ bool is_valid_eta(int t)
int compare_eta(int a, int b)
{
int ret;
bool const a_valid = is_valid_eta(a);
bool const b_valid = is_valid_eta(b);
if (!a_valid && !b_valid)
{
ret = 0;
}
else if (!a_valid)
{
ret = -1;
}
else if (!b_valid)
{
ret = 1;
}
else
{
ret = a < b ? 1 : -1;
return 0;
}
return ret;
if (!a_valid)
{
return -1;
}
if (!b_valid)
{
return 1;
}
return a < b ? 1 : -1;
}
int compare_double(double a, double b)
@ -1319,24 +1315,20 @@ namespace
int gtr_compare_double(double const a, double const b, int decimal_places)
{
int ret;
auto const ia = int64_t(a * pow(10, decimal_places));
auto const ib = int64_t(b * pow(10, decimal_places));
if (ia < ib)
{
ret = -1;
}
else if (ia > ib)
{
ret = 1;
}
else
{
ret = 0;
return -1;
}
return ret;
if (ia > ib)
{
return 1;
}
return 0;
}
void update_foreach(Gtk::TreeModel::Row const& row)

View File

@ -143,33 +143,31 @@ Glib::ustring getShortTransferString(
double uploadSpeed_KBps,
double downloadSpeed_KBps)
{
Glib::ustring buf;
bool const haveMeta = tr_torrentHasMetadata(tor);
bool const haveUp = haveMeta && st->peersGettingFromUs > 0;
bool const haveDown = haveMeta && (st->peersSendingToUs > 0 || st->webseedsSendingToUs > 0);
if (haveDown)
if (bool const haveDown = haveMeta && (st->peersSendingToUs > 0 || st->webseedsSendingToUs > 0); haveDown)
{
/* down speed, down symbol, up speed, up symbol */
buf += gtr_sprintf(
return gtr_sprintf(
_("%1$s %2$s %3$s %4$s"),
tr_formatter_speed_KBps(downloadSpeed_KBps),
gtr_get_unicode_string(GTR_UNICODE_DOWN),
tr_formatter_speed_KBps(uploadSpeed_KBps),
gtr_get_unicode_string(GTR_UNICODE_UP));
}
else if (haveUp)
if (bool const haveUp = haveMeta && st->peersGettingFromUs > 0; haveUp)
{
/* up speed, up symbol */
buf += gtr_sprintf(_("%1$s %2$s"), tr_formatter_speed_KBps(uploadSpeed_KBps), gtr_get_unicode_string(GTR_UNICODE_UP));
}
else if (st->isStalled)
{
buf += _("Stalled");
return gtr_sprintf(_("%1$s %2$s"), tr_formatter_speed_KBps(uploadSpeed_KBps), gtr_get_unicode_string(GTR_UNICODE_UP));
}
return buf;
if (st->isStalled)
{
return _("Stalled");
}
return {};
}
Glib::ustring getShortStatusString(tr_torrent const* tor, tr_stat const* st, double uploadSpeed_KBps, double downloadSpeed_KBps)

View File

@ -56,8 +56,7 @@ 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)
{
auto const announce = tr_urlParseTracker(announce_url_sv);
if (!announce || !canAdd(*announce))
if (auto const announce = tr_urlParseTracker(announce_url_sv); !announce || !canAdd(*announce))
{
return false;
}

View File

@ -337,9 +337,14 @@ static int compareAddressRangesByFirstAddress(void const* va, void const* vb)
auto const* a = static_cast<struct tr_ipv4_range const*>(va);
auto const* b = static_cast<struct tr_ipv4_range const*>(vb);
if (a->begin != b->begin)
if (a->begin < b->begin)
{
return a->begin < b->begin ? -1 : 1;
return -1;
}
if (a->begin > b->begin)
{
return 1;
}
return 0;

View File

@ -356,9 +356,8 @@ int tr_cacheReadBlock(
uint8_t* setme)
{
int err = 0;
struct cache_block* cb = findBlock(cache, torrent, piece, offset);
if (cb != nullptr)
if (auto* const cb = findBlock(cache, torrent, piece, offset); cb != nullptr)
{
evbuffer_copyout(cb->evbuf, setme, len);
}
@ -373,9 +372,8 @@ int tr_cacheReadBlock(
int tr_cachePrefetchBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t piece, uint32_t offset, uint32_t len)
{
int err = 0;
struct cache_block const* const cb = findBlock(cache, torrent, piece, offset);
if (cb == nullptr)
if (auto const* const cb = findBlock(cache, torrent, piece, offset); cb == nullptr)
{
err = tr_ioPrefetch(torrent, piece, offset, len);
}

View File

@ -257,8 +257,7 @@ static handshake_parse_err_t parseHandshake(tr_handshake* handshake, struct evbu
/* peer id */
dbgmsg(handshake, "peer-id is [%" TR_PRIsv "]", TR_PRIsv_ARG(peer_id));
auto* const tor = handshake->session->getTorrent(hash);
if (peer_id == tr_torrentGetPeerId(tor))
if (auto* const tor = handshake->session->getTorrent(hash); peer_id == tr_torrentGetPeerId(tor))
{
dbgmsg(handshake, "streuth! we've connected to ourselves.");
return HANDSHAKE_PEER_IS_SELF;
@ -855,9 +854,8 @@ static ReadState readCryptoProvide(tr_handshake* handshake, struct evbuffer* inb
static ReadState readPadC(tr_handshake* handshake, struct evbuffer* inbuf)
{
uint16_t ia_len = 0;
size_t const needlen = handshake->pad_c_len + sizeof(uint16_t);
if (evbuffer_get_length(inbuf) < needlen)
if (auto const needlen = handshake->pad_c_len + sizeof(uint16_t); evbuffer_get_length(inbuf) < needlen)
{
return READ_LATER;
}

View File

@ -2402,12 +2402,11 @@ static void closePeer(tr_peer* peer)
{
TR_ASSERT(peer != nullptr);
auto* const s = peer->swarm;
peer_atom* const atom = peer->atom;
/* if we transferred piece data, then they might be good peers,
so reset their `numFails' weight to zero. otherwise we connected
to them fruitlessly, so mark it as another fail */
if (atom->piece_data_time != 0)
if (auto* const atom = peer->atom; atom->piece_data_time != 0)
{
tordbg(s, "resetting atom %s numFails to 0", tr_atomAddrStr(atom));
atom->numFails = 0;

View File

@ -2127,11 +2127,10 @@ static size_t fillOutputBuffer(tr_peerMsgsImpl* msgs, time_t now)
auto ok = bool{ false };
auto dataLen = size_t{};
auto* data = static_cast<char*>(tr_torrentGetMetadataPiece(msgs->torrent, piece, &dataLen));
if (data != nullptr)
if (auto* data = static_cast<char*>(tr_torrentGetMetadataPiece(msgs->torrent, piece, &dataLen)); data != nullptr)
{
evbuffer* const out = msgs->outMessages;
auto* const out = msgs->outMessages;
/* build the data message */
auto tmp = tr_variant{};

View File

@ -269,8 +269,7 @@ static std::string getXdgEntryFromUserDirs(std::string_view key)
// if val contains "$HOME", replace that with getHomeDir()
auto constexpr Home = "$HOME"sv;
auto const it = std::search(std::begin(val), std::end(val), std::begin(Home), std::end(Home));
if (it != std::end(val))
if (auto const it = std::search(std::begin(val), std::end(val), std::begin(Home), std::end(Home)); it != std::end(val))
{
val.replace(it, it + std::size(Home), std::string_view{ getHomeDir() });
}
@ -284,8 +283,7 @@ char const* tr_getDefaultDownloadDir()
if (user_dir == nullptr)
{
auto const xdg_user_dir = getXdgEntryFromUserDirs("XDG_DOWNLOAD_DIR"sv);
if (!std::empty(xdg_user_dir))
if (auto const xdg_user_dir = getXdgEntryFromUserDirs("XDG_DOWNLOAD_DIR"sv); !std::empty(xdg_user_dir))
{
user_dir = tr_strvDup(xdg_user_dir);
}

View File

@ -573,9 +573,7 @@ static uint64_t loadProgress(tr_variant* dict, tr_torrent* tor)
auto blocks = tr_bitfield{ tor->blockCount() };
char const* err = nullptr;
auto sv = std::string_view{};
tr_variant const* const b = tr_variantDictFind(prog, TR_KEY_blocks);
if (b != nullptr)
if (tr_variant const* const b = tr_variantDictFind(prog, TR_KEY_blocks); b != nullptr)
{
uint8_t const* buf = nullptr;
auto buflen = size_t{};
@ -589,7 +587,7 @@ static uint64_t loadProgress(tr_variant* dict, tr_torrent* tor)
rawToBitfield(blocks, buf, buflen);
}
}
else if (tr_variantDictFindStrView(prog, TR_KEY_have, &sv))
else if (auto sv = std::string_view{}; tr_variantDictFindStrView(prog, TR_KEY_have, &sv))
{
if (sv == "all"sv)
{

View File

@ -237,8 +237,7 @@ static void handle_web_client(struct evhttp_request* req, tr_rpc_server* server)
{
// TODO: string_view
char* const subpath = tr_strdup(req->uri + std::size(server->url) + 4);
char* pch = strchr(subpath, '?');
if (pch != nullptr)
if (char* pch = strchr(subpath, '?'); pch != nullptr)
{
*pch = '\0';
}

View File

@ -1316,8 +1316,7 @@ static char const* torrentRenamePath(
auto newname = std::string_view{};
(void)tr_variantDictFindStrView(args_in, TR_KEY_name, &newname);
auto const torrents = getTorrents(session, args_in);
if (std::size(torrents) == 1)
if (auto const torrents = getTorrents(session, args_in); std::size(torrents) == 1)
{
torrents[0]->renamePath(oldpath, newname, torrentRenamePathDone, idle_data);
}
@ -2265,8 +2264,7 @@ static void addSessionField(tr_session* s, tr_variant* d, tr_quark key)
static char const* sessionGet(tr_session* s, tr_variant* args_in, tr_variant* args_out, tr_rpc_idle_data* /*idle_data*/)
{
tr_variant* fields = nullptr;
if (tr_variantDictFindList(args_in, TR_KEY_fields, &fields))
if (tr_variant* fields = nullptr; tr_variantDictFindList(args_in, TR_KEY_fields, &fields))
{
size_t const field_count = tr_variantListSize(fields);
@ -2427,8 +2425,7 @@ void tr_rpc_request_exec_json(
tr_variantDictAddDict(&response, TR_KEY_arguments, 0);
tr_variantDictAddStr(&response, TR_KEY_result, result);
auto tag = int64_t{};
if (tr_variantDictFindInt(mutable_request, TR_KEY_tag, &tag))
if (auto tag = int64_t{}; tr_variantDictFindInt(mutable_request, TR_KEY_tag, &tag))
{
tr_variantDictAddInt(&response, TR_KEY_tag, tag);
}
@ -2451,8 +2448,7 @@ void tr_rpc_request_exec_json(
tr_variantDictAddStr(&response, TR_KEY_result, result);
auto tag = int64_t{};
if (tr_variantDictFindInt(mutable_request, TR_KEY_tag, &tag))
if (auto tag = int64_t{}; tr_variantDictFindInt(mutable_request, TR_KEY_tag, &tag))
{
tr_variantDictAddInt(&response, TR_KEY_tag, tag);
}
@ -2468,8 +2464,7 @@ void tr_rpc_request_exec_json(
data->response = tr_new0(tr_variant, 1);
tr_variantInitDict(data->response, 3);
auto tag = int64_t{};
if (tr_variantDictFindInt(mutable_request, TR_KEY_tag, &tag))
if (auto tag = int64_t{}; tr_variantDictFindInt(mutable_request, TR_KEY_tag, &tag))
{
tr_variantDictAddInt(data->response, TR_KEY_tag, tag);
}

View File

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

View File

@ -140,9 +140,8 @@ void* tr_torrentGetMetadataPiece(tr_torrent const* tor, int piece, size_t* len)
if (0 < l && l <= METADATA_PIECE_SIZE)
{
auto* buf = tr_new(char, l);
auto n = uint64_t{};
if (tr_sys_file_read(fd, buf, l, &n, nullptr) && n == l)
if (auto n = uint64_t{}; tr_sys_file_read(fd, buf, l, &n, nullptr) && n == l)
{
*len = l;
ret = buf;
@ -274,8 +273,7 @@ static bool useNewMetainfo(tr_torrent* tor, tr_incomplete_metadata const* m, tr_
}
// save it
auto const filename = tor->torrentFile();
if (!tr_saveFile(filename, benc, error))
if (auto const filename = tor->torrentFile(); !tr_saveFile(filename, benc, error))
{
return false;
}

View File

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

View File

@ -107,8 +107,7 @@ static void bootstrap_from_name(char const* name, tr_port port, int af)
tr_snprintf(pp, sizeof(pp), "%d", (int)port);
addrinfo* info = nullptr;
int const rc = getaddrinfo(name, pp, &hints, &info);
if (rc != 0)
if (int const rc = getaddrinfo(name, pp, &hints, &info); rc != 0)
{
tr_logAddNamedError("DHT", "%s:%s: %s", name, pp, gai_strerror(rc));
return;

View File

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

View File

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

View File

@ -450,8 +450,7 @@ static void jsonChildFunc(struct jsonWalk* data)
case TR_VARIANT_TYPE_LIST:
{
++pstate.childIndex;
bool const is_last = pstate.childIndex == pstate.childCount;
if (!is_last)
if (bool const is_last = pstate.childIndex == pstate.childCount; !is_last)
{
evbuffer_add(data->out, ",", 1);
jsonIndent(data);

View File

@ -354,8 +354,7 @@ bool tr_variantGetBool(tr_variant const* v, bool* setme)
return true;
}
auto sv = std::string_view{};
if (tr_variantGetStrView(v, &sv))
if (auto sv = std::string_view{}; tr_variantGetStrView(v, &sv))
{
if (sv == "true"sv)
{
@ -731,9 +730,8 @@ tr_variant* tr_variantDictSteal(tr_variant* dict, tr_quark const key, tr_variant
bool tr_variantDictRemove(tr_variant* dict, tr_quark const key)
{
bool removed = false;
int const i = dictIndexOf(dict, key);
if (i >= 0)
if (int const i = dictIndexOf(dict, key); i >= 0)
{
int const last = (int)dict->val.l.count - 1;

View File

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

View File

@ -82,10 +82,9 @@ int measureViewItem(QTreeWidget const* view, int column, QString const& text)
QString collateAddress(QString const& address)
{
QString collated;
auto collated = QString{};
QHostAddress ip_address;
if (ip_address.setAddress(address))
if (auto ip_address = QHostAddress{}; ip_address.setAddress(address))
{
if (ip_address.protocol() == QAbstractSocket::IPv4Protocol)
{

View File

@ -332,14 +332,14 @@ void FileTreeModel::addFile(
while (filename_it.hasNext())
{
QString const& token = filename_it.next();
std::pair<int, int> const changed = item->update(token, wanted, priority, have, update_fields);
auto const& token = filename_it.next();
auto const& [first_col, last_col] = item->update(token, wanted, priority, have, update_fields);
if (changed.first >= 0)
if (first_col >= 0)
{
emit dataChanged(indexOf(item, changed.first), indexOf(item, changed.second));
emit dataChanged(indexOf(item, first_col), indexOf(item, last_col));
if (!index_with_changed_parents.isValid() && changed.first <= COL_PRIORITY && changed.second >= COL_SIZE)
if (!index_with_changed_parents.isValid() && first_col <= COL_PRIORITY && last_col >= COL_SIZE)
{
index_with_changed_parents = indexOf(item, 0);
}
@ -398,11 +398,11 @@ void FileTreeModel::addFile(
index_cache_[file_index] = item;
std::pair<int, int> const changed = item->update(item->name(), wanted, priority, have, added || update_fields);
auto const [first_col, last_col] = item->update(item->name(), wanted, priority, have, added || update_fields);
if (changed.first >= 0)
if (first_col >= 0)
{
emit dataChanged(indexOf(item, changed.first), indexOf(item, changed.second));
emit dataChanged(indexOf(item, first_col), indexOf(item, last_col));
}
}
}

View File

@ -156,7 +156,7 @@ void FileTreeView::keyPressEvent(QKeyEvent* event)
void FileTreeView::mouseDoubleClickEvent(QMouseEvent* event)
{
QModelIndex const index = currentIndex();
auto const index = currentIndex();
if (!index.isValid() || index.column() == FileTreeModel::COL_WANTED || index.column() == FileTreeModel::COL_PRIORITY)
{