From 1e3d20422a6ff18a7ffdd2e35a706c81c0eb868a Mon Sep 17 00:00:00 2001 From: Mike Gelfand Date: Sun, 14 May 2017 01:38:31 +0300 Subject: [PATCH] Reduce for loop variables scope --- daemon/daemon.c | 3 +- daemon/remote.c | 79 ++----- gtk/actions.c | 20 +- gtk/details.c | 290 +++++++++--------------- gtk/dialogs.c | 6 +- gtk/file-list.c | 6 +- gtk/filter.c | 38 ++-- gtk/main.c | 21 +- gtk/makemeta-ui.c | 16 +- gtk/notify.c | 3 +- gtk/open-dialog.c | 6 +- gtk/tr-core.c | 27 +-- gtk/tr-prefs.c | 19 +- gtk/tr-window.c | 11 +- gtk/util.c | 13 +- libtransmission/CMakeLists.txt | 4 +- libtransmission/announcer-http.c | 34 +-- libtransmission/announcer-udp.c | 48 ++-- libtransmission/announcer.c | 116 ++++------ libtransmission/bandwidth.c | 19 +- libtransmission/bitfield-test.c | 32 ++- libtransmission/bitfield.c | 18 +- libtransmission/blocklist.c | 12 +- libtransmission/cache.c | 27 +-- libtransmission/clients.c | 12 +- libtransmission/completion.c | 19 +- libtransmission/crypto-test.c | 51 ++--- libtransmission/crypto-utils-polarssl.c | 4 +- libtransmission/crypto-utils.c | 3 +- libtransmission/fdlimit.c | 21 +- libtransmission/file-test.c | 41 ++-- libtransmission/file-win32.c | 5 +- libtransmission/file.c | 13 +- libtransmission/handshake.c | 9 +- libtransmission/json-test.c | 13 +- libtransmission/libtransmission-test.c | 12 +- libtransmission/list.c | 15 +- libtransmission/magnet-test.c | 5 +- libtransmission/magnet.c | 23 +- libtransmission/makemeta-test.c | 15 +- libtransmission/makemeta.c | 35 ++- libtransmission/metainfo-test.c | 4 +- libtransmission/metainfo.c | 34 +-- libtransmission/move-test.c | 12 +- libtransmission/peer-io.c | 3 +- libtransmission/peer-mgr.c | 272 +++++++++------------- libtransmission/peer-msgs-test.c | 7 +- libtransmission/peer-msgs.c | 57 ++--- libtransmission/platform-quota.c | 14 +- libtransmission/platform.c | 7 +- libtransmission/ptrarray.c | 8 +- libtransmission/quark-test.c | 6 +- libtransmission/quark.c | 5 +- libtransmission/rename-test.c | 18 +- libtransmission/resume.c | 64 ++---- libtransmission/rpc-server.c | 28 +-- libtransmission/rpcimpl.c | 113 +++------ libtransmission/session-test.c | 6 +- libtransmission/session.c | 61 ++--- libtransmission/torrent-ctor.c | 8 +- libtransmission/torrent-magnet.c | 16 +- libtransmission/torrent.c | 172 ++++++-------- libtransmission/tr-dht.c | 21 +- libtransmission/tr-getopt.c | 11 +- libtransmission/tr-lpd.c | 3 +- libtransmission/tr-udp.c | 2 +- libtransmission/utils-test.c | 27 +-- libtransmission/utils.c | 76 +++---- libtransmission/utils.h | 2 + libtransmission/variant-test.c | 7 +- libtransmission/variant.c | 18 +- libtransmission/webseed.c | 15 +- utils/edit.c | 3 +- utils/show.c | 13 +- 74 files changed, 843 insertions(+), 1434 deletions(-) diff --git a/daemon/daemon.c b/daemon/daemon.c index b61030a55..e156dd302 100644 --- a/daemon/daemon.c +++ b/daemon/daemon.c @@ -310,10 +310,9 @@ static void printMessage(tr_sys_file_t logfile, int level, char const* name, cha static void pumpLogMessages(tr_sys_file_t logfile) { - tr_log_message const* l; tr_log_message* list = tr_logGetQueue(); - for (l = list; l != NULL; l = l->next) + for (tr_log_message const* l = list; l != NULL; l = l->next) { printMessage(logfile, l->level, l->name, l->message, l->file, l->line); } diff --git a/daemon/remote.c b/daemon/remote.c index f66e2f0c6..f1edb4a9f 100644 --- a/daemon/remote.c +++ b/daemon/remote.c @@ -558,16 +558,12 @@ static void addIdArg(tr_variant* args, char const* id, char const* fallback) } else if (strcmp(id, "all") != 0) { - char const* pch; bool isList = strchr(id, ',') != NULL || strchr(id, '-') != NULL; bool isNum = true; - for (pch = id; isNum && *pch != '\0'; ++pch) + for (char const* pch = id; isNum && *pch != '\0'; ++pch) { - if (!isdigit(*pch)) - { - isNum = false; - } + isNum = isdigit(*pch); } if (isNum || isList) @@ -616,13 +612,12 @@ static void addDays(tr_variant* args, tr_quark const key, char const* arg) if (arg != NULL) { - int i; int valueCount; int* values; values = tr_parseNumberRange(arg, TR_BAD_SIZE, &valueCount); - for (i = 0; i < valueCount; ++i) + for (int i = 0; i < valueCount; ++i) { if (values[i] < 0 || values[i] > 7) { @@ -662,11 +657,10 @@ static void addFiles(tr_variant* args, tr_quark const key, char const* arg) if (strcmp(arg, "all") != 0) { - int i; int valueCount; int* values = tr_parseNumberRange(arg, TR_BAD_SIZE, &valueCount); - for (i = 0; i < valueCount; ++i) + for (int i = 0; i < valueCount; ++i) { tr_variantListAddInt(files, values[i]); } @@ -675,8 +669,6 @@ static void addFiles(tr_variant* args, tr_quark const key, char const* arg) } } -#define TR_N_ELEMENTS(ary) (sizeof(ary) / sizeof(*ary)) - static tr_quark const files_keys[] = { TR_KEY_files, @@ -907,10 +899,7 @@ static void printDetails(tr_variant* top) if (tr_variantDictFindDict(top, TR_KEY_arguments, &args) && tr_variantDictFindList(args, TR_KEY_torrents, &torrents)) { - int ti; - int tCount; - - for (ti = 0, tCount = tr_variantListSize(torrents); ti < tCount; ++ti) + for (int ti = 0, tCount = tr_variantListSize(torrents); ti < tCount; ++ti) { tr_variant* t = tr_variantListChild(torrents, ti); tr_variant* l; @@ -1217,10 +1206,7 @@ static void printFileList(tr_variant* top) if (tr_variantDictFindDict(top, TR_KEY_arguments, &args) && tr_variantDictFindList(args, TR_KEY_torrents, &torrents)) { - int i; - int in; - - for (i = 0, in = tr_variantListSize(torrents); i < in; ++i) + for (int i = 0, in = tr_variantListSize(torrents); i < in; ++i) { tr_variant* d = tr_variantListChild(torrents, i); tr_variant* files; @@ -1231,12 +1217,11 @@ static void printFileList(tr_variant* top) if (tr_variantDictFindStr(d, TR_KEY_name, &name, NULL) && tr_variantDictFindList(d, TR_KEY_files, &files) && tr_variantDictFindList(d, TR_KEY_priorities, &priorities) && tr_variantDictFindList(d, TR_KEY_wanted, &wanteds)) { - int j = 0; - int jn = tr_variantListSize(files); + int const jn = tr_variantListSize(files); printf("%s (%d files):\n", name, jn); printf("%3s %4s %8s %3s %9s %s\n", "#", "Done", "Priority", "Get", "Size", "Name"); - for (j = 0, jn = tr_variantListSize(files); j < jn; ++j) + for (int j = 0; j < jn; ++j) { int64_t have; int64_t length; @@ -1280,11 +1265,9 @@ static void printFileList(tr_variant* top) static void printPeersImpl(tr_variant* peers) { - int i; - int n; printf("%-40s %-12s %-5s %-6s %-6s %s\n", "Address", "Flags", "Done", "Down", "Up", "Client"); - for (i = 0, n = tr_variantListSize(peers); i < n; ++i) + for (int i = 0, n = tr_variantListSize(peers); i < n; ++i) { double progress; char const* address; @@ -1311,10 +1294,7 @@ static void printPeers(tr_variant* top) if (tr_variantDictFindDict(top, TR_KEY_arguments, &args) && tr_variantDictFindList(args, TR_KEY_torrents, &torrents)) { - int i; - int n; - - for (i = 0, n = tr_variantListSize(torrents); i < n; ++i) + for (int i = 0, n = tr_variantListSize(torrents); i < n; ++i) { tr_variant* peers; tr_variant* torrent = tr_variantListChild(torrents, i); @@ -1334,17 +1314,13 @@ static void printPeers(tr_variant* top) static void printPiecesImpl(uint8_t const* raw, size_t rawlen, size_t j) { - size_t i; - size_t k; size_t len; char* str = tr_base64_decode(raw, rawlen, &len); printf(" "); - for (i = k = 0; k < len; ++k) + for (size_t i = 0, k = 0; k < len; ++k) { - int e; - - for (e = 0; i < j && e < 8; ++e, ++i) + for (int e = 0; i < j && e < 8; ++e, ++i) { printf("%c", str[k] & (1 << (7 - e)) ? '1' : '0'); } @@ -1368,10 +1344,7 @@ static void printPieces(tr_variant* top) if (tr_variantDictFindDict(top, TR_KEY_arguments, &args) && tr_variantDictFindList(args, TR_KEY_torrents, &torrents)) { - int i; - int n; - - for (i = 0, n = tr_variantListSize(torrents); i < n; ++i) + for (int i = 0, n = tr_variantListSize(torrents); i < n; ++i) { int64_t j; uint8_t const* raw; @@ -1414,8 +1387,6 @@ static void printTorrentList(tr_variant* top) if (tr_variantDictFindDict(top, TR_KEY_arguments, &args) && tr_variantDictFindList(args, TR_KEY_torrents, &list)) { - int i; - int n; int64_t total_size = 0; double total_up = 0; double total_down = 0; @@ -1424,7 +1395,7 @@ static void printTorrentList(tr_variant* top) printf("%-4s %-4s %9s %-8s %6s %6s %-5s %-11s %s\n", "ID", "Done", "Have", "ETA", "Up", "Down", "Ratio", "Status", "Name"); - for (i = 0, n = tr_variantListSize(list); i < n; ++i) + for (int i = 0, n = tr_variantListSize(list); i < n; ++i) { int64_t id; int64_t eta; @@ -1496,11 +1467,10 @@ static void printTorrentList(tr_variant* top) static void printTrackersImpl(tr_variant* trackerStats) { - int i; char buf[512]; tr_variant* t; - for (i = 0; (t = tr_variantListChild(trackerStats, i)) != NULL; ++i) + for (int i = 0; (t = tr_variantListChild(trackerStats, i)) != NULL; ++i) { int64_t downloadCount; bool hasAnnounced; @@ -1656,10 +1626,7 @@ static void printTrackers(tr_variant* top) if (tr_variantDictFindDict(top, TR_KEY_arguments, &args) && tr_variantDictFindList(args, TR_KEY_torrents, &torrents)) { - int i; - int n; - - for (i = 0, n = tr_variantListSize(torrents); i < n; ++i) + for (int i = 0, n = tr_variantListSize(torrents); i < n; ++i) { tr_variant* trackerStats; tr_variant* torrent = tr_variantListChild(torrents, i); @@ -2328,8 +2295,6 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv) } else if (stepMode == MODE_TORRENT_GET) { - size_t i; - size_t n; tr_variant* top = tr_new0(tr_variant, 1); tr_variant* args; tr_variant* fields; @@ -2348,9 +2313,8 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv) { case 'i': tr_variantDictAddInt(top, TR_KEY_tag, TAG_DETAILS); - n = TR_N_ELEMENTS(details_keys); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < TR_N_ELEMENTS(details_keys); ++i) { tr_variantListAddQuark(fields, details_keys[i]); } @@ -2360,9 +2324,8 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv) case 'l': tr_variantDictAddInt(top, TR_KEY_tag, TAG_LIST); - n = TR_N_ELEMENTS(list_keys); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < TR_N_ELEMENTS(list_keys); ++i) { tr_variantListAddQuark(fields, list_keys[i]); } @@ -2372,9 +2335,8 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv) case 940: tr_variantDictAddInt(top, TR_KEY_tag, TAG_FILES); - n = TR_N_ELEMENTS(files_keys); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < TR_N_ELEMENTS(files_keys); ++i) { tr_variantListAddQuark(fields, files_keys[i]); } @@ -2952,7 +2914,6 @@ static void getHostAndPortAndRpcUrl(int* argc, char** argv, char** host, int* po { if (*argv[1] != '-') { - int i; char const* s = argv[1]; char const* delim = strchr(s, ':'); @@ -2987,7 +2948,7 @@ static void getHostAndPortAndRpcUrl(int* argc, char** argv, char** host, int* po *argc -= 1; - for (i = 1; i < *argc; ++i) + for (int i = 1; i < *argc; ++i) { argv[i] = argv[i + 1]; } diff --git a/gtk/actions.c b/gtk/actions.c index 1c753b51b..5c71046b2 100644 --- a/gtk/actions.c +++ b/gtk/actions.c @@ -136,14 +136,12 @@ static BuiltinIconInfo const my_fallback_icons[] = static void register_my_icons(void) { - int i; - int const n = G_N_ELEMENTS(my_fallback_icons); GtkIconTheme* theme = gtk_icon_theme_get_default(); GtkIconFactory* factory = gtk_icon_factory_new(); gtk_icon_factory_add_default(factory); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < G_N_ELEMENTS(my_fallback_icons); ++i) { char const* name = my_fallback_icons[i].name; @@ -185,9 +183,7 @@ void gtr_actions_set_core(TrCore* core) void gtr_actions_init(GtkUIManager* ui_manager, gpointer callback_user_data) { - int i; - int n; - int active; + int active = -1; char const* match; int const n_entries = G_N_ELEMENTS(entries); GtkActionGroup* action_group; @@ -201,7 +197,7 @@ void gtr_actions_init(GtkUIManager* ui_manager, gpointer callback_user_data) match = gtr_pref_string_get(TR_KEY_sort_mode); - for (i = 0, n = G_N_ELEMENTS(sort_radio_entries), active = -1; active == -1 && i < n; ++i) + for (size_t i = 0; active == -1 && i < G_N_ELEMENTS(sort_radio_entries); ++i) { if (g_strcmp0(sort_radio_entries[i].name, match) == 0) { @@ -214,7 +210,7 @@ void gtr_actions_init(GtkUIManager* ui_manager, gpointer callback_user_data) gtk_action_group_add_toggle_actions(action_group, show_toggle_entries, G_N_ELEMENTS(show_toggle_entries), callback_user_data); - for (i = 0, n = G_N_ELEMENTS(pref_toggle_entries); i < n; ++i) + for (size_t i = 0; i < G_N_ELEMENTS(pref_toggle_entries); ++i) { pref_toggle_entries[i].is_active = gtr_pref_flag_get(tr_quark_new(pref_toggle_entries[i].name, TR_BAD_SIZE)); } @@ -235,8 +231,6 @@ static GHashTable* key_to_action = NULL; static void ensure_action_map_loaded(GtkUIManager* uim) { - GList* l; - if (key_to_action != NULL) { return; @@ -244,12 +238,12 @@ static void ensure_action_map_loaded(GtkUIManager* uim) key_to_action = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL); - for (l = gtk_ui_manager_get_action_groups(uim); l != NULL; l = l->next) + for (GList* l = gtk_ui_manager_get_action_groups(uim); l != NULL; l = l->next) { GtkActionGroup* action_group = GTK_ACTION_GROUP(l->data); - GList* ait, * actions = gtk_action_group_list_actions(action_group); + GList* actions = gtk_action_group_list_actions(action_group); - for (ait = actions; ait != NULL; ait = ait->next) + for (GList* ait = actions; ait != NULL; ait = ait->next) { GtkAction* action = GTK_ACTION(ait->data); char const* name = gtk_action_get_name(action); diff --git a/gtk/details.c b/gtk/details.c index b7a290bf1..3a685dbd7 100644 --- a/gtk/details.c +++ b/gtk/details.c @@ -106,14 +106,13 @@ struct DetailsImpl static tr_torrent** getTorrents(struct DetailsImpl* d, int* setmeCount) { - GSList* l; int torrentCount = 0; int const n = g_slist_length(d->ids); tr_torrent** torrents = g_new(tr_torrent*, n); - for (l = d->ids; l != NULL; l = l->next) + for (GSList* l = d->ids; l != NULL; l = l->next) { - if ((torrents[torrentCount] = gtr_core_find_torrent(d->core, GPOINTER_TO_INT(l->data)))) + if ((torrents[torrentCount] = gtr_core_find_torrent(d->core, GPOINTER_TO_INT(l->data))) != NULL) { ++torrentCount; } @@ -186,18 +185,15 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n) /* honor_limits_check */ if (n != 0) { - int i; bool const baseline = tr_torrentUsesSessionLimits(torrents[0]); + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (baseline != tr_torrentUsesSessionLimits(torrents[i])) - { - break; - } + is_uniform = baseline == tr_torrentUsesSessionLimits(torrents[i]); } - if (i == n) + if (is_uniform) { set_togglebutton_if_different(di->honor_limits_check, di->honor_limits_check_tag, baseline); } @@ -206,18 +202,15 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n) /* down_limited_check */ if (n != 0) { - int i; bool const baseline = tr_torrentUsesSpeedLimit(torrents[0], TR_DOWN); + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (baseline != tr_torrentUsesSpeedLimit(torrents[i], TR_DOWN)) - { - break; - } + is_uniform = baseline == tr_torrentUsesSpeedLimit(torrents[i], TR_DOWN); } - if (i == n) + if (is_uniform) { set_togglebutton_if_different(di->down_limited_check, di->down_limited_check_tag, baseline); } @@ -226,18 +219,15 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n) /* down_limit_spin */ if (n != 0) { - int i; unsigned int const baseline = tr_torrentGetSpeedLimit_KBps(torrents[0], TR_DOWN); + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (baseline != tr_torrentGetSpeedLimit_KBps(torrents[i], TR_DOWN)) - { - break; - } + is_uniform = baseline == tr_torrentGetSpeedLimit_KBps(torrents[i], TR_DOWN); } - if (i == n) + if (is_uniform) { set_int_spin_if_different(di->down_limit_spin, di->down_limit_spin_tag, baseline); } @@ -246,18 +236,15 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n) /* up_limited_check */ if (n != 0) { - int i; bool const baseline = tr_torrentUsesSpeedLimit(torrents[0], TR_UP); + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (baseline != tr_torrentUsesSpeedLimit(torrents[i], TR_UP)) - { - break; - } + is_uniform = baseline == tr_torrentUsesSpeedLimit(torrents[i], TR_UP); } - if (i == n) + if (is_uniform) { set_togglebutton_if_different(di->up_limited_check, di->up_limited_check_tag, baseline); } @@ -266,18 +253,15 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n) /* up_limit_sping */ if (n != 0) { - int i; unsigned int const baseline = tr_torrentGetSpeedLimit_KBps(torrents[0], TR_UP); + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (baseline != tr_torrentGetSpeedLimit_KBps(torrents[i], TR_UP)) - { - break; - } + is_uniform = baseline == tr_torrentGetSpeedLimit_KBps(torrents[i], TR_UP); } - if (i == n) + if (is_uniform) { set_int_spin_if_different(di->up_limit_sping, di->up_limit_spin_tag, baseline); } @@ -286,18 +270,15 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n) /* bandwidth_combo */ if (n != 0) { - int i; int const baseline = tr_torrentGetPriority(torrents[0]); + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (baseline != tr_torrentGetPriority(torrents[i])) - { - break; - } + is_uniform = baseline == tr_torrentGetPriority(torrents[i]); } - if (i == n) + if (is_uniform) { GtkWidget* w = di->bandwidth_combo; g_signal_handler_block(w, di->bandwidth_combo_tag); @@ -313,18 +294,15 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n) /* ratio_combo */ if (n != 0) { - int i; int const baseline = tr_torrentGetRatioMode(torrents[0]); + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (baseline != (int)tr_torrentGetRatioMode(torrents[i])) - { - break; - } + is_uniform = baseline == (int)tr_torrentGetRatioMode(torrents[i]); } - if (i == n) + if (is_uniform) { GtkWidget* w = di->ratio_combo; g_signal_handler_block(w, di->ratio_combo_tag); @@ -344,18 +322,15 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n) /* idle_combo */ if (n != 0) { - int i; int const baseline = tr_torrentGetIdleMode(torrents[0]); + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (baseline != (int)tr_torrentGetIdleMode(torrents[i])) - { - break; - } + is_uniform = baseline == (int)tr_torrentGetIdleMode(torrents[i]); } - if (i == n) + if (is_uniform) { GtkWidget* w = di->idle_combo; g_signal_handler_block(w, di->idle_combo_tag); @@ -382,7 +357,6 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n) static void torrent_set_bool(struct DetailsImpl* di, tr_quark const key, gboolean value) { - GSList* l; tr_variant top; tr_variant* args; tr_variant* ids; @@ -393,7 +367,7 @@ static void torrent_set_bool(struct DetailsImpl* di, tr_quark const key, gboolea tr_variantDictAddBool(args, key, value); ids = tr_variantDictAddList(args, TR_KEY_ids, g_slist_length(di->ids)); - for (l = di->ids; l != NULL; l = l->next) + for (GSList* l = di->ids; l != NULL; l = l->next) { tr_variantListAddInt(ids, GPOINTER_TO_INT(l->data)); } @@ -404,7 +378,6 @@ static void torrent_set_bool(struct DetailsImpl* di, tr_quark const key, gboolea static void torrent_set_int(struct DetailsImpl* di, tr_quark const key, int value) { - GSList* l; tr_variant top; tr_variant* args; tr_variant* ids; @@ -415,7 +388,7 @@ static void torrent_set_int(struct DetailsImpl* di, tr_quark const key, int valu tr_variantDictAddInt(args, key, value); ids = tr_variantDictAddList(args, TR_KEY_ids, g_slist_length(di->ids)); - for (l = di->ids; l != NULL; l = l->next) + for (GSList* l = di->ids; l != NULL; l = l->next) { tr_variantListAddInt(ids, GPOINTER_TO_INT(l->data)); } @@ -426,7 +399,6 @@ static void torrent_set_int(struct DetailsImpl* di, tr_quark const key, int valu static void torrent_set_real(struct DetailsImpl* di, tr_quark const key, double value) { - GSList* l; tr_variant top; tr_variant* args; tr_variant* ids; @@ -437,7 +409,7 @@ static void torrent_set_real(struct DetailsImpl* di, tr_quark const key, double tr_variantDictAddReal(args, key, value); ids = tr_variantDictAddList(args, TR_KEY_ids, g_slist_length(di->ids)); - for (l = di->ids; l != NULL; l = l->next) + for (GSList* l = di->ids; l != NULL; l = l->next) { tr_variantListAddInt(ids, GPOINTER_TO_INT(l->data)); } @@ -688,7 +660,6 @@ static char* get_short_date_string(time_t t) static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) { - int i; char const* str; char const* mixed = _("Mixed"); char const* no_torrent = _("No Torrents Selected"); @@ -698,7 +669,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) tr_stat const** stats = g_new(tr_stat const*, n); tr_info const** infos = g_new(tr_info const*, n); - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { stats[i] = tr_torrentStatCached(torrents[i]); infos[i] = tr_torrentInfo(torrents[i]); @@ -712,26 +683,20 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) else { bool const baseline = infos[0]->isPrivate; + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (baseline != infos[i]->isPrivate) - { - break; - } + is_uniform = baseline == infos[i]->isPrivate; } - if (i != n) + if (is_uniform) { - str = mixed; - } - else if (baseline) - { - str = _("Private to this tracker -- DHT and PEX disabled"); + str = baseline ? _("Private to this tracker -- DHT and PEX disabled") : _("Public torrent"); } else { - str = _("Public torrent"); + str = mixed; } } @@ -744,16 +709,16 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) } else { - char const* creator = infos[0]->creator ? infos[0]->creator : ""; + char const* creator = infos[0]->creator != NULL ? infos[0]->creator : ""; time_t const date = infos[0]->dateCreated; char* datestr = get_short_date_string(date); gboolean mixed_creator = FALSE; gboolean mixed_date = FALSE; - for (i = 1; i < n; ++i) + for (int i = 1; i < n; ++i) { - mixed_creator |= g_strcmp0(creator, infos[i]->creator ? infos[i]->creator : "") != 0; - mixed_date |= (date != infos[i]->dateCreated); + mixed_creator |= g_strcmp0(creator, infos[i]->creator != NULL ? infos[i]->creator : "") != 0; + mixed_date |= date != infos[i]->dateCreated; } gboolean const empty_creator = *creator == '\0'; @@ -798,23 +763,14 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) else { char const* baseline = infos[0]->comment != NULL ? infos[0]->comment : ""; + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (g_strcmp0(baseline, infos[i]->comment != NULL ? infos[i]->comment : "") != 0) - { - break; - } + is_uniform = g_strcmp0(baseline, infos[i]->comment != NULL ? infos[i]->comment : "") == 0; } - if (i == n) - { - str = baseline; - } - else - { - str = mixed; - } + str = is_uniform ? baseline : mixed; } gtr_text_buffer_set_text(di->comment_buffer, str); @@ -827,23 +783,14 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) else { char const* baseline = tr_torrentGetDownloadDir(torrents[0]); + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (g_strcmp0(baseline, tr_torrentGetDownloadDir(torrents[i])) != 0) - { - break; - } + is_uniform = g_strcmp0(baseline, tr_torrentGetDownloadDir(torrents[i])) == 0; } - if (i == n) - { - str = baseline; - } - else - { - str = mixed; - } + str = is_uniform ? baseline : mixed; } gtr_label_set_text(GTK_LABEL(di->destination_lb), str); @@ -856,14 +803,12 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) else { tr_torrent_activity const activity = stats[0]->activity; + bool is_uniform = true; bool allFinished = stats[0]->finished; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (activity != stats[i]->activity) - { - break; - } + is_uniform = activity == stats[i]->activity; if (!stats[i]->finished) { @@ -871,7 +816,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) } } - str = i < n ? mixed : activityString(activity, allFinished); + str = is_uniform ? activityString(activity, allFinished) : mixed; } stateString = str; @@ -885,16 +830,14 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) else { time_t const baseline = stats[0]->startDate; + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (baseline != stats[i]->startDate) - { - break; - } + is_uniform = baseline == stats[i]->startDate; } - if (i != n) + if (!is_uniform) { str = mixed; } @@ -918,16 +861,14 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) else { int const baseline = stats[0]->eta; + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (baseline != stats[i]->eta) - { - break; - } + is_uniform = baseline == stats[i]->eta; } - if (i != n) + if (!is_uniform) { str = mixed; } @@ -950,7 +891,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) int pieces = 0; int32_t pieceSize = 0; - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { size += infos[i]->totalSize; pieces += infos[i]->pieceCount; @@ -1000,7 +941,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) uint64_t haveValid = 0; uint64_t available = 0; - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { tr_stat const* st = stats[i]; haveUnchecked += st->haveUnchecked; @@ -1055,7 +996,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) uint64_t d = 0; uint64_t f = 0; - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { d += stats[i]->downloadedEver; f += stats[i]->corruptEver; @@ -1090,7 +1031,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) uint64_t up = 0; uint64_t down = 0; - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { up += stats[i]->uploadedEver; down += stats[i]->downloadedEver; @@ -1128,23 +1069,14 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) else { char const* baseline = stats[0]->errorString; + bool is_uniform = true; - for (i = 1; i < n; ++i) + for (int i = 1; is_uniform && i < n; ++i) { - if (g_strcmp0(baseline, stats[i]->errorString) != 0) - { - break; - } + is_uniform = g_strcmp0(baseline, stats[i]->errorString) == 0; } - if (i == n) - { - str = baseline; - } - else - { - str = mixed; - } + str = is_uniform ? baseline : mixed; } if (str == NULL || *str == '\0') @@ -1163,7 +1095,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) { time_t latest = 0; - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { if (latest < stats[i]->activityDate) { @@ -1562,7 +1494,6 @@ static void refreshPeerRow(GtkListStore* store, GtkTreeIter* iter, tr_peer_stat static void refreshPeerList(struct DetailsImpl* di, tr_torrent** torrents, int n) { - int i; int* peerCount; GtkTreeIter iter; GtkTreeModel* model; @@ -1574,7 +1505,7 @@ static void refreshPeerList(struct DetailsImpl* di, tr_torrent** torrents, int n peers = g_new(struct tr_peer_stat*, n); peerCount = g_new(int, n); - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { peers[i] = tr_torrentPeers(torrents[i], &peerCount[i]); } @@ -1592,12 +1523,11 @@ static void refreshPeerList(struct DetailsImpl* di, tr_torrent** torrents, int n } /* step 3: add any new peers */ - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { - int j; tr_torrent const* tor = torrents[i]; - for (j = 0; j < peerCount[i]; ++j) + for (int j = 0; j < peerCount[i]; ++j) { char key[128]; tr_peer_stat const* s = &peers[i][j]; @@ -1617,12 +1547,11 @@ static void refreshPeerList(struct DetailsImpl* di, tr_torrent** torrents, int n } /* step 4: update the peers */ - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { - int j; tr_torrent const* tor = torrents[i]; - for (j = 0; j < peerCount[i]; ++j) + for (int j = 0; j < peerCount[i]; ++j) { char key[128]; GtkTreePath* p; @@ -1666,7 +1595,7 @@ static void refreshPeerList(struct DetailsImpl* di, tr_torrent** torrents, int n } /* step 6: cleanup */ - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { tr_torrentPeersFree(peers[i], peerCount[i]); } @@ -1677,7 +1606,6 @@ static void refreshPeerList(struct DetailsImpl* di, tr_torrent** torrents, int n static void refreshWebseedList(struct DetailsImpl* di, tr_torrent** torrents, int n) { - int i; int total = 0; GtkTreeIter iter; GHashTable* hash = di->webseed_hash; @@ -1695,15 +1623,14 @@ static void refreshWebseedList(struct DetailsImpl* di, tr_torrent** torrents, in } /* step 2: add any new webseeds */ - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { - unsigned int j; tr_torrent const* tor = torrents[i]; tr_info const* inf = tr_torrentInfo(tor); total += inf->webseedCount; - for (j = 0; j < inf->webseedCount; ++j) + for (unsigned int j = 0; j < inf->webseedCount; ++j) { char key[256]; char const* url = inf->webseeds[j]; @@ -1725,14 +1652,13 @@ static void refreshWebseedList(struct DetailsImpl* di, tr_torrent** torrents, in } /* step 3: update the webseeds */ - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { - unsigned int j; tr_torrent* tor = torrents[i]; tr_info const* inf = tr_torrentInfo(tor); double* speeds_KBps = tr_torrentWebSpeeds_KBps(tor); - for (j = 0; j < inf->webseedCount; ++j) + for (unsigned int j = 0; j < inf->webseedCount; ++j) { char buf[128]; char key[256]; @@ -1816,7 +1742,6 @@ static gboolean onPeerViewQueryTooltip(GtkWidget* widget, gint x, gint y, gboole if (gtk_tree_view_get_tooltip_context(GTK_TREE_VIEW(widget), &x, &y, keyboard_tip, &model, NULL, &iter)) { - char const* pch; char* name = NULL; char* addr = NULL; char* markup = NULL; @@ -1835,7 +1760,7 @@ static gboolean onPeerViewQueryTooltip(GtkWidget* widget, gint x, gint y, gboole g_string_append_printf(gstr, "%s\n%s\n \n", markup, addr); g_free(markup); - for (pch = flagstr; pch != NULL && *pch != '\0'; ++pch) + for (char const* pch = flagstr; pch != NULL && *pch != '\0'; ++pch) { char const* s = NULL; @@ -1914,7 +1839,6 @@ static gboolean onPeerViewQueryTooltip(GtkWidget* widget, gint x, gint y, gboole static void setPeerViewColumns(GtkTreeView* peer_view) { - int i; int n; int view_columns[32]; GtkCellRenderer* r; @@ -1968,7 +1892,7 @@ static void setPeerViewColumns(GtkTreeView* peer_view) gtk_tree_view_remove_column(peer_view, c); } - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { int const col = view_columns[i]; char const* t = getPeerColumnName(col); @@ -2402,7 +2326,6 @@ static void favicon_ready_cb(gpointer pixbuf, gpointer vreference) static void refreshTracker(struct DetailsImpl* di, tr_torrent** torrents, int n) { - int i; int* statCount; tr_tracker_stat** stats; GtkTreeIter iter; @@ -2417,7 +2340,7 @@ static void refreshTracker(struct DetailsImpl* di, tr_torrent** torrents, int n) statCount = g_new0(int, n); stats = g_new0(tr_tracker_stat*, n); - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { stats[i] = tr_torrentTrackers(torrents[i], &statCount[i]); } @@ -2435,12 +2358,11 @@ static void refreshTracker(struct DetailsImpl* di, tr_torrent** torrents, int n) } /* step 3: add any new trackers */ - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { - int j; int const jn = statCount[i]; - for (j = 0; j < jn; ++j) + for (int j = 0; j < jn; ++j) { tr_torrent const* tor = torrents[i]; tr_tracker_stat const* st = &stats[i][j]; @@ -2473,13 +2395,12 @@ static void refreshTracker(struct DetailsImpl* di, tr_torrent** torrents, int n) } /* step 4: update the peers */ - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { - int j; tr_torrent const* tor = torrents[i]; char const* summary_name = n > 1 ? tr_torrentName(tor) : NULL; - for (j = 0; j < statCount[i]; ++j) + for (int j = 0; j < statCount[i]; ++j) { GtkTreePath* p; GtkTreeRowReference* ref; @@ -2535,7 +2456,7 @@ static void refreshTracker(struct DetailsImpl* di, tr_torrent** torrents, int n) gtk_widget_set_sensitive(di->edit_trackers_button, tracker_list_get_current_torrent_id(di) >= 0); /* cleanup */ - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { tr_torrentTrackersFree(stats[i], statCount[i]); } @@ -2567,7 +2488,6 @@ static void on_edit_trackers_response(GtkDialog* dialog, int response, gpointer if (response == GTK_RESPONSE_ACCEPT) { - int i; int n; int tier; GtkTextIter start; @@ -2587,25 +2507,22 @@ static void on_edit_trackers_response(GtkDialog* dialog, int response, gpointer tracker_text = gtk_text_buffer_get_text(text_buffer, &start, &end, FALSE); tracker_strings = g_strsplit(tracker_text, "\n", 0); - for (i = 0; tracker_strings[i];) - { - ++i; - } - - trackers = g_new0(tr_tracker_info, i); + trackers = g_new0(tr_tracker_info, g_strv_length(tracker_strings)); + n = 0; + tier = 0; - for (i = n = tier = 0; tracker_strings[i]; ++i) + for (int i = 0; tracker_strings[i] != NULL; ++i) { - char const* str = tracker_strings[i]; + char* const str = tracker_strings[i]; - if (!*str) + if (*str == '\0') { ++tier; } else { trackers[n].tier = tier; - trackers[n].announce = tracker_strings[i]; + trackers[n].announce = str; ++n; } } @@ -2643,11 +2560,10 @@ static void on_edit_trackers_response(GtkDialog* dialog, int response, gpointer static void get_editable_tracker_list(GString* gstr, tr_torrent const* tor) { - unsigned int i; int tier = 0; tr_info const* inf = tr_torrentInfo(tor); - for (i = 0; i < inf->trackerCount; ++i) + for (unsigned int i = 0; i < inf->trackerCount; ++i) { tr_tracker_info const* t = &inf->trackers[i]; diff --git a/gtk/dialogs.c b/gtk/dialogs.c index 28f3d3a99..c64cce6bb 100644 --- a/gtk/dialogs.c +++ b/gtk/dialogs.c @@ -41,12 +41,11 @@ struct delete_data static void on_remove_dialog_response(GtkDialog* dialog, gint response, gpointer gdd) { - GSList* l; struct delete_data* dd = gdd; if (response == GTK_RESPONSE_ACCEPT) { - for (l = dd->torrent_ids; l != NULL; l = l->next) + for (GSList* l = dd->torrent_ids; l != NULL; l = l->next) { gtr_core_remove_torrent(dd->core, GPOINTER_TO_INT(l->data), dd->delete_files); } @@ -59,7 +58,6 @@ static void on_remove_dialog_response(GtkDialog* dialog, gint response, gpointer void gtr_confirm_remove(GtkWindow* parent, TrCore* core, GSList* torrent_ids, gboolean delete_files) { - GSList* l; GtkWidget* d; GString* primary_text; GString* secondary_text; @@ -78,7 +76,7 @@ void gtr_confirm_remove(GtkWindow* parent, TrCore* core, GSList* torrent_ids, gb dd->torrent_ids = torrent_ids; dd->delete_files = delete_files; - for (l = torrent_ids; l != NULL; l = l->next) + for (GSList* l = torrent_ids; l != NULL; l = l->next) { int const id = GPOINTER_TO_INT(l->data); tr_torrent* tor = gtr_core_find_torrent(core, id); diff --git a/gtk/file-list.c b/gtk/file-list.c index e05d573cf..0656967a7 100644 --- a/gtk/file-list.c +++ b/gtk/file-list.c @@ -527,7 +527,6 @@ void gtr_file_list_set_torrent(GtkWidget* w, int torrentId) if (tor != NULL) { - tr_file_index_t i; tr_info const* inf = tr_torrentInfo(tor); struct row_struct* root_data; GNode* root; @@ -540,14 +539,13 @@ void gtr_file_list_set_torrent(GtkWidget* w, int torrentId) root_data->length = 0; root = g_node_new(root_data); - for (i = 0; i < inf->fileCount; ++i) + for (tr_file_index_t i = 0; i < inf->fileCount; ++i) { - int j; GNode* parent = root; tr_file const* file = &inf->files[i]; char** tokens = g_strsplit(file->name, G_DIR_SEPARATOR_S, 0); - for (j = 0; tokens[j]; ++j) + for (int j = 0; tokens[j] != NULL; ++j) { gboolean const isLeaf = tokens[j + 1] == NULL; char const* name = tokens[j]; diff --git a/gtk/filter.c b/gtk/filter.c index e16691575..09716b27e 100644 --- a/gtk/filter.c +++ b/gtk/filter.c @@ -114,7 +114,6 @@ static void favicon_ready_cb(gpointer pixbuf, gpointer vreference) static gboolean tracker_filter_model_update(gpointer gstore) { - int i, n; int all = 0; int store_pos; GtkTreeIter iter; @@ -146,9 +145,8 @@ static gboolean tracker_filter_model_update(gpointer gstore) keyCount = 0; keys = g_new(char*, inf->trackerCount); - for (i = 0, n = inf->trackerCount; i < n; ++i) + for (unsigned int i = 0; i < inf->trackerCount; ++i) { - int k; int* count; char buf[1024]; char* key; @@ -165,21 +163,20 @@ static gboolean tracker_filter_model_update(gpointer gstore) g_ptr_array_add(hosts, key); } - for (k = 0; k < keyCount; ++k) + bool found = false; + + for (int k = 0; !found && k < keyCount; ++k) { - if (g_strcmp0(keys[k], key) == 0) - { - break; - } + found = g_strcmp0(keys[k], key) == 0; } - if (k == keyCount) + if (!found) { keys[keyCount++] = key; } } - for (i = 0; i < keyCount; ++i) + for (int i = 0; i < keyCount; ++i) { int* incrementme = g_hash_table_lookup(hosts_hash, keys[i]); ++*incrementme; @@ -202,7 +199,7 @@ static gboolean tracker_filter_model_update(gpointer gstore) store_pos = first_tracker_pos; - for (i = 0, n = hosts->len;;) + for (int i = 0, n = hosts->len;;) { gboolean const new_hosts_done = i >= n; gboolean const old_hosts_done = !gtk_tree_model_iter_nth_child(model, &iter, NULL, store_pos); @@ -432,21 +429,16 @@ static gboolean test_tracker(tr_torrent* tor, int active_tracker_type, char cons if (active_tracker_type == TRACKER_FILTER_TYPE_HOST) { - unsigned int i; char tmp[1024]; tr_info const* const inf = tr_torrentInfo(tor); - for (i = 0; i < inf->trackerCount; ++i) + matches = FALSE; + + for (unsigned int i = 0; !matches && i < inf->trackerCount; ++i) { gtr_get_host_from_url(tmp, sizeof(tmp), inf->trackers[i].announce); - - if (g_strcmp0(tmp, host) == 0) - { - break; - } + matches = g_strcmp0(tmp, host) == 0; } - - matches = i < inf->trackerCount; } return matches; @@ -579,7 +571,6 @@ static gboolean activity_filter_model_update(gpointer gstore) static GtkTreeModel* activity_filter_model_new(GtkTreeModel* tmodel) { - int i, n; struct { int type; @@ -606,7 +597,7 @@ static GtkTreeModel* activity_filter_model_new(GtkTreeModel* tmodel) G_TYPE_INT, G_TYPE_STRING); - for (i = 0, n = G_N_ELEMENTS(types); i < n; ++i) + for (size_t i = 0; i < G_N_ELEMENTS(types); ++i) { char const* name = types[i].context != NULL ? g_dpgettext2(NULL, types[i].context, types[i].name) : _(types[i].name); gtk_list_store_insert_with_values(store, NULL, -1, @@ -718,7 +709,6 @@ static gboolean testText(tr_torrent const* tor, char const* key) } else { - tr_file_index_t i; tr_info const* inf = tr_torrentInfo(tor); /* test the torrent name... */ @@ -729,7 +719,7 @@ static gboolean testText(tr_torrent const* tor, char const* key) } /* test the files... */ - for (i = 0; i < inf->fileCount && !ret; ++i) + for (tr_file_index_t i = 0; i < inf->fileCount && !ret; ++i) { char* pch = g_utf8_casefold(inf->files[i].name, -1); ret = key == NULL || strstr(pch, key) != NULL; diff --git a/gtk/main.c b/gtk/main.c index 2f2c994fa..a164ab439 100644 --- a/gtk/main.c +++ b/gtk/main.c @@ -113,11 +113,10 @@ static int compare_integers(gconstpointer a, gconstpointer b) static char* get_details_dialog_key(GSList* id_list) { - GSList* l; GSList* tmp = g_slist_sort(g_slist_copy(id_list), compare_integers); GString* gstr = g_string_new(NULL); - for (l = tmp; l != NULL; l = l->next) + for (GSList* l = tmp; l != NULL; l = l->next) { g_string_append_printf(gstr, "%d ", GPOINTER_TO_INT(l->data)); } @@ -151,11 +150,10 @@ static void on_details_dialog_closed(gpointer gdata, GObject* dead) static void show_details_dialog_for_selected_torrents(struct cbdata* data) { GtkWidget* dialog = NULL; - GSList* l; GSList* ids = get_selected_torrent_ids(data); char* key = get_details_dialog_key(ids); - for (l = data->details; dialog == NULL && l != NULL; l = l->next) + for (GSList* l = data->details; dialog == NULL && l != NULL; l = l->next) { if (g_strcmp0(key, g_object_get_data(l->data, "key")) == 0) { @@ -389,18 +387,16 @@ static gboolean on_rpc_changed_idle(gpointer gdata) case TR_RPC_SESSION_CHANGED: { - int i; tr_variant tmp; tr_variant* newval; tr_variant* oldvals = gtr_pref_get_all(); tr_quark key; - GSList* l; GSList* changed_keys = NULL; tr_session* session = gtr_core_session(data->core); tr_variantInitDict(&tmp, 100); tr_sessionGetSettings(session, &tmp); - for (i = 0; tr_variantDictChild(&tmp, i, &key, &newval); ++i) + for (int i = 0; tr_variantDictChild(&tmp, i, &key, &newval); ++i) { bool changed; tr_variant* oldval = tr_variantDictFind(oldvals, key); @@ -426,7 +422,7 @@ static gboolean on_rpc_changed_idle(gpointer gdata) tr_sessionGetSettings(session, oldvals); - for (l = changed_keys; l != NULL; l = l->next) + for (GSList* l = changed_keys; l != NULL; l = l->next) { gtr_core_pref_changed(data->core, GPOINTER_TO_INT(l->data)); } @@ -587,10 +583,9 @@ static void open_files(GSList* files, gpointer gdata) static void on_open(GApplication* application UNUSED, GFile** f, gint file_count, gchar* hint UNUSED, gpointer gdata) { - int i; GSList* files = NULL; - for (i = 0; i < file_count; i++) + for (gint i = 0; i < file_count; i++) { files = g_slist_prepend(files, f[i]); } @@ -840,12 +835,11 @@ static void rowChangedCB(GtkTreeModel* model UNUSED, GtkTreePath* path, GtkTreeI static void on_drag_data_received(GtkWidget* widget UNUSED, GdkDragContext* drag_context, gint x UNUSED, gint y UNUSED, GtkSelectionData* selection_data, guint info UNUSED, guint time_, gpointer gdata) { - guint i; char** uris = gtk_selection_data_get_uris(selection_data); guint const file_count = g_strv_length(uris); GSList* files = NULL; - for (i = 0; i < file_count; ++i) + for (guint i = 0; i < file_count; ++i) { files = g_slist_prepend(files, g_file_new_for_uri(uris[i])); } @@ -1021,12 +1015,11 @@ static void on_app_exit(gpointer vdata) static void show_torrent_errors(GtkWindow* window, char const* primary, GSList** files) { - GSList* l; GtkWidget* w; GString* s = g_string_new(NULL); char const* leader = g_slist_length(*files) > 1 ? gtr_get_unicode_string(GTR_UNICODE_BULLET) : ""; - for (l = *files; l != NULL; l = l->next) + for (GSList* l = *files; l != NULL; l = l->next) { g_string_append_printf(s, "%s %s\n", leader, (char const*)l->data); } diff --git a/gtk/makemeta-ui.c b/gtk/makemeta-ui.c index 0eaaf8681..7e01fcef6 100644 --- a/gtk/makemeta-ui.c +++ b/gtk/makemeta-ui.c @@ -217,7 +217,6 @@ static void onResponse(GtkDialog* d, int response, gpointer user_data) { if (ui->builder != NULL) { - int i; int n; int tier; GtkTextIter start, end; @@ -244,16 +243,13 @@ static void onResponse(GtkDialog* d, int response, gpointer user_data) tracker_text = gtk_text_buffer_get_text(ui->announce_text_buffer, &start, &end, FALSE); tracker_strings = g_strsplit(tracker_text, "\n", 0); - for (i = 0; tracker_strings[i] != NULL;) - { - ++i; - } - - trackers = g_new0(tr_tracker_info, i); + trackers = g_new0(tr_tracker_info, g_strv_length(tracker_strings)); + n = 0; + tier = 0; - for (i = n = tier = 0; tracker_strings[i] != NULL; ++i) + for (int i = 0; tracker_strings[i] != NULL; ++i) { - char const* str = tracker_strings[i]; + char* const str = tracker_strings[i]; if (*str == '\0') { @@ -262,7 +258,7 @@ static void onResponse(GtkDialog* d, int response, gpointer user_data) else { trackers[n].tier = tier; - trackers[n].announce = tracker_strings[i]; + trackers[n].announce = str; ++n; } } diff --git a/gtk/notify.c b/gtk/notify.c index 03719715f..4b2bf6b77 100644 --- a/gtk/notify.c +++ b/gtk/notify.c @@ -44,7 +44,6 @@ static void tr_notification_free(gpointer data) static void get_capabilities_callback(GObject* source, GAsyncResult* res, gpointer user_data UNUSED) { - int i; char** caps; GVariant* result; @@ -62,7 +61,7 @@ static void get_capabilities_callback(GObject* source, GAsyncResult* res, gpoint g_variant_get(result, "(^a&s)", &caps); - for (i = 0; caps[i] != NULL; i++) + for (int i = 0; caps[i] != NULL; i++) { if (g_strcmp0(caps[i], "actions") == 0) { diff --git a/gtk/open-dialog.c b/gtk/open-dialog.c index be0e38056..12aca8c07 100644 --- a/gtk/open-dialog.c +++ b/gtk/open-dialog.c @@ -29,10 +29,9 @@ static GSList* get_recent_destinations(void) { - int i; GSList* list = NULL; - for (i = 0; i < N_RECENT; ++i) + for (int i = 0; i < N_RECENT; ++i) { char key[64]; char const* val; @@ -280,7 +279,6 @@ GtkWidget* gtr_torrent_options_dialog_new(GtkWindow* parent, TrCore* core, tr_ct struct OpenData* data; bool flag; GSList* list; - GSList* walk; /* make the dialog */ d = gtk_dialog_new_with_buttons(_("Torrent Options"), parent, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_STOCK_CANCEL, @@ -343,7 +341,7 @@ GtkWidget* gtr_torrent_options_dialog_new(GtkWindow* parent, TrCore* core, tr_ct list = get_recent_destinations(); - for (walk = list; walk != NULL; walk = walk->next) + for (GSList* walk = list; walk != NULL; walk = walk->next) { gtk_file_chooser_add_shortcut_folder(GTK_FILE_CHOOSER(w), walk->data, NULL); } diff --git a/gtk/tr-core.c b/gtk/tr-core.c index e8cb98d9d..6ff817323 100644 --- a/gtk/tr-core.c +++ b/gtk/tr-core.c @@ -712,7 +712,6 @@ static void rename_torrent_and_unref_file(GFile* file) static gboolean core_watchdir_idle(gpointer gcore) { - GSList* l; GSList* changing = NULL; GSList* unchanging = NULL; TrCore* core = TR_CORE(gcore); @@ -720,7 +719,7 @@ static gboolean core_watchdir_idle(gpointer gcore) struct TrCorePrivate* p = core->priv; /* separate the files into two lists: changing and unchanging */ - for (l = p->monitor_files; l != NULL; l = l->next) + for (GSList* l = p->monitor_files; l != NULL; l = l->next) { GFile* file = l->data; time_t const mtime = get_file_mtime(file); @@ -770,19 +769,16 @@ static void core_watchdir_monitor_file(TrCore* core, GFile* file) if (is_torrent) { - GSList* l; struct TrCorePrivate* p = core->priv; + bool found = false; /* if we're not already watching this file, start watching it now */ - for (l = p->monitor_files; l != NULL; l = l->next) + for (GSList* l = p->monitor_files; !found && l != NULL; l = l->next) { - if (g_file_equal(file, l->data)) - { - break; - } + found = g_file_equal(file, l->data); } - if (l == NULL) + if (!found) { g_object_ref(file); p->monitor_files = g_slist_prepend(p->monitor_files, file); @@ -1058,14 +1054,12 @@ static void on_torrent_metadata_changed(tr_torrent* tor, void* gcore) static unsigned int build_torrent_trackers_hash(tr_torrent* tor) { - unsigned int i; - char const* pch; uint64_t hash = 0; tr_info const* const inf = tr_torrentInfo(tor); - for (i = 0; i < inf->trackerCount; ++i) + for (unsigned int i = 0; i < inf->trackerCount; ++i) { - for (pch = inf->trackers[i].announce; *pch != '\0'; ++pch) + for (char const* pch = inf->trackers[i].announce; *pch != '\0'; ++pch) { hash = (hash << 4) ^ (hash >> 28) ^ *pch; } @@ -1361,9 +1355,7 @@ bool gtr_core_add_from_url(TrCore* core, char const* uri) void gtr_core_add_files(TrCore* core, GSList* files, gboolean do_start, gboolean do_prompt, gboolean do_notify) { - GSList* l; - - for (l = files; l != NULL; l = l->next) + for (GSList* l = files; l != NULL; l = l->next) { add_file(core, l->data, do_start, do_prompt, do_notify); } @@ -1411,7 +1403,6 @@ void gtr_core_remove_torrent(TrCore* core, int id, gboolean delete_local_data) void gtr_core_load(TrCore* self, gboolean forcePaused) { - int i; tr_ctor* ctor; tr_torrent** torrents; int count = 0; @@ -1427,7 +1418,7 @@ void gtr_core_load(TrCore* self, gboolean forcePaused) torrents = tr_sessionLoadTorrents(gtr_core_session(self), ctor, &count); - for (i = 0; i < count; ++i) + for (int i = 0; i < count; ++i) { gtr_core_add_torrent(self, torrents[i], FALSE); } diff --git a/gtk/tr-prefs.c b/gtk/tr-prefs.c index ef5f50992..0ca4eacbe 100644 --- a/gtk/tr-prefs.c +++ b/gtk/tr-prefs.c @@ -565,7 +565,6 @@ enum static GtkTreeModel* whitelist_tree_model_new(char const* whitelist) { - int i; char** rules; GtkListStore* store = gtk_list_store_new(N_COLS, G_TYPE_STRING, @@ -573,7 +572,7 @@ static GtkTreeModel* whitelist_tree_model_new(char const* whitelist) rules = g_strsplit(whitelist, ",", 0); - for (i = 0; rules != NULL && rules[i] != NULL; ++i) + for (int i = 0; rules != NULL && rules[i] != NULL; ++i) { GtkTreeIter iter; char const* s = rules[i]; @@ -676,7 +675,6 @@ static void onRemoveWhitelistClicked(GtkButton* b UNUSED, gpointer gpage) static void refreshRPCSensitivity(struct remote_page* page) { - GSList* l; int const rpc_active = gtk_toggle_button_get_active(page->rpc_tb); int const auth_active = gtk_toggle_button_get_active(page->auth_tb); int const whitelist_active = gtk_toggle_button_get_active(page->whitelist_tb); @@ -684,17 +682,17 @@ static void refreshRPCSensitivity(struct remote_page* page) int const have_addr = gtk_tree_selection_get_selected(sel, NULL, NULL); int const n_rules = gtk_tree_model_iter_n_children(GTK_TREE_MODEL(page->store), NULL); - for (l = page->widgets; l != NULL; l = l->next) + for (GSList* l = page->widgets; l != NULL; l = l->next) { gtk_widget_set_sensitive(GTK_WIDGET(l->data), rpc_active); } - for (l = page->auth_widgets; l != NULL; l = l->next) + for (GSList* l = page->auth_widgets; l != NULL; l = l->next) { gtk_widget_set_sensitive(GTK_WIDGET(l->data), rpc_active && auth_active); } - for (l = page->whitelist_widgets; l != NULL; l = l->next) + for (GSList* l = page->whitelist_widgets; l != NULL; l = l->next) { gtk_widget_set_sensitive(GTK_WIDGET(l->data), rpc_active && whitelist_active); } @@ -872,10 +870,9 @@ struct BandwidthPage static void refreshSchedSensitivity(struct BandwidthPage* p) { - GSList* l; gboolean const sched_enabled = gtr_pref_flag_get(TR_KEY_alt_speed_time_enabled); - for (l = p->sched_widgets; l != NULL; l = l->next) + for (GSList* l = p->sched_widgets; l != NULL; l = l->next) { gtk_widget_set_sensitive(GTK_WIDGET(l->data), sched_enabled); } @@ -902,7 +899,6 @@ static void onTimeComboChanged(GtkComboBox* w, gpointer core) static GtkWidget* new_time_combo(GObject* core, tr_quark const key) { int val; - int i; GtkWidget* w; GtkCellRenderer* r; GtkListStore* store; @@ -910,7 +906,7 @@ static GtkWidget* new_time_combo(GObject* core, tr_quark const key) /* build a store at 15 minute intervals */ store = gtk_list_store_new(2, G_TYPE_INT, G_TYPE_STRING); - for (i = 0; i < 60 * 24; i += 15) + for (int i = 0; i < 60 * 24; i += 15) { char buf[128]; GtkTreeIter iter; @@ -1238,7 +1234,6 @@ static void on_core_prefs_changed(TrCore* core, tr_quark const key, gpointer gda GtkWidget* gtr_prefs_dialog_new(GtkWindow* parent, GObject* core) { - size_t i; GtkWidget* d; GtkWidget* n; struct prefs_dialog_data* data; @@ -1266,7 +1261,7 @@ GtkWidget* gtr_prefs_dialog_new(GtkWindow* parent, GObject* core) gtk_notebook_append_page(GTK_NOTEBOOK(n), remotePage(core), gtk_label_new(_("Remote"))); /* init from prefs keys */ - for (i = 0; i < sizeof(prefs_quarks) / sizeof(prefs_quarks[0]); ++i) + for (size_t i = 0; i < G_N_ELEMENTS(prefs_quarks); ++i) { on_core_prefs_changed(TR_CORE(core), prefs_quarks[i], data); } diff --git a/gtk/tr-window.c b/gtk/tr-window.c index e1440a8c8..7b466195e 100644 --- a/gtk/tr-window.c +++ b/gtk/tr-window.c @@ -361,8 +361,6 @@ static void onSpeedSet(GtkCheckMenuItem* check, gpointer vp) static GtkWidget* createSpeedMenu(PrivateData* p, tr_direction dir) { - int i; - int n; GObject* o; GtkWidget* w; GtkWidget* m; @@ -391,7 +389,7 @@ static GtkWidget* createSpeedMenu(PrivateData* p, tr_direction dir) w = gtk_separator_menu_item_new(); gtk_menu_shell_append(menu_shell, w); - for (i = 0, n = G_N_ELEMENTS(speeds_KBps); i < n; ++i) + for (size_t i = 0; i < G_N_ELEMENTS(speeds_KBps); ++i) { char buf[128]; tr_formatter_speed_KBps(buf, speeds_KBps[i], sizeof(buf)); @@ -435,8 +433,6 @@ static void onRatioSet(GtkCheckMenuItem* check, gpointer vp) static GtkWidget* createRatioMenu(PrivateData* p) { - int i; - int n; GtkWidget* m; GtkWidget* w; GtkMenuShell* menu_shell; @@ -459,7 +455,7 @@ static GtkWidget* createRatioMenu(PrivateData* p) w = gtk_separator_menu_item_new(); gtk_menu_shell_append(menu_shell, w); - for (i = 0, n = G_N_ELEMENTS(stockRatios); i < n; ++i) + for (size_t i = 0; i < G_N_ELEMENTS(stockRatios); ++i) { char buf[128]; tr_strlratio(buf, stockRatios[i], sizeof(buf)); @@ -541,7 +537,6 @@ static void onOptionsClicked(GtkButton* button UNUSED, gpointer vp) GtkWidget* gtr_window_new(GtkApplication* app, GtkUIManager* ui_mgr, TrCore* core) { - int i, n; char const* pch; char const* style; PrivateData* p; @@ -612,7 +607,7 @@ GtkWidget* gtr_window_new(GtkApplication* app, GtkUIManager* ui_mgr, TrCore* cor l = NULL; pch = gtr_pref_string_get(TR_KEY_statusbar_stats); - for (i = 0, n = G_N_ELEMENTS(stats_modes); i < n; ++i) + for (size_t i = 0; i < G_N_ELEMENTS(stats_modes); ++i) { char const* val = stats_modes[i].val; w = gtk_radio_menu_item_new_with_label(l, _(stats_modes[i].i18n)); diff --git a/gtk/util.c b/gtk/util.c index 2df667c25..1cc376ecc 100644 --- a/gtk/util.c +++ b/gtk/util.c @@ -216,14 +216,12 @@ gboolean gtr_is_magnet_link(char const* str) gboolean gtr_is_hex_hashcode(char const* str) { - int i; - if (str == NULL || strlen(str) != 40) { return FALSE; } - for (i = 0; i < 40; ++i) + for (int i = 0; i < 40; ++i) { if (!isxdigit(str[i])) { @@ -530,11 +528,10 @@ void gtr_widget_set_visible(GtkWidget* w, gboolean b) /* toggle the transient children, too */ if (GTK_IS_WINDOW(w)) { - GList* l; GList* windows = gtk_window_list_toplevels(); GtkWindow* window = GTK_WINDOW(w); - for (l = windows; l != NULL; l = l->next) + for (GList* l = windows; l != NULL; l = l->next) { if (!GTK_IS_WINDOW(l->data)) { @@ -624,15 +621,13 @@ void gtr_unrecognized_url_dialog(GtkWidget* parent, char const* url) void gtr_paste_clipboard_url_into_entry(GtkWidget* e) { - size_t i; - char* text[] = { g_strstrip(gtk_clipboard_wait_for_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY))), g_strstrip(gtk_clipboard_wait_for_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD))) }; - for (i = 0; i < G_N_ELEMENTS(text); ++i) + for (size_t i = 0; i < G_N_ELEMENTS(text); ++i) { char* s = text[i]; @@ -643,7 +638,7 @@ void gtr_paste_clipboard_url_into_entry(GtkWidget* e) } } - for (i = 0; i < G_N_ELEMENTS(text); ++i) + for (size_t i = 0; i < G_N_ELEMENTS(text); ++i) { g_free(text[i]); } diff --git a/libtransmission/CMakeLists.txt b/libtransmission/CMakeLists.txt index 20e92768c..148cbeb94 100644 --- a/libtransmission/CMakeLists.txt +++ b/libtransmission/CMakeLists.txt @@ -274,8 +274,8 @@ if(ENABLE_TESTS) set(watchdir@generic-test_DEFINITIONS WATCHDIR_TEST_FORCE_GENERIC) - foreach(T bitfield blocklist clients crypto error file history json magnet metainfo move peer-msgs quark rename rpc session - tr-getopt utils variant watchdir watchdir@generic) + foreach(T bitfield blocklist clients crypto error file history json magnet makemeta metainfo move peer-msgs quark rename rpc + session tr-getopt utils variant watchdir watchdir@generic) set(TP ${TR_NAME}-test-${T}) if(T MATCHES "^([^@]+)@.+$") string(REPLACE "@" "_" TP "${TP}") diff --git a/libtransmission/announcer-http.c b/libtransmission/announcer-http.c index a73d67c3f..8ad64143c 100644 --- a/libtransmission/announcer-http.c +++ b/libtransmission/announcer-http.c @@ -138,12 +138,11 @@ static char* announce_url_new(tr_session const* session, tr_announce_request con static tr_pex* listToPex(tr_variant* peerList, size_t* setme_len) { - size_t i; - size_t n; + size_t n = 0; size_t const len = tr_variantListSize(peerList); tr_pex* pex = tr_new0(tr_pex, len); - for (i = n = 0; i < len; ++i) + for (size_t i = 0; i < len; ++i) { int64_t port; char const* ip; @@ -244,12 +243,11 @@ static void on_announce_done(tr_session* session, bool did_connect, bool did_tim } else { - size_t i; size_t len; char* str = tr_variantToStr(&benc, TR_VARIANT_FMT_JSON, &len); fprintf(stderr, "%s", "Announce response:\n< "); - for (i = 0; i < len; ++i) + for (size_t i = 0; i < len; ++i) { fputc(str[i], stderr); } @@ -418,12 +416,11 @@ static void on_scrape_done(tr_session* session, bool did_connect, bool did_timeo } else { - size_t i; size_t len; char* str = tr_variantToStr(&top, TR_VARIANT_FMT_JSON, &len); fprintf(stderr, "%s", "Scrape response:\n< "); - for (i = 0; i < len; ++i) + for (size_t i = 0; i < len; ++i) { fputc(str[i], stderr); } @@ -450,22 +447,13 @@ static void on_scrape_done(tr_session* session, bool did_connect, bool did_timeo if (tr_variantDictFindDict(&top, TR_KEY_files, &files)) { - int i = 0; + tr_quark key; + tr_variant* val; - for (;;) + for (int i = 0; tr_variantDictChild(files, i, &key, &val); ++i) { - int j; - tr_quark key; - tr_variant* val; - - /* get the next "file" */ - if (!tr_variantDictChild(files, i++, &key, &val)) - { - break; - } - /* populate the corresponding row in our response array */ - for (j = 0; j < response->row_count; ++j) + for (int j = 0; j < response->row_count; ++j) { struct tr_scrape_response_row* row = &response->rows[j]; @@ -506,14 +494,13 @@ static void on_scrape_done(tr_session* session, bool did_connect, bool did_timeo static char* scrape_url_new(tr_scrape_request const* req) { - int i; char delimiter; struct evbuffer* buf = evbuffer_new(); evbuffer_add_printf(buf, "%s", req->url); delimiter = strchr(req->url, '?') != NULL ? '&' : '?'; - for (i = 0; i < req->info_hash_count; ++i) + for (int i = 0; i < req->info_hash_count; ++i) { char str[SHA_DIGEST_LENGTH * 3 + 1]; tr_http_escape_sha1(str, req->info_hash[i]); @@ -527,7 +514,6 @@ static char* scrape_url_new(tr_scrape_request const* req) void tr_tracker_http_scrape(tr_session* session, tr_scrape_request const* request, tr_scrape_response_func response_func, void* response_func_user_data) { - int i; struct scrape_data* d; char* url = scrape_url_new(request); @@ -537,7 +523,7 @@ void tr_tracker_http_scrape(tr_session* session, tr_scrape_request const* reques d->response_func_user_data = response_func_user_data; d->response.row_count = request->info_hash_count; - for (i = 0; i < d->response.row_count; ++i) + for (int i = 0; i < d->response.row_count; ++i) { memcpy(d->response.rows[i].info_hash, request->info_hash[i], SHA_DIGEST_LENGTH); d->response.rows[i].seeders = -1; diff --git a/libtransmission/announcer-udp.c b/libtransmission/announcer-udp.c index bc40fceff..2838166a1 100644 --- a/libtransmission/announcer-udp.c +++ b/libtransmission/announcer-udp.c @@ -180,7 +180,6 @@ struct tau_scrape_request static struct tau_scrape_request* tau_scrape_request_new(tr_scrape_request const* in, tr_scrape_response_func callback, void* user_data) { - int i; struct evbuffer* buf; struct tau_scrape_request* req; tau_transaction_t const transaction_id = tau_transaction_new(); @@ -190,7 +189,7 @@ static struct tau_scrape_request* tau_scrape_request_new(tr_scrape_request const evbuffer_add_hton_32(buf, TAU_ACTION_SCRAPE); evbuffer_add_hton_32(buf, transaction_id); - for (i = 0; i < in->info_hash_count; ++i) + for (int i = 0; i < in->info_hash_count; ++i) { evbuffer_add(buf, in->info_hash[i], SHA_DIGEST_LENGTH); } @@ -206,7 +205,7 @@ static struct tau_scrape_request* tau_scrape_request_new(tr_scrape_request const req->payload_len = evbuffer_get_length(buf); req->payload = tr_memdup(evbuffer_pullup(buf, -1), req->payload_len); - for (i = 0; i < req->response.row_count; ++i) + for (int i = 0; i < req->response.row_count; ++i) { req->response.rows[i].seeders = -1; req->response.rows[i].leechers = -1; @@ -250,9 +249,7 @@ static void on_scrape_response(struct tau_scrape_request* request, tau_action_t if (action == TAU_ACTION_SCRAPE) { - int i; - - for (i = 0; i < request->response.row_count; ++i) + for (int i = 0; i < request->response.row_count; ++i) { struct tr_scrape_response_row* row; @@ -487,14 +484,12 @@ static void tau_tracker_free(struct tau_tracker* t) static void tau_tracker_fail_all(struct tau_tracker* tracker, bool did_connect, bool did_timeout, char const* errmsg) { - int i; - int n; tr_ptrArray* reqs; /* fail all the scrapes */ reqs = &tracker->scrapes; - for (i = 0, n = tr_ptrArraySize(reqs); i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(reqs); i < n; ++i) { tau_scrape_request_fail(tr_ptrArrayNth(reqs, i), did_connect, did_timeout, errmsg); } @@ -505,7 +500,7 @@ static void tau_tracker_fail_all(struct tau_tracker* tracker, bool did_connect, /* fail all the announces */ reqs = &tracker->announces; - for (i = 0, n = tr_ptrArraySize(reqs); i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(reqs); i < n; ++i) { tau_announce_request_fail(tr_ptrArrayNth(reqs, i), did_connect, did_timeout, errmsg); } @@ -548,8 +543,6 @@ static void tau_tracker_send_request(struct tau_tracker* tracker, void const* pa static void tau_tracker_send_reqs(struct tau_tracker* tracker) { - int i; - int n; tr_ptrArray* reqs; time_t const now = tr_time(); @@ -560,7 +553,7 @@ static void tau_tracker_send_reqs(struct tau_tracker* tracker) reqs = &tracker->announces; - for (i = 0, n = tr_ptrArraySize(reqs); i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(reqs); i < n; ++i) { struct tau_announce_request* req = tr_ptrArrayNth(reqs, i); @@ -582,7 +575,7 @@ static void tau_tracker_send_reqs(struct tau_tracker* tracker) reqs = &tracker->scrapes; - for (i = 0, n = tr_ptrArraySize(reqs); i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(reqs); i < n; ++i) { struct tau_scrape_request* req = tr_ptrArrayNth(reqs, i); @@ -640,8 +633,6 @@ static void on_tracker_connection_response(struct tau_tracker* tracker, tau_acti static void tau_tracker_timeout_reqs(struct tau_tracker* tracker) { - int i; - int n; tr_ptrArray* reqs; time_t const now = time(NULL); bool const cancel_all = tracker->close_at != 0 && (tracker->close_at <= now); @@ -653,7 +644,7 @@ static void tau_tracker_timeout_reqs(struct tau_tracker* tracker) reqs = &tracker->announces; - for (i = 0, n = tr_ptrArraySize(reqs); i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(reqs); i < n; ++i) { struct tau_announce_request* req = tr_ptrArrayNth(reqs, i); @@ -670,7 +661,7 @@ static void tau_tracker_timeout_reqs(struct tau_tracker* tracker) reqs = &tracker->scrapes; - for (i = 0, n = tr_ptrArraySize(reqs); i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(reqs); i < n; ++i) { struct tau_scrape_request* req = tr_ptrArrayNth(reqs, i); @@ -785,8 +776,6 @@ static struct tr_announcer_udp* announcer_udp_get(tr_session* session) If it doesn't exist yet, create one. */ static struct tau_tracker* tau_session_get_tracker(struct tr_announcer_udp* tau, char const* url) { - int i; - int n; int port; char* host; char* key; @@ -796,7 +785,7 @@ static struct tau_tracker* tau_session_get_tracker(struct tr_announcer_udp* tau, tr_urlParse(url, TR_BAD_SIZE, NULL, &host, &port, NULL); key = tr_strdup_printf("%s:%d", host, port); - for (i = 0, n = tr_ptrArraySize(&tau->trackers); !tracker && i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(&tau->trackers); tracker == NULL && i < n; ++i) { struct tau_tracker* tmp = tr_ptrArrayNth(&tau->trackers, i); @@ -846,13 +835,11 @@ void tr_tracker_udp_upkeep(tr_session* session) bool tr_tracker_udp_is_idle(tr_session const* session) { - int i; - int n; struct tr_announcer_udp* tau = session->announcer_udp; if (tau != NULL) { - for (i = 0, n = tr_ptrArraySize(&tau->trackers); i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(&tau->trackers); i < n; ++i) { if (!tau_tracker_is_idle(tr_ptrArrayNth(&tau->trackers, i))) { @@ -887,9 +874,7 @@ void tr_tracker_udp_start_shutdown(tr_session* session) if (tau != NULL) { - int i, n; - - for (i = 0, n = tr_ptrArraySize(&tau->trackers); i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(&tau->trackers); i < n; ++i) { struct tau_tracker* tracker = tr_ptrArrayNth(&tau->trackers, i); @@ -908,8 +893,6 @@ void tr_tracker_udp_start_shutdown(tr_session* session) * @return true if msg was a tracker response; false otherwise */ bool tau_handle_message(tr_session* session, uint8_t const* msg, size_t msglen) { - int i; - int n; struct tr_announcer_udp* tau; tau_action_t action_id; tau_transaction_t transaction_id; @@ -943,9 +926,8 @@ bool tau_handle_message(tr_session* session, uint8_t const* msg, size_t msglen) transaction_id = evbuffer_read_ntoh_32(buf); /* fprintf(stderr, "UDP got a transaction_id %u...\n", transaction_id); */ - for (i = 0, n = tr_ptrArraySize(&tau->trackers); i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(&tau->trackers); i < n; ++i) { - int j, jn; tr_ptrArray* reqs; struct tau_tracker* tracker = tr_ptrArrayNth(&tau->trackers, i); @@ -961,7 +943,7 @@ bool tau_handle_message(tr_session* session, uint8_t const* msg, size_t msglen) /* is it a response to one of this tracker's announces? */ reqs = &tracker->announces; - for (j = 0, jn = tr_ptrArraySize(reqs); j < jn; ++j) + for (int j = 0, jn = tr_ptrArraySize(reqs); j < jn; ++j) { struct tau_announce_request* req = tr_ptrArrayNth(reqs, j); @@ -979,7 +961,7 @@ bool tau_handle_message(tr_session* session, uint8_t const* msg, size_t msglen) /* is it a response to one of this tracker's scrapes? */ reqs = &tracker->scrapes; - for (j = 0, jn = tr_ptrArraySize(reqs); j < jn; ++j) + for (int j = 0, jn = tr_ptrArraySize(reqs); j < jn; ++j) { struct tau_scrape_request* req = tr_ptrArrayNth(reqs, j); diff --git a/libtransmission/announcer.c b/libtransmission/announcer.c index a03c92d41..9e1ca4cdd 100644 --- a/libtransmission/announcer.c +++ b/libtransmission/announcer.c @@ -410,16 +410,14 @@ static tr_torrent_tiers* tiersNew(void) static void tiersDestruct(tr_torrent_tiers* tt) { - int i; - - for (i = 0; i < tt->tracker_count; ++i) + for (int i = 0; i < tt->tracker_count; ++i) { trackerDestruct(&tt->trackers[i]); } tr_free(tt->trackers); - for (i = 0; i < tt->tier_count; ++i) + for (int i = 0; i < tt->tier_count; ++i) { tierDestruct(&tt->tiers[i]); } @@ -444,10 +442,9 @@ static tr_tier* getTier(tr_announcer* announcer, uint8_t const* info_hash, int t if (tor != NULL && tor->tiers != NULL) { - int i; tr_torrent_tiers* tt = tor->tiers; - for (i = 0; tier == NULL && i < tt->tier_count; ++i) + for (int i = 0; tier == NULL && i < tt->tier_count; ++i) { if (tt->tiers[i].key == tierId) { @@ -566,23 +563,19 @@ static int filter_trackers_compare_func(void const* va, void const* vb) */ static tr_tracker_info* filter_trackers(tr_tracker_info* input, int input_count, int* setme_count) { - int i; - int in; - int j; - int jn; int n = 0; struct tr_tracker_info* ret; struct ann_tracker_info* tmp = tr_new0(struct ann_tracker_info, input_count); /* - for (i = 0, in = input_count; i < in; ++i) + for (int i = 0; i < input_count; ++i) { fprintf(stderr, "IN: [%d][%s]\n", input[i].tier, input[i].announce); } */ /* build a list of valid trackers */ - for (i = 0, in = input_count; i < in; ++i) + for (int i = 0; i < input_count; ++i) { if (tr_urlIsValidTracker(input[i].announce)) { @@ -597,7 +590,7 @@ static tr_tracker_info* filter_trackers(tr_tracker_info* input, int input_count, * "http://tracker/announce" + * "http://tracker:80/announce" */ - for (j = 0, jn = n; !is_duplicate && j < jn; ++j) + for (int j = 0; !is_duplicate && j < n; ++j) { is_duplicate = tmp[j].port == port && strcmp(tmp[j].scheme, scheme) == 0 && strcmp(tmp[j].host, host) == 0 && strcmp(tmp[j].path, path) == 0; @@ -623,9 +616,9 @@ static tr_tracker_info* filter_trackers(tr_tracker_info* input, int input_count, /* if two announce URLs differ only by scheme, put them in the same tier. * (note: this can leave gaps in the `tier' values, but since the calling * function doesn't care, there's no point in removing the gaps...) */ - for (i = 0, in = n; i < in; ++i) + for (int i = 0; i < n; ++i) { - for (j = i + 1, jn = n; j < jn; ++j) + for (int j = i + 1; j < n; ++j) { if (tmp[i].info.tier != tmp[j].info.tier && tmp[i].port == tmp[j].port && tr_strcmp0(tmp[i].host, tmp[j].host) == 0 && tr_strcmp0(tmp[i].path, tmp[j].path) == 0) @@ -644,13 +637,13 @@ static tr_tracker_info* filter_trackers(tr_tracker_info* input, int input_count, *setme_count = n; ret = tr_new0(tr_tracker_info, n); - for (i = 0, in = n; i < in; ++i) + for (int i = 0; i < n; ++i) { ret[i] = tmp[i].info; } /* cleanup */ - for (i = 0, in = n; i < in; ++i) + for (int i = 0; i < n; ++i) { tr_free(tmp[i].path); tr_free(tmp[i].host); @@ -659,13 +652,18 @@ static tr_tracker_info* filter_trackers(tr_tracker_info* input, int input_count, tr_free(tmp); - /*for (i=0, in=n; itrackers = tr_new0(tr_tracker, n); tt->tracker_count = n; - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { trackerConstruct(&tt->trackers[i], &infos[i]); } @@ -683,7 +681,7 @@ static void addTorrentToTier(tr_torrent_tiers* tt, tr_torrent* tor) /* count how many tiers there are */ tier_count = 0; - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { if (i == 0 || infos[i].tier != infos[i - 1].tier) { @@ -696,7 +694,7 @@ static void addTorrentToTier(tr_torrent_tiers* tt, tr_torrent* tor) tt->tiers = tr_new0(tr_tier, tier_count); tt->tier_count = 0; - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { if (i != 0 && infos[i].tier == infos[i - 1].tier) { @@ -742,7 +740,6 @@ static bool tierCanManualAnnounce(tr_tier const* tier) bool tr_announcerCanManualAnnounce(tr_torrent const* tor) { - int i; struct tr_torrent_tiers* tt = NULL; assert(tr_isTorrent(tor)); @@ -754,7 +751,7 @@ bool tr_announcerCanManualAnnounce(tr_torrent const* tor) } /* return true if any tier can manual announce */ - for (i = 0; tt && i < tt->tier_count; ++i) + for (int i = 0; tt != NULL && i < tt->tier_count; ++i) { if (tierCanManualAnnounce(&tt->tiers[i])) { @@ -767,12 +764,11 @@ bool tr_announcerCanManualAnnounce(tr_torrent const* tor) time_t tr_announcerNextManualAnnounce(tr_torrent const* tor) { - int i; time_t ret = ~(time_t)0; struct tr_torrent_tiers* tt = tor->tiers; /* find the earliest manual announce time from all peers */ - for (i = 0; tt && i < tt->tier_count; ++i) + for (int i = 0; tt != NULL && i < tt->tier_count; ++i) { if (tt->tiers[i].isRunning) { @@ -787,14 +783,13 @@ static void dbgmsg_tier_announce_queue(tr_tier const* tier) { if (tr_logGetDeepEnabled()) { - int i; char name[128]; char* message; struct evbuffer* buf = evbuffer_new(); tier_build_log_name(tier, name, sizeof(name)); - for (i = 0; i < tier->announce_event_count; ++i) + for (int i = 0; i < tier->announce_event_count; ++i) { tr_announce_event const e = tier->announce_events[i]; char const* str = tr_announce_event_get_string(e); @@ -817,8 +812,6 @@ static void tier_announce_remove_trailing(tr_tier* tier, tr_announce_event e) static void tier_announce_event_push(tr_tier* tier, tr_announce_event e, time_t announceAt) { - int i; - assert(tier != NULL); dbgmsg_tier_announce_queue(tier); @@ -833,7 +826,7 @@ static void tier_announce_event_push(tr_tier* tier, tr_announce_event e, time_t bool has_completed = false; tr_announce_event const c = TR_ANNOUNCE_EVENT_COMPLETED; - for (i = 0; !has_completed && i < tier->announce_event_count; ++i) + for (int i = 0; !has_completed && i < tier->announce_event_count; ++i) { has_completed = c == tier->announce_events[i]; } @@ -879,11 +872,10 @@ static tr_announce_event tier_announce_event_pull(tr_tier* tier) static void torrentAddAnnounce(tr_torrent* tor, tr_announce_event e, time_t announceAt) { - int i; struct tr_torrent_tiers* tt = tor->tiers; /* walk through each tier and tell them to announce */ - for (i = 0; i < tt->tier_count; ++i) + for (int i = 0; i < tt->tier_count; ++i) { tier_announce_event_push(&tt->tiers[i], e, announceAt); } @@ -920,13 +912,12 @@ void tr_announcerChangeMyPort(tr_torrent* tor) void tr_announcerAddBytes(tr_torrent* tor, int type, uint32_t byteCount) { - int i; struct tr_torrent_tiers* tt = tor->tiers; assert(tr_isTorrent(tor)); assert(type == TR_ANN_UP || type == TR_ANN_DOWN || type == TR_ANN_CORRUPT); - for (i = 0; i < tt->tier_count; ++i) + for (int i = 0; i < tt->tier_count; ++i) { tt->tiers[i].byteCounts[type] += byteCount; } @@ -965,9 +956,7 @@ void tr_announcerRemoveTorrent(tr_announcer* announcer, tr_torrent* tor) if (tt != NULL) { - int i; - - for (i = 0; i < tt->tier_count; ++i) + for (int i = 0; i < tt->tier_count; ++i) { tr_tier* tier = &tt->tiers[i]; @@ -1341,10 +1330,9 @@ static void on_scrape_error(tr_session* session, tr_tier* tier, char const* errm static tr_tier* find_tier(tr_torrent* tor, char const* scrape) { - int i; struct tr_torrent_tiers* tt = tor->tiers; - for (i = 0; tt && i < tt->tier_count; ++i) + for (int i = 0; tt != NULL && i < tt->tier_count; ++i) { tr_tracker const* const tracker = tt->tiers[i].currentTracker; @@ -1359,12 +1347,11 @@ static tr_tier* find_tier(tr_torrent* tor, char const* scrape) static void on_scrape_done(tr_scrape_response const* response, void* vsession) { - int i; time_t const now = tr_time(); tr_session* session = vsession; tr_announcer* announcer = session->announcer; - for (i = 0; i < response->row_count; ++i) + for (int i = 0; i < response->row_count; ++i) { struct tr_scrape_response_row const* row = &response->rows[i]; tr_torrent* tor = tr_torrentFindFromHash(session, row->info_hash); @@ -1473,7 +1460,6 @@ static void scrape_request_delegate(tr_announcer* announcer, tr_scrape_request c static void multiscrape(tr_announcer* announcer, tr_ptrArray* tiers) { - int i; int request_count = 0; time_t const now = tr_time(); int const tier_count = tr_ptrArraySize(tiers); @@ -1481,15 +1467,15 @@ static void multiscrape(tr_announcer* announcer, tr_ptrArray* tiers) tr_scrape_request* requests = tr_new0(tr_scrape_request, max_request_count); /* batch as many info_hashes into a request as we can */ - for (i = 0; i < tier_count; ++i) + for (int i = 0; i < tier_count; ++i) { - int j; tr_tier* tier = tr_ptrArrayNth(tiers, i); char* url = tier->currentTracker->scrape; uint8_t const* hash = tier->tor->info.hash; + bool found = false; /* if there's a request with this scrape URL and a free slot, use it */ - for (j = 0; j < request_count; ++j) + for (int j = 0; !found && j < request_count; ++j) { tr_scrape_request* req = &requests[j]; @@ -1506,11 +1492,11 @@ static void multiscrape(tr_announcer* announcer, tr_ptrArray* tiers) memcpy(req->info_hash[req->info_hash_count++], hash, SHA_DIGEST_LENGTH); tier->isScraping = true; tier->lastScrapeStartTime = now; - break; + found = true; } /* otherwise, if there's room for another request, build a new one */ - if (j == request_count && request_count < max_request_count) + if (!found && request_count < max_request_count) { tr_scrape_request* req = &requests[request_count++]; req->url = url; @@ -1523,7 +1509,7 @@ static void multiscrape(tr_announcer* announcer, tr_ptrArray* tiers) } /* send the requests we just built */ - for (i = 0; i < request_count; ++i) + for (int i = 0; i < request_count; ++i) { scrape_request_delegate(announcer, &requests[i], on_scrape_done, announcer->session); } @@ -1534,10 +1520,7 @@ static void multiscrape(tr_announcer* announcer, tr_ptrArray* tiers) static void flushCloseMessages(tr_announcer* announcer) { - int i; - int const n = tr_ptrArraySize(&announcer->stops); - - for (i = 0; i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(&announcer->stops); i < n; ++i) { announce_request_delegate(announcer, tr_ptrArrayNth(&announcer->stops, i), NULL, NULL); } @@ -1578,7 +1561,6 @@ static int compareTiers(void const* va, void const* vb) static void announceMore(tr_announcer* announcer) { - int i; int n; tr_torrent* tor; tr_ptrArray announceMe = TR_PTR_ARRAY_INIT; @@ -1599,7 +1581,7 @@ static void announceMore(tr_announcer* announcer) { struct tr_torrent_tiers* tt = tor->tiers; - for (i = 0; tt != NULL && i < tt->tier_count; ++i) + for (int i = 0; tt != NULL && i < tt->tier_count; ++i) { tr_tier* tier = &tt->tiers[i]; @@ -1614,18 +1596,17 @@ static void announceMore(tr_announcer* announcer) } } - /* if there are more tiers than slots available, prioritize */ n = tr_ptrArraySize(&announceMe); + /* if there are more tiers than slots available, prioritize */ if (n > announcer->slotsAvailable) { qsort(tr_ptrArrayBase(&announceMe), n, sizeof(tr_tier*), compareTiers); + n = announcer->slotsAvailable; } /* announce some */ - n = MIN(tr_ptrArraySize(&announceMe), announcer->slotsAvailable); - - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { tr_tier* tier = tr_ptrArrayNth(&announceMe, i); tr_logAddTorDbg(tier->tor, "%s", "Announcing to tracker"); @@ -1678,7 +1659,6 @@ static void onUpkeepTimer(evutil_socket_t foo UNUSED, short bar UNUSED, void* va tr_tracker_stat* tr_announcerStats(tr_torrent const* torrent, int* setmeTrackerCount) { - int i; int out = 0; tr_tracker_stat* ret; struct tr_torrent_tiers* tt; @@ -1693,12 +1673,11 @@ tr_tracker_stat* tr_announcerStats(tr_torrent const* torrent, int* setmeTrackerC ret = tr_new0(tr_tracker_stat, tt->tracker_count); /* populate the stats */ - for (i = 0; i < tt->tier_count; ++i) + for (int i = 0; i < tt->tier_count; ++i) { - int j; tr_tier const* const tier = &tt->tiers[i]; - for (j = 0; j < tier->tracker_count; ++j) + for (int j = 0; j < tier->tracker_count; ++j) { tr_tracker const* const tracker = &tier->trackers[j]; tr_tracker_stat* st = &ret[out++]; @@ -1830,14 +1809,12 @@ static void copy_tier_attributes_impl(struct tr_tier* tgt, int trackerIndex, tr_ static void copy_tier_attributes(struct tr_torrent_tiers* tt, tr_tier const* src) { - int i; - int j; bool found = false; /* find a tier (if any) which has a match for src->currentTracker */ - for (i = 0; !found && i < tt->tier_count; ++i) + for (int i = 0; !found && i < tt->tier_count; ++i) { - for (j = 0; !found && j < tt->tiers[i].tracker_count; ++j) + for (int j = 0; !found && j < tt->tiers[i].tracker_count; ++j) { if ((found = tr_strcmp0(src->currentTracker->announce, tt->tiers[i].trackers[j].announce) == 0)) { @@ -1849,7 +1826,6 @@ static void copy_tier_attributes(struct tr_torrent_tiers* tt, tr_tier const* src void tr_announcerResetTorrent(tr_announcer* announcer UNUSED, tr_torrent* tor) { - int i; time_t const now = tr_time(); struct tr_torrent_tiers* tt = tor->tiers; tr_torrent_tiers old = *tt; @@ -1866,7 +1842,7 @@ void tr_announcerResetTorrent(tr_announcer* announcer UNUSED, tr_torrent* tor) addTorrentToTier(tt, tor); /* copy the old tiers' states into their replacements */ - for (i = 0; i < old.tier_count; ++i) + for (int i = 0; i < old.tier_count; ++i) { if (old.tiers[i].currentTracker != NULL) { @@ -1877,7 +1853,7 @@ void tr_announcerResetTorrent(tr_announcer* announcer UNUSED, tr_torrent* tor) /* kickstart any tiers that didn't get started */ if (tor->isRunning) { - for (i = 0; i < tt->tier_count; ++i) + for (int i = 0; i < tt->tier_count; ++i) { if (!tt->tiers[i].wasCopied) { diff --git a/libtransmission/bandwidth.c b/libtransmission/bandwidth.c index 06cd1c045..a1d900156 100644 --- a/libtransmission/bandwidth.c +++ b/libtransmission/bandwidth.c @@ -39,18 +39,12 @@ static unsigned int getSpeed_Bps(struct bratecontrol const* r, unsigned int inte if (now != r->cache_time) { - int i = r->newest; uint64_t bytes = 0; uint64_t const cutoff = now - interval_msec; struct bratecontrol* rvolatile = (struct bratecontrol*)r; - for (;;) + for (int i = r->newest; r->transfers[i].date > cutoff;) { - if (r->transfers[i].date <= cutoff) - { - break; - } - bytes += r->transfers[i].size; if (--i == -1) @@ -188,11 +182,9 @@ static void allocateBandwidth(tr_bandwidth* b, tr_priority_t parent_priority, tr /* traverse & repeat for the subtree */ if (true) { - int i; struct tr_bandwidth** children = (struct tr_bandwidth**)tr_ptrArrayBase(&b->children); - int const n = tr_ptrArraySize(&b->children); - for (i = 0; i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(&b->children); i < n; ++i) { allocateBandwidth(children[i], priority, dir, period_msec, peer_pool); } @@ -238,7 +230,6 @@ static void phaseOne(tr_ptrArray* peerArray, tr_direction dir) void tr_bandwidthAllocate(tr_bandwidth* b, tr_direction dir, unsigned int period_msec) { - int i; int peerCount; tr_ptrArray tmp = TR_PTR_ARRAY_INIT; tr_ptrArray low = TR_PTR_ARRAY_INIT; @@ -253,7 +244,7 @@ void tr_bandwidthAllocate(tr_bandwidth* b, tr_direction dir, unsigned int period peers = (struct tr_peerIo**)tr_ptrArrayBase(&tmp); peerCount = tr_ptrArraySize(&tmp); - for (i = 0; i < peerCount; ++i) + for (int i = 0; i < peerCount; ++i) { tr_peerIo* io = peers[i]; tr_peerIoRef(io); @@ -285,12 +276,12 @@ void tr_bandwidthAllocate(tr_bandwidth* b, tr_direction dir, unsigned int period * enable on-demand IO for peers with bandwidth left to burn. * This on-demand IO is enabled until (1) the peer runs out of bandwidth, * or (2) the next tr_bandwidthAllocate () call, when we start over again. */ - for (i = 0; i < peerCount; ++i) + for (int i = 0; i < peerCount; ++i) { tr_peerIoSetEnabled(peers[i], dir, tr_peerIoHasBandwidthLeft(peers[i], dir)); } - for (i = 0; i < peerCount; ++i) + for (int i = 0; i < peerCount; ++i) { tr_peerIoUnref(peers[i]); } diff --git a/libtransmission/bitfield-test.c b/libtransmission/bitfield-test.c index a0d1c3780..933c93eff 100644 --- a/libtransmission/bitfield-test.c +++ b/libtransmission/bitfield-test.c @@ -16,8 +16,6 @@ static int test_bitfield_count_range(void) { - int i; - int n; int begin; int end; int count1; @@ -28,7 +26,7 @@ static int test_bitfield_count_range(void) /* generate a random bitfield */ tr_bitfieldConstruct(&bf, bitCount); - for (i = 0, n = tr_rand_int_weak(bitCount); i < n; ++i) + for (int i = 0, n = tr_rand_int_weak(bitCount); i < n; ++i) { tr_bitfieldAdd(&bf, tr_rand_int_weak(bitCount)); } @@ -52,7 +50,7 @@ static int test_bitfield_count_range(void) /* test the bitfield */ count1 = 0; - for (i = begin; i < end; ++i) + for (int i = begin; i < end; ++i) { if (tr_bitfieldHas(&bf, i)) { @@ -70,14 +68,13 @@ static int test_bitfield_count_range(void) static int test_bitfields(void) { - unsigned int i; unsigned int bitcount = 500; tr_bitfield field; tr_bitfieldConstruct(&field, bitcount); /* test tr_bitfieldAdd */ - for (i = 0; i < bitcount; i++) + for (unsigned int i = 0; i < bitcount; i++) { if (i % 7 == 0) { @@ -85,7 +82,7 @@ static int test_bitfields(void) } } - for (i = 0; i < bitcount; i++) + for (unsigned int i = 0; i < bitcount; i++) { check(tr_bitfieldHas(&field, i) == (i % 7 == 0)); } @@ -93,13 +90,13 @@ static int test_bitfields(void) /* test tr_bitfieldAddRange */ tr_bitfieldAddRange(&field, 0, bitcount); - for (i = 0; i < bitcount; i++) + for (unsigned int i = 0; i < bitcount; i++) { check(tr_bitfieldHas(&field, i)); } /* test tr_bitfieldRem */ - for (i = 0; i < bitcount; i++) + for (unsigned int i = 0; i < bitcount; i++) { if (i % 7 != 0) { @@ -107,7 +104,7 @@ static int test_bitfields(void) } } - for (i = 0; i < bitcount; i++) + for (unsigned int i = 0; i < bitcount; i++) { check(tr_bitfieldHas(&field, i) == (i % 7 == 0)); } @@ -116,7 +113,7 @@ static int test_bitfields(void) tr_bitfieldAddRange(&field, 0, 64); tr_bitfieldRemRange(&field, 4, 21); - for (i = 0; i < 64; i++) + for (unsigned int i = 0; i < 64; i++) { check(tr_bitfieldHas(&field, i) == (i < 4 || i >= 21)); } @@ -125,7 +122,7 @@ static int test_bitfields(void) tr_bitfieldAddRange(&field, 0, 64); tr_bitfieldRemRange(&field, 8, 24); - for (i = 0; i < 64; i++) + for (unsigned int i = 0; i < 64; i++) { check(tr_bitfieldHas(&field, i) == (i < 8 || i >= 24)); } @@ -134,7 +131,7 @@ static int test_bitfields(void) tr_bitfieldAddRange(&field, 0, 64); tr_bitfieldRemRange(&field, 4, 5); - for (i = 0; i < 64; i++) + for (unsigned int i = 0; i < 64; i++) { check(tr_bitfieldHas(&field, i) == (i < 4 || i >= 5)); } @@ -143,7 +140,7 @@ static int test_bitfields(void) tr_bitfieldRemRange(&field, 0, 64); tr_bitfieldAddRange(&field, 4, 21); - for (i = 0; i < 64; i++) + for (unsigned int i = 0; i < 64; i++) { check(tr_bitfieldHas(&field, i) == (4 <= i && i < 21)); } @@ -152,7 +149,7 @@ static int test_bitfields(void) tr_bitfieldRemRange(&field, 0, 64); tr_bitfieldAddRange(&field, 8, 24); - for (i = 0; i < 64; i++) + for (unsigned int i = 0; i < 64; i++) { check(tr_bitfieldHas(&field, i) == (8 <= i && i < 24)); } @@ -161,7 +158,7 @@ static int test_bitfields(void) tr_bitfieldRemRange(&field, 0, 64); tr_bitfieldAddRange(&field, 4, 5); - for (i = 0; i < 64; i++) + for (unsigned int i = 0; i < 64; i++) { check(tr_bitfieldHas(&field, i) == (4 <= i && i < 5)); } @@ -226,7 +223,6 @@ static int test_bitfield_has_all_none(void) int main(void) { - int l; int ret; testFunc const tests[] = { @@ -240,7 +236,7 @@ int main(void) } /* bitfield count range */ - for (l = 0; l < 10000; ++l) + for (int l = 0; l < 10000; ++l) { if ((ret = test_bitfield_count_range()) != 0) { diff --git a/libtransmission/bitfield.c b/libtransmission/bitfield.c index 70ab427d9..329484471 100644 --- a/libtransmission/bitfield.c +++ b/libtransmission/bitfield.c @@ -87,19 +87,18 @@ static size_t countRange(tr_bitfield const* b, size_t begin, size_t end) } else { - size_t i; uint8_t val; size_t const walk_end = MIN(b->alloc_count, last_byte); /* first byte */ - i = begin - (first_byte * 8); + size_t const first_shift = begin - (first_byte * 8); val = b->bits[first_byte]; - val <<= i; - val >>= i; + val <<= first_shift; + val >>= first_shift; ret += trueBitCount[val]; /* middle bytes */ - for (i = first_byte + 1; i < walk_end; ++i) + for (size_t i = first_byte + 1; i < walk_end; ++i) { ret += trueBitCount[b->bits[i]]; } @@ -107,10 +106,10 @@ static size_t countRange(tr_bitfield const* b, size_t begin, size_t end) /* last byte */ if (last_byte < b->alloc_count) { - i = (last_byte + 1) * 8 - end; + size_t const last_shift = (last_byte + 1) * 8 - end; val = b->bits[last_byte]; - val >>= i; - val <<= i; + val >>= last_shift; + val <<= last_shift; ret += trueBitCount[val]; } } @@ -381,13 +380,12 @@ void tr_bitfieldSetRaw(tr_bitfield* b, void const* bits, size_t byte_count, bool void tr_bitfieldSetFromFlags(tr_bitfield* b, bool const* flags, size_t n) { - size_t i; size_t trueCount = 0; tr_bitfieldFreeArray(b); tr_bitfieldEnsureBitsAlloced(b, n); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { if (flags[i]) { diff --git a/libtransmission/blocklist.c b/libtransmission/blocklist.c index 71191adb5..b8e4dfa3d 100644 --- a/libtransmission/blocklist.c +++ b/libtransmission/blocklist.c @@ -384,16 +384,16 @@ int tr_blocklistFileSetContent(tr_blocklistFile* b, char const* filename) if (ranges_count > 0) /* sort and merge */ { - struct tr_ipv4_range* r; struct tr_ipv4_range* keep = ranges; - struct tr_ipv4_range const* end; /* sort */ qsort(ranges, ranges_count, sizeof(struct tr_ipv4_range), compareAddressRangesByFirstAddress); /* merge */ - for (r = ranges + 1, end = ranges + ranges_count; r != end; ++r) + for (size_t i = 1; i < ranges_count; ++i) { + struct tr_ipv4_range const* r = &ranges[i]; + if (keep->end < r->begin) { *++keep = *r; @@ -411,14 +411,12 @@ int tr_blocklistFileSetContent(tr_blocklistFile* b, char const* filename) /* sanity checks: make sure the rules are sorted * in ascending order and don't overlap */ { - size_t i; - - for (i = 0; i < ranges_count; ++i) + for (size_t i = 0; i < ranges_count; ++i) { assert(ranges[i].begin <= ranges[i].end); } - for (i = 1; i < ranges_count; ++i) + for (size_t i = 1; i < ranges_count; ++i) { assert(ranges[i - 1].end < ranges[i].begin); } diff --git a/libtransmission/cache.c b/libtransmission/cache.c index 3393eae63..daf0005f3 100644 --- a/libtransmission/cache.c +++ b/libtransmission/cache.c @@ -79,13 +79,13 @@ struct run_info /* return a count of how many contiguous blocks there are starting at this pos */ static int getBlockRun(tr_cache const* cache, int pos, struct run_info* info) { - int i; int const n = tr_ptrArraySize(&cache->blocks); struct cache_block const* const* blocks = (struct cache_block const* const*)tr_ptrArrayBase(&cache->blocks); struct cache_block const* ref = blocks[pos]; tr_block_index_t block = ref->block; + int len = 0; - for (i = pos; i < n; ++i, ++block) + for (int i = pos; i < n; ++i, ++block, ++len) { struct cache_block const* b = blocks[i]; @@ -102,19 +102,19 @@ static int getBlockRun(tr_cache const* cache, int pos, struct run_info* info) // fprintf(stderr, "pos %d tor %d block %zu time %zu\n", i, b->tor->uniqueId, (size_t)b->block, (size_t)b->time); } - // fprintf(stderr, "run is %d long from [%d to %d)\n", (int)(i - pos), i, (int)pos); + // fprintf(stderr, "run is %d long from [%d to %d)\n", len, pos, pos + len); if (info != NULL) { - struct cache_block const* b = blocks[i - 1]; + struct cache_block const* b = blocks[pos + len - 1]; info->last_block_time = b->time; info->is_piece_done = tr_torrentPieceIsComplete(b->tor, b->piece); info->is_multi_piece = b->piece != blocks[pos]->piece; - info->len = i - pos; + info->len = len; info->pos = pos; } - return i - pos; + return len; } /* higher rank comes before lower rank */ @@ -140,10 +140,9 @@ static int calcRuns(tr_cache* cache, struct run_info* runs) { int const n = tr_ptrArraySize(&cache->blocks); int i = 0; - int pos; time_t const now = tr_time(); - for (pos = 0; pos < n; pos += runs[i++].len) + for (int pos = 0; pos < n; pos += runs[i++].len) { int rank = getBlockRun(cache, pos, &runs[i]); @@ -172,7 +171,6 @@ static int calcRuns(tr_cache* cache, struct run_info* runs) static int flushContiguous(tr_cache* cache, int pos, int n) { - int i; int err = 0; uint8_t* buf = tr_new(uint8_t, n * MAX_BLOCK_SIZE); uint8_t* walk = buf; @@ -183,9 +181,9 @@ static int flushContiguous(tr_cache* cache, int pos, int n) tr_piece_index_t const piece = b->piece; uint32_t const offset = b->offset; - for (i = pos; i < pos + n; ++i) + for (int i = 0; i < n; ++i) { - b = blocks[i]; + b = blocks[pos + i]; evbuffer_copyout(b->evbuf, walk, b->length); walk += b->length; evbuffer_free(b->evbuf); @@ -204,16 +202,13 @@ static int flushContiguous(tr_cache* cache, int pos, int n) static int flushRuns(tr_cache* cache, struct run_info* runs, int n) { - int i; int err = 0; - for (i = 0; err == 0 && i < n; i++) + for (int i = 0; err == 0 && i < n; i++) { - int j; - err = flushContiguous(cache, runs[i].pos, runs[i].len); - for (j = i + 1; j < n; j++) + for (int j = i + 1; j < n; j++) { if (runs[j].pos > runs[i].pos) { diff --git a/libtransmission/clients.c b/libtransmission/clients.c index ccde2e2b3..12cee8675 100644 --- a/libtransmission/clients.c +++ b/libtransmission/clients.c @@ -821,18 +821,18 @@ char* tr_clientForId(char* buf, size_t buflen, void const* id_in) { char out[32]; char* walk = out; - char const* in; - char const* in_end; - for (in = (char const*)id, in_end = in + 8; in != in_end; ++in) + for (size_t i = 0; i < 8; ++i) { - if (isprint((unsigned char)*in)) + char const c = chid[i]; + + if (isprint((unsigned char)c)) { - *walk++ = *in; + *walk++ = c; } else { - tr_snprintf(walk, out + sizeof(out) - walk, "%%%02X", (unsigned int)*in); + tr_snprintf(walk, out + sizeof(out) - walk, "%%%02X", (unsigned int)c); walk += 3; } } diff --git a/libtransmission/completion.c b/libtransmission/completion.c index 932bf309a..956da9c05 100644 --- a/libtransmission/completion.c +++ b/libtransmission/completion.c @@ -78,14 +78,13 @@ tr_completeness tr_cpGetStatus(tr_completion const* cp) void tr_cpPieceRem(tr_completion* cp, tr_piece_index_t piece) { - tr_block_index_t i; tr_block_index_t f; tr_block_index_t l; tr_torrent const* tor = cp->tor; tr_torGetPieceBlockRange(cp->tor, piece, &f, &l); - for (i = f; i <= l; ++i) + for (tr_block_index_t i = f; i <= l; ++i) { if (tr_cpBlockIsComplete(cp, i)) { @@ -100,12 +99,11 @@ void tr_cpPieceRem(tr_completion* cp, tr_piece_index_t piece) void tr_cpPieceAdd(tr_completion* cp, tr_piece_index_t piece) { - tr_block_index_t i; tr_block_index_t f; tr_block_index_t l; tr_torGetPieceBlockRange(cp->tor, piece, &f, &l); - for (i = f; i <= l; ++i) + for (tr_block_index_t i = f; i <= l; ++i) { tr_cpBlockAdd(cp, i); } @@ -135,13 +133,12 @@ uint64_t tr_cpHaveValid(tr_completion const* ccp) { if (ccp->haveValidIsDirty) { - tr_piece_index_t i; uint64_t size = 0; tr_completion* cp = (tr_completion*)ccp; /* mutable */ tr_torrent const* tor = ccp->tor; tr_info const* info = &tor->info; - for (i = 0; i < info->pieceCount; ++i) + for (tr_piece_index_t i = 0; i < info->pieceCount; ++i) { if (tr_cpPieceIsComplete(ccp, i)) { @@ -171,9 +168,7 @@ uint64_t tr_cpSizeWhenDone(tr_completion const* ccp) } else { - tr_piece_index_t p; - - for (p = 0; p < inf->pieceCount; ++p) + for (tr_piece_index_t p = 0; p < inf->pieceCount; ++p) { uint64_t n = 0; uint64_t const pieceSize = tr_torPieceCountBytes(tor, p); @@ -223,11 +218,10 @@ uint64_t tr_cpLeftUntilDone(tr_completion const* cp) void tr_cpGetAmountDone(tr_completion const* cp, float* tab, int tabCount) { - int i; bool const seed = tr_cpHasAll(cp); float const interval = cp->tor->info.pieceCount / (float)tabCount; - for (i = 0; i < tabCount; ++i) + for (int i = 0; i < tabCount; ++i) { if (seed) { @@ -324,10 +318,9 @@ void* tr_cpCreatePieceBitfield(tr_completion const* cp, size_t* byte_count) } else if (!tr_cpHasNone(cp)) { - tr_piece_index_t i; bool* flags = tr_new(bool, n); - for (i = 0; i < n; ++i) + for (tr_piece_index_t i = 0; i < n; ++i) { flags[i] = tr_cpPieceIsComplete(cp, i); } diff --git a/libtransmission/crypto-test.c b/libtransmission/crypto-test.c index c7ab98181..e39bb0d27 100644 --- a/libtransmission/crypto-test.c +++ b/libtransmission/crypto-test.c @@ -11,6 +11,7 @@ #include "transmission.h" #include "crypto.h" #include "crypto-utils.h" +#include "utils.h" #include "libtransmission-test.h" @@ -20,9 +21,8 @@ static int test_torrent_hash(void) { tr_crypto a; uint8_t hash[SHA_DIGEST_LENGTH]; - uint8_t i; - for (i = 0; i < SHA_DIGEST_LENGTH; ++i) + for (uint8_t i = 0; i < SHA_DIGEST_LENGTH; ++i) { hash[i] = i; } @@ -39,7 +39,7 @@ static int test_torrent_hash(void) tr_cryptoDestruct(&a); - for (i = 0; i < SHA_DIGEST_LENGTH; ++i) + for (uint8_t i = 0; i < SHA_DIGEST_LENGTH; ++i) { hash[i] = i + 1; } @@ -70,17 +70,17 @@ static int test_encrypt_decrypt(void) char const test2[] = { "@#)C$@)#(*%bvkdjfhwbc039bc4603756VB3)" }; char buf21[sizeof(test2)]; char buf22[sizeof(test2)]; - int i; + int public_key_length; - for (i = 0; i < SHA_DIGEST_LENGTH; ++i) + for (int i = 0; i < SHA_DIGEST_LENGTH; ++i) { hash[i] = (uint8_t)i; } tr_cryptoConstruct(&a, hash, false); tr_cryptoConstruct_(&b, hash, true); - check(tr_cryptoComputeSecret(&a, tr_cryptoGetMyPublicKey_(&b, &i))); - check(tr_cryptoComputeSecret_(&b, tr_cryptoGetMyPublicKey(&a, &i))); + check(tr_cryptoComputeSecret(&a, tr_cryptoGetMyPublicKey_(&b, &public_key_length))); + check(tr_cryptoComputeSecret_(&b, tr_cryptoGetMyPublicKey(&a, &public_key_length))); tr_cryptoEncryptInit(&a); tr_cryptoEncrypt(&a, sizeof(test1), test1, buf11); @@ -133,20 +133,17 @@ static int test_ssha1(void) { "QNY)(*#$B)!_X$B !_B#($^!)*&$%CV!#)&$C!@$(P*)", "{10e2d7acbb104d970514a147cd16d51dfa40fb3c0OSwJtOL" } }; - size_t i; - #define HASH_COUNT (4 * 1024) - for (i = 0; i < sizeof(test_data) / sizeof(*test_data); ++i) + for (size_t i = 0; i < TR_N_ELEMENTS(test_data); ++i) { char* const phrase = tr_strdup(test_data[i].plain_text); char** hashes = tr_new(char*, HASH_COUNT); - size_t j; check(tr_ssha1_matches(test_data[i].ssha1, phrase)); check(tr_ssha1_matches_(test_data[i].ssha1, phrase)); - for (j = 0; j < HASH_COUNT; ++j) + for (size_t j = 0; j < HASH_COUNT; ++j) { hashes[j] = j % 2 == 0 ? tr_ssha1(phrase) : tr_ssha1_(phrase); @@ -157,12 +154,10 @@ static int test_ssha1(void) check(tr_ssha1_matches_(hashes[j], phrase)); } - for (j = 0; j < HASH_COUNT; ++j) + for (size_t j = 0; j < HASH_COUNT; ++j) { - size_t k; - /* all hashes are different */ - for (k = 0; k < HASH_COUNT; ++k) + for (size_t k = 0; k < HASH_COUNT; ++k) { check(k == j || strcmp(hashes[j], hashes[k]) != 0); } @@ -173,14 +168,14 @@ static int test_ssha1(void) phrase[1] ^= phrase[0]; phrase[0] ^= phrase[1]; - for (j = 0; j < HASH_COUNT; ++j) + for (size_t j = 0; j < HASH_COUNT; ++j) { /* changed phrase doesn't match the hashes */ check(!tr_ssha1_matches(hashes[j], phrase)); check(!tr_ssha1_matches_(hashes[j], phrase)); } - for (j = 0; j < HASH_COUNT; ++j) + for (size_t j = 0; j < HASH_COUNT; ++j) { tr_free(hashes[j]); } @@ -200,10 +195,8 @@ static int test_ssha1(void) static int test_random(void) { - int i; - /* test that tr_rand_int() stays in-bounds */ - for (i = 0; i < 100000; ++i) + for (int i = 0; i < 100000; ++i) { int const val = tr_rand_int(100); check(val >= 0); @@ -241,7 +234,6 @@ static int test_base64(void) size_t len; char* in; char* out; - size_t i; out = tr_base64_encode_str("YOYO!", &len); check_uint_eq(strlen(out), len); @@ -270,35 +262,34 @@ static int test_base64(void) #define MAX_BUF_SIZE 1024 - for (i = 1; i <= MAX_BUF_SIZE; ++i) + for (size_t i = 1; i <= MAX_BUF_SIZE; ++i) { - size_t j; char buf[MAX_BUF_SIZE + 1]; - for (j = 0; j < i; ++j) + for (size_t j = 0; j < i; ++j) { buf[j] = (char)tr_rand_int_weak(256); } - out = tr_base64_encode(buf, j, &len); + out = tr_base64_encode(buf, i, &len); check_uint_eq(strlen(out), len); in = tr_base64_decode(out, len, &len); - check_uint_eq(j, len); + check_uint_eq(i, len); check(memcmp(in, buf, len) == 0); tr_free(in); tr_free(out); - for (j = 0; j < i; ++j) + for (size_t j = 0; j < i; ++j) { buf[j] = (char)(1 + tr_rand_int_weak(255)); } - buf[j] = '\0'; + buf[i] = '\0'; out = tr_base64_encode_str(buf, &len); check_uint_eq(strlen(out), len); in = tr_base64_decode_str(out, &len); - check_uint_eq(j, len); + check_uint_eq(i, len); check_streq(in, buf); tr_free(in); tr_free(out); diff --git a/libtransmission/crypto-utils-polarssl.c b/libtransmission/crypto-utils-polarssl.c index 80c04aca6..0b2b006f2 100644 --- a/libtransmission/crypto-utils-polarssl.c +++ b/libtransmission/crypto-utils-polarssl.c @@ -82,9 +82,7 @@ static bool check_polarssl_result(int result, int expected_result, char const* f static int my_rand(void* context UNUSED, unsigned char* buffer, size_t buffer_size) { - size_t i; - - for (i = 0; i < buffer_size; ++i) + for (size_t i = 0; i < buffer_size; ++i) { buffer[i] = tr_rand_int_weak(256); } diff --git a/libtransmission/crypto-utils.c b/libtransmission/crypto-utils.c index ffbb07d6f..8ea781e9c 100644 --- a/libtransmission/crypto-utils.c +++ b/libtransmission/crypto-utils.c @@ -141,14 +141,13 @@ char* tr_ssha1(char const* plain_text) assert(plain_text != NULL); - size_t i; unsigned char salt[saltval_len]; uint8_t sha[SHA_DIGEST_LENGTH]; char buf[2 * SHA_DIGEST_LENGTH + saltval_len + 2]; tr_rand_buffer(salt, saltval_len); - for (i = 0; i < saltval_len; ++i) + for (size_t i = 0; i < saltval_len; ++i) { salt[i] = salter[salt[i] % salter_len]; } diff --git a/libtransmission/fdlimit.c b/libtransmission/fdlimit.c index 0879fd1c6..77d56fff7 100644 --- a/libtransmission/fdlimit.c +++ b/libtransmission/fdlimit.c @@ -273,13 +273,12 @@ struct tr_fileset static void fileset_construct(struct tr_fileset* set, int n) { - struct tr_cached_file* o; struct tr_cached_file const TR_CACHED_FILE_INIT = { false, TR_BAD_SYS_FILE, 0, 0, 0 }; set->begin = tr_new(struct tr_cached_file, n); set->end = set->begin + n; - for (o = set->begin; o != set->end; ++o) + for (struct tr_cached_file* o = set->begin; o != set->end; ++o) { *o = TR_CACHED_FILE_INIT; } @@ -287,11 +286,9 @@ static void fileset_construct(struct tr_fileset* set, int n) static void fileset_close_all(struct tr_fileset* set) { - struct tr_cached_file* o; - if (set != NULL) { - for (o = set->begin; o != set->end; ++o) + for (struct tr_cached_file* o = set->begin; o != set->end; ++o) { if (cached_file_is_open(o)) { @@ -310,11 +307,9 @@ static void fileset_destruct(struct tr_fileset* set) static void fileset_close_torrent(struct tr_fileset* set, int torrent_id) { - struct tr_cached_file* o; - if (set != NULL) { - for (o = set->begin; o != set->end; ++o) + for (struct tr_cached_file* o = set->begin; o != set->end; ++o) { if (o->torrent_id == torrent_id && cached_file_is_open(o)) { @@ -326,11 +321,9 @@ static void fileset_close_torrent(struct tr_fileset* set, int torrent_id) static struct tr_cached_file* fileset_lookup(struct tr_fileset* set, int torrent_id, tr_file_index_t i) { - struct tr_cached_file* o; - if (set != NULL) { - for (o = set->begin; o != set->end; ++o) + for (struct tr_cached_file* o = set->begin; o != set->end; ++o) { if (torrent_id == o->torrent_id && i == o->file_index && cached_file_is_open(o)) { @@ -348,10 +341,8 @@ static struct tr_cached_file* fileset_get_empty_slot(struct tr_fileset* set) if (set->begin != NULL) { - struct tr_cached_file* o; - /* try to find an unused slot */ - for (o = set->begin; o != set->end; ++o) + for (struct tr_cached_file* o = set->begin; o != set->end; ++o) { if (!cached_file_is_open(o)) { @@ -360,7 +351,7 @@ static struct tr_cached_file* fileset_get_empty_slot(struct tr_fileset* set) } /* all slots are full... recycle the least recently used */ - for (cull = NULL, o = set->begin; o != set->end; ++o) + for (struct tr_cached_file* o = set->begin; o != set->end; ++o) { if (cull == NULL || o->used_at < cull->used_at) { diff --git a/libtransmission/file-test.c b/libtransmission/file-test.c index 11e891af8..686d2c8f6 100644 --- a/libtransmission/file-test.c +++ b/libtransmission/file-test.c @@ -698,13 +698,12 @@ static int test_path_basename_dirname(void) #endif }; - if (test_path_xname(common_xname_tests, sizeof(common_xname_tests) / sizeof(*common_xname_tests), - tr_sys_path_basename) != 0) + if (test_path_xname(common_xname_tests, TR_N_ELEMENTS(common_xname_tests), tr_sys_path_basename) != 0) { return 1; } - if (test_path_xname(common_xname_tests, sizeof(common_xname_tests) / sizeof(*common_xname_tests), tr_sys_path_dirname) != 0) + if (test_path_xname(common_xname_tests, TR_N_ELEMENTS(common_xname_tests), tr_sys_path_dirname) != 0) { return 1; } @@ -733,7 +732,7 @@ static int test_path_basename_dirname(void) #endif }; - if (test_path_xname(basename_tests, sizeof(basename_tests) / sizeof(*basename_tests), tr_sys_path_basename) != 0) + if (test_path_xname(basename_tests, TR_N_ELEMENTS(basename_tests), tr_sys_path_basename) != 0) { return 1; } @@ -767,7 +766,7 @@ static int test_path_basename_dirname(void) #endif }; - if (test_path_xname(dirname_tests, sizeof(dirname_tests) / sizeof(*dirname_tests), tr_sys_path_dirname) != 0) + if (test_path_xname(dirname_tests, TR_N_ELEMENTS(dirname_tests), tr_sys_path_dirname) != 0) { return 1; } @@ -1298,31 +1297,31 @@ static int test_file_utilities(void) fd = tr_sys_file_open(path1, TR_SYS_FILE_READ, 0, NULL); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("a", buffer); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("bc", buffer); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("def", buffer); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("ghij", buffer); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("", buffer); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("", buffer); check(tr_sys_file_read_line(fd, buffer, 4, &err)); check(err == NULL); check_streq("klmn", buffer); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("o", buffer); - check(!tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(!tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("o", buffer); /* on EOF, buffer stays unchanged */ @@ -1347,28 +1346,28 @@ static int test_file_utilities(void) tr_sys_file_seek(fd, 0, TR_SEEK_SET, NULL, NULL); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("p", buffer); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("", buffer); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("qr", buffer); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("stu", buffer); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("", buffer); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("", buffer); - check(tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("vwxy2", buffer); - check(!tr_sys_file_read_line(fd, buffer, sizeof(buffer) / sizeof(*buffer), &err)); + check(!tr_sys_file_read_line(fd, buffer, TR_N_ELEMENTS(buffer), &err)); check(err == NULL); check_streq("vwxy2", buffer); /* on EOF, buffer stays unchanged */ diff --git a/libtransmission/file-win32.c b/libtransmission/file-win32.c index 972c2ce2a..e03e0a93c 100644 --- a/libtransmission/file-win32.c +++ b/libtransmission/file-win32.c @@ -154,7 +154,7 @@ static wchar_t* path_to_native_path_ex(char const* path, int extra_chars_after, bool const is_unc = is_unc_path(path); /* `-2` for UNC since we overwrite existing prefix slashes */ - int const extra_chars_before = is_relative ? 0 : (is_unc ? ARRAYSIZE(unc_prefix) - 2 : ARRAYSIZE(local_prefix)); + int const extra_chars_before = is_relative ? 0 : (is_unc ? TR_N_ELEMENTS(unc_prefix) - 2 : TR_N_ELEMENTS(local_prefix)); /* TODO (?): assert(!is_relative); */ @@ -280,7 +280,6 @@ static void create_temp_path(char* path_template, void (* callback)(char const* { char* path; size_t path_size; - int attempt; tr_error* my_error = NULL; assert(path_template != NULL); @@ -291,7 +290,7 @@ static void create_temp_path(char* path_template, void (* callback)(char const* assert(path_size > 0); - for (attempt = 0; attempt < 100; ++attempt) + for (int attempt = 0; attempt < 100; ++attempt) { size_t i = path_size; diff --git a/libtransmission/file.c b/libtransmission/file.c index 40d0f5a11..c2edcd223 100644 --- a/libtransmission/file.c +++ b/libtransmission/file.c @@ -26,9 +26,6 @@ bool tr_sys_file_read_line(tr_sys_file_t handle, char* buffer, size_t buffer_siz while (buffer_size > 0) { - size_t i; - bool found_eol = false; - ret = tr_sys_file_read(handle, buffer + offset, MIN(buffer_size, 1024u), &bytes_read, error); if (!ret || (offset == 0 && bytes_read == 0)) @@ -37,19 +34,19 @@ bool tr_sys_file_read_line(tr_sys_file_t handle, char* buffer, size_t buffer_siz break; } - for (i = 0; i < bytes_read; ++i, ++offset, --buffer_size) + int64_t delta = 0; + + for (size_t i = 0; i < bytes_read; ++i, ++offset, --buffer_size) { if (buffer[offset] == '\n') { - found_eol = true; + delta = i - (int64_t)bytes_read + 1; break; } } - if (found_eol || buffer_size == 0 || bytes_read == 0) + if (delta != 0 || buffer_size == 0 || bytes_read == 0) { - int64_t const delta = -(int64_t)bytes_read + i + (found_eol ? 1 : 0); - if (delta != 0) { ret = tr_sys_file_seek(handle, delta, TR_SEEK_CUR, NULL, error); diff --git a/libtransmission/handshake.c b/libtransmission/handshake.c index abfecf104..819ade15f 100644 --- a/libtransmission/handshake.c +++ b/libtransmission/handshake.c @@ -357,7 +357,6 @@ static uint32_t getCryptoProvide(tr_handshake const* handshake) static uint32_t getCryptoSelect(tr_handshake const* handshake, uint32_t crypto_provide) { uint32_t choices[2]; - int i; int nChoices = 0; switch (handshake->encryptionMode) @@ -377,7 +376,7 @@ static uint32_t getCryptoSelect(tr_handshake const* handshake, uint32_t crypto_p break; } - for (i = 0; i < nChoices; ++i) + for (int i = 0; i < nChoices; ++i) { if (crypto_provide & choices[i]) { @@ -450,7 +449,6 @@ static ReadState readYb(tr_handshake* handshake, struct evbuffer* inbuf) /* HASH('req2', SKEY) xor HASH('req3', S) */ { - int i; uint8_t req2[SHA_DIGEST_LENGTH]; uint8_t req3[SHA_DIGEST_LENGTH]; uint8_t buf[SHA_DIGEST_LENGTH]; @@ -458,7 +456,7 @@ static ReadState readYb(tr_handshake* handshake, struct evbuffer* inbuf) tr_sha1(req2, "req2", 4, tr_cryptoGetTorrentHash(handshake->crypto), SHA_DIGEST_LENGTH, NULL); computeRequestHash(handshake, "req3", req3); - for (i = 0; i < SHA_DIGEST_LENGTH; ++i) + for (int i = 0; i < SHA_DIGEST_LENGTH; ++i) { buf[i] = req2[i] ^ req3[i]; } @@ -816,7 +814,6 @@ static ReadState readCryptoProvide(tr_handshake* handshake, struct evbuffer* inb { /* HASH('req2', SKEY) xor HASH('req3', S), ENCRYPT(VC, crypto_provide, len(PadC)) */ - int i; uint8_t vc_in[VC_LENGTH]; uint8_t req2[SHA_DIGEST_LENGTH]; uint8_t req3[SHA_DIGEST_LENGTH]; @@ -843,7 +840,7 @@ static ReadState readCryptoProvide(tr_handshake* handshake, struct evbuffer* inb evbuffer_remove(inbuf, req2, SHA_DIGEST_LENGTH); computeRequestHash(handshake, "req3", req3); - for (i = 0; i < SHA_DIGEST_LENGTH; ++i) + for (int i = 0; i < SHA_DIGEST_LENGTH; ++i) { obfuscatedTorrentHash[i] = req2[i] ^ req3[i]; } diff --git a/libtransmission/json-test.c b/libtransmission/json-test.c index b22edae65..693d1f2be 100644 --- a/libtransmission/json-test.c +++ b/libtransmission/json-test.c @@ -241,8 +241,6 @@ static int test_unescape(void) int main(void) { - int i; - int n; int rv; char const* comma_locales[] = @@ -271,17 +269,14 @@ int main(void) } /* run the tests in a locale with a decimal point of ',' */ - n = sizeof(comma_locales) / sizeof(comma_locales[0]); + bool is_locale_set = false; - for (i = 0; i < n; ++i) + for (size_t i = 0; !is_locale_set && i < TR_N_ELEMENTS(comma_locales); ++i) { - if (setlocale(LC_NUMERIC, comma_locales[i]) != NULL) - { - break; - } + is_locale_set = setlocale(LC_NUMERIC, comma_locales[i]) != NULL; } - if (i == n) + if (!is_locale_set) { fprintf(stderr, "WARNING: unable to run locale-specific json tests. add a locale like %s or %s\n", comma_locales[0], comma_locales[1]); diff --git a/libtransmission/libtransmission-test.c b/libtransmission/libtransmission-test.c index 90f4be1e5..02f227916 100644 --- a/libtransmission/libtransmission-test.c +++ b/libtransmission/libtransmission-test.c @@ -141,12 +141,11 @@ bool check_ptr_eq_impl(char const* file, int line, void const* expected, void co int runTests(testFunc const* const tests, int numTests) { - int i; int ret; (void)current_test; /* Use test even if we don't have any tests to run */ - for (i = 0; i < numTests; i++) + for (int i = 0; i < numTests; i++) { if ((ret = (*tests[i])()) != 0) { @@ -412,12 +411,9 @@ tr_torrent* libttest_zero_torrent_init(tr_session* session) void libttest_zero_torrent_populate(tr_torrent* tor, bool complete) { - tr_file_index_t i; - - for (i = 0; i < tor->info.fileCount; ++i) + for (tr_file_index_t i = 0; i < tor->info.fileCount; ++i) { int err; - uint64_t j; tr_sys_file_t fd; char* path; char* dirname; @@ -436,9 +432,9 @@ void libttest_zero_torrent_populate(tr_torrent* tor, bool complete) tr_sys_dir_create(dirname, TR_SYS_DIR_CREATE_PARENTS, 0700, NULL); fd = tr_sys_file_open(path, TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE | TR_SYS_FILE_TRUNCATE, 0600, NULL); - for (j = 0; j < file->length; ++j) + for (uint64_t j = 0; j < file->length; ++j) { - tr_sys_file_write(fd, ((!complete) && (i == 0) && (j < tor->info.pieceSize)) ? "\1" : "\0", 1, NULL, NULL); + tr_sys_file_write(fd, (!complete && i == 0 && j < tor->info.pieceSize) ? "\1" : "\0", 1, NULL, NULL); } tr_sys_file_close(fd, NULL); diff --git a/libtransmission/list.c b/libtransmission/list.c index d01b048cb..421d18d72 100644 --- a/libtransmission/list.c +++ b/libtransmission/list.c @@ -201,24 +201,25 @@ tr_list* tr_list_find(tr_list* list, void const* b, TrListCompareFunc func) void tr_list_insert_sorted(tr_list** list, void* data, TrListCompareFunc compare) { - /* find l, the node that we'll insert this data before */ - tr_list* l; + /* find the node that we'll insert this data before */ + tr_list* next_node = NULL; - for (l = *list; l != NULL; l = l->next) + for (tr_list* l = *list; l != NULL; l = l->next) { int const c = (*compare)(data, l->data); if (c <= 0) { + next_node = l; break; } } - if (l == NULL) + if (next_node == NULL) { tr_list_append(list, data); } - else if (l == *list) + else if (next_node == *list) { tr_list_prepend(list, data); } @@ -226,8 +227,8 @@ void tr_list_insert_sorted(tr_list** list, void* data, TrListCompareFunc compare { tr_list* node = node_alloc(); node->data = data; - node->prev = l->prev; - node->next = l; + node->prev = next_node->prev; + node->next = next_node; node->prev->next = node; node->next->prev = node; } diff --git a/libtransmission/magnet-test.c b/libtransmission/magnet-test.c index 6e81ffc38..4933e734e 100644 --- a/libtransmission/magnet-test.c +++ b/libtransmission/magnet-test.c @@ -14,7 +14,6 @@ static int test1(void) { - int i; char const* uri; tr_magnet_info* info; int const dec[] = @@ -39,7 +38,7 @@ static int test1(void) check_streq("http://server.webseed.org/path/to/file", info->webseeds[0]); check_streq("Display Name", info->displayName); - for (i = 0; i < 20; ++i) + for (int i = 0; i < 20; ++i) { check(info->hash[i] == dec[i]); } @@ -64,7 +63,7 @@ static int test1(void) check_streq("http://server.webseed.org/path/to/file", info->webseeds[0]); check_streq("Display Name", info->displayName); - for (i = 0; i < 20; ++i) + for (int i = 0; i < 20; ++i) { check(info->hash[i] == dec[i]); } diff --git a/libtransmission/magnet.c b/libtransmission/magnet.c index aa990f4cc..f17283c89 100644 --- a/libtransmission/magnet.c +++ b/libtransmission/magnet.c @@ -13,6 +13,7 @@ #include "transmission.h" #include "crypto-utils.h" /* tr_hex_to_sha1() */ #include "magnet.h" +#include "utils.h" #include "variant.h" #include "web.h" @@ -37,20 +38,17 @@ static int const base32Lookup[] = 0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF /* 'x', 'y', 'z', '{', '|', '}', '~', 'DEL' */ }; -static int const base32LookupLen = sizeof(base32Lookup) / sizeof(base32Lookup[0]); +static int const base32LookupLen = TR_N_ELEMENTS(base32Lookup); static void base32_to_sha1(uint8_t* out, char const* in, size_t const inlen) { size_t const outlen = 20; - size_t i; - size_t index; - size_t offset; memset(out, 0, 20); assert(inlen == 32); - for (i = 0, index = 0, offset = 0; i < inlen; ++i) + for (size_t i = 0, index = 0, offset = 0; i < inlen; ++i) { int digit; int lookup = in[i] - '0'; @@ -124,9 +122,7 @@ tr_magnet_info* tr_magnetParse(char const* uri) if (uri != NULL && strncmp(uri, "magnet:?", 8) == 0) { - char const* walk; - - for (walk = uri + 8; walk != NULL && *walk != '\0';) + for (char const* walk = uri + 8; walk != NULL && *walk != '\0';) { char const* key = walk; char const* delim = strchr(key, '='); @@ -224,16 +220,14 @@ void tr_magnetFree(tr_magnet_info* info) { if (info != NULL) { - int i; - - for (i = 0; i < info->trackerCount; ++i) + for (int i = 0; i < info->trackerCount; ++i) { tr_free(info->trackers[i]); } tr_free(info->trackers); - for (i = 0; i < info->webseedCount; ++i) + for (int i = 0; i < info->webseedCount; ++i) { tr_free(info->webseeds[i]); } @@ -247,7 +241,6 @@ void tr_magnetFree(tr_magnet_info* info) void tr_magnetCreateMetainfo(tr_magnet_info const* info, tr_variant* top) { - int i; tr_variant* d; tr_variantInitDict(top, 4); @@ -260,7 +253,7 @@ void tr_magnetCreateMetainfo(tr_magnet_info const* info, tr_variant* top) { tr_variant* trackers = tr_variantDictAddList(top, TR_KEY_announce_list, info->trackerCount); - for (i = 0; i < info->trackerCount; ++i) + for (int i = 0; i < info->trackerCount; ++i) { tr_variantListAddStr(tr_variantListAddList(trackers, 1), info->trackers[i]); } @@ -271,7 +264,7 @@ void tr_magnetCreateMetainfo(tr_magnet_info const* info, tr_variant* top) { tr_variant* urls = tr_variantDictAddList(top, TR_KEY_url_list, info->webseedCount); - for (i = 0; i < info->webseedCount; ++i) + for (int i = 0; i < info->webseedCount; ++i) { tr_variantListAddStr(urls, info->webseeds[i]); } diff --git a/libtransmission/makemeta-test.c b/libtransmission/makemeta-test.c index f063aded1..ab67857b7 100644 --- a/libtransmission/makemeta-test.c +++ b/libtransmission/makemeta-test.c @@ -122,7 +122,6 @@ static int test_single_directory_impl(tr_tracker_info const* trackers, size_t co char* top; char** files; size_t totalSize; - size_t i; char* tmpstr; /* set up our local test sandbox */ @@ -136,7 +135,7 @@ static int test_single_directory_impl(tr_tracker_info const* trackers, size_t co files = tr_new(char*, payloadCount); totalSize = 0; - for (i = 0; i < payloadCount; i++) + for (size_t i = 0; i < payloadCount; i++) { char tmpl[16]; tr_snprintf(tmpl, sizeof(tmpl), "file.%04zu%s", i, "XXXXXX"); @@ -155,7 +154,7 @@ static int test_single_directory_impl(tr_tracker_info const* trackers, size_t co check_int_eq(totalSize, builder->totalSize); check(builder->isFolder); - for (i = 0; i < builder->fileCount; i++) + for (size_t i = 0; i < builder->fileCount; i++) { check_streq(files[i], builder->files[i].filename); check_int_eq(payloadSizes[i], builder->files[i].size); @@ -198,7 +197,7 @@ static int test_single_directory_impl(tr_tracker_info const* trackers, size_t co tr_metainfoFree(&inf); tr_metaInfoBuilderFree(builder); - for (i = 0; i < payloadCount; i++) + for (size_t i = 0; i < payloadCount; i++) { tr_free(files[i]); } @@ -214,7 +213,6 @@ static int test_single_directory_impl(tr_tracker_info const* trackers, size_t co static int test_single_directory_random_payload_impl(tr_tracker_info const* trackers, size_t const trackerCount, size_t const maxFileCount, size_t const maxFileSize, char const* comment, bool const isPrivate) { - size_t i; void** payloads; size_t* payloadSizes; size_t payloadCount; @@ -224,7 +222,7 @@ static int test_single_directory_random_payload_impl(tr_tracker_info const* trac payloads = tr_new0(void*, payloadCount); payloadSizes = tr_new0(size_t, payloadCount); - for (i = 0; i < payloadCount; i++) + for (size_t i = 0; i < payloadCount; i++) { size_t const n = 1 + tr_rand_int_weak(maxFileSize); payloads[i] = tr_new(char, n); @@ -236,7 +234,7 @@ static int test_single_directory_random_payload_impl(tr_tracker_info const* trac test_single_directory_impl(trackers, trackerCount, (void const**)payloads, payloadSizes, payloadCount, comment, isPrivate); /* cleanup */ - for (i = 0; i < payloadCount; i++) + for (size_t i = 0; i < payloadCount; i++) { tr_free(payloads[i]); } @@ -256,7 +254,6 @@ static int test_single_directory_random_payload(void) size_t trackerCount; bool isPrivate; char const* comment; - size_t i; trackerCount = 0; trackers[trackerCount].tier = trackerCount; @@ -268,7 +265,7 @@ static int test_single_directory_random_payload(void) comment = "This is the comment"; isPrivate = false; - for (i = 0; i < 10; i++) + for (size_t i = 0; i < 10; i++) { test_single_directory_random_payload_impl(trackers, trackerCount, DEFAULT_MAX_FILE_COUNT, DEFAULT_MAX_FILE_SIZE, comment, isPrivate); diff --git a/libtransmission/makemeta.c b/libtransmission/makemeta.c index ffa27de53..51c37b3f8 100644 --- a/libtransmission/makemeta.c +++ b/libtransmission/makemeta.c @@ -134,9 +134,7 @@ static int builderFileCompare(void const* va, void const* vb) tr_metainfo_builder* tr_metaInfoBuilderCreate(char const* topFileArg) { - int i; struct FileList* files; - struct FileList* walk; tr_metainfo_builder* ret = tr_new0(tr_metainfo_builder, 1); ret->top = tr_sys_path_resolve(topFileArg, NULL); @@ -156,21 +154,24 @@ tr_metainfo_builder* tr_metaInfoBuilderCreate(char const* topFileArg) tr_free(dir); } - for (walk = files; walk != NULL; walk = walk->next) + for (struct FileList* walk = files; walk != NULL; walk = walk->next) { ++ret->fileCount; } ret->files = tr_new0(tr_metainfo_builder_file, ret->fileCount); - for (i = 0, walk = files; walk != NULL; ++i) + for (int i = 0; files != NULL; ++i) { - struct FileList* tmp = walk; + struct FileList* tmp = files; + files = files->next; + tr_metainfo_builder_file* file = &ret->files[i]; - walk = walk->next; file->filename = tmp->filename; file->size = tmp->size; + ret->totalSize += tmp->size; + tr_free(tmp); } @@ -215,19 +216,16 @@ void tr_metaInfoBuilderFree(tr_metainfo_builder* builder) { if (builder != NULL) { - int i; - tr_file_index_t t; - - for (t = 0; t < builder->fileCount; ++t) + for (uint32_t i = 0; i < builder->fileCount; ++i) { - tr_free(builder->files[t].filename); + tr_free(builder->files[i].filename); } tr_free(builder->files); tr_free(builder->top); tr_free(builder->comment); - for (i = 0; i < builder->trackerCount; ++i) + for (int i = 0; i < builder->trackerCount; ++i) { tr_free(builder->trackers[i].announce); } @@ -388,10 +386,9 @@ static void makeInfoDict(tr_variant* dict, tr_metainfo_builder* builder) if (builder->isFolder) /* root node is a directory */ { - uint32_t i; tr_variant* list = tr_variantDictAddList(dict, TR_KEY_files, builder->fileCount); - for (i = 0; i < builder->fileCount; ++i) + for (uint32_t i = 0; i < builder->fileCount; ++i) { tr_variant* d = tr_variantListAddDict(list, 2); tr_variant* length = tr_variantDictAdd(d, TR_KEY_length); @@ -425,11 +422,10 @@ static void makeInfoDict(tr_variant* dict, tr_metainfo_builder* builder) static void tr_realMakeMetaInfo(tr_metainfo_builder* builder) { - int i; tr_variant top; /* allow an empty set, but if URLs *are* listed, verify them. #814, #971 */ - for (i = 0; i < builder->trackerCount && !builder->result; ++i) + for (int i = 0; i < builder->trackerCount && builder->result == TR_MAKEMETA_OK; ++i) { if (!tr_urlIsValidTracker(builder->trackers[i].announce)) { @@ -457,7 +453,7 @@ static void tr_realMakeMetaInfo(tr_metainfo_builder* builder) { tr_variant* annList = tr_variantDictAddList(&top, TR_KEY_announce_list, 0); - for (i = 0; i < builder->trackerCount; ++i) + for (int i = 0; i < builder->trackerCount; ++i) { if (prevTier != builder->trackers[i].tier) { @@ -562,13 +558,12 @@ static void makeMetaWorkerFunc(void* unused UNUSED) void tr_makeMetaInfo(tr_metainfo_builder* builder, char const* outputFile, tr_tracker_info const* trackers, int trackerCount, char const* comment, bool isPrivate) { - int i; tr_lock* lock; assert(tr_isBool(isPrivate)); /* free any variables from a previous run */ - for (i = 0; i < builder->trackerCount; ++i) + for (int i = 0; i < builder->trackerCount; ++i) { tr_free(builder->trackers[i].announce); } @@ -585,7 +580,7 @@ void tr_makeMetaInfo(tr_metainfo_builder* builder, char const* outputFile, tr_tr builder->trackerCount = trackerCount; builder->trackers = tr_new0(tr_tracker_info, builder->trackerCount); - for (i = 0; i < builder->trackerCount; ++i) + for (int i = 0; i < builder->trackerCount; ++i) { builder->trackers[i].tier = trackers[i].tier; builder->trackers[i].announce = tr_strdup(trackers[i].announce); diff --git a/libtransmission/metainfo-test.c b/libtransmission/metainfo-test.c index 25c191bcc..951457cd0 100644 --- a/libtransmission/metainfo-test.c +++ b/libtransmission/metainfo-test.c @@ -9,6 +9,7 @@ #include "libtransmission-test.h" #include "transmission.h" +#include "utils.h" #include @@ -51,7 +52,6 @@ static int test_magnet_link(void) static int test_metainfo(void) { - size_t i; struct { int expected_benc_err; @@ -83,7 +83,7 @@ static int test_metainfo(void) tr_logSetLevel(0); /* yes, we already know these will generate errors, thank you... */ - for (i = 0; i < (sizeof(metainfo) / sizeof(metainfo[0])); i++) + for (size_t i = 0; i < TR_N_ELEMENTS(metainfo); i++) { tr_ctor* ctor = tr_ctorNew(NULL); int const err = tr_ctorSetMetainfo(ctor, metainfo[i].benc, strlen(metainfo[i].benc)); diff --git a/libtransmission/metainfo.c b/libtransmission/metainfo.c index 273036850..059200841 100644 --- a/libtransmission/metainfo.c +++ b/libtransmission/metainfo.c @@ -38,12 +38,11 @@ static inline bool char_is_path_separator(char c) char* tr_metainfoGetBasename(tr_info const* inf) { - size_t i; char const* name = inf->originalName; size_t const name_len = strlen(name); char* ret = tr_strdup_printf("%s.%16.16s", name, inf->hashString); - for (i = 0; i < name_len; ++i) + for (size_t i = 0; i < name_len; ++i) { if (char_is_path_separator(ret[i])) { @@ -84,15 +83,12 @@ static bool getfile(char** setme, char const* root, tr_variant* path, struct evb if (tr_variantIsList(path)) { - int i; - int const n = tr_variantListSize(path); - success = true; evbuffer_drain(buf, evbuffer_get_length(buf)); root_len = strlen(root); evbuffer_add(buf, root, root_len); - for (i = 0; i < n; i++) + for (int i = 0, n = tr_variantListSize(path); i < n; i++) { size_t len; char const* str; @@ -135,7 +131,6 @@ static char const* parseFiles(tr_info* inf, tr_variant* files, tr_variant const* if (tr_variantIsList(files)) /* multi-file mode */ { - tr_file_index_t i; struct evbuffer* buf; char const* result; @@ -151,7 +146,7 @@ static char const* parseFiles(tr_info* inf, tr_variant* files, tr_variant const* inf->fileCount = tr_variantListSize(files); inf->files = tr_new0(tr_file, inf->fileCount); - for (i = 0; i < inf->fileCount; i++) + for (tr_file_index_t i = 0; i < inf->fileCount; i++) { tr_variant* file; tr_variant* path; @@ -263,27 +258,24 @@ static char const* getannounce(tr_info* inf, tr_variant* meta) if (tr_variantDictFindList(meta, TR_KEY_announce_list, &tiers)) { int n; - int i; - int j; - int validTiers; int const numTiers = tr_variantListSize(tiers); n = 0; - for (i = 0; i < numTiers; i++) + for (int i = 0; i < numTiers; i++) { n += tr_variantListSize(tr_variantListChild(tiers, i)); } trackers = tr_new0(tr_tracker_info, n); - for (i = 0, validTiers = 0; i < numTiers; i++) + for (int i = 0, validTiers = 0; i < numTiers; i++) { tr_variant* tier = tr_variantListChild(tiers, i); int const tierSize = tr_variantListSize(tier); bool anyAdded = false; - for (j = 0; j < tierSize; j++) + for (int j = 0; j < tierSize; j++) { if (tr_variantGetStr(tr_variantListChild(tier, j), &str, &len)) { @@ -392,13 +384,12 @@ static void geturllist(tr_info* inf, tr_variant* meta) if (tr_variantDictFindList(meta, TR_KEY_url_list, &urls)) { - int i; int const n = tr_variantListSize(urls); inf->webseedCount = 0; inf->webseeds = tr_new0(char*, n); - for (i = 0; i < n; i++) + for (int i = 0; i < n; i++) { if (tr_variantGetStr(tr_variantListChild(urls, i), &url, NULL)) { @@ -605,7 +596,7 @@ static char const* tr_metainfoParseImpl(tr_session const* session, tr_info* inf, inf->pieceCount = len / SHA_DIGEST_LENGTH; inf->pieces = tr_new0(tr_piece, inf->pieceCount); - for (i = 0; i < inf->pieceCount; i++) + for (tr_piece_index_t i = 0; i < inf->pieceCount; i++) { memcpy(inf->pieces[i].hash, &raw[i * SHA_DIGEST_LENGTH], SHA_DIGEST_LENGTH); } @@ -663,15 +654,12 @@ bool tr_metainfoParse(tr_session const* session, tr_variant const* meta_in, tr_i void tr_metainfoFree(tr_info* inf) { - unsigned int i; - tr_file_index_t ff; - - for (i = 0; i < inf->webseedCount; i++) + for (unsigned int i = 0; i < inf->webseedCount; i++) { tr_free(inf->webseeds[i]); } - for (ff = 0; ff < inf->fileCount; ff++) + for (tr_file_index_t ff = 0; ff < inf->fileCount; ff++) { tr_free(inf->files[ff].name); } @@ -685,7 +673,7 @@ void tr_metainfoFree(tr_info* inf) tr_free(inf->originalName); tr_free(inf->name); - for (i = 0; i < inf->trackerCount; i++) + for (unsigned int i = 0; i < inf->trackerCount; i++) { tr_free(inf->trackers[i].announce); tr_free(inf->trackers[i].scrape); diff --git a/libtransmission/move-test.c b/libtransmission/move-test.c index 6f19299ef..2a709ba12 100644 --- a/libtransmission/move-test.c +++ b/libtransmission/move-test.c @@ -64,7 +64,6 @@ static void test_incomplete_dir_threadfunc(void* vdata) static int test_incomplete_dir_impl(char const* incomplete_dir, char const* download_dir) { - tr_file_index_t file_index; tr_session* session; tr_torrent* tor; tr_completeness completeness; @@ -96,8 +95,8 @@ static int test_incomplete_dir_impl(char const* incomplete_dir, char const* down /* now finish writing it */ { - tr_block_index_t block_index; - tr_block_index_t first, last; + tr_block_index_t first; + tr_block_index_t last; char* zero_block = tr_new0(char, tor->blockSize); struct test_incomplete_dir_data data; @@ -108,7 +107,7 @@ static int test_incomplete_dir_impl(char const* incomplete_dir, char const* down tr_torGetPieceBlockRange(tor, data.pieceIndex, &first, &last); - for (block_index = first; block_index <= last; ++block_index) + for (tr_block_index_t block_index = first; block_index <= last; ++block_index) { evbuffer_add(data.buf, zero_block, tor->blockSize); data.block = block_index; @@ -137,7 +136,7 @@ static int test_incomplete_dir_impl(char const* incomplete_dir, char const* down check_int_eq(TR_SEED, completeness); - for (file_index = 0; file_index < tor->info.fileCount; ++file_index) + for (tr_file_index_t file_index = 0; file_index < tor->info.fileCount; ++file_index) { check_file_location(tor, file_index, tr_buildPath(download_dir, tor->info.files[file_index].name, NULL)); } @@ -179,7 +178,6 @@ static int test_incomplete_dir(void) static int test_set_location(void) { - tr_file_index_t file_index; int state; char* target_dir; tr_torrent* tor; @@ -215,7 +213,7 @@ static int test_set_location(void) /* confirm the filest really got moved */ libttest_sync(); - for (file_index = 0; file_index < tor->info.fileCount; ++file_index) + for (tr_file_index_t file_index = 0; file_index < tor->info.fileCount; ++file_index) { check_file_location(tor, file_index, tr_buildPath(target_dir, tor->info.files[file_index].name, NULL)); } diff --git a/libtransmission/peer-io.c b/libtransmission/peer-io.c index 86ee43b16..4a3430eb0 100644 --- a/libtransmission/peer-io.c +++ b/libtransmission/peer-io.c @@ -1376,11 +1376,10 @@ int tr_peerIoFlush(tr_peerIo* io, tr_direction dir, size_t limit) int tr_peerIoFlushOutgoingProtocolMsgs(tr_peerIo* io) { size_t byteCount = 0; - struct tr_datatype const* it; /* count up how many bytes are used by non-piece-data messages at the front of our outbound queue */ - for (it = io->outbuf_datatypes; it != NULL; it = it->next) + for (struct tr_datatype const* it = io->outbuf_datatypes; it != NULL; it = it->next) { if (it->isPieceData) { diff --git a/libtransmission/peer-mgr.c b/libtransmission/peer-mgr.c index 4bf9141d9..44926fe06 100644 --- a/libtransmission/peer-mgr.c +++ b/libtransmission/peer-mgr.c @@ -429,7 +429,6 @@ static void replicationFree(tr_swarm* s) static void replicationNew(tr_swarm* s) { - tr_piece_index_t piece_i; tr_piece_index_t const piece_count = s->tor->info.pieceCount; int const n = tr_ptrArraySize(&s->peers); @@ -438,12 +437,11 @@ static void replicationNew(tr_swarm* s) s->pieceReplicationSize = piece_count; s->pieceReplication = tr_new0(uint16_t, piece_count); - for (piece_i = 0; piece_i < piece_count; ++piece_i) + for (tr_piece_index_t piece_i = 0; piece_i < piece_count; ++piece_i) { - int peer_i; uint16_t r = 0; - for (peer_i = 0; peer_i < n; ++peer_i) + for (int peer_i = 0; peer_i < n; ++peer_i) { tr_peer* peer = tr_ptrArrayNth(&s->peers, peer_i); @@ -484,7 +482,6 @@ static void peerCallbackFunc(tr_peer*, tr_peer_event const*, void*); static void rebuildWebseedArray(tr_swarm* s, tr_torrent* tor) { - unsigned int i; tr_info const* inf = &tor->info; /* clear the array */ @@ -493,7 +490,7 @@ static void rebuildWebseedArray(tr_swarm* s, tr_torrent* tor) s->stats.activeWebseedCount = 0; /* repopulate it */ - for (i = 0; i < inf->webseedCount; ++i) + for (unsigned int i = 0; i < inf->webseedCount; ++i) { tr_webseed* w = tr_webseedNew(tor, inf->webseeds[i], peerCallbackFunc, s); tr_ptrArrayAppend(&s->webseeds, w); @@ -577,11 +574,9 @@ void tr_peerMgrOnBlocklistChanged(tr_peerMgr* mgr) since the blocklist has changed, erase that cached value */ while ((tor = tr_torrentNext(session, tor)) != NULL) { - int i; tr_swarm* s = tor->swarm; - int const n = tr_ptrArraySize(&s->pool); - for (i = 0; i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(&s->pool); i < n; ++i) { struct peer_atom* atom = tr_ptrArrayNth(&s->pool, i); atom->blocklisted = -1; @@ -772,7 +767,6 @@ static struct block_request* requestListLookup(tr_swarm* s, tr_block_index_t blo static void getBlockRequestPeers(tr_swarm* s, tr_block_index_t block, tr_ptrArray* peerArr) { bool exact; - int i; int pos; struct block_request key; @@ -782,7 +776,7 @@ static void getBlockRequestPeers(tr_swarm* s, tr_block_index_t block, tr_ptrArra assert(!exact); /* shouldn't have a request with .peer == NULL */ - for (i = pos; i < s->requestCount; ++i) + for (int i = pos; i < s->requestCount; ++i) { if (s->requests[i].block != block) { @@ -828,11 +822,9 @@ static int countActiveWebseeds(tr_swarm* s) if (s->tor->isRunning && !tr_torrentIsSeed(s->tor)) { - int i; - int const n = tr_ptrArraySize(&s->webseeds); uint64_t const now = tr_time_msec(); - for (i = 0; i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(&s->webseeds); i < n; ++i) { if (tr_peerIsTransferringPieces(tr_ptrArrayNth(&s->webseeds, i), now, TR_DOWN, NULL)) { @@ -862,12 +854,10 @@ static void updateEndgame(tr_swarm* s) } else if (s->endgame == 0) /* only recalculate when endgame first begins */ { - int i; int numDownloading = 0; - int const n = tr_ptrArraySize(&s->peers); /* add the active bittorrent peers... */ - for (i = 0; i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(&s->peers); i < n; ++i) { tr_peer const* p = tr_ptrArrayNth(&s->peers, i); @@ -1035,10 +1025,9 @@ static void assertWeightedPiecesAreSorted(Torrent* t) { if (t->endgame == 0) { - int i; setComparePieceByWeightTorrent(t); - for (i = 0; i < t->pieceCount - 1; ++i) + for (int i = 0; i < t->pieceCount - 1; ++i) { assert(comparePieceByWeight(&t->pieces[i], &t->pieces[i + 1]) <= 0); } @@ -1052,7 +1041,6 @@ static void assertReplicationCountIsExact(Torrent* t) * from a client. If a such a behavior is noticed, * a bug report should be filled to the faulty client. */ - size_t piece_i; uint16_t const* rep = t->pieceReplication; size_t const piece_count = t->pieceReplicationSize; tr_peer const** peers = (tr_peer const**)tr_ptrArrayBase(&t->peers); @@ -1060,12 +1048,11 @@ static void assertReplicationCountIsExact(Torrent* t) assert(piece_count == t->tor->info.pieceCount); - for (piece_i = 0; piece_i < piece_count; ++piece_i) + for (size_t piece_i = 0; piece_i < piece_count; ++piece_i) { - int peer_i; uint16_t r = 0; - for (peer_i = 0; peer_i < peer_count; ++peer_i) + for (int peer_i = 0; peer_i < peer_count; ++peer_i) { if (tr_bitsetHas(&peers[peer_i]->have, piece_i)) { @@ -1081,9 +1068,7 @@ static void assertReplicationCountIsExact(Torrent* t) static struct weighted_piece* pieceListLookup(tr_swarm* s, tr_piece_index_t index) { - int i; - - for (i = 0; i < s->pieceCount; ++i) + for (int i = 0; i < s->pieceCount; ++i) { if (s->pieces[i].index == index) { @@ -1098,7 +1083,6 @@ static void pieceListRebuild(tr_swarm* s) { if (!tr_torrentIsSeed(s->tor)) { - tr_piece_index_t i; tr_piece_index_t* pool; tr_piece_index_t poolCount = 0; tr_torrent const* tor = s->tor; @@ -1109,7 +1093,7 @@ static void pieceListRebuild(tr_swarm* s) /* build the new list */ pool = tr_new(tr_piece_index_t, inf->pieceCount); - for (i = 0; i < inf->pieceCount; ++i) + for (tr_piece_index_t i = 0; i < inf->pieceCount; ++i) { if (!inf->pieces[i].dnd) { @@ -1123,7 +1107,7 @@ static void pieceListRebuild(tr_swarm* s) pieceCount = poolCount; pieces = tr_new0(struct weighted_piece, pieceCount); - for (i = 0; i < poolCount; ++i) + for (tr_piece_index_t i = 0; i < poolCount; ++i) { struct weighted_piece* piece = pieces + i; piece->index = pool[i]; @@ -1279,13 +1263,12 @@ static void tr_incrReplicationOfPiece(tr_swarm* s, size_t const index) */ static void tr_incrReplicationFromBitfield(tr_swarm* s, tr_bitfield const* b) { - size_t i; uint16_t* rep = s->pieceReplication; size_t const n = s->tor->info.pieceCount; assert(replicationExists(s)); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { if (tr_bitfieldHas(b, i)) { @@ -1304,13 +1287,10 @@ static void tr_incrReplicationFromBitfield(tr_swarm* s, tr_bitfield const* b) */ static void tr_incrReplication(tr_swarm* s) { - int i; - int const n = s->pieceReplicationSize; - assert(replicationExists(s)); assert(s->pieceReplicationSize == s->tor->info.pieceCount); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < s->pieceReplicationSize; ++i) { ++s->pieceReplication[i]; } @@ -1321,22 +1301,19 @@ static void tr_incrReplication(tr_swarm* s) */ static void tr_decrReplicationFromBitfield(tr_swarm* s, tr_bitfield const* b) { - int i; - int const n = s->pieceReplicationSize; - assert(replicationExists(s)); assert(s->pieceReplicationSize == s->tor->info.pieceCount); if (tr_bitfieldHasAll(b)) { - for (i = 0; i < n; ++i) + for (size_t i = 0; i < s->pieceReplicationSize; ++i) { --s->pieceReplication[i]; } } else if (!tr_bitfieldHasNone(b)) { - for (i = 0; i < n; ++i) + for (size_t i = 0; i < s->pieceReplicationSize; ++i) { if (tr_bitfieldHas(b, i)) { @@ -1365,10 +1342,7 @@ void tr_peerMgrRebuildRequests(tr_torrent* tor) void tr_peerMgrGetNextRequests(tr_torrent* tor, tr_peer* peer, int numwant, tr_block_index_t* setme, int* numgot, bool get_intervals) { - int i; - int got; tr_swarm* s; - struct weighted_piece* pieces; tr_bitfield const* const have = &peer->have; /* sanity clause */ @@ -1376,7 +1350,6 @@ void tr_peerMgrGetNextRequests(tr_torrent* tor, tr_peer* peer, int numwant, tr_b assert(numwant > 0); /* walk through the pieces and find blocks that should be requested */ - got = 0; s = tor->swarm; /* prep the pieces list */ @@ -1394,23 +1367,26 @@ void tr_peerMgrGetNextRequests(tr_torrent* tor, tr_peer* peer, int numwant, tr_b assertWeightedPiecesAreSorted(s); updateEndgame(s); - pieces = s->pieces; - for (i = 0; i < s->pieceCount && got < numwant; ++i) + struct weighted_piece* pieces = s->pieces; + int got = 0; + int checkedPieceCount = 0; + + for (int i = 0; i < s->pieceCount && got < numwant; ++i, ++checkedPieceCount) { struct weighted_piece* p = pieces + i; /* if the peer has this piece that we want... */ if (tr_bitfieldHas(have, p->index)) { - tr_block_index_t b; tr_block_index_t first; tr_block_index_t last; tr_ptrArray peerArr = TR_PTR_ARRAY_INIT; tr_torGetPieceBlockRange(tor, p->index, &first, &last); - for (b = first; b <= last && (got < numwant || (get_intervals && setme[2 * got - 1] == b - 1)); ++b) + for (tr_block_index_t b = first; b <= last && (got < numwant || (get_intervals && setme[2 * got - 1] == b - 1)); + ++b) { int peerCount; tr_peer** peers; @@ -1470,7 +1446,8 @@ void tr_peerMgrGetNextRequests(tr_torrent* tor, tr_peer* peer, int numwant, tr_b else { /* begin a new interval */ - setme[2 * got] = setme[2 * got + 1] = b; + setme[2 * got] = b; + setme[2 * got + 1] = b; ++got; } @@ -1489,14 +1466,14 @@ void tr_peerMgrGetNextRequests(tr_torrent* tor, tr_peer* peer, int numwant, tr_b if (got > 0) { /* not enough requests || last piece modified */ - if (i == s->pieceCount) + if (checkedPieceCount == s->pieceCount) { - --i; + --checkedPieceCount; } setComparePieceByWeightTorrent(s); - while (--i >= 0) + for (int i = checkedPieceCount - 1; i >= 0; --i) { bool exact; @@ -1507,7 +1484,7 @@ void tr_peerMgrGetNextRequests(tr_torrent* tor, tr_peer* peer, int numwant, tr_b if (newpos > 0) { struct weighted_piece const piece = s->pieces[i]; - memmove(&s->pieces[i], &s->pieces[i + 1], sizeof(struct weighted_piece) * (newpos)); + memmove(&s->pieces[i], &s->pieces[i + 1], sizeof(struct weighted_piece) * newpos); s->pieces[i + newpos] = piece; } } @@ -1561,22 +1538,21 @@ static void refillUpkeep(evutil_socket_t foo UNUSED, short bar UNUSED, void* vmg { int keepCount = 0; int cancelCount = 0; - struct block_request const* it; - struct block_request const* end; - for (it = s->requests, end = it + n; it != end; ++it) + for (int i = 0; i < n; ++i) { - tr_peerMsgs* msgs = PEER_MSGS(it->peer); + struct block_request const* const request = &s->requests[i]; + tr_peerMsgs* msgs = PEER_MSGS(request->peer); - if (msgs != NULL && it->sentAt <= too_old && !tr_peerMsgsIsReadingBlock(msgs, it->block)) + if (msgs != NULL && request->sentAt <= too_old && !tr_peerMsgsIsReadingBlock(msgs, request->block)) { - cancel[cancelCount++] = *it; + cancel[cancelCount++] = *request; } else { - if (it != &s->requests[keepCount]) + if (i != keepCount) { - s->requests[keepCount] = *it; + s->requests[keepCount] = *request; } keepCount++; @@ -1587,22 +1563,25 @@ static void refillUpkeep(evutil_socket_t foo UNUSED, short bar UNUSED, void* vmg s->requestCount = keepCount; /* send cancel messages for all the "cancel" ones */ - for (it = cancel, end = it + cancelCount; it != end; ++it) + for (int i = 0; i < cancelCount; ++i) { - tr_peerMsgs* msgs = PEER_MSGS(it->peer); + struct block_request const* const request = &cancel[i]; + tr_peerMsgs* msgs = PEER_MSGS(request->peer); if (msgs != NULL) { - tr_historyAdd(&it->peer->cancelsSentToPeer, now, 1); - tr_peerMsgsCancel(msgs, it->block); - decrementPendingReqCount(it); + tr_historyAdd(&request->peer->cancelsSentToPeer, now, 1); + tr_peerMsgsCancel(msgs, request->block); + decrementPendingReqCount(request); } } /* decrement the pending request counts for the timed-out blocks */ - for (it = cancel, end = it + cancelCount; it != end; ++it) + for (int i = 0; i < cancelCount; ++i) { - pieceListRemoveRequest(s, it->block); + struct block_request const* const request = &cancel[i]; + + pieceListRemoveRequest(s, request->block); } } } @@ -1660,14 +1639,13 @@ static void peerSuggestedPiece(tr_swarm* s UNUSED, tr_peer* peer UNUSED, tr_piec /* request the blocks that we don't have in this piece */ { - tr_block_index_t b; tr_block_index_t first; tr_block_index_t last; tr_torrent const* tor = t->tor; tr_torGetPieceBlockRange(t->tor, pieceIndex, &first, &last); - for (b = first; b <= last; ++b) + for (tr_block_index_t b = first; b <= last; ++b) { if (tr_torrentBlockIsComplete(tor, b)) { @@ -1692,11 +1670,10 @@ static void removeRequestFromTables(tr_swarm* s, tr_block_index_t block, tr_peer either way we need to remove all its requests */ static void peerDeclinedAllRequests(tr_swarm* s, tr_peer const* peer) { - int i; - int n; + int n = 0; tr_block_index_t* blocks = tr_new(tr_block_index_t, s->requestCount); - for (i = n = 0; i < s->requestCount; ++i) + for (int i = 0; i < s->requestCount; ++i) { if (peer == s->requests[i].peer) { @@ -1704,7 +1681,7 @@ static void peerDeclinedAllRequests(tr_swarm* s, tr_peer const* peer) } } - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { removeRequestFromTables(s, blocks[i], peer); } @@ -1714,7 +1691,6 @@ static void peerDeclinedAllRequests(tr_swarm* s, tr_peer const* peer) static void cancelAllRequestsForBlock(tr_swarm* s, tr_block_index_t block, tr_peer* no_notify) { - int i; int peerCount; tr_peer** peers; tr_ptrArray peerArr; @@ -1723,7 +1699,7 @@ static void cancelAllRequestsForBlock(tr_swarm* s, tr_block_index_t block, tr_pe getBlockRequestPeers(s, block, &peerArr); peers = (tr_peer**)tr_ptrArrayPeek(&peerArr, &peerCount); - for (i = 0; i < peerCount; ++i) + for (int i = 0; i < peerCount; ++i) { tr_peer* p = peers[i]; @@ -1741,13 +1717,11 @@ static void cancelAllRequestsForBlock(tr_swarm* s, tr_block_index_t block, tr_pe void tr_peerMgrPieceCompleted(tr_torrent* tor, tr_piece_index_t p) { - int i; bool pieceCameFromPeers = false; tr_swarm* const s = tor->swarm; - int const n = tr_ptrArraySize(&s->peers); /* walk through our peers */ - for (i = 0; i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(&s->peers); i < n; ++i) { tr_peer* peer = tr_ptrArrayNth(&s->peers, i); @@ -2243,12 +2217,11 @@ void tr_peerMgrMarkAllAsSeeds(tr_torrent* tor) tr_pex* tr_peerMgrCompactToPex(void const* compact, size_t compactLen, uint8_t const* added_f, size_t added_f_len, size_t* pexCount) { - size_t i; size_t n = compactLen / 6; uint8_t const* walk = compact; tr_pex* pex = tr_new0(tr_pex, n); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { pex[i].addr.type = TR_AF_INET; memcpy(&pex[i].addr.addr, walk, 4); @@ -2269,12 +2242,11 @@ tr_pex* tr_peerMgrCompactToPex(void const* compact, size_t compactLen, uint8_t c tr_pex* tr_peerMgrCompact6ToPex(void const* compact, size_t compactLen, uint8_t const* added_f, size_t added_f_len, size_t* pexCount) { - size_t i; size_t n = compactLen / 18; uint8_t const* walk = compact; tr_pex* pex = tr_new0(tr_pex, n); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { pex[i].addr.type = TR_AF_INET6; memcpy(&pex[i].addr.addr.addr6.s6_addr, walk, 16); @@ -2294,12 +2266,11 @@ tr_pex* tr_peerMgrCompact6ToPex(void const* compact, size_t compactLen, uint8_t tr_pex* tr_peerMgrArrayToPex(void const* array, size_t arrayLen, size_t* pexCount) { - size_t i; size_t n = arrayLen / (sizeof(tr_address) + 2); uint8_t const* walk = array; tr_pex* pex = tr_new0(tr_pex, n); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { memcpy(&pex[i].addr, walk, sizeof(tr_address)); memcpy(&pex[i].port, walk + sizeof(tr_address), 2); @@ -2317,12 +2288,10 @@ tr_pex* tr_peerMgrArrayToPex(void const* array, size_t arrayLen, size_t* pexCoun void tr_peerMgrGotBadPiece(tr_torrent* tor, tr_piece_index_t pieceIndex) { - int i; - int n; tr_swarm* s = tor->swarm; uint32_t const byteCount = tr_torPieceCountBytes(tor, pieceIndex); - for (i = 0, n = tr_ptrArraySize(&s->peers); i != n; ++i) + for (int i = 0, n = tr_ptrArraySize(&s->peers); i != n; ++i) { tr_peer* peer = tr_ptrArrayNth(&s->peers, i); @@ -2413,7 +2382,6 @@ static bool isAtomInteresting(tr_torrent const* tor, struct peer_atom* atom) int tr_peerMgrGetPeers(tr_torrent* tor, tr_pex** setme_pex, uint8_t af, uint8_t list_mode, int maxCount) { - int i; int n; int count = 0; int atomCount = 0; @@ -2435,24 +2403,22 @@ int tr_peerMgrGetPeers(tr_torrent* tor, tr_pex** setme_pex, uint8_t af, uint8_t if (list_mode == TR_PEERS_CONNECTED) /* connected peers only */ { - int i; tr_peer const** peers = (tr_peer const**)tr_ptrArrayBase(&s->peers); atomCount = tr_ptrArraySize(&s->peers); atoms = tr_new(struct peer_atom*, atomCount); - for (i = 0; i < atomCount; ++i) + for (int i = 0; i < atomCount; ++i) { atoms[i] = peers[i]->atom; } } else /* TR_PEERS_INTERESTING */ { - int i; struct peer_atom** atomBase = (struct peer_atom**)tr_ptrArrayBase(&s->pool); n = tr_ptrArraySize(&s->pool); atoms = tr_new(struct peer_atom*, n); - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { if (isAtomInteresting(tor, atomBase[i])) { @@ -2470,7 +2436,7 @@ int tr_peerMgrGetPeers(tr_torrent* tor, tr_pex** setme_pex, uint8_t af, uint8_t n = MIN(atomCount, maxCount); pex = walk = tr_new0(tr_pex, n); - for (i = 0; i < atomCount && count < n; ++i) + for (int i = 0; i < atomCount && count < n; ++i) { struct peer_atom const* atom = atoms[i]; @@ -2638,7 +2604,6 @@ void tr_peerUpdateProgress(tr_torrent* tor, tr_peer* peer) void tr_peerMgrOnTorrentGotMetainfo(tr_torrent* tor) { - int i; int peerCount; tr_peer** peers; @@ -2650,13 +2615,13 @@ void tr_peerMgrOnTorrentGotMetainfo(tr_torrent* tor) peerCount = tr_ptrArraySize(&tor->swarm->peers); peers = (tr_peer**)tr_ptrArrayBase(&tor->swarm->peers); - for (i = 0; i < peerCount; ++i) + for (int i = 0; i < peerCount; ++i) { tr_peerUpdateProgress(tor, peers[i]); } /* update the bittorrent peers' willingnes... */ - for (i = 0; i < peerCount; ++i) + for (int i = 0; i < peerCount; ++i) { tr_peerMsgsUpdateActive(tr_peerMsgsCast(peers[i]), TR_UP); tr_peerMsgsUpdateActive(tr_peerMsgsCast(peers[i]), TR_DOWN); @@ -2673,13 +2638,12 @@ void tr_peerMgrTorrentAvailability(tr_torrent const* tor, int8_t* tab, unsigned if (tr_torrentHasMetadata(tor)) { - tr_piece_index_t i; int const peerCount = tr_ptrArraySize(&tor->swarm->peers); tr_peer const** peers = (const tr_peer**)tr_ptrArrayBase(&tor->swarm->peers); float const interval = tor->info.pieceCount / (float)tabCount; bool const isSeed = tr_torrentGetCompleteness(tor) == TR_SEED; - for (i = 0; i < tabCount; ++i) + for (tr_piece_index_t i = 0; i < tabCount; ++i) { int const piece = i * interval; @@ -2689,9 +2653,7 @@ void tr_peerMgrTorrentAvailability(tr_torrent const* tor, int8_t* tab, unsigned } else if (peerCount != 0) { - int j; - - for (j = 0; j < peerCount; ++j) + for (int j = 0; j < peerCount; ++j) { if (tr_bitfieldHas(&peers[j]->have, piece)) { @@ -2748,8 +2710,6 @@ bool tr_peerIsSeed(tr_peer const* peer) /* count how many bytes we want that connected peers have */ uint64_t tr_peerMgrGetDesiredAvailable(tr_torrent const* tor) { - size_t i; - size_t n; uint64_t desiredAvailable; tr_swarm const* s; @@ -2769,7 +2729,7 @@ uint64_t tr_peerMgrGetDesiredAvailable(tr_torrent const* tor) return 0; } - n = tr_ptrArraySize(&s->peers); + size_t const n = tr_ptrArraySize(&s->peers); if (n == 0) { @@ -2779,9 +2739,9 @@ uint64_t tr_peerMgrGetDesiredAvailable(tr_torrent const* tor) { tr_peer const** peers = (tr_peer const**)tr_ptrArrayBase(&s->peers); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { - if (peers[i]->atom && atomIsSeed(peers[i]->atom)) + if (peers[i]->atom != NULL && atomIsSeed(peers[i]->atom)) { return tr_torrentGetLeftUntilDone(tor); } @@ -2797,7 +2757,7 @@ uint64_t tr_peerMgrGetDesiredAvailable(tr_torrent const* tor) desiredAvailable = 0; - for (i = 0, n = MIN(tor->info.pieceCount, s->pieceReplicationSize); i < n; ++i) + for (size_t i = 0, n = MIN(tor->info.pieceCount, s->pieceReplicationSize); i < n; ++i) { if (!tor->info.pieces[i].dnd && s->pieceReplication[i] > 0) { @@ -2811,7 +2771,6 @@ uint64_t tr_peerMgrGetDesiredAvailable(tr_torrent const* tor) double* tr_peerMgrWebSpeeds_KBps(tr_torrent const* tor) { - unsigned int i; tr_swarm* s; unsigned int n; double* ret = NULL; @@ -2826,7 +2785,7 @@ double* tr_peerMgrWebSpeeds_KBps(tr_torrent const* tor) assert(s->manager != NULL); assert(n == tor->info.webseedCount); - for (i = 0; i < n; ++i) + for (unsigned int i = 0; i < n; ++i) { unsigned int Bps = 0; @@ -2845,7 +2804,6 @@ double* tr_peerMgrWebSpeeds_KBps(tr_torrent const* tor) struct tr_peer_stat* tr_peerMgrPeerStats(tr_torrent const* tor, int* setmeCount) { - int i; int size = 0; tr_peer_stat* ret; tr_swarm const* s; @@ -2861,7 +2819,7 @@ struct tr_peer_stat* tr_peerMgrPeerStats(tr_torrent const* tor, int* setmeCount) size = tr_ptrArraySize(&s->peers); ret = tr_new0(tr_peer_stat, size); - for (i = 0; i < size; ++i) + for (int i = 0; i < size; ++i) { char* pch; tr_peer* peer = peers[i]; @@ -2968,14 +2926,13 @@ struct tr_peer_stat* tr_peerMgrPeerStats(tr_torrent const* tor, int* setmeCount) void tr_peerMgrClearInterest(tr_torrent* tor) { - int i; tr_swarm* s = tor->swarm; int const peerCount = tr_ptrArraySize(&s->peers); assert(tr_isTorrent(tor)); assert(tr_torrentIsLocked(tor)); - for (i = 0; i < peerCount; ++i) + for (int i = 0; i < peerCount; ++i) { tr_peerMsgsSetInterested(tr_ptrArrayNth(&s->peers, i), false); } @@ -2984,9 +2941,6 @@ void tr_peerMgrClearInterest(tr_torrent* tor) /* does this peer have any pieces that we want? */ static bool isPeerInteresting(tr_torrent* const tor, bool const* const piece_is_interesting, tr_peer const* const peer) { - tr_piece_index_t i; - tr_piece_index_t n; - /* these cases should have already been handled by the calling code... */ assert(!tr_torrentIsSeed(tor)); assert(tr_torrentIsPieceTransferAllowed(tor, TR_PEER_TO_CLIENT)); @@ -2996,7 +2950,7 @@ static bool isPeerInteresting(tr_torrent* const tor, bool const* const piece_is_ return true; } - for (i = 0, n = tor->info.pieceCount; i < n; ++i) + for (tr_piece_index_t i = 0; i < tor->info.pieceCount; ++i) { if (piece_is_interesting[i] && tr_bitfieldHas(&peer->have, i)) { @@ -3038,7 +2992,6 @@ static int compare_rechoke_info(void const* va, void const* vb) /* determines who we send "interested" messages to */ static void rechokeDownloads(tr_swarm* s) { - int i; int maxPeers = 0; int rechoke_count = 0; struct tr_rechoke_info* rechoke = NULL; @@ -3077,7 +3030,7 @@ static void rechokeDownloads(tr_swarm* s) * peers in our calculations lest they confuse Transmission into * thinking it's hit its bandwidth cap. */ - for (i = 0; i < peerCount; ++i) + for (int i = 0; i < peerCount; ++i) { tr_peer const* peer = tr_ptrArrayNth(&s->peers, i); int const b = tr_historyGet(&peer->blocksSentToClient, now, CANCEL_HISTORY_SEC); @@ -3140,13 +3093,13 @@ static void rechokeDownloads(tr_swarm* s) /* build a bitfield of interesting pieces... */ piece_is_interesting = tr_new(bool, n); - for (i = 0; i < n; i++) + for (int i = 0; i < n; ++i) { piece_is_interesting[i] = !tor->info.pieces[i].dnd && !tr_torrentPieceIsComplete(tor, i); } /* decide WHICH peers to be interested in (based on their cancel-to-block ratio) */ - for (i = 0; i < peerCount; ++i) + for (int i = 0; i < peerCount; ++i) { tr_peer* peer = tr_ptrArrayNth(&s->peers, i); @@ -3200,7 +3153,7 @@ static void rechokeDownloads(tr_swarm* s) qsort(rechoke, rechoke_count, sizeof(struct tr_rechoke_info), compare_rechoke_info); s->interestedCount = MIN(maxPeers, rechoke_count); - for (i = 0; i < rechoke_count; ++i) + for (int i = 0; i < rechoke_count; ++i) { tr_peerMsgsSetInterested(PEER_MSGS(rechoke[i].peer), i < s->interestedCount); } @@ -3294,9 +3247,6 @@ static inline bool isBandwidthMaxedOut(tr_bandwidth const* b, uint64_t const now static void rechokeUploads(tr_swarm* s, uint64_t const now) { - int i; - int size; - int unchokedInterested; int const peerCount = tr_ptrArraySize(&s->peers); tr_peer** peers = (tr_peer**)tr_ptrArrayBase(&s->peers); struct ChokeData* choke = tr_new0(struct ChokeData, peerCount); @@ -3317,8 +3267,10 @@ static void rechokeUploads(tr_swarm* s, uint64_t const now) s->optimistic = NULL; } + int size = 0; + /* sort the peers by preference and rate */ - for (i = 0, size = 0; i < peerCount; ++i) + for (int i = 0; i < peerCount; ++i) { tr_peer* peer = peers[i]; tr_peerMsgs* msgs = PEER_MSGS(peer); @@ -3364,9 +3316,10 @@ static void rechokeUploads(tr_swarm* s, uint64_t const now) * * If our bandwidth is maxed out, don't unchoke any more peers. */ - unchokedInterested = 0; + int unchokedInterested = 0; + int checkedChokeCount = 0; - for (i = 0; i < size && unchokedInterested < session->uploadSlotsPerTorrent; ++i) + for (int i = 0; i < size && unchokedInterested < session->uploadSlotsPerTorrent; ++i, ++checkedChokeCount) { choke[i].isChoked = isMaxedOut ? choke[i].wasChoked : false; @@ -3377,26 +3330,20 @@ static void rechokeUploads(tr_swarm* s, uint64_t const now) } /* optimistic unchoke */ - if (s->optimistic == NULL && !isMaxedOut && i < size) + if (s->optimistic == NULL && !isMaxedOut && checkedChokeCount < size) { int n; struct ChokeData* c; tr_ptrArray randPool = TR_PTR_ARRAY_INIT; - for (; i < size; ++i) + for (int i = checkedChokeCount; i < size; ++i) { if (choke[i].isInterested) { tr_peerMsgs const* msgs = choke[i].msgs; - int x = 1; - int y; + int const x = isNew(msgs) ? 3 : 1; - if (isNew(msgs)) - { - x *= 3; - } - - for (y = 0; y < x; ++y) + for (int y = 0; y < x; ++y) { tr_ptrArrayAppend(&randPool, &choke[i]); } @@ -3414,7 +3361,7 @@ static void rechokeUploads(tr_swarm* s, uint64_t const now) tr_ptrArrayDestruct(&randPool, NULL); } - for (i = 0; i < size; ++i) + for (int i = 0; i < size; ++i) { tr_peerMsgsSetChoke(choke[i].msgs, choke[i].isChoked); } @@ -3504,13 +3451,14 @@ static bool shouldPeerBeClosed(tr_swarm const* s, tr_peer const* peer, int peerC static tr_peer** getPeersToClose(tr_swarm* s, time_t const now_sec, int* setmeSize) { - int i, peerCount, outsize; + int peerCount; + int outsize = 0; struct tr_peer** ret = NULL; tr_peer** peers = (tr_peer**)tr_ptrArrayPeek(&s->peers, &peerCount); assert(swarmIsLocked(s)); - for (i = outsize = 0; i < peerCount; ++i) + for (int i = 0; i < peerCount; ++i) { if (shouldPeerBeClosed(s, peers[i], peerCount, now_sec)) { @@ -3652,13 +3600,12 @@ static void closeBadPeers(tr_swarm* s, time_t const now_sec) { if (!tr_ptrArrayEmpty(&s->peers)) { - int i; int peerCount; struct tr_peer** peers; peers = getPeersToClose(s, now_sec, &peerCount); - for (i = 0; i < peerCount; ++i) + for (int i = 0; i < peerCount; ++i) { closePeer(s, peers[i]); } @@ -3710,14 +3657,14 @@ static int comparePeerLiveliness(void const* va, void const* vb) static void sortPeersByLivelinessImpl(tr_peer** peers, void** clientData, int n, uint64_t now, int (* compare)(void const* va, void const* vb)) { - int i; struct peer_liveliness* lives; struct peer_liveliness* l; /* build a sortable array of peer + extra info */ - lives = l = tr_new0(struct peer_liveliness, n); + lives = tr_new0(struct peer_liveliness, n); + l = lives; - for (i = 0; i < n; ++i, ++l) + for (int i = 0; i < n; ++i, ++l) { tr_peer* p = peers[i]; l->peer = p; @@ -3736,8 +3683,10 @@ static void sortPeersByLivelinessImpl(tr_peer** peers, void** clientData, int n, assert(n == l - lives); qsort(lives, n, sizeof(struct peer_liveliness), compare); + l = lives; + /* build the peer array */ - for (i = 0, l = lives; i < n; ++i, ++l) + for (int i = 0; i < n; ++i, ++l) { peers[i] = l->peer; @@ -3802,11 +3751,9 @@ static void enforceSessionPeerLimit(tr_session* session, uint64_t now) while ((tor = tr_torrentNext(session, tor)) != NULL) { - int i; tr_swarm* s = tor->swarm; - int const tn = tr_ptrArraySize(&s->peers); - for (i = 0; i < tn; ++i, ++n) + for (int i = 0, tn = tr_ptrArraySize(&s->peers); i < tn; ++i, ++n) { peers[n] = tr_ptrArrayNth(&s->peers, i); swarms[n] = s; @@ -3886,10 +3833,9 @@ static void pumpAllPeers(tr_peerMgr* mgr) while ((tor = tr_torrentNext(mgr->session, tor)) != NULL) { - int j; tr_swarm* s = tor->swarm; - for (j = 0; j < tr_ptrArraySize(&s->peers); ++j) + for (int j = 0, n = tr_ptrArraySize(&s->peers); j < n; ++j) { tr_peerMsgsPulse(tr_ptrArrayNth(&s->peers, j)); } @@ -4052,14 +3998,13 @@ static void atomPulse(evutil_socket_t foo UNUSED, short bar UNUSED, void* vmgr) if (atomCount > maxAtomCount) /* we've got too many atoms... time to prune */ { - int i; int keepCount = 0; int testCount = 0; struct peer_atom** keep = tr_new(struct peer_atom*, atomCount); struct peer_atom** test = tr_new(struct peer_atom*, atomCount); /* keep the ones that are in use */ - for (i = 0; i < atomCount; ++i) + for (int i = 0; i < atomCount; ++i) { struct peer_atom* atom = atoms[i]; @@ -4074,7 +4019,7 @@ static void atomPulse(evutil_socket_t foo UNUSED, short bar UNUSED, void* vmgr) } /* if there's room, keep the best of what's left */ - i = 0; + int i = 0; if (keepCount < maxAtomCount) { @@ -4097,7 +4042,7 @@ static void atomPulse(evutil_socket_t foo UNUSED, short bar UNUSED, void* vmgr) s->pool = TR_PTR_ARRAY_INIT; qsort(keep, keepCount, sizeof(struct peer_atom*), compareAtomPtrsByAddress); - for (i = 0; i < keepCount; ++i) + for (int i = 0; i < keepCount; ++i) { tr_ptrArrayAppend(&s->pool, keep[i]); } @@ -4280,11 +4225,10 @@ static void selectPeerCandidates(struct peer_candidate* candidates, int candidat static bool checkBestScoresComeFirst(struct peer_candidate const* candidates, int n, int k) { - int i; uint64_t worstFirstScore = 0; int const x = MIN(n, k) - 1; - for (i = 0; i < x; i++) + for (int i = 0; i < x; i++) { if (worstFirstScore < candidates[i].score) { @@ -4292,12 +4236,12 @@ static bool checkBestScoresComeFirst(struct peer_candidate const* candidates, in } } - for (i = 0; i < x; i++) + for (int i = 0; i < x; i++) { assert(candidates[i].score <= worstFirstScore); } - for (i = x + 1; i < n; i++) + for (int i = x + 1; i < n; i++) { assert(candidates[i].score >= worstFirstScore); } @@ -4346,7 +4290,6 @@ static struct peer_candidate* getPeerCandidates(tr_session* session, int* candid while ((tor = tr_torrentNext(session, tor)) != NULL) { - int i; int nAtoms; struct peer_atom** atoms; @@ -4369,7 +4312,7 @@ static struct peer_candidate* getPeerCandidates(tr_session* session, int* candid atoms = (struct peer_atom**)tr_ptrArrayPeek(&tor->swarm->pool, &nAtoms); - for (i = 0; i < nAtoms; ++i) + for (int i = 0; i < nAtoms; ++i) { struct peer_atom* atom = atoms[i]; @@ -4450,13 +4393,12 @@ static void initiateCandidateConnection(tr_peerMgr* mgr, struct peer_candidate* static void makeNewPeerConnections(struct tr_peerMgr* mgr, int const max) { - int i; int n; struct peer_candidate* candidates; candidates = getPeerCandidates(mgr->session, &n, max); - for (i = 0; i < n && i < max; ++i) + for (int i = 0; i < n && i < max; ++i) { initiateCandidateConnection(mgr, &candidates[i]); } diff --git a/libtransmission/peer-msgs-test.c b/libtransmission/peer-msgs-test.c index 94232667e..864429a9f 100644 --- a/libtransmission/peer-msgs-test.c +++ b/libtransmission/peer-msgs-test.c @@ -17,7 +17,6 @@ int main(void) { #if 0 - uint32_t i; uint8_t infohash[SHA_DIGEST_LENGTH]; struct tr_address addr; tr_piece_index_t pieceCount = 1313; @@ -26,7 +25,7 @@ int main(void) tr_piece_index_t pieces[] = { 1059, 431, 808, 1217, 287, 376, 1188, 353, 508 }; tr_piece_index_t buf[16]; - for (i = 0; i < SHA_DIGEST_LENGTH; ++i) + for (uint32_t i = 0; i < SHA_DIGEST_LENGTH; ++i) { infohash[i] = 0xaa; } @@ -37,7 +36,7 @@ int main(void) numgot = tr_generateAllowedSet(buf, numwant, pieceCount, infohash, &addr); check(numgot == numwant); - for (i = 0; i < numgot; ++i) + for (uint32_t i = 0; i < numgot; ++i) { check(buf[i] == pieces[i]); } @@ -46,7 +45,7 @@ int main(void) numgot = tr_generateAllowedSet(buf, numwant, pieceCount, infohash, &addr); check(numgot == numwant); - for (i = 0; i < numgot; ++i) + for (uint32_t i = 0; i < numgot; ++i) { check(buf[i] == pieces[i]); } diff --git a/libtransmission/peer-msgs.c b/libtransmission/peer-msgs.c index 1547b52c6..07293b000 100644 --- a/libtransmission/peer-msgs.c +++ b/libtransmission/peer-msgs.c @@ -594,24 +594,19 @@ size_t tr_generateAllowedSet(tr_piece_index_t* setmePieces, size_t desiredSetSiz while (setSize < desiredSetSize) { - int i; - - for (i = 0; i < 5 && setSize < desiredSetSize; ++i) /* (4) */ + for (int i = 0; i < 5 && setSize < desiredSetSize; ++i) /* (4) */ { - size_t k; uint32_t j = i * 4; /* (5) */ uint32_t y = ntohl(*(uint32_t*)(x + j)); /* (6) */ uint32_t index = y % pieceCount; /* (7) */ + bool found = false; - for (k = 0; k < setSize; ++k) /* (8) */ + for (size_t k = 0; !found && k < setSize; ++k) /* (8) */ { - if (setmePieces[k] == index) - { - break; - } + found = setmePieces[k] == index; } - if (k == setSize) + if (!found) { setmePieces[setSize++] = index; /* (9) */ } @@ -631,7 +626,6 @@ static void updateFastSet(tr_peerMsgs* msgs UNUSED) if (fext && peerIsNeedy && !msgs->haveFastSet) { - size_t i; struct tr_address const* addr = tr_peerIoGetAddress(msgs->io, NULL); tr_info const* inf = &msgs->torrent->info; size_t const numwant = MIN(MAX_FAST_SET_SIZE, inf->pieceCount); @@ -641,7 +635,7 @@ static void updateFastSet(tr_peerMsgs* msgs UNUSED) msgs->haveFastSet = true; /* send it to the peer */ - for (i = 0; i < msgs->fastsetSize; ++i) + for (size_t i = 0; i < msgs->fastsetSize; ++i) { protocolSendAllowedFast(msgs, msgs->fastset[i]); } @@ -1170,7 +1164,6 @@ static void parseUtPex(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer* inbu if (tr_variantDictFindRaw(&val, TR_KEY_added, &added, &added_len)) { tr_pex* pex; - size_t i; size_t n; size_t added_f_len = 0; uint8_t const* added_f = NULL; @@ -1180,7 +1173,7 @@ static void parseUtPex(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer* inbu n = MIN(n, MAX_PEX_PEER_COUNT); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { int seedProbability = -1; @@ -1198,7 +1191,6 @@ static void parseUtPex(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer* inbu if (tr_variantDictFindRaw(&val, TR_KEY_added6, &added, &added_len)) { tr_pex* pex; - size_t i; size_t n; size_t added_f_len = 0; uint8_t const* added_f = NULL; @@ -1208,7 +1200,7 @@ static void parseUtPex(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer* inbu n = MIN(n, MAX_PEX_PEER_COUNT); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { int seedProbability = -1; @@ -1338,14 +1330,12 @@ static void updatePeerProgress(tr_peerMsgs* msgs) static void prefetchPieces(tr_peerMsgs* msgs) { - int i; - if (!getSession(msgs)->isPrefetchEnabled) { return; } - for (i = msgs->prefetchCount; i < msgs->peer.pendingReqsToClient && i < PREFETCH_SIZE; ++i) + for (int i = msgs->prefetchCount; i < msgs->peer.pendingReqsToClient && i < PREFETCH_SIZE; ++i) { struct peer_request const* req = msgs->peerAskedFor + i; @@ -1620,7 +1610,6 @@ static int readBtMessage(tr_peerMsgs* msgs, struct evbuffer* inbuf, size_t inlen case BT_CANCEL: { - int i; struct peer_request r; tr_peerIoReadUint32(msgs->io, inbuf, &r.index); tr_peerIoReadUint32(msgs->io, inbuf, &r.offset); @@ -1628,21 +1617,18 @@ static int readBtMessage(tr_peerMsgs* msgs, struct evbuffer* inbuf, size_t inlen tr_historyAdd(&msgs->peer.cancelsSentToClient, tr_time(), 1); dbgmsg(msgs, "got a Cancel %u:%u->%u", r.index, r.offset, r.length); - for (i = 0; i < msgs->peer.pendingReqsToClient; ++i) + for (int i = 0; i < msgs->peer.pendingReqsToClient; ++i) { struct peer_request const* req = msgs->peerAskedFor + i; if (req->index == r.index && req->offset == r.offset && req->length == r.length) { + tr_removeElementFromArray(msgs->peerAskedFor, i, sizeof(struct peer_request), + msgs->peer.pendingReqsToClient--); break; } } - if (i < msgs->peer.pendingReqsToClient) - { - tr_removeElementFromArray(msgs->peerAskedFor, i, sizeof(struct peer_request), msgs->peer.pendingReqsToClient--); - } - break; } @@ -1979,7 +1965,6 @@ static void updateBlockRequests(tr_peerMsgs* msgs) if (tr_torrentIsPieceTransferAllowed(msgs->torrent, TR_PEER_TO_CLIENT) && msgs->desiredRequestCount > 0 && msgs->peer.pendingReqsToPeer <= msgs->desiredRequestCount * 0.66) { - int i; int n; tr_block_index_t* blocks; int const numwant = msgs->desiredRequestCount - msgs->peer.pendingReqsToPeer; @@ -1990,7 +1975,7 @@ static void updateBlockRequests(tr_peerMsgs* msgs) blocks = tr_new(tr_block_index_t, numwant); tr_peerMgrGetNextRequests(msgs->torrent, &msgs->peer, numwant, blocks, &n, false); - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { struct peer_request req; blockToReq(msgs->torrent, blocks[i], &req); @@ -2417,9 +2402,9 @@ static void sendPex(tr_peerMsgs* msgs) } else { - int i; tr_variant val; - uint8_t* tmp, * walk; + uint8_t* tmp; + uint8_t* walk; struct evbuffer* payload; struct evbuffer* out = msgs->outMessages; @@ -2439,7 +2424,7 @@ static void sendPex(tr_peerMsgs* msgs) /* "added" */ tmp = walk = tr_new(uint8_t, diffs.addedCount * 6); - for (i = 0; i < diffs.addedCount; ++i) + for (int i = 0; i < diffs.addedCount; ++i) { memcpy(walk, &diffs.added[i].addr.addr, 4); walk += 4; @@ -2455,7 +2440,7 @@ static void sendPex(tr_peerMsgs* msgs) * unset each holepunch flag because we don't support it. */ tmp = walk = tr_new(uint8_t, diffs.addedCount); - for (i = 0; i < diffs.addedCount; ++i) + for (int i = 0; i < diffs.addedCount; ++i) { *walk++ = diffs.added[i].flags & ~ADDED_F_HOLEPUNCH; } @@ -2470,7 +2455,7 @@ static void sendPex(tr_peerMsgs* msgs) /* "dropped" */ tmp = walk = tr_new(uint8_t, diffs.droppedCount * 6); - for (i = 0; i < diffs.droppedCount; ++i) + for (int i = 0; i < diffs.droppedCount; ++i) { memcpy(walk, &diffs.dropped[i].addr.addr, 4); walk += 4; @@ -2488,7 +2473,7 @@ static void sendPex(tr_peerMsgs* msgs) /* "added6" */ tmp = walk = tr_new(uint8_t, diffs6.addedCount * 18); - for (i = 0; i < diffs6.addedCount; ++i) + for (int i = 0; i < diffs6.addedCount; ++i) { memcpy(walk, &diffs6.added[i].addr.addr.addr6.s6_addr, 16); walk += 16; @@ -2504,7 +2489,7 @@ static void sendPex(tr_peerMsgs* msgs) * unset each holepunch flag because we don't support it. */ tmp = walk = tr_new(uint8_t, diffs6.addedCount); - for (i = 0; i < diffs6.addedCount; ++i) + for (int i = 0; i < diffs6.addedCount; ++i) { *walk++ = diffs6.added[i].flags & ~ADDED_F_HOLEPUNCH; } @@ -2519,7 +2504,7 @@ static void sendPex(tr_peerMsgs* msgs) /* "dropped6" */ tmp = walk = tr_new(uint8_t, diffs6.droppedCount * 18); - for (i = 0; i < diffs6.droppedCount; ++i) + for (int i = 0; i < diffs6.droppedCount; ++i) { memcpy(walk, &diffs6.dropped[i].addr.addr.addr6.s6_addr, 16); walk += 16; diff --git a/libtransmission/platform-quota.c b/libtransmission/platform-quota.c index d81cac0a1..f1c439003 100644 --- a/libtransmission/platform-quota.c +++ b/libtransmission/platform-quota.c @@ -126,7 +126,6 @@ static char const* getdev(char const* path) #else /* BSD derived systems */ - int i; int n; struct statfs* mnt; @@ -137,15 +136,15 @@ static char const* getdev(char const* path) return NULL; } - for (i = 0; i < n; i++) + for (int i = 0; i < n; i++) { if (tr_strcmp0(path, mnt[i].f_mntonname) == 0) { - break; + return mnt[i].f_mntfromname; } } - return i < n ? mnt[i].f_mntfromname : NULL; + return NULL; #endif } @@ -203,7 +202,6 @@ static char const* getfstype(char const* device) #else /* BSD derived systems */ - int i; int n; struct statfs* mnt; @@ -214,15 +212,15 @@ static char const* getfstype(char const* device) return NULL; } - for (i = 0; i < n; i++) + for (int i = 0; i < n; i++) { if (tr_strcmp0(device, mnt[i].f_mntfromname) == 0) { - break; + return mnt[i].f_fstypename; } } - return i < n ? mnt[i].f_fstypename : NULL; + return NULL; #endif } diff --git a/libtransmission/platform.c b/libtransmission/platform.c index fa9732a5b..120c44704 100644 --- a/libtransmission/platform.c +++ b/libtransmission/platform.c @@ -531,7 +531,7 @@ char const* tr_getWebClientDir(tr_session const* session UNUSED) &FOLDERID_ProgramData }; - for (size_t i = 0; s == NULL && i < ARRAYSIZE(known_folder_ids); ++i) + for (size_t i = 0; s == NULL && i < TR_N_ELEMENTS(known_folder_ids); ++i) { char* dir = win32_get_known_folder(known_folder_ids[i]); s = tr_buildPath(dir, "Transmission", "Web", NULL); @@ -549,7 +549,7 @@ char const* tr_getWebClientDir(tr_session const* session UNUSED) wchar_t wide_module_path[MAX_PATH]; char* module_path; char* dir; - GetModuleFileNameW(NULL, wide_module_path, sizeof(wide_module_path) / sizeof(*wide_module_path)); + GetModuleFileNameW(NULL, wide_module_path, TR_N_ELEMENTS(wide_module_path)); module_path = tr_win32_native_to_utf8(wide_module_path, -1); dir = tr_sys_path_dirname(module_path, NULL); tr_free(module_path); @@ -570,7 +570,6 @@ char const* tr_getWebClientDir(tr_session const* session UNUSED) #else /* everyone else, follow the XDG spec */ tr_list* candidates = NULL; - tr_list* l; char* tmp; /* XDG_DATA_HOME should be the first in the list of candidates */ @@ -620,7 +619,7 @@ char const* tr_getWebClientDir(tr_session const* session UNUSED) } /* walk through the candidates & look for a match */ - for (l = candidates; l != NULL; l = l->next) + for (tr_list* l = candidates; l != NULL; l = l->next) { char* path = tr_buildPath(l->data, "transmission", "web", NULL); bool const found = isWebClientDir(path); diff --git a/libtransmission/ptrarray.c b/libtransmission/ptrarray.c index 5f4af685c..823763a52 100644 --- a/libtransmission/ptrarray.c +++ b/libtransmission/ptrarray.c @@ -31,13 +31,11 @@ void tr_ptrArrayDestruct(tr_ptrArray* p, PtrArrayForeachFunc func) void tr_ptrArrayForeach(tr_ptrArray* t, PtrArrayForeachFunc func) { - int i; - assert(t != NULL); assert(t->items != NULL || t->n_items == 0); assert(func != NULL); - for (i = 0; i < t->n_items; ++i) + for (int i = 0; i < t->n_items; ++i) { func(t->items[i]); } @@ -172,9 +170,7 @@ int tr_ptrArrayLowerBound(tr_ptrArray const* t, void const* ptr, int (* compare) static void assertArrayIsSortedAndUnique(tr_ptrArray const* t, int (* compare)(void const*, void const*)) { - int i; - - for (i = 0; i < t->n_items - 2; ++i) + for (int i = 0; i < t->n_items - 2; ++i) { assert(compare(t->items[i], t->items[i + 1]) < 0); } diff --git a/libtransmission/quark-test.c b/libtransmission/quark-test.c index be4eb5596..c41e1918b 100644 --- a/libtransmission/quark-test.c +++ b/libtransmission/quark-test.c @@ -14,9 +14,7 @@ static int test_static_quarks(void) { - int i; - - for (i = 0; i < TR_N_KEYS; i++) + for (int i = 0; i < TR_N_KEYS; i++) { tr_quark q; size_t len; @@ -28,7 +26,7 @@ static int test_static_quarks(void) check_int_eq(i, (int)q); } - for (i = 0; i + 1 < TR_N_KEYS; i++) + for (int i = 0; i + 1 < TR_N_KEYS; i++) { size_t len1; size_t len2; diff --git a/libtransmission/quark.c b/libtransmission/quark.c index 6844c38b3..dbff574f6 100644 --- a/libtransmission/quark.c +++ b/libtransmission/quark.c @@ -424,7 +424,7 @@ bool tr_quark_lookup(void const* str, size_t len, tr_quark* setme) { struct tr_key_struct tmp; struct tr_key_struct* match; - static size_t const n_static = sizeof(my_static) / sizeof(struct tr_key_struct); + static size_t const n_static = TR_N_ELEMENTS(my_static); bool success = false; assert(n_static == TR_N_KEYS); @@ -444,11 +444,10 @@ bool tr_quark_lookup(void const* str, size_t len, tr_quark* setme) /* was it added during runtime? */ if (!success && !tr_ptrArrayEmpty(&my_runtime)) { - size_t i; struct tr_key_struct** runtime = (struct tr_key_struct**)tr_ptrArrayBase(&my_runtime); size_t const n_runtime = tr_ptrArraySize(&my_runtime); - for (i = 0; i < n_runtime; ++i) + for (size_t i = 0; i < n_runtime; ++i) { if (compareKeys(&tmp, runtime[i]) == 0) { diff --git a/libtransmission/rename-test.c b/libtransmission/rename-test.c index 343c659f7..c3d45ce82 100644 --- a/libtransmission/rename-test.c +++ b/libtransmission/rename-test.c @@ -264,7 +264,6 @@ static void create_multifile_torrent_contents(char const* top) static int test_multifile_torrent(void) { - tr_file_index_t i; uint64_t loaded; tr_torrent* tor; tr_ctor* ctor; @@ -307,7 +306,7 @@ static int test_multifile_torrent(void) check_uint_eq(totalSize, tor->info.totalSize); check_uint_eq(4, tor->info.fileCount); - for (i = 0; i < 4; ++i) + for (tr_file_index_t i = 0; i < 4; ++i) { check_streq(expected_files[i], files[i].name); } @@ -372,7 +371,7 @@ static int test_multifile_torrent(void) /* ...and back again */ check_int_eq(0, torrentRenameAndWait(tor, "Felidae/Felinae/Felis/placeholder", "catus")); - for (i = 0; i < 4; ++i) + for (tr_file_index_t i = 0; i < 4; ++i) { check_streq(expected_files[i], files[i].name); check(testFileExistsAndConsistsOfThisString(tor, i, expected_contents[i])); @@ -403,7 +402,7 @@ static int test_multifile_torrent(void) libttest_blockingTorrentVerify(tor); testFileExistsAndConsistsOfThisString(tor, 0, expected_contents[0]); - for (i = 1; i <= 2; ++i) + for (tr_file_index_t i = 1; i <= 2; ++i) { str = tr_torrentFindFile(tor, i); check_streq(NULL, str); @@ -422,7 +421,7 @@ static int test_multifile_torrent(void) /* ...and back again */ check_int_eq(0, torrentRenameAndWait(tor, "Felidae/Felinae/Felis/foo", "catus")); - for (i = 0; i < 4; ++i) + for (tr_file_index_t i = 0; i < 4; ++i) { check_streq(expected_files[i], files[i].name); } @@ -433,7 +432,7 @@ static int test_multifile_torrent(void) strings[2] = "gabba/Felinae/Felis/catus/Saffron"; strings[3] = "gabba/Pantherinae/Panthera/Tiger/Tony"; - for (i = 0; i < 4; ++i) + for (tr_file_index_t i = 0; i < 4; ++i) { check_streq(strings[i], files[i].name); testFileExistsAndConsistsOfThisString(tor, i, expected_contents[i]); @@ -448,7 +447,7 @@ static int test_multifile_torrent(void) strings[2] = "Felidae/Felinae/Felis/catus/Saffron"; strings[3] = "Felidae/Pantherinae/Panthera/Snow Leopard/10.6"; - for (i = 0; i < 4; ++i) + for (tr_file_index_t i = 0; i < 4; ++i) { check_streq(strings[i], files[i].name); testFileExistsAndConsistsOfThisString(tor, i, expected_contents[i]); @@ -506,7 +505,6 @@ static int test_multifile_torrent(void) static int test_partial_file(void) { - tr_file_index_t i; tr_torrent* tor; tr_stat const* st; tr_file_stat* fst; @@ -548,14 +546,14 @@ static int test_partial_file(void) strings[1] = "foo/4096"; strings[2] = "foo/512"; - for (i = 0; i < 3; ++i) + for (tr_file_index_t i = 0; i < 3; ++i) { check_streq(strings[i], tor->info.files[i].name); } strings[0] = "foo/bar.part"; - for (i = 0; i < 3; ++i) + for (tr_file_index_t i = 0; i < 3; ++i) { char* expected = tr_buildPath(tor->currentDir, strings[i], NULL); char* path = tr_torrentFindFile(tor, i); diff --git a/libtransmission/resume.c b/libtransmission/resume.c index d63c52b4e..a37147773 100644 --- a/libtransmission/resume.c +++ b/libtransmission/resume.c @@ -65,11 +65,10 @@ static void savePeers(tr_variant* dict, tr_torrent const* tor) static int addPeers(tr_torrent* tor, uint8_t const* buf, int buflen) { - int i; int numAdded = 0; int const count = buflen / sizeof(tr_pex); - for (i = 0; i < count && numAdded < MAX_REMEMBERED_PEERS; ++i) + for (int i = 0; i < count && numAdded < MAX_REMEMBERED_PEERS; ++i) { tr_pex pex; memcpy(&pex, buf + i * sizeof(tr_pex), sizeof(tr_pex)); @@ -114,13 +113,12 @@ static uint64_t loadPeers(tr_variant* dict, tr_torrent* tor) static void saveDND(tr_variant* dict, tr_torrent const* tor) { tr_variant* list; - tr_file_index_t i; tr_info const* const inf = tr_torrentInfo(tor); tr_file_index_t const n = inf->fileCount; list = tr_variantDictAddList(dict, TR_KEY_dnd, n); - for (i = 0; i < n; ++i) + for (tr_file_index_t i = 0; i < n; ++i) { tr_variantListAddInt(list, inf->files[i].dnd ? 1 : 0); } @@ -137,9 +135,10 @@ static uint64_t loadDND(tr_variant* dict, tr_torrent* tor) int64_t tmp; tr_file_index_t* dl = tr_new(tr_file_index_t, n); tr_file_index_t* dnd = tr_new(tr_file_index_t, n); - tr_file_index_t i, dlCount = 0, dndCount = 0; + tr_file_index_t dlCount = 0; + tr_file_index_t dndCount = 0; - for (i = 0; i < n; ++i) + for (tr_file_index_t i = 0; i < n; ++i) { if (tr_variantGetInt(tr_variantListChild(list, i), &tmp) && tmp != 0) { @@ -183,13 +182,12 @@ static uint64_t loadDND(tr_variant* dict, tr_torrent* tor) static void saveFilePriorities(tr_variant* dict, tr_torrent const* tor) { tr_variant* list; - tr_file_index_t i; tr_info const* const inf = tr_torrentInfo(tor); tr_file_index_t const n = inf->fileCount; list = tr_variantDictAddList(dict, TR_KEY_priority, n); - for (i = 0; i < n; ++i) + for (tr_file_index_t i = 0; i < n; ++i) { tr_variantListAddInt(list, inf->files[i].priority); } @@ -204,9 +202,8 @@ static uint64_t loadFilePriorities(tr_variant* dict, tr_torrent* tor) if (tr_variantDictFindList(dict, TR_KEY_priority, &list) && tr_variantListSize(list) == n) { int64_t priority; - tr_file_index_t i; - for (i = 0; i < n; ++i) + for (tr_file_index_t i = 0; i < n; ++i) { if (tr_variantGetInt(tr_variantListChild(list, i), &priority)) { @@ -383,14 +380,13 @@ static uint64_t loadName(tr_variant* dict, tr_torrent* tor) static void saveFilenames(tr_variant* dict, tr_torrent const* tor) { - tr_file_index_t i; bool any_renamed; tr_file_index_t const n = tor->info.fileCount; tr_file const* files = tor->info.files; any_renamed = false; - for (i = 0; !any_renamed && i < n; ++i) + for (tr_file_index_t i = 0; !any_renamed && i < n; ++i) { any_renamed = files[i].is_renamed; } @@ -399,7 +395,7 @@ static void saveFilenames(tr_variant* dict, tr_torrent const* tor) { tr_variant* list = tr_variantDictAddList(dict, TR_KEY_files, n); - for (i = 0; i < n; ++i) + for (tr_file_index_t i = 0; i < n; ++i) { tr_variantListAddStr(list, files[i].is_renamed ? files[i].name : ""); } @@ -413,11 +409,10 @@ static uint64_t loadFilenames(tr_variant* dict, tr_torrent* tor) if (tr_variantDictFindList(dict, TR_KEY_files, &list)) { - size_t i; size_t const n = tr_variantListSize(list); tr_file* files = tor->info.files; - for (i = 0; i < tor->info.fileCount && i < n; ++i) + for (size_t i = 0; i < tor->info.fileCount && i < n; ++i) { char const* str; size_t str_len; @@ -463,7 +458,6 @@ static void saveProgress(tr_variant* dict, tr_torrent* tor) { tr_variant* l; tr_variant* prog; - tr_file_index_t fi; tr_info const* inf = tr_torrentInfo(tor); time_t const now = tr_time(); @@ -472,10 +466,8 @@ static void saveProgress(tr_variant* dict, tr_torrent* tor) /* add the file/piece check timestamps... */ l = tr_variantDictAddList(prog, TR_KEY_time_checked, inf->fileCount); - for (fi = 0; fi < inf->fileCount; ++fi) + for (tr_file_index_t fi = 0; fi < inf->fileCount; ++fi) { - tr_piece const* p; - tr_piece const* pend; time_t oldest_nonzero = now; time_t newest = 0; bool has_zero = false; @@ -483,8 +475,10 @@ static void saveProgress(tr_variant* dict, tr_torrent* tor) tr_file const* f = &inf->files[fi]; /* get the oldest and newest nonzero timestamps for pieces in this file */ - for (p = &inf->pieces[f->firstPiece], pend = &inf->pieces[f->lastPiece] + 1; p != pend; ++p) + for (tr_piece_index_t i = f->firstPiece; i <= f->lastPiece; ++i) { + tr_piece const* const p = &inf->pieces[i]; + if (p->timeChecked == 0) { has_zero = true; @@ -523,8 +517,10 @@ static void saveProgress(tr_variant* dict, tr_torrent* tor) tr_variant* ll = tr_variantListAddList(l, 2 + f->lastPiece - f->firstPiece); tr_variantListAddInt(ll, offset); - for (p = &inf->pieces[f->firstPiece], pend = &inf->pieces[f->lastPiece] + 1; p != pend; ++p) + for (tr_piece_index_t i = f->firstPiece; i <= f->lastPiece; ++i) { + tr_piece const* const p = &inf->pieces[i]; + tr_variantListAddInt(ll, p->timeChecked != 0 ? p->timeChecked - offset : 0); } } @@ -542,12 +538,11 @@ static void saveProgress(tr_variant* dict, tr_torrent* tor) static uint64_t loadProgress(tr_variant* dict, tr_torrent* tor) { - size_t i, n; uint64_t ret = 0; tr_variant* prog; tr_info const* inf = tr_torrentInfo(tor); - for (i = 0, n = inf->pieceCount; i < n; ++i) + for (size_t i = 0; i < inf->pieceCount; ++i) { inf->pieces[i].timeChecked = 0; } @@ -575,34 +570,29 @@ static uint64_t loadProgress(tr_variant* dict, tr_torrent* tor) only a single timestamp is saved for the file if *all* or *none* of the pieces were tested more recently than the file's mtime. */ - tr_file_index_t fi; - - for (fi = 0; fi < inf->fileCount; ++fi) + for (tr_file_index_t fi = 0; fi < inf->fileCount; ++fi) { tr_variant* b = tr_variantListChild(l, fi); tr_file const* f = &inf->files[fi]; - tr_piece* p = &inf->pieces[f->firstPiece]; - tr_piece const* pend = &inf->pieces[f->lastPiece] + 1; if (tr_variantIsInt(b)) { int64_t t; tr_variantGetInt(b, &t); - for (; p != pend; ++p) + for (tr_piece_index_t i = f->firstPiece; i <= f->lastPiece; ++i) { - p->timeChecked = (time_t)t; + inf->pieces[i].timeChecked = (time_t)t; } } else if (tr_variantIsList(b)) { - int i = 0; int64_t offset = 0; int const pieces = f->lastPiece + 1 - f->firstPiece; tr_variantGetInt(tr_variantListChild(b, 0), &offset); - for (i = 0; i < pieces; ++i) + for (int i = 0; i < pieces; ++i) { int64_t t = 0; tr_variantGetInt(tr_variantListChild(b, i + 1), &t); @@ -613,27 +603,23 @@ static uint64_t loadProgress(tr_variant* dict, tr_torrent* tor) } else if (tr_variantDictFindList(prog, TR_KEY_mtimes, &l)) { - tr_file_index_t fi; - /* Before 2.20, we stored the files' mtimes in the .resume file. When loading the .resume file, a torrent's file would be flagged as untested if its stored mtime didn't match its real mtime. */ - for (fi = 0; fi < inf->fileCount; ++fi) + for (tr_file_index_t fi = 0; fi < inf->fileCount; ++fi) { int64_t t; if (tr_variantGetInt(tr_variantListChild(l, fi), &t)) { tr_file const* f = &inf->files[fi]; - tr_piece* p = &inf->pieces[f->firstPiece]; - tr_piece const* pend = &inf->pieces[f->lastPiece] + 1; time_t const mtime = tr_torrentGetFileMTime(tor, fi); time_t const timeChecked = mtime == t ? mtime : 0; - for (; p != pend; ++p) + for (tr_piece_index_t i = f->firstPiece; i <= f->lastPiece; ++i) { - p->timeChecked = timeChecked; + inf->pieces[i].timeChecked = timeChecked; } } } diff --git a/libtransmission/rpc-server.c b/libtransmission/rpc-server.c index 731d4d480..8b1c5a7c8 100644 --- a/libtransmission/rpc-server.c +++ b/libtransmission/rpc-server.c @@ -45,7 +45,6 @@ #define MY_NAME "RPC Server" #define MY_REALM "Transmission" -#define TR_N_ELEMENTS(ary) (sizeof(ary) / sizeof(*ary)) struct tr_rpc_server { @@ -175,7 +174,6 @@ static void handle_upload(struct evhttp_request* req, struct tr_rpc_server* serv } else { - int i; int n; bool hasSessionId = false; tr_ptrArray parts = TR_PTR_ARRAY_INIT; @@ -187,24 +185,19 @@ static void handle_upload(struct evhttp_request* req, struct tr_rpc_server* serv n = tr_ptrArraySize(&parts); /* first look for the session id */ - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { struct tr_mimepart* p = tr_ptrArrayNth(&parts, i); if (tr_memmem(p->headers, p->headers_len, TR_RPC_SESSION_ID_HEADER, strlen(TR_RPC_SESSION_ID_HEADER)) != NULL) { + char const* ours = get_current_session_id(server); + size_t const ourlen = strlen(ours); + hasSessionId = ourlen <= p->body_len && memcmp(p->body, ours, ourlen) == 0; break; } } - if (i < n) - { - struct tr_mimepart const* p = tr_ptrArrayNth(&parts, i); - char const* ours = get_current_session_id(server); - size_t const ourlen = strlen(ours); - hasSessionId = ourlen <= p->body_len && memcmp(p->body, ours, ourlen) == 0; - } - if (!hasSessionId) { int code = 409; @@ -216,7 +209,7 @@ static void handle_upload(struct evhttp_request* req, struct tr_rpc_server* serv } else { - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { struct tr_mimepart* p = tr_ptrArrayNth(&parts, i); size_t body_len = p->body_len; @@ -278,8 +271,6 @@ static void handle_upload(struct evhttp_request* req, struct tr_rpc_server* serv static char const* mimetype_guess(char const* path) { - unsigned int i; - struct { char const* suffix; @@ -297,7 +288,7 @@ static char const* mimetype_guess(char const* path) }; char const* dot = strrchr(path, '.'); - for (i = 0; dot != NULL && i < TR_N_ELEMENTS(types); ++i) + for (unsigned int i = 0; dot != NULL && i < TR_N_ELEMENTS(types); ++i) { if (strcmp(dot + 1, types[i].suffix) == 0) { @@ -547,14 +538,12 @@ static void handle_rpc(struct evhttp_request* req, struct tr_rpc_server* server) static bool isAddressAllowed(tr_rpc_server const* server, char const* address) { - tr_list* l; - if (!server->isWhitelistEnabled) { return true; } - for (l = server->whitelist; l != NULL; l = l->next) + for (tr_list* l = server->whitelist; l != NULL; l = l->next) { if (tr_wildmat(address, l->data)) { @@ -849,7 +838,6 @@ char const* tr_rpcGetUrl(tr_rpc_server const* server) void tr_rpcSetWhitelist(tr_rpc_server* server, char const* whitelistStr) { void* tmp; - char const* walk; /* keep the string */ tmp = server->whitelistStr; @@ -863,7 +851,7 @@ void tr_rpcSetWhitelist(tr_rpc_server* server, char const* whitelistStr) } /* build the new whitelist entries */ - for (walk = whitelistStr; walk != NULL && *walk != '\0';) + for (char const* walk = whitelistStr; walk != NULL && *walk != '\0';) { char const* delimiters = " ,;"; size_t const len = strcspn(walk, delimiters); diff --git a/libtransmission/rpcimpl.c b/libtransmission/rpcimpl.c index 993bf35dc..af92ea434 100644 --- a/libtransmission/rpcimpl.c +++ b/libtransmission/rpcimpl.c @@ -38,8 +38,6 @@ #define RECENTLY_ACTIVE_SECONDS 60 -#define TR_N_ELEMENTS(ary) (sizeof(ary) / sizeof(*ary)) - #if 0 #define dbgmsg(fmt, ...) \ @@ -126,12 +124,11 @@ static tr_torrent** getTorrents(tr_session* session, tr_variant* args, int* setm if (tr_variantDictFindList(args, TR_KEY_ids, &ids)) { - int i; int const n = tr_variantListSize(ids); torrents = tr_new0(tr_torrent*, n); - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { char const* str; tr_torrent* tor; @@ -206,9 +203,7 @@ static tr_torrent** getTorrents(tr_session* session, tr_variant* args, int* setm static void notifyBatchQueueChange(tr_session* session, tr_torrent** torrents, int n) { - int i; - - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { notify(session, TR_RPC_TORRENT_CHANGED, torrents[i]); } @@ -271,7 +266,6 @@ static int compareTorrentByQueuePosition(void const* va, void const* vb) static char const* torrentStart(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int i; int torrentCount; tr_torrent** torrents; @@ -280,7 +274,7 @@ static char const* torrentStart(tr_session* session, tr_variant* args_in, tr_var torrents = getTorrents(session, args_in, &torrentCount); qsort(torrents, torrentCount, sizeof(tr_torrent*), compareTorrentByQueuePosition); - for (i = 0; i < torrentCount; ++i) + for (int i = 0; i < torrentCount; ++i) { tr_torrent* tor = torrents[i]; @@ -298,7 +292,6 @@ static char const* torrentStart(tr_session* session, tr_variant* args_in, tr_var static char const* torrentStartNow(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int i; int torrentCount; tr_torrent** torrents; @@ -307,7 +300,7 @@ static char const* torrentStartNow(tr_session* session, tr_variant* args_in, tr_ torrents = getTorrents(session, args_in, &torrentCount); qsort(torrents, torrentCount, sizeof(tr_torrent*), compareTorrentByQueuePosition); - for (i = 0; i < torrentCount; ++i) + for (int i = 0; i < torrentCount; ++i) { tr_torrent* tor = torrents[i]; @@ -325,7 +318,6 @@ static char const* torrentStartNow(tr_session* session, tr_variant* args_in, tr_ static char const* torrentStop(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int i; int torrentCount; tr_torrent** torrents; @@ -333,7 +325,7 @@ static char const* torrentStop(tr_session* session, tr_variant* args_in, tr_vari torrents = getTorrents(session, args_in, &torrentCount); - for (i = 0; i < torrentCount; ++i) + for (int i = 0; i < torrentCount; ++i) { tr_torrent* tor = torrents[i]; @@ -351,7 +343,6 @@ static char const* torrentStop(tr_session* session, tr_variant* args_in, tr_vari static char const* torrentRemove(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int i; int torrentCount; tr_rpc_callback_type type; bool deleteFlag; @@ -368,7 +359,7 @@ static char const* torrentRemove(tr_session* session, tr_variant* args_in, tr_va torrents = getTorrents(session, args_in, &torrentCount); - for (i = 0; i < torrentCount; ++i) + for (int i = 0; i < torrentCount; ++i) { tr_torrent* tor = torrents[i]; tr_rpc_callback_status const status = notify(session, type, tor); @@ -386,7 +377,6 @@ static char const* torrentRemove(tr_session* session, tr_variant* args_in, tr_va static char const* torrentReannounce(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int i; int torrentCount; tr_torrent** torrents; @@ -394,7 +384,7 @@ static char const* torrentReannounce(tr_session* session, tr_variant* args_in, t torrents = getTorrents(session, args_in, &torrentCount); - for (i = 0; i < torrentCount; ++i) + for (int i = 0; i < torrentCount; ++i) { tr_torrent* tor = torrents[i]; @@ -412,7 +402,6 @@ static char const* torrentReannounce(tr_session* session, tr_variant* args_in, t static char const* torrentVerify(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int i; int torrentCount; tr_torrent** torrents; @@ -420,7 +409,7 @@ static char const* torrentVerify(tr_session* session, tr_variant* args_in, tr_va torrents = getTorrents(session, args_in, &torrentCount); - for (i = 0; i < torrentCount; ++i) + for (int i = 0; i < torrentCount; ++i) { tr_torrent* tor = torrents[i]; tr_torrentVerify(tor, NULL, NULL); @@ -437,12 +426,11 @@ static char const* torrentVerify(tr_session* session, tr_variant* args_in, tr_va static void addFileStats(tr_torrent const* tor, tr_variant* list) { - tr_file_index_t i; tr_file_index_t n; tr_info const* info = tr_torrentInfo(tor); tr_file_stat* files = tr_torrentFiles(tor, &n); - for (i = 0; i < info->fileCount; ++i) + for (tr_file_index_t i = 0; i < info->fileCount; ++i) { tr_file const* file = &info->files[i]; tr_variant* d = tr_variantListAddDict(list, 3); @@ -456,12 +444,11 @@ static void addFileStats(tr_torrent const* tor, tr_variant* list) static void addFiles(tr_torrent const* tor, tr_variant* list) { - tr_file_index_t i; tr_file_index_t n; tr_info const* info = tr_torrentInfo(tor); tr_file_stat* files = tr_torrentFiles(tor, &n); - for (i = 0; i < info->fileCount; ++i) + for (tr_file_index_t i = 0; i < info->fileCount; ++i) { tr_file const* file = &info->files[i]; tr_variant* d = tr_variantListAddDict(list, 3); @@ -475,9 +462,7 @@ static void addFiles(tr_torrent const* tor, tr_variant* list) static void addWebseeds(tr_info const* info, tr_variant* webseeds) { - unsigned int i; - - for (i = 0; i < info->webseedCount; ++i) + for (unsigned int i = 0; i < info->webseedCount; ++i) { tr_variantListAddStr(webseeds, info->webseeds[i]); } @@ -485,9 +470,7 @@ static void addWebseeds(tr_info const* info, tr_variant* webseeds) static void addTrackers(tr_info const* info, tr_variant* trackers) { - unsigned int i; - - for (i = 0; i < info->trackerCount; ++i) + for (unsigned int i = 0; i < info->trackerCount; ++i) { tr_tracker_info const* t = &info->trackers[i]; tr_variant* d = tr_variantListAddDict(trackers, 4); @@ -500,9 +483,7 @@ static void addTrackers(tr_info const* info, tr_variant* trackers) static void addTrackerStats(tr_tracker_stat const* st, int n, tr_variant* list) { - int i; - - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { tr_tracker_stat const* s = &st[i]; tr_variant* d = tr_variantListAddDict(list, 26); @@ -537,13 +518,12 @@ static void addTrackerStats(tr_tracker_stat const* st, int n, tr_variant* list) static void addPeers(tr_torrent* tor, tr_variant* list) { - int i; int peerCount; tr_peer_stat* peers = tr_torrentPeers(tor, &peerCount); tr_variantInitList(list, peerCount); - for (i = 0; i < peerCount; ++i) + for (int i = 0; i < peerCount; ++i) { tr_variant* d = tr_variantListAddDict(list, 16); tr_peer_stat const* peer = peers + i; @@ -770,10 +750,9 @@ static void addField(tr_torrent* const tor, tr_info const* const inf, tr_stat co case TR_KEY_priorities: { - tr_file_index_t i; tr_variant* p = tr_variantDictAddList(d, key, inf->fileCount); - for (i = 0; i < inf->fileCount; ++i) + for (tr_file_index_t i = 0; i < inf->fileCount; ++i) { tr_variantListAddInt(p, inf->files[i].priority); } @@ -876,10 +855,9 @@ static void addField(tr_torrent* const tor, tr_info const* const inf, tr_stat co case TR_KEY_wanted: { - tr_file_index_t i; tr_variant* w = tr_variantDictAddList(d, key, inf->fileCount); - for (i = 0; i < inf->fileCount; ++i) + for (tr_file_index_t i = 0; i < inf->fileCount; ++i) { tr_variantListAddInt(w, inf->files[i].dnd ? 0 : 1); } @@ -908,11 +886,10 @@ static void addInfo(tr_torrent* tor, tr_variant* d, tr_variant* fields) if (n > 0) { - int i; tr_info const* const inf = tr_torrentInfo(tor); tr_stat const* const st = tr_torrentStat((tr_torrent*)tor); - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { size_t len; char const* str; @@ -928,7 +905,6 @@ static void addInfo(tr_torrent* tor, tr_variant* d, tr_variant* fields) static char const* torrentGet(tr_session* session, tr_variant* args_in, tr_variant* args_out, struct tr_rpc_idle_data* idle_data UNUSED) { - int i; int torrentCount; tr_torrent** torrents = getTorrents(session, args_in, &torrentCount); tr_variant* list = tr_variantDictAddList(args_out, TR_KEY_torrents, torrentCount); @@ -964,7 +940,7 @@ static char const* torrentGet(tr_session* session, tr_variant* args_in, tr_varia } else { - for (i = 0; i < torrentCount; ++i) + for (int i = 0; i < torrentCount; ++i) { addInfo(torrents[i], tr_variantListAdd(list), fields); } @@ -980,7 +956,6 @@ static char const* torrentGet(tr_session* session, tr_variant* args_in, tr_varia static char const* setFilePriorities(tr_torrent* tor, int priority, tr_variant* list) { - int i; int64_t tmp; int fileCount = 0; int const n = tr_variantListSize(list); @@ -989,7 +964,7 @@ static char const* setFilePriorities(tr_torrent* tor, int priority, tr_variant* if (n != 0) { - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { if (tr_variantGetInt(tr_variantListChild(list, i), &tmp)) { @@ -1006,9 +981,7 @@ static char const* setFilePriorities(tr_torrent* tor, int priority, tr_variant* } else /* if empty set, apply to all */ { - tr_file_index_t t; - - for (t = 0; t < tor->info.fileCount; ++t) + for (tr_file_index_t t = 0; t < tor->info.fileCount; ++t) { files[fileCount++] = t; } @@ -1025,7 +998,6 @@ static char const* setFilePriorities(tr_torrent* tor, int priority, tr_variant* static char const* setFileDLs(tr_torrent* tor, bool do_download, tr_variant* list) { - int i; int64_t tmp; int fileCount = 0; int const n = tr_variantListSize(list); @@ -1034,7 +1006,7 @@ static char const* setFileDLs(tr_torrent* tor, bool do_download, tr_variant* lis if (n != 0) /* if argument list, process them */ { - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { if (tr_variantGetInt(tr_variantListChild(list, i), &tmp)) { @@ -1051,9 +1023,7 @@ static char const* setFileDLs(tr_torrent* tor, bool do_download, tr_variant* lis } else /* if empty set, apply to all */ { - tr_file_index_t t; - - for (t = 0; t < tor->info.fileCount; ++t) + for (tr_file_index_t t = 0; t < tor->info.fileCount; ++t) { files[fileCount++] = t; } @@ -1070,10 +1040,9 @@ static char const* setFileDLs(tr_torrent* tor, bool do_download, tr_variant* lis static bool findAnnounceUrl(tr_tracker_info const* t, int n, char const* url, int* pos) { - int i; bool found = false; - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { if (strcmp(t[i].announce, url) == 0) { @@ -1093,10 +1062,9 @@ static bool findAnnounceUrl(tr_tracker_info const* t, int n, char const* url, in static int copyTrackers(tr_tracker_info* tgt, tr_tracker_info const* src, int n) { - int i; int maxTier = -1; - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { tgt[i].tier = src[i].tier; tgt[i].announce = tr_strdup(src[i].announce); @@ -1108,9 +1076,7 @@ static int copyTrackers(tr_tracker_info* tgt, tr_tracker_info const* src, int n) static void freeTrackers(tr_tracker_info* trackers, int n) { - int i; - - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { tr_free(trackers[i].announce); } @@ -1276,7 +1242,6 @@ static char const* removeTrackers(tr_torrent* tor, tr_variant* ids) static char const* torrentSet(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int i; int torrentCount; tr_torrent** torrents; char const* errmsg = NULL; @@ -1285,7 +1250,7 @@ static char const* torrentSet(tr_session* session, tr_variant* args_in, tr_varia torrents = getTorrents(session, args_in, &torrentCount); - for (i = 0; i < torrentCount; ++i) + for (int i = 0; i < torrentCount; ++i) { int64_t tmp; double d; @@ -1424,7 +1389,6 @@ static char const* torrentSetLocation(tr_session* session, tr_variant* args_in, } bool move; - int i; int torrentCount; tr_torrent** torrents = getTorrents(session, args_in, &torrentCount); @@ -1433,7 +1397,7 @@ static char const* torrentSetLocation(tr_session* session, tr_variant* args_in, move = false; } - for (i = 0; i < torrentCount; ++i) + for (int i = 0; i < torrentCount; ++i) { tr_torrent* tor = torrents[i]; tr_torrentSetLocation(tor, location, move, NULL, NULL); @@ -1744,12 +1708,11 @@ static bool isCurlURL(char const* filename) static tr_file_index_t* fileListFromList(tr_variant* list, tr_file_index_t* setmeCount) { - size_t i; size_t const childCount = tr_variantListSize(list); tr_file_index_t n = 0; tr_file_index_t* files = tr_new0(tr_file_index_t, childCount); - for (i = 0; i < childCount; ++i) + for (size_t i = 0; i < childCount; ++i) { int64_t intVal; @@ -2565,11 +2528,11 @@ static void noop_response_callback(tr_session* session UNUSED, tr_variant* respo void tr_rpc_request_exec_json(tr_session* session, tr_variant const* request, tr_rpc_response_func callback, void* callback_user_data) { - int i; char const* str; tr_variant* const mutable_request = (tr_variant*)request; tr_variant* args_in = tr_variantDictFind(mutable_request, TR_KEY_arguments); char const* result = NULL; + struct method* method = NULL; if (callback == NULL) { @@ -2583,17 +2546,15 @@ void tr_rpc_request_exec_json(tr_session* session, tr_variant const* request, tr } else { - int const n = TR_N_ELEMENTS(methods); - - for (i = 0; i < n; ++i) + for (size_t i = 0; method == NULL && i < TR_N_ELEMENTS(methods); ++i) { if (strcmp(str, methods[i].name) == 0) { - break; + method = &methods[i]; } } - if (i == n) + if (method == NULL) { result = "method name not recognized"; } @@ -2618,7 +2579,7 @@ void tr_rpc_request_exec_json(tr_session* session, tr_variant const* request, tr tr_variantFree(&response); } - else if (methods[i].immediate) + else if (method->immediate) { int64_t tag; tr_variant response; @@ -2626,7 +2587,7 @@ void tr_rpc_request_exec_json(tr_session* session, tr_variant const* request, tr tr_variantInitDict(&response, 3); args_out = tr_variantDictAddDict(&response, TR_KEY_arguments, 0); - result = (*methods[i].func)(session, args_in, args_out, NULL); + result = (*method->func)(session, args_in, args_out, NULL); if (result == NULL) { @@ -2660,7 +2621,7 @@ void tr_rpc_request_exec_json(tr_session* session, tr_variant const* request, tr data->args_out = tr_variantDictAddDict(data->response, TR_KEY_arguments, 0); data->callback = callback; data->callback_user_data = callback_user_data; - result = (*methods[i].func)(session, args_in, data->args_out, data); + result = (*method->func)(session, args_in, data->args_out, data); /* Async operation failed prematurely? Invoke callback or else client will not get a reply */ if (result != NULL) @@ -2694,11 +2655,9 @@ void tr_rpc_parse_list_str(tr_variant* setme, char const* str, size_t len) } else { - int i; - tr_variantInitList(setme, valueCount); - for (i = 0; i < valueCount; ++i) + for (int i = 0; i < valueCount; ++i) { tr_variantListAddInt(setme, values[i]); } diff --git a/libtransmission/session-test.c b/libtransmission/session-test.c index af9ffc616..7f3f454f9 100644 --- a/libtransmission/session-test.c +++ b/libtransmission/session-test.c @@ -20,12 +20,10 @@ static int testPeerId(void) { - int i; uint8_t peer_id[PEER_ID_LEN + 1]; - for (i = 0; i < 100000; ++i) + for (int i = 0; i < 100000; ++i) { - int j; int val = 0; tr_peerIdInit(peer_id); @@ -33,7 +31,7 @@ static int testPeerId(void) check(strlen((char*)peer_id) == PEER_ID_LEN); check(memcmp(peer_id, PEERID_PREFIX, 8) == 0); - for (j = 8; j < PEER_ID_LEN; ++j) + for (int j = 8; j < PEER_ID_LEN; ++j) { char tmp[2] = { (char)peer_id[j], '\0' }; val += strtoul(tmp, NULL, 36); diff --git a/libtransmission/session.c b/libtransmission/session.c index b26c8d102..be711f875 100644 --- a/libtransmission/session.c +++ b/libtransmission/session.c @@ -92,7 +92,6 @@ static tr_port getRandomPort(tr_session* s) designates beta (Azureus-style) */ void tr_peerIdInit(uint8_t* buf) { - int i; int val; int total = 0; char const* pool = "0123456789abcdefghijklmnopqrstuvwxyz"; @@ -102,14 +101,14 @@ void tr_peerIdInit(uint8_t* buf) tr_rand_buffer(buf + 8, 11); - for (i = 8; i < 19; ++i) + for (int i = 8; i < 19; ++i) { val = buf[i] % base; total += val; buf[i] = pool[val]; } - val = total % base != 0 ? base - (total % base) : 0; + val = total % base != 0 ? base - total % base : 0; buf[19] = pool[val]; buf[20] = '\0'; } @@ -1475,16 +1474,14 @@ enum static void turtleUpdateTable(struct tr_turtle_info* t) { - int day; tr_bitfield* b = &t->minutes; tr_bitfieldSetHasNone(b); - for (day = 0; day < 7; ++day) + for (int day = 0; day < 7; ++day) { if ((t->days & (1 << day)) != 0) { - int i; time_t const begin = t->beginMinute; time_t end = t->endMinute; @@ -1493,7 +1490,7 @@ static void turtleUpdateTable(struct tr_turtle_info* t) end += MINUTES_PER_DAY; } - for (i = begin; i < end; ++i) + for (int i = begin; i < end; ++i) { tr_bitfieldAdd(b, (i + day * MINUTES_PER_DAY) % MINUTES_PER_WEEK); } @@ -1890,7 +1887,6 @@ int tr_sessionCountTorrents(tr_session const* session) tr_torrent** tr_sessionGetTorrents(tr_session* session, int* setme_n) { - int i; int n; tr_torrent** torrents; tr_torrent* tor; @@ -1904,7 +1900,7 @@ tr_torrent** tr_sessionGetTorrents(tr_session* session, int* setme_n) torrents = tr_new(tr_torrent*, n); tor = NULL; - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { torrents[i] = tor = tr_torrentNext(session, tor); } @@ -1933,7 +1929,6 @@ static void sessionCloseImplWaitForIdleUdp(evutil_socket_t foo UNUSED, short bar static void sessionCloseImplStart(tr_session* session) { - int i; int n; tr_torrent** torrents; @@ -1965,7 +1960,7 @@ static void sessionCloseImplStart(tr_session* session) torrents = tr_sessionGetTorrents(session, &n); qsort(torrents, n, sizeof(tr_torrent*), compareTorrentByCur); - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { tr_torrentFree(torrents[i]); } @@ -2141,7 +2136,6 @@ static void sessionLoadTorrents(void* vdata) int n = 0; tr_sys_path_info info; tr_sys_dir_t odir = NULL; - tr_list* l = NULL; tr_list* list = NULL; struct sessionLoadTorrentsData* data = vdata; char const* dirname = tr_getTorrentDir(data->session); @@ -2177,8 +2171,9 @@ static void sessionLoadTorrents(void* vdata) } data->torrents = tr_new(tr_torrent*, n); + i = 0; - for (i = 0, l = list; l != NULL; l = l->next) + for (tr_list* l = list; l != NULL; l = l->next) { data->torrents[i++] = (tr_torrent*)l->data; } @@ -2520,11 +2515,10 @@ static void loadBlocklists(tr_session* session) if (!tr_ptrArrayEmpty(&loadme)) { - int i; int const n = tr_ptrArraySize(&loadme); char const* const* paths = (char const* const*)tr_ptrArrayBase(&loadme); - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { tr_list_append(&blocklists, tr_blocklistFileNew(paths[i], isEnabled)); } @@ -2552,12 +2546,11 @@ void tr_sessionReloadBlocklists(tr_session* session) int tr_blocklistGetRuleCount(tr_session const* session) { - tr_list* l; int n = 0; assert(tr_isSession(session)); - for (l = session->blocklists; l != NULL; l = l->next) + for (tr_list* l = session->blocklists; l != NULL; l = l->next) { n += tr_blocklistFileGetRuleCount(l->data); } @@ -2574,14 +2567,12 @@ bool tr_blocklistIsEnabled(tr_session const* session) void tr_blocklistSetEnabled(tr_session* session, bool isEnabled) { - tr_list* l; - assert(tr_isSession(session)); assert(tr_isBool(isEnabled)); session->isBlocklistEnabled = isEnabled; - for (l = session->blocklists; l != NULL; l = l->next) + for (tr_list* l = session->blocklists; l != NULL; l = l->next) { tr_blocklistFileSetEnabled(l->data, isEnabled); } @@ -2596,13 +2587,12 @@ bool tr_blocklistExists(tr_session const* session) int tr_blocklistSetContent(tr_session* session, char const* contentFilename) { - tr_list* l; int ruleCount; - tr_blocklistFile* b; + tr_blocklistFile* b = NULL; char const* defaultName = DEFAULT_BLOCKLIST_FILENAME; tr_sessionLock(session); - for (b = NULL, l = session->blocklists; b == NULL && l != NULL; l = l->next) + for (tr_list* l = session->blocklists; b == NULL && l != NULL; l = l->next) { if (tr_stringEndsWith(tr_blocklistFileGetFilename(l->data), defaultName)) { @@ -2625,11 +2615,9 @@ int tr_blocklistSetContent(tr_session* session, char const* contentFilename) bool tr_sessionIsAddressBlocked(tr_session const* session, tr_address const* addr) { - tr_list* l; - assert(tr_isSession(session)); - for (l = session->blocklists; l != NULL; l = l->next) + for (tr_list* l = session->blocklists; l != NULL; l = l->next) { if (tr_blocklistFileHasAddress(l->data, addr)) { @@ -2998,10 +2986,10 @@ static int compareTorrentAndPositions(void const* va, void const* vb) void tr_sessionGetNextQueuedTorrents(tr_session* session, tr_direction direction, size_t num_wanted, tr_ptrArray* setme) { - size_t i; size_t n; tr_torrent* tor; struct TorrentAndPosition* candidates; + size_t num_candidates; assert(tr_isSession(session)); assert(tr_isDirection(direction)); @@ -3009,7 +2997,7 @@ void tr_sessionGetNextQueuedTorrents(tr_session* session, tr_direction direction /* build an array of the candidates */ n = tr_sessionCountTorrents(session); candidates = tr_new(struct TorrentAndPosition, n); - i = 0; + num_candidates = 0; tor = NULL; while ((tor = tr_torrentNext(session, tor)) != NULL) @@ -3024,23 +3012,24 @@ void tr_sessionGetNextQueuedTorrents(tr_session* session, tr_direction direction continue; } - candidates[i].tor = tor; - candidates[i].position = tr_torrentGetQueuePosition(tor); - ++i; + candidates[num_candidates].tor = tor; + candidates[num_candidates].position = tr_torrentGetQueuePosition(tor); + ++num_candidates; } /* find the best n candidates */ - if (num_wanted > i) + if (num_wanted > num_candidates) { - num_wanted = i; + num_wanted = num_candidates; } - else if (num_wanted < i) + else if (num_wanted < num_candidates) { - tr_quickfindFirstK(candidates, i, sizeof(struct TorrentAndPosition), compareTorrentAndPositions, num_wanted); + tr_quickfindFirstK(candidates, num_candidates, sizeof(struct TorrentAndPosition), compareTorrentAndPositions, + num_wanted); } /* add them to the return array */ - for (i = 0; i < num_wanted; ++i) + for (size_t i = 0; i < num_wanted; ++i) { tr_ptrArrayAppend(setme, candidates[i].tor); } diff --git a/libtransmission/torrent-ctor.c b/libtransmission/torrent-ctor.c index 18e22cbab..4722f86b1 100644 --- a/libtransmission/torrent-ctor.c +++ b/libtransmission/torrent-ctor.c @@ -228,19 +228,17 @@ void tr_ctorSetFilePriorities(tr_ctor* ctor, tr_file_index_t const* files, tr_fi void tr_ctorInitTorrentPriorities(tr_ctor const* ctor, tr_torrent* tor) { - tr_file_index_t i; - - for (i = 0; i < ctor->lowSize; ++i) + for (tr_file_index_t i = 0; i < ctor->lowSize; ++i) { tr_torrentInitFilePriority(tor, ctor->low[i], TR_PRI_LOW); } - for (i = 0; i < ctor->normalSize; ++i) + for (tr_file_index_t i = 0; i < ctor->normalSize; ++i) { tr_torrentInitFilePriority(tor, ctor->normal[i], TR_PRI_NORMAL); } - for (i = 0; i < ctor->highSize; ++i) + for (tr_file_index_t i = 0; i < ctor->highSize; ++i) { tr_torrentInitFilePriority(tor, ctor->high[i], TR_PRI_HIGH); } diff --git a/libtransmission/torrent-magnet.c b/libtransmission/torrent-magnet.c index 87e991f06..07d1e97f2 100644 --- a/libtransmission/torrent-magnet.c +++ b/libtransmission/torrent-magnet.c @@ -215,7 +215,6 @@ void* tr_torrentGetMetadataPiece(tr_torrent* tor, int piece, size_t* len) void tr_torrentSetMetadataPiece(tr_torrent* tor, int piece, void const* data, int len) { - int i; struct tr_incomplete_metadata* m; int const offset = piece * METADATA_PIECE_SIZE; @@ -251,8 +250,10 @@ void tr_torrentSetMetadataPiece(tr_torrent* tor, int piece, void const* data, in return; } + int neededPieceIndex = 0; + /* do we need this piece? */ - for (i = 0; i < m->piecesNeededCount; ++i) + for (int i = 0; i < m->piecesNeededCount; ++i, ++neededPieceIndex) { if (m->piecesNeeded[i].piece == piece) { @@ -260,14 +261,14 @@ void tr_torrentSetMetadataPiece(tr_torrent* tor, int piece, void const* data, in } } - if (i == m->piecesNeededCount) + if (neededPieceIndex == m->piecesNeededCount) { return; } memcpy(m->metadata + offset, data, len); - tr_removeElementFromArray(m->piecesNeeded, i, sizeof(struct metadata_node), m->piecesNeededCount--); + tr_removeElementFromArray(m->piecesNeeded, neededPieceIndex, sizeof(struct metadata_node), m->piecesNeededCount--); dbgmsg(tor, "saving metainfo piece %d... %d remain", piece, m->piecesNeededCount); @@ -352,7 +353,7 @@ void tr_torrentSetMetadataPiece(tr_torrent* tor, int piece, void const* data, in { int const n = m->pieceCount; - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { m->piecesNeeded[i].piece = i; m->piecesNeeded[i].requestedAt = 0; @@ -422,7 +423,6 @@ double tr_torrentGetMetadataPercent(tr_torrent const* tor) /* FIXME: this should be renamed tr_metainfoGetMagnetLink() and moved to metainfo.c for consistency */ char* tr_torrentInfoGetMagnetLink(tr_info const* inf) { - unsigned int i; char const* name; struct evbuffer* s = evbuffer_new(); @@ -436,13 +436,13 @@ char* tr_torrentInfoGetMagnetLink(tr_info const* inf) tr_http_escape(s, name, TR_BAD_SIZE, true); } - for (i = 0; i < inf->trackerCount; ++i) + for (unsigned int i = 0; i < inf->trackerCount; ++i) { evbuffer_add_printf(s, "%s", "&tr="); tr_http_escape(s, inf->trackers[i].announce, TR_BAD_SIZE, true); } - for (i = 0; i < inf->webseedCount; i++) + for (unsigned int i = 0; i < inf->webseedCount; i++) { evbuffer_add_printf(s, "%s", "&ws="); tr_http_escape(s, inf->webseeds[i], TR_BAD_SIZE, true); diff --git a/libtransmission/torrent.c b/libtransmission/torrent.c index 5c80a47cb..68bb28857 100644 --- a/libtransmission/torrent.c +++ b/libtransmission/torrent.c @@ -597,7 +597,6 @@ static void onTrackerResponse(tr_torrent* tor, tr_tracker_event const* event, vo { case TR_TRACKER_PEERS: { - size_t i; int8_t const seedProbability = event->seedProbability; bool const allAreSeeds = seedProbability == 100; @@ -610,7 +609,7 @@ static void onTrackerResponse(tr_torrent* tor, tr_tracker_event const* event, vo tr_logAddTorDbg(tor, "Got %zu peers from tracker", event->pexCount); } - for (i = 0; i < event->pexCount; ++i) + for (size_t i = 0; i < event->pexCount; ++i) { tr_peerMgrAddPex(tor, TR_PEER_FROM_TRACKER, &event->pex[i], seedProbability); } @@ -689,22 +688,24 @@ static bool pieceHasFile(tr_piece_index_t piece, tr_file const* file) static tr_priority_t calculatePiecePriority(tr_torrent const* tor, tr_piece_index_t piece, int fileHint) { - tr_file_index_t i; + tr_file_index_t firstFileIndex; tr_priority_t priority = TR_PRI_LOW; /* find the first file that has data in this piece */ if (fileHint >= 0) { - i = fileHint; + firstFileIndex = fileHint; - while (i > 0 && pieceHasFile(piece, &tor->info.files[i - 1])) + while (firstFileIndex > 0 && pieceHasFile(piece, &tor->info.files[firstFileIndex - 1])) { - --i; + --firstFileIndex; } } else { - for (i = 0; i < tor->info.fileCount; ++i) + firstFileIndex = 0; + + for (tr_file_index_t i = 0; i < tor->info.fileCount; ++i, ++firstFileIndex) { if (pieceHasFile(piece, &tor->info.files[i])) { @@ -715,7 +716,7 @@ static tr_priority_t calculatePiecePriority(tr_torrent const* tor, tr_piece_inde /* the piece's priority is the max of the priorities * of all the files in that piece */ - for (; i < tor->info.fileCount; ++i) + for (tr_file_index_t i = firstFileIndex; i < tor->info.fileCount; ++i) { tr_file const* file = &tor->info.files[i]; @@ -743,14 +744,11 @@ static tr_priority_t calculatePiecePriority(tr_torrent const* tor, tr_piece_inde static void tr_torrentInitFilePieces(tr_torrent* tor) { - int* firstFiles; - tr_file_index_t f; - tr_piece_index_t p; uint64_t offset = 0; tr_info* inf = &tor->info; /* assign the file offsets */ - for (f = 0; f < inf->fileCount; ++f) + for (tr_file_index_t f = 0; f < inf->fileCount; ++f) { inf->files[f].offset = offset; offset += inf->files[f].length; @@ -758,9 +756,10 @@ static void tr_torrentInitFilePieces(tr_torrent* tor) } /* build the array of first-file hints to give calculatePiecePriority */ - firstFiles = tr_new(int, inf->pieceCount); + int* firstFiles = tr_new(int, inf->pieceCount); + tr_file_index_t f = 0; - for (p = f = 0; p < inf->pieceCount; ++p) + for (tr_piece_index_t p = 0; p < inf->pieceCount; ++p) { while (inf->files[f].lastPiece < p) { @@ -773,9 +772,9 @@ static void tr_torrentInitFilePieces(tr_torrent* tor) #if 0 /* test to confirm the first-file hints are correct */ - for (p = 0; p < inf->pieceCount; ++p) + for (tr_piece_index_t p = 0; p < inf->pieceCount; ++p) { - f = firstFiles[p]; + tr_file_index_t f = firstFiles[p]; assert(inf->files[f].firstPiece <= p); assert(inf->files[f].lastPiece >= p); @@ -784,9 +783,11 @@ static void tr_torrentInitFilePieces(tr_torrent* tor) assert(inf->files[f - 1].lastPiece < p); } - for (f = 0; f < inf->fileCount; ++f) + f = 0; + + for (tr_file_index_t i = 0; i < inf->fileCount; ++i, ++f) { - if (pieceHasFile(p, &inf->files[f])) + if (pieceHasFile(p, &inf->files[i])) { break; } @@ -797,7 +798,7 @@ static void tr_torrentInitFilePieces(tr_torrent* tor) #endif - for (p = 0; p < inf->pieceCount; ++p) + for (tr_piece_index_t p = 0; p < inf->pieceCount; ++p) { inf->pieces[p].priority = calculatePiecePriority(tor, p, firstFiles[p]); } @@ -901,9 +902,7 @@ void tr_torrentGotNewInfoDict(tr_torrent* tor) static bool hasAnyLocalData(tr_torrent const* tor) { - tr_file_index_t i; - - for (i = 0; i < tor->info.fileCount; ++i) + for (tr_file_index_t i = 0; i < tor->info.fileCount; ++i) { if (tr_torrentFindFile2(tor, i, NULL, NULL, NULL)) { @@ -1325,11 +1324,9 @@ static double getVerifyProgress(tr_torrent const* tor) if (tr_torrentHasMetadata(tor)) { - tr_piece_index_t i; - tr_piece_index_t n; tr_piece_index_t checked = 0; - for (i = 0, n = tor->info.pieceCount; i != n; ++i) + for (tr_piece_index_t i = 0; i < tor->info.pieceCount; ++i) { if (tor->info.pieces[i].timeChecked != 0) { @@ -1354,7 +1351,6 @@ tr_stat const* tr_torrentStat(tr_torrent* tor) unsigned int pieceUploadSpeed_Bps; unsigned int pieceDownloadSpeed_Bps; struct tr_swarm_stats swarm_stats; - int i; assert(tr_isTorrent(tor)); @@ -1383,7 +1379,7 @@ tr_stat const* tr_torrentStat(tr_torrent* tor) s->peersGettingFromUs = swarm_stats.activePeerCount[TR_UP]; s->webseedsSendingToUs = swarm_stats.activeWebseedCount; - for (i = 0; i < TR_PEER_FROM__MAX; i++) + for (int i = 0; i < TR_PEER_FROM__MAX; i++) { s->peersFrom[i] = swarm_stats.peerFromCount[i]; } @@ -1570,7 +1566,6 @@ static uint64_t countFileBytesCompleted(tr_torrent const* tor, tr_file_index_t i tr_file_stat* tr_torrentFiles(tr_torrent const* tor, tr_file_index_t* fileCount) { - tr_file_index_t i; tr_file_index_t const n = tor->info.fileCount; tr_file_stat* files = tr_new0(tr_file_stat, n); tr_file_stat* walk = files; @@ -1578,7 +1573,7 @@ tr_file_stat* tr_torrentFiles(tr_torrent const* tor, tr_file_index_t* fileCount) assert(tr_isTorrent(tor)); - for (i = 0; i < n; ++i, ++walk) + for (tr_file_index_t i = 0; i < n; ++i, ++walk) { uint64_t const b = isSeed ? tor->info.files[i].length : countFileBytesCompleted(tor, i); walk->bytesCompleted = b; @@ -1689,7 +1684,6 @@ static bool queueIsSequenced(tr_session*); static void freeTorrent(tr_torrent* tor) { - tr_torrent* t; tr_session* session = tor->session; tr_info* inf = &tor->info; time_t const now = tr_time(); @@ -1713,7 +1707,7 @@ static void freeTorrent(tr_torrent* tor) } else { - for (t = session->torrentList; t != NULL; t = t->next) + for (tr_torrent* t = session->torrentList; t != NULL; t = t->next) { if (t->next == tor) { @@ -1728,7 +1722,7 @@ static void freeTorrent(tr_torrent* tor) session->torrentCount--; /* resequence the queue positions */ - t = NULL; + tr_torrent* t = NULL; while ((t = tr_torrentNext(session, t)) != NULL) { @@ -1787,11 +1781,10 @@ static void torrentStartImpl(void* vtor) uint64_t tr_torrentGetCurrentSizeOnDisk(tr_torrent const* tor) { - tr_file_index_t i; uint64_t byte_count = 0; tr_file_index_t const n = tor->info.fileCount; - for (i = 0; i < n; ++i) + for (tr_file_index_t i = 0; i < n; ++i) { tr_sys_path_info info; char* filename = tr_torrentFindFile(tor, i); @@ -2248,7 +2241,6 @@ static void torrentCallScript(tr_torrent const* tor, char const* script) if (script != NULL && *script != '\0') { - size_t i; char* cmd[] = { tr_strdup(script), NULL @@ -2269,7 +2261,7 @@ static void torrentCallScript(tr_torrent const* tor, char const* script) #ifndef NDEBUG /* Win32 environment block strings should be sorted alphabetically */ - for (i = 1; env[i] != NULL; ++i) + for (size_t i = 1; env[i] != NULL; ++i) { assert(strcmp(env[i - 1], env[i]) < 0); } @@ -2283,7 +2275,7 @@ static void torrentCallScript(tr_torrent const* tor, char const* script) size_t env_block_size = 0; char* env_block = NULL; - for (i = 0; env[i] != NULL; ++i) + for (size_t i = 0; env[i] != NULL; ++i) { size_t const len = strlen(env[i]) + 1; env_block = tr_renew(char, env_block, env_block_size + len + 1); @@ -2329,7 +2321,7 @@ static void torrentCallScript(tr_torrent const* tor, char const* script) if (fork() == 0) { - for (i = 0; env[i] != NULL; ++i) + for (size_t i = 0; env[i] != NULL; ++i) { putenv(env[i]); } @@ -2349,12 +2341,12 @@ static void torrentCallScript(tr_torrent const* tor, char const* script) #endif /* _WIN32 */ - for (i = 0; cmd[i] != NULL; ++i) + for (size_t i = 0; cmd[i] != NULL; ++i) { tr_free(cmd[i]); } - for (i = 0; env[i] != NULL; ++i) + for (size_t i = 0; env[i] != NULL; ++i) { tr_free(env[i]); } @@ -2455,7 +2447,6 @@ void tr_torrentSetMetadataCallback(tr_torrent* tor, tr_torrent_metadata_func fun void tr_torrentInitFilePriority(tr_torrent* tor, tr_file_index_t fileIndex, tr_priority_t priority) { tr_file* file; - tr_piece_index_t i; assert(tr_isTorrent(tor)); assert(fileIndex < tor->info.fileCount); @@ -2464,7 +2455,7 @@ void tr_torrentInitFilePriority(tr_torrent* tor, tr_file_index_t fileIndex, tr_p file = &tor->info.files[fileIndex]; file->priority = priority; - for (i = file->firstPiece; i <= file->lastPiece; ++i) + for (tr_piece_index_t i = file->firstPiece; i <= file->lastPiece; ++i) { tor->info.pieces[i].priority = calculatePiecePriority(tor, i, fileIndex); } @@ -2473,11 +2464,10 @@ void tr_torrentInitFilePriority(tr_torrent* tor, tr_file_index_t fileIndex, tr_p void tr_torrentSetFilePriorities(tr_torrent* tor, tr_file_index_t const* files, tr_file_index_t fileCount, tr_priority_t priority) { - tr_file_index_t i; assert(tr_isTorrent(tor)); tr_torrentLock(tor); - for (i = 0; i < fileCount; ++i) + for (tr_file_index_t i = 0; i < fileCount; ++i) { if (files[i] < tor->info.fileCount) { @@ -2493,14 +2483,13 @@ void tr_torrentSetFilePriorities(tr_torrent* tor, tr_file_index_t const* files, tr_priority_t* tr_torrentGetFilePriorities(tr_torrent const* tor) { - tr_file_index_t i; tr_priority_t* p; assert(tr_isTorrent(tor)); p = tr_new0(tr_priority_t, tor->info.fileCount); - for (i = 0; i < tor->info.fileCount; ++i) + for (tr_file_index_t i = 0; i < tor->info.fileCount; ++i) { p[i] = tor->info.files[i].priority; } @@ -2519,7 +2508,6 @@ static void setFileDND(tr_torrent* tor, tr_file_index_t fileIndex, int doDownloa int8_t firstPieceDND; tr_piece_index_t lastPiece; int8_t lastPieceDND; - tr_file_index_t i; tr_file* file = &tor->info.files[fileIndex]; file->dnd = dnd; @@ -2532,7 +2520,7 @@ static void setFileDND(tr_torrent* tor, tr_file_index_t fileIndex, int doDownloa if (fileIndex > 0) { - for (i = fileIndex - 1; firstPieceDND; --i) + for (tr_file_index_t i = fileIndex - 1; firstPieceDND; --i) { if (tor->info.files[i].lastPiece != firstPiece) { @@ -2552,7 +2540,7 @@ static void setFileDND(tr_torrent* tor, tr_file_index_t fileIndex, int doDownloa every file using that piece is DND */ lastPieceDND = dnd; - for (i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i) + for (tr_file_index_t i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i) { if (tor->info.files[i].firstPiece != lastPiece) { @@ -2568,11 +2556,10 @@ static void setFileDND(tr_torrent* tor, tr_file_index_t fileIndex, int doDownloa } else { - tr_piece_index_t pp; tor->info.pieces[firstPiece].dnd = firstPieceDND; tor->info.pieces[lastPiece].dnd = lastPieceDND; - for (pp = firstPiece + 1; pp < lastPiece; ++pp) + for (tr_piece_index_t pp = firstPiece + 1; pp < lastPiece; ++pp) { tor->info.pieces[pp].dnd = dnd; } @@ -2581,13 +2568,12 @@ static void setFileDND(tr_torrent* tor, tr_file_index_t fileIndex, int doDownloa void tr_torrentInitFileDLs(tr_torrent* tor, tr_file_index_t const* files, tr_file_index_t fileCount, bool doDownload) { - tr_file_index_t i; assert(tr_isTorrent(tor)); tr_torrentLock(tor); - for (i = 0; i < fileCount; ++i) + for (tr_file_index_t i = 0; i < fileCount; ++i) { if (files[i] < tor->info.fileCount) { @@ -2777,12 +2763,9 @@ void tr_torrentSetPieceChecked(tr_torrent* tor, tr_piece_index_t pieceIndex) void tr_torrentSetChecked(tr_torrent* tor, time_t when) { - tr_piece_index_t i; - tr_piece_index_t n; - assert(tr_isTorrent(tor)); - for (i = 0, n = tor->info.pieceCount; i != n; ++i) + for (tr_piece_index_t i = 0; i < tor->info.pieceCount; ++i) { tor->info.pieces[i].timeChecked = when; } @@ -2830,11 +2813,11 @@ bool tr_torrentPieceNeedsCheck(tr_torrent const* tor, tr_piece_index_t p) * then it needs to be rechecked */ tr_ioFindFileLocation(tor, p, 0, &f, &unused); - for (; f < inf->fileCount && pieceHasFile(p, &inf->files[f]); ++f) + for (tr_file_index_t i = f; i < inf->fileCount && pieceHasFile(p, &inf->files[i]); ++i) { - if (tr_cpFileIsComplete(&tor->completion, f)) + if (tr_cpFileIsComplete(&tor->completion, i)) { - if (tr_torrentGetFileMTime(tor, f) > inf->pieces[p].timeChecked) + if (tr_torrentGetFileMTime(tor, i) > inf->pieces[p].timeChecked) { return true; } @@ -2865,7 +2848,6 @@ static int compareTrackerByTier(void const* va, void const* vb) bool tr_torrentSetAnnounceList(tr_torrent* tor, tr_tracker_info const* trackers_in, int trackerCount) { - int i; tr_variant metainfo; bool ok = true; tr_tracker_info* trackers; @@ -2879,7 +2861,7 @@ bool tr_torrentSetAnnounceList(tr_torrent* tor, tr_tracker_info const* trackers_ qsort(trackers, trackerCount, sizeof(tr_tracker_info), compareTrackerByTier); /* look for bad URLs */ - for (i = 0; ok && i < trackerCount; ++i) + for (int i = 0; ok && i < trackerCount; ++i) { if (!tr_urlIsValidTracker(trackers[i].announce)) { @@ -2905,12 +2887,11 @@ bool tr_torrentSetAnnounceList(tr_torrent* tor, tr_tracker_info const* trackers_ if (trackerCount > 1) { - int i; int prevTier = -1; tr_variant* tier = NULL; tr_variant* announceList = tr_variantDictAddList(&metainfo, TR_KEY_announce_list, 0); - for (i = 0; i < trackerCount; ++i) + for (int i = 0; i < trackerCount; ++i) { if (prevTier != trackers[i].tier) { @@ -2951,7 +2932,7 @@ bool tr_torrentSetAnnounceList(tr_torrent* tor, tr_tracker_info const* trackers_ { bool clear = true; - for (i = 0; clear && i < trackerCount; ++i) + for (int i = 0; clear && i < trackerCount; ++i) { if (strcmp(trackers[i].announce, tor->errorTracker) == 0) { @@ -3009,12 +2990,11 @@ void tr_torrentSetDoneDate(tr_torrent* tor, time_t t) uint64_t tr_torrentGetBytesLeftToAllocate(tr_torrent const* tor) { - tr_file_index_t i; uint64_t bytesLeft = 0; assert(tr_isTorrent(tor)); - for (i = 0; i < tor->info.fileCount; ++i) + for (tr_file_index_t i = 0; i < tor->info.fileCount; ++i) { if (!tor->info.files[i].dnd) { @@ -3043,16 +3023,14 @@ uint64_t tr_torrentGetBytesLeftToAllocate(tr_torrent const* tor) static bool isJunkFile(char const* base) { - int i; static char const* files[] = { ".DS_Store", "desktop.ini", "Thumbs.db" }; - static int const file_count = sizeof(files) / sizeof(files[0]); - for (i = 0; i < file_count; ++i) + for (size_t i = 0; i < TR_N_ELEMENTS(files); ++i) { if (strcmp(base, files[i]) == 0) { @@ -3117,9 +3095,6 @@ static void removeEmptyFoldersAndJunkFiles(char const* folder) */ static void deleteLocalData(tr_torrent* tor, tr_fileFunc func) { - int i; - int n; - tr_file_index_t f; char* base; tr_sys_dir_t odir; char* tmpdir = NULL; @@ -3149,7 +3124,7 @@ static void deleteLocalData(tr_torrent* tor, tr_fileFunc func) tr_sys_dir_create_temp(tmpdir, NULL); tr_free(base); - for (f = 0; f < tor->info.fileCount; ++f) + for (tr_file_index_t f = 0; f < tor->info.fileCount; ++f) { char* filename; @@ -3208,7 +3183,7 @@ static void deleteLocalData(tr_torrent* tor, tr_fileFunc func) } /* go from the bottom up */ - for (i = 0, n = tr_ptrArraySize(&files); i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(&files); i < n; ++i) { char* walk = tr_strdup(tr_ptrArrayNth(&files, i)); @@ -3230,7 +3205,7 @@ static void deleteLocalData(tr_torrent* tor, tr_fileFunc func) ***/ /* build a list of 'top's child directories that belong to this torrent */ - for (f = 0; f < tor->info.fileCount; ++f) + for (tr_file_index_t f = 0; f < tor->info.fileCount; ++f) { char* dir; char* filename; @@ -3272,7 +3247,7 @@ static void deleteLocalData(tr_torrent* tor, tr_fileFunc func) tr_free(dir); } - for (i = 0, n = tr_ptrArraySize(&folders); i < n; ++i) + for (int i = 0, n = tr_ptrArraySize(&folders); i < n; ++i) { removeEmptyFoldersAndJunkFiles(tr_ptrArrayNth(&folders, i)); } @@ -3331,15 +3306,13 @@ static void setLocation(void* vdata) if (!tr_sys_path_is_same(location, tor->currentDir, NULL)) { - tr_file_index_t i; - /* bad idea to move files while they're being verified... */ tr_verifyRemove(tor); /* try to move the files. * FIXME: there are still all kinds of nasty cases, like what * if the target directory runs out of space halfway through... */ - for (i = 0; !err && i < tor->info.fileCount; ++i) + for (tr_file_index_t i = 0; !err && i < tor->info.fileCount; ++i) { char* sub; char const* oldbase; @@ -3446,8 +3419,6 @@ static void tr_torrentFileCompleted(tr_torrent* tor, tr_file_index_t fileIndex) char const* base; tr_info const* inf = &tor->info; tr_file const* f = &inf->files[fileIndex]; - tr_piece* p; - tr_piece const* pend; time_t const now = tr_time(); /* close the file so that we can reopen in read-only mode as needed */ @@ -3456,9 +3427,9 @@ static void tr_torrentFileCompleted(tr_torrent* tor, tr_file_index_t fileIndex) /* now that the file is complete and closed, we can start watching its * mtime timestamp for changes to know if we need to reverify pieces */ - for (p = &inf->pieces[f->firstPiece], pend = &inf->pieces[f->lastPiece] + 1; p != pend; ++p) + for (tr_piece_index_t i = f->firstPiece; i <= f->lastPiece; ++i) { - p->timeChecked = now; + inf->pieces[i].timeChecked = now; } /* if the torrent's current filename isn't the same as the one in the @@ -3488,12 +3459,10 @@ static void tr_torrentFileCompleted(tr_torrent* tor, tr_file_index_t fileIndex) static void tr_torrentPieceCompleted(tr_torrent* tor, tr_piece_index_t pieceIndex) { - tr_file_index_t i; - tr_peerMgrPieceCompleted(tor, pieceIndex); /* if this piece completes any file, invoke the fileCompleted func for it */ - for (i = 0; i < tor->info.fileCount; ++i) + for (tr_file_index_t i = 0; i < tor->info.fileCount; ++i) { tr_file const* file = &tor->info.files[i]; @@ -3707,7 +3676,6 @@ static int compareTorrentByQueuePosition(void const* va, void const* vb) static bool queueIsSequenced(tr_session* session) { - int i; int n; bool is_sequenced; tr_torrent** torrents; @@ -3720,7 +3688,7 @@ static bool queueIsSequenced(tr_session* session) fprintf(stderr, "%s", "queue: "); - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { fprintf(stderr, "%d ", tmp[i]->queuePosition); } @@ -3732,12 +3700,9 @@ static bool queueIsSequenced(tr_session* session) /* test them */ is_sequenced = true; - for (i = 0; is_sequenced && i < n; ++i) + for (int i = 0; is_sequenced && i < n; ++i) { - if (torrents[i]->queuePosition != i) - { - is_sequenced = false; - } + is_sequenced = torrents[i]->queuePosition == i; } tr_free(torrents); @@ -3801,11 +3766,10 @@ void tr_torrentSetQueuePosition(tr_torrent* tor, int pos) void tr_torrentsQueueMoveTop(tr_torrent** torrents_in, int n) { - int i; tr_torrent** torrents = tr_memdup(torrents_in, sizeof(tr_torrent*) * n); qsort(torrents, n, sizeof(tr_torrent*), compareTorrentByQueuePosition); - for (i = n - 1; i >= 0; --i) + for (int i = n - 1; i >= 0; --i) { tr_torrentSetQueuePosition(torrents[i], 0); } @@ -3815,13 +3779,12 @@ void tr_torrentsQueueMoveTop(tr_torrent** torrents_in, int n) void tr_torrentsQueueMoveUp(tr_torrent** torrents_in, int n) { - int i; tr_torrent** torrents; torrents = tr_memdup(torrents_in, sizeof(tr_torrent*) * n); qsort(torrents, n, sizeof(tr_torrent*), compareTorrentByQueuePosition); - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { tr_torrentSetQueuePosition(torrents[i], torrents[i]->queuePosition - 1); } @@ -3831,13 +3794,12 @@ void tr_torrentsQueueMoveUp(tr_torrent** torrents_in, int n) void tr_torrentsQueueMoveDown(tr_torrent** torrents_in, int n) { - int i; tr_torrent** torrents; torrents = tr_memdup(torrents_in, sizeof(tr_torrent*) * n); qsort(torrents, n, sizeof(tr_torrent*), compareTorrentByQueuePosition); - for (i = n - 1; i >= 0; --i) + for (int i = n - 1; i >= 0; --i) { tr_torrentSetQueuePosition(torrents[i], torrents[i]->queuePosition + 1); } @@ -3847,13 +3809,12 @@ void tr_torrentsQueueMoveDown(tr_torrent** torrents_in, int n) void tr_torrentsQueueMoveBottom(tr_torrent** torrents_in, int n) { - int i; tr_torrent** torrents; torrents = tr_memdup(torrents_in, sizeof(tr_torrent*) * n); qsort(torrents, n, sizeof(tr_torrent*), compareTorrentByQueuePosition); - for (i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { tr_torrentSetQueuePosition(torrents[i], INT_MAX); } @@ -3896,13 +3857,12 @@ static tr_file_index_t* renameFindAffectedFiles(tr_torrent* tor, char const* old { size_t n; size_t oldpath_len; - tr_file_index_t i; tr_file_index_t* indices = tr_new0(tr_file_index_t, tor->info.fileCount); n = 0; oldpath_len = strlen(oldpath); - for (i = 0; i != tor->info.fileCount; ++i) + for (tr_file_index_t i = 0; i < tor->info.fileCount; ++i) { char const* name = tor->info.files[i].name; size_t const len = strlen(name); @@ -4075,14 +4035,12 @@ static void torrentRenamePath(void* vdata) } else { - size_t i; - error = renamePath(tor, oldpath, newname); if (error == 0) { /* update tr_info.files */ - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { renameTorrentFileString(tor, oldpath, newname, file_indices[i]); } diff --git a/libtransmission/tr-dht.c b/libtransmission/tr-dht.c index 018921dfe..c1e670cca 100644 --- a/libtransmission/tr-dht.c +++ b/libtransmission/tr-dht.c @@ -158,7 +158,6 @@ static void bootstrap_from_name(char const* name, tr_port port, int af) static void dht_bootstrap(void* closure) { struct bootstrap_closure* cl = closure; - int i; int num = cl->len / 6; int num6 = cl->len6 / 18; @@ -177,7 +176,7 @@ static void dht_bootstrap(void* closure) tr_logAddNamedInfo("DHT", "Bootstrapping from %d IPv6 nodes", num6); } - for (i = 0; i < MAX(num, num6); i++) + for (int i = 0; i < MAX(num, num6); ++i) { if (i < num && !bootstrap_done(cl->session, AF_INET)) { @@ -281,7 +280,7 @@ static void dht_bootstrap(void* closure) if (!bootstrap_done(cl->session, 0)) { - for (i = 0; i < 6; i++) + for (int i = 0; i < 6; ++i) { /* We don't want to abuse our bootstrap nodes, so be very slow. The initial wait is to give other nodes a chance @@ -449,30 +448,22 @@ void tr_dhtUninit(tr_session* ss) char compact[300 * 6]; char compact6[300 * 18]; char* dat_file; - int i; - int j; int num = 300; int num6 = 300; int n = dht_get_nodes(sins, &num, sins6, &num6); tr_logAddNamedInfo("DHT", "Saving %d (%d + %d) nodes", n, num, num6); - j = 0; - - for (i = 0; i < num; ++i) + for (int i = 0, j = 0; i < num; ++i, j += 6) { memcpy(compact + j, &sins[i].sin_addr, 4); memcpy(compact + j + 4, &sins[i].sin_port, 2); - j += 6; } - j = 0; - - for (i = 0; i < num6; ++i) + for (int i = 0, j = 0; i < num6; ++i, j += 18) { memcpy(compact6 + j, &sins6[i].sin6_addr, 16); memcpy(compact6 + j + 16, &sins6[i].sin6_port, 2); - j += 18; } tr_variantInitDict(&benc, 3); @@ -654,7 +645,7 @@ static void callback(void* ignore UNUSED, int event, unsigned char const* info_h if (tor != NULL && tr_torrentAllowsDHT(tor)) { - size_t i, n; + size_t n; tr_pex* pex; if (event == DHT_EVENT_VALUES) @@ -666,7 +657,7 @@ static void callback(void* ignore UNUSED, int event, unsigned char const* info_h pex = tr_peerMgrCompact6ToPex(data, data_len, NULL, 0, &n); } - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { tr_peerMgrAddPex(tor, TR_PEER_FROM_DHT, pex + i, -1); } diff --git a/libtransmission/tr-getopt.c b/libtransmission/tr-getopt.c index 25214de64..f26e585cb 100644 --- a/libtransmission/tr-getopt.c +++ b/libtransmission/tr-getopt.c @@ -120,9 +120,8 @@ void tr_getopt_usage(char const* progName, char const* description, struct tr_op int shortWidth = 0; int argWidth = 0; struct tr_option help; - struct tr_option const* o; - for (o = opts; o->val != 0; ++o) + for (tr_option const* o = opts; o->val != 0; ++o) { maxWidth(o, &longWidth, &shortWidth, &argWidth); } @@ -143,7 +142,7 @@ void tr_getopt_usage(char const* progName, char const* description, struct tr_op printf("\n\nOptions:\n"); getopts_usage_line(&help, longWidth, shortWidth, argWidth); - for (o = opts; o->val != 0; ++o) + for (tr_option const* o = opts; o->val != 0; ++o) { getopts_usage_line(o, longWidth, shortWidth, argWidth); } @@ -153,11 +152,10 @@ static tr_option const* findOption(tr_option const* opts, char const* str, char { size_t matchlen = 0; char const* arg = NULL; - tr_option const* o; tr_option const* match = NULL; /* find the longest matching option */ - for (o = opts; o->val != 0; ++o) + for (tr_option const* o = opts; o->val != 0; ++o) { size_t len = o->longName != NULL ? strlen(o->longName) : 0; @@ -203,14 +201,13 @@ static tr_option const* findOption(tr_option const* opts, char const* str, char int tr_getopt(char const* usage, int argc, char const* const* argv, tr_option const* opts, char const** setme_optarg) { - int i; char const* arg = NULL; tr_option const* o = NULL; *setme_optarg = NULL; /* handle the builtin 'help' option */ - for (i = 1; i < argc; ++i) + for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { diff --git a/libtransmission/tr-lpd.c b/libtransmission/tr-lpd.c index a2b73a7f5..a9829569c 100644 --- a/libtransmission/tr-lpd.c +++ b/libtransmission/tr-lpd.c @@ -484,7 +484,6 @@ UNUSED static inline void lpd_consistencyCheck(void) */ bool tr_lpdSendAnnounce(tr_torrent const* t) { - size_t i; char const fmt[] = "BT-SEARCH * HTTP/%u.%u" CRLF "Host: %s:%u" CRLF @@ -502,7 +501,7 @@ bool tr_lpdSendAnnounce(tr_torrent const* t) } /* make sure the hash string is normalized, just in case */ - for (i = 0; i < sizeof(hashString); i++) + for (size_t i = 0; i < TR_N_ELEMENTS(hashString); ++i) { hashString[i] = toupper(t->info.hashString[i]); } diff --git a/libtransmission/tr-udp.c b/libtransmission/tr-udp.c index 2366599dd..acc736385 100644 --- a/libtransmission/tr-udp.c +++ b/libtransmission/tr-udp.c @@ -346,7 +346,7 @@ void tr_udpInit(tr_session* ss) } ipv6: - if (tr_globalIPv6()) + if (tr_globalIPv6() != NULL) { rebind_ipv6(ss, true); } diff --git a/libtransmission/utils-test.c b/libtransmission/utils-test.c index dacc49853..d8b5b57c3 100644 --- a/libtransmission/utils-test.c +++ b/libtransmission/utils-test.c @@ -145,7 +145,6 @@ static int test_utf8(void) static int test_numbers(void) { - int i; int count; int* numbers; @@ -163,7 +162,7 @@ static int test_numbers(void) check(count == 7); check(numbers != NULL); - for (i = 0; i < count; ++i) + for (int i = 0; i < count; ++i) { check_int_eq(i + 1, numbers[i]); } @@ -194,13 +193,12 @@ static int compareInts(void const* va, void const* vb) static int test_lowerbound(void) { - int i; int const A[] = { 1, 2, 3, 3, 3, 5, 8 }; int const expected_pos[] = { 0, 1, 2, 5, 5, 6, 6, 6, 7, 7 }; bool const expected_exact[] = { true, true, true, false, true, false, false, true, false, false }; - int const N = sizeof(A) / sizeof(A[0]); + int const N = TR_N_ELEMENTS(A); - for (i = 1; i <= 10; i++) + for (int i = 1; i <= 10; i++) { bool exact; int const pos = tr_lowerBound(&i, A, N, sizeof(int), compareInts, &exact); @@ -230,12 +228,11 @@ static int test_lowerbound(void) static int test_quickFindFirst_Iteration(size_t const k, size_t const n, int* buf, int range) { - size_t i; int highest_low; int lowest_high; /* populate buf with random ints */ - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { buf[i] = tr_rand_int_weak(range); } @@ -247,7 +244,7 @@ static int test_quickFindFirst_Iteration(size_t const k, size_t const n, int* bu highest_low = INT_MIN; - for (i = 0; i < k; ++i) + for (size_t i = 0; i < k; ++i) { if (highest_low < buf[i]) { @@ -257,7 +254,7 @@ static int test_quickFindFirst_Iteration(size_t const k, size_t const n, int* bu lowest_high = INT_MAX; - for (i = k; i < n; ++i) + for (size_t i = k; i < n; ++i) { if (lowest_high > buf[i]) { @@ -272,13 +269,12 @@ static int test_quickFindFirst_Iteration(size_t const k, size_t const n, int* bu static int test_quickfindFirst(void) { - size_t i; size_t const k = 10; size_t const n = 100; size_t const n_trials = 1000; int* buf = tr_new(int, n); - for (i = 0; i < n_trials; ++i) + for (size_t i = 0; i < n_trials; ++i) { check_int_eq(0, test_quickFindFirst_Iteration(k, n, buf, 100)); } @@ -315,20 +311,19 @@ static int test_hex(void) static int test_array(void) { - size_t i; size_t array[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - size_t n = sizeof(array) / sizeof(array[0]); + size_t n = TR_N_ELEMENTS(array); tr_removeElementFromArray(array, 5u, sizeof(size_t), n--); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { check_int_eq(i < 5 ? i : i + 1, array[i]); } tr_removeElementFromArray(array, 0u, sizeof(size_t), n--); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { check_int_eq(i < 4 ? i + 1 : i + 2, array[i]); } @@ -336,7 +331,7 @@ static int test_array(void) tr_removeElementFromArray(array, n - 1, sizeof(size_t), n); n--; - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { check_int_eq(i < 4 ? i + 1 : i + 2, array[i]); } diff --git a/libtransmission/utils.c b/libtransmission/utils.c index abd0a9f2f..5608068ba 100644 --- a/libtransmission/utils.c +++ b/libtransmission/utils.c @@ -175,7 +175,9 @@ char const* tr_strip_positional_args(char const* str) buf = tr_renew(char, buf, bufsize); } - for (out = buf; str && *str; ++str) + out = buf; + + for (; str != NULL && *str != '\0'; ++str) { *out++ = *str; @@ -417,8 +419,6 @@ char const* tr_memmem(char const* haystack, size_t haystacklen, char const* need #else - size_t i; - if (needlelen == 0) { return haystack; @@ -429,7 +429,7 @@ char const* tr_memmem(char const* haystack, size_t haystacklen, char const* need return NULL; } - for (i = 0; i <= haystacklen - needlelen; ++i) + for (size_t i = 0; i <= haystacklen - needlelen; ++i) { if (memcmp(haystack + i, needle, needlelen) == 0) { @@ -539,7 +539,6 @@ char* tr_strstrip(char* str) { if (str != NULL) { - size_t pos; size_t len = strlen(str); while (len != 0 && isspace(str[len - 1])) @@ -547,7 +546,9 @@ char* tr_strstrip(char* str) --len; } - for (pos = 0; pos < len && isspace(str[pos]);) + size_t pos = 0; + + while (pos < len && isspace(str[pos])) { ++pos; } @@ -726,9 +727,8 @@ void tr_hex_to_binary(char const* input, void* output, size_t byte_length) { static char const hex[] = "0123456789abcdef"; uint8_t* output_octets = output; - size_t i; - for (i = 0; i < byte_length; ++i) + for (size_t i = 0; i < byte_length; ++i) { int const hi = strchr(hex, tolower(*input++)) - hex; int const lo = strchr(hex, tolower(*input++)) - hex; @@ -1007,7 +1007,6 @@ int tr_lowerBound(void const* key, void const* base, size_t nmemb, size_t size, static size_t quickfindPartition(char* base, size_t left, size_t right, size_t size, int (* compar)(void const*, void const*), size_t pivotIndex) { - size_t i; size_t storeIndex; /* move pivot to the end */ @@ -1015,7 +1014,7 @@ static size_t quickfindPartition(char* base, size_t left, size_t right, size_t s storeIndex = left; - for (i = left; i <= right - 1; ++i) + for (size_t i = left; i < right; ++i) { if ((*compar)(base + (size * i), base + (size * right)) <= 0) { @@ -1033,12 +1032,12 @@ static size_t quickfindPartition(char* base, size_t left, size_t right, size_t s assert(storeIndex >= left); assert(storeIndex <= right); - for (i = left; i < storeIndex; ++i) + for (size_t i = left; i < storeIndex; ++i) { assert((*compar)(base + (size * i), base + (size * storeIndex)) <= 0); } - for (i = storeIndex + 1; i <= right; ++i) + for (size_t i = storeIndex + 1; i <= right; ++i) { assert((*compar)(base + (size * i), base + (size * storeIndex)) >= 0); } @@ -1072,10 +1071,9 @@ static void quickfindFirstK(char* base, size_t left, size_t right, size_t size, static void checkBestScoresComeFirst(char* base, size_t nmemb, size_t size, int (* compar)(void const*, void const*), size_t k) { - size_t i; size_t worstFirstPos = 0; - for (i = 1; i < k; ++i) + for (size_t i = 1; i < k; ++i) { if ((*compar)(base + (size * worstFirstPos), base + (size * i)) < 0) { @@ -1083,12 +1081,12 @@ static void checkBestScoresComeFirst(char* base, size_t nmemb, size_t size, int } } - for (i = 0; i < k; ++i) + for (size_t i = 0; i < k; ++i) { assert((*compar)(base + (size * i), base + (size * worstFirstPos)) <= 0); } - for (i = k; i < nmemb; ++i) + for (size_t i = k; i < nmemb; ++i) { assert((*compar)(base + (size * i), base + (size * worstFirstPos)) >= 0); } @@ -1137,13 +1135,11 @@ static char* to_utf8(const char* in, size_t inlen) #ifdef HAVE_ICONV - int i; char const* encodings[] = { "CURRENT", "ISO-8859-15" }; - int const encoding_count = sizeof(encodings) / sizeof(encodings[1]); size_t const buflen = inlen * 4 + 10; char* out = tr_new(char, buflen); - for (i = 0; ret == NULL && i < encoding_count; ++i) + for (size_t i = 0; ret == NULL && i < TR_N_ELEMENTS(encodings); ++i) { #ifdef ICONV_SECOND_ARGUMENT_IS_CONST char const* inbuf = in; @@ -1320,8 +1316,6 @@ char* tr_win32_format_message(uint32_t code) void tr_win32_make_args_utf8(int* argc, char*** argv) { int my_argc; - int i; - char** my_argv; wchar_t** my_wide_argv; my_wide_argv = CommandLineToArgvW(GetCommandLineW(), &my_argc); @@ -1333,9 +1327,10 @@ void tr_win32_make_args_utf8(int* argc, char*** argv) assert(*argc == my_argc); - my_argv = tr_new(char*, my_argc + 1); + char** my_argv = tr_new(char*, my_argc + 1); + int processed_argc = 0; - for (i = 0; i < my_argc; ++i) + for (int i = 0; i < my_argc; ++i, ++processed_argc) { my_argv[i] = tr_win32_native_to_utf8(my_wide_argv[i], -1); @@ -1345,13 +1340,11 @@ void tr_win32_make_args_utf8(int* argc, char*** argv) } } - if (i < my_argc) + if (processed_argc < my_argc) { - int j; - - for (j = 0; j < i; ++j) + for (int i = 0; i < processed_argc; ++i) { - tr_free(my_argv[j]); + tr_free(my_argv[i]); } tr_free(my_argv); @@ -1495,15 +1488,13 @@ int* tr_parseNumberRange(char const* str_in, size_t len, int* setmeCount) } else { - int i; int n2; - tr_list* l; int* sorted = NULL; /* build a sorted number array */ n = n2 = 0; - for (l = ranges; l != NULL; l = l->next) + for (tr_list* l = ranges; l != NULL; l = l->next) { struct number_range const* r = l->data; n += r->high + 1 - r->low; @@ -1518,12 +1509,11 @@ int* tr_parseNumberRange(char const* str_in, size_t len, int* setmeCount) } else { - for (l = ranges; l != NULL; l = l->next) + for (tr_list* l = ranges; l != NULL; l = l->next) { - int i; struct number_range const* r = l->data; - for (i = r->low; i <= r->high; ++i) + for (int i = r->low; i <= r->high; ++i) { sorted[n2++] = i; } @@ -1534,14 +1524,11 @@ int* tr_parseNumberRange(char const* str_in, size_t len, int* setmeCount) /* remove duplicates */ uniq = tr_new(int, n); + n = 0; - if (uniq == NULL) - { - n = 0; - } - else + if (uniq != NULL) { - for (i = n = 0; i < n2; ++i) + for (int i = 0; i < n2; ++i) { if (n == 0 || uniq[n - 1] != sorted[i]) { @@ -1993,7 +1980,6 @@ char* tr_formatter_mem_B(char* buf, int64_t bytes_per_second, size_t buflen) void tr_formatter_get_units(void* vdict) { - int i; tr_variant* l; tr_variant* dict = vdict; @@ -2002,7 +1988,7 @@ void tr_formatter_get_units(void* vdict) tr_variantDictAddInt(dict, TR_KEY_memory_bytes, mem_units.units[TR_FMT_KB].value); l = tr_variantDictAddList(dict, TR_KEY_memory_units, 4); - for (i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) { tr_variantListAddStr(l, mem_units.units[i].name); } @@ -2010,7 +1996,7 @@ void tr_formatter_get_units(void* vdict) tr_variantDictAddInt(dict, TR_KEY_size_bytes, size_units.units[TR_FMT_KB].value); l = tr_variantDictAddList(dict, TR_KEY_size_units, 4); - for (i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) { tr_variantListAddStr(l, size_units.units[i].name); } @@ -2018,7 +2004,7 @@ void tr_formatter_get_units(void* vdict) tr_variantDictAddInt(dict, TR_KEY_speed_bytes, speed_units.units[TR_FMT_KB].value); l = tr_variantDictAddList(dict, TR_KEY_speed_units, 4); - for (i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) { tr_variantListAddStr(l, speed_units.units[i].name); } @@ -2047,7 +2033,7 @@ int tr_env_get_int(char const* key, int default_value) assert(key != NULL); - if (GetEnvironmentVariableA(key, value, ARRAYSIZE(value)) > 1) + if (GetEnvironmentVariableA(key, value, TR_N_ELEMENTS(value)) > 1) { return atoi(value); } diff --git a/libtransmission/utils.h b/libtransmission/utils.h index 4d511aa0d..d280cc338 100644 --- a/libtransmission/utils.h +++ b/libtransmission/utils.h @@ -134,6 +134,8 @@ char const* tr_strip_positional_args(char const* fmt); ***** ****/ +#define TR_N_ELEMENTS(ary) (sizeof(ary) / sizeof(*(ary))) + /** * @brief Rich Salz's classic implementation of shell-style pattern matching for ?, \, [], and * characters. * @return 1 if the pattern matches, 0 if it doesn't, or -1 if an error occured diff --git a/libtransmission/variant-test.c b/libtransmission/variant-test.c index aa9f3e237..d59e97f25 100644 --- a/libtransmission/variant-test.c +++ b/libtransmission/variant-test.c @@ -322,9 +322,9 @@ static int testParse(void) static void stripWhitespace(char* in) { - char* out; + char* out = in; - for (out = in; in != NULL && *in != '\0'; ++in) + for (; in != NULL && *in != '\0'; ++in) { if (!isspace(*in)) { @@ -469,7 +469,6 @@ static int testMerge(void) static int testStackSmash(void) { - int i; size_t len; int err; char* in; @@ -480,7 +479,7 @@ static int testStackSmash(void) in = tr_new(char, depth * 2 + 1); - for (i = 0; i < depth; ++i) + for (int i = 0; i < depth; ++i) { in[i] = 'l'; in[depth + i] = 'e'; diff --git a/libtransmission/variant.c b/libtransmission/variant.c index 19a54751e..344af9586 100644 --- a/libtransmission/variant.c +++ b/libtransmission/variant.c @@ -228,15 +228,11 @@ static int dictIndexOf(tr_variant const* dict, tr_quark const key) { if (tr_variantIsDict(dict)) { - tr_variant const* walk; - tr_variant const* const begin = dict->val.l.vals; - tr_variant const* const end = begin + dict->val.l.count; - - for (walk = begin; walk != end; ++walk) + for (size_t i = 0; i < dict->val.l.count; ++i) { - if (walk->key == key) + if (dict->val.l.vals[i].key == key) { - return walk - begin; + return (int)i; } } } @@ -763,11 +759,10 @@ static void nodeConstruct(struct SaveNode* node, tr_variant const* v, bool sort_ { /* make node->sorted a sorted version of this dictionary */ - size_t i; size_t const n = v->val.l.count; struct KeyIndex* tmp = tr_new(struct KeyIndex, n); - for (i = 0; i < n; i++) + for (size_t i = 0; i < n; i++) { tmp[i].val = v->val.l.vals + i; tmp[i].keystr = tr_quark_get_string(tmp[i].val->key, NULL); @@ -777,7 +772,7 @@ static void nodeConstruct(struct SaveNode* node, tr_variant const* v, bool sort_ tr_variantInitDict(&node->sorted, n); - for (i = 0; i < n; ++i) + for (size_t i = 0; i < n; ++i) { node->sorted.val.l.vals[i] = *tmp[i].val; } @@ -1027,7 +1022,6 @@ bool tr_variantDictChild(tr_variant* dict, size_t n, tr_quark* key, tr_variant** void tr_variantMergeDicts(tr_variant* target, tr_variant const* source) { - size_t i; size_t const sourceCount = tr_variantDictSize(source); assert(tr_variantIsDict(target)); @@ -1035,7 +1029,7 @@ void tr_variantMergeDicts(tr_variant* target, tr_variant const* source) tr_variantDictReserve(target, sourceCount + tr_variantDictSize(target)); - for (i = 0; i < sourceCount; ++i) + for (size_t i = 0; i < sourceCount; ++i) { tr_quark key; tr_variant* val; diff --git a/libtransmission/webseed.c b/libtransmission/webseed.c index 4075ffa28..69a3cc952 100644 --- a/libtransmission/webseed.c +++ b/libtransmission/webseed.c @@ -84,12 +84,11 @@ static void publish(tr_webseed* w, tr_peer_event* e) static void fire_client_got_rejs(tr_torrent* tor, tr_webseed* w, tr_block_index_t block, tr_block_index_t count) { - tr_block_index_t i; tr_peer_event e = TR_PEER_EVENT_INIT; e.eventType = TR_PEER_CLIENT_GOT_REJ; tr_torrentGetBlockLocation(tor, block, &e.pieceIndex, &e.offset, &e.length); - for (i = 1; i <= count; i++) + for (tr_block_index_t i = 1; i <= count; i++) { if (i == count) { @@ -103,12 +102,11 @@ static void fire_client_got_rejs(tr_torrent* tor, tr_webseed* w, tr_block_index_ static void fire_client_got_blocks(tr_torrent* tor, tr_webseed* w, tr_block_index_t block, tr_block_index_t count) { - tr_block_index_t i; tr_peer_event e = TR_PEER_EVENT_INIT; e.eventType = TR_PEER_CLIENT_GOT_BLOCK; tr_torrentGetBlockLocation(tor, block, &e.pieceIndex, &e.offset, &e.length); - for (i = 1; i <= count; i++) + for (tr_block_index_t i = 1; i <= count; i++) { if (i == count) { @@ -320,7 +318,6 @@ static void on_idle(tr_webseed* w) if (tor != NULL && tor->isRunning && !tr_torrentIsSeed(tor) && want > 0) { - int i; int got = 0; tr_block_index_t* blocks = NULL; @@ -334,7 +331,7 @@ static void on_idle(tr_webseed* w) w->retry_tickcount = 0; } - for (i = 0; i < got; ++i) + for (int i = 0; i < got; ++i) { tr_block_index_t const b = blocks[i * 2]; tr_block_index_t const be = blocks[i * 2 + 1]; @@ -540,11 +537,10 @@ static bool webseed_is_transferring_pieces(tr_peer const* peer, uint64_t now, tr static void webseed_destruct(tr_peer* peer) { - tr_list* l; tr_webseed* w = (tr_webseed*)peer; /* flag all the pending tasks as dead */ - for (l = w->tasks; l != NULL; l = l->next) + for (tr_list* l = w->tasks; l != NULL; l = l->next) { struct tr_webseed_task* task = l->data; task->dead = true; @@ -555,11 +551,10 @@ static void webseed_destruct(tr_peer* peer) /* if we have an array of file URLs, free it */ if (w->file_urls != NULL) { - tr_file_index_t i; tr_torrent* tor = tr_torrentFindFromId(w->session, w->torrent_id); tr_info const* inf = tr_torrentInfo(tor); - for (i = 0; i < inf->fileCount; ++i) + for (tr_file_index_t i = 0; i < inf->fileCount; ++i) { tr_free(w->file_urls[i]); } diff --git a/utils/edit.c b/utils/edit.c index 050612935..dc771f5f2 100644 --- a/utils/edit.c +++ b/utils/edit.c @@ -296,7 +296,6 @@ static bool addURL(tr_variant* metainfo, char const* url) int tr_main(int argc, char* argv[]) { - int i; int changedCount = 0; files = tr_new0(char const*, argc); @@ -330,7 +329,7 @@ int tr_main(int argc, char* argv[]) return EXIT_FAILURE; } - for (i = 0; i < fileCount; ++i) + for (int i = 0; i < fileCount; ++i) { tr_variant top; bool changed = false; diff --git a/utils/show.c b/utils/show.c index 2611c5f1a..748a95aab 100644 --- a/utils/show.c +++ b/utils/show.c @@ -95,7 +95,6 @@ static int compare_files_by_name(void const* va, void const* vb) static void showInfo(tr_info const* inf) { - unsigned int i; char buf[128]; tr_file** files; int prevTier = -1; @@ -135,7 +134,7 @@ static void showInfo(tr_info const* inf) printf("\nTRACKERS\n"); - for (i = 0; i < inf->trackerCount; ++i) + for (unsigned int i = 0; i < inf->trackerCount; ++i) { if (prevTier != inf->trackers[i].tier) { @@ -154,7 +153,7 @@ static void showInfo(tr_info const* inf) { printf("\nWEBSEEDS\n\n"); - for (i = 0; i < inf->webseedCount; ++i) + for (unsigned int i = 0; i < inf->webseedCount; ++i) { printf(" %s\n", inf->webseeds[i]); } @@ -167,14 +166,14 @@ static void showInfo(tr_info const* inf) printf("\nFILES\n\n"); files = tr_new(tr_file*, inf->fileCount); - for (i = 0; i < inf->fileCount; ++i) + for (unsigned int i = 0; i < inf->fileCount; ++i) { files[i] = &inf->files[i]; } qsort(files, inf->fileCount, sizeof(tr_file*), compare_files_by_name); - for (i = 0; i < inf->fileCount; ++i) + for (unsigned int i = 0; i < inf->fileCount; ++i) { printf(" %s (%s)\n", files[i]->name, tr_formatter_size_B(buf, files[i]->length, sizeof(buf))); } @@ -203,9 +202,7 @@ static CURL* tr_curl_easy_init(struct evbuffer* writebuf) static void doScrape(tr_info const* inf) { - unsigned int i; - - for (i = 0; i < inf->trackerCount; ++i) + for (unsigned int i = 0; i < inf->trackerCount; ++i) { CURL* curl; CURLcode res; -- 2.40.0