]> granicus.if.org Git - transmission/commitdiff
Make conditional expressions explicitly boolean
authorMike Gelfand <mikedld@mikedld.com>
Sun, 30 Apr 2017 16:25:26 +0000 (19:25 +0300)
committerMike Gelfand <mikedld@mikedld.com>
Sun, 30 Apr 2017 16:26:01 +0000 (19:26 +0300)
108 files changed:
cli/cli.c
daemon/daemon.c
daemon/remote.c
gtk/details.c
gtk/dialogs.c
gtk/file-list.c
gtk/filter.c
gtk/main.c
gtk/makemeta-ui.c
gtk/msgwin.c
gtk/notify.c
gtk/open-dialog.c
gtk/torrent-cell-renderer.c
gtk/tr-core.c
gtk/tr-prefs.c
gtk/tr-window.c
gtk/util.c
libtransmission/announcer-http.c
libtransmission/announcer-udp.c
libtransmission/announcer.c
libtransmission/bandwidth.c
libtransmission/bandwidth.h
libtransmission/bitfield-test.c
libtransmission/bitfield.c
libtransmission/blocklist.c
libtransmission/cache.c
libtransmission/clients.c
libtransmission/completion.c
libtransmission/crypto.c
libtransmission/fdlimit.c
libtransmission/handshake.c
libtransmission/history.c
libtransmission/inout.c
libtransmission/json-test.c
libtransmission/libtransmission-test.c
libtransmission/list.c
libtransmission/log.c
libtransmission/magnet.c
libtransmission/makemeta.c
libtransmission/metainfo-test.c
libtransmission/metainfo.c
libtransmission/move-test.c
libtransmission/natpmp.c
libtransmission/net.c
libtransmission/peer-io.c
libtransmission/peer-io.h
libtransmission/peer-mgr.c
libtransmission/peer-msgs.c
libtransmission/platform-quota.c
libtransmission/platform.c
libtransmission/port-forwarding.c
libtransmission/ptrarray.c
libtransmission/ptrarray.h
libtransmission/rename-test.c
libtransmission/resume.c
libtransmission/rpc-server.c
libtransmission/rpcimpl.c
libtransmission/session-test.c
libtransmission/session.c
libtransmission/session.h
libtransmission/stats.c
libtransmission/torrent-ctor.c
libtransmission/torrent-magnet.c
libtransmission/torrent.c
libtransmission/torrent.h
libtransmission/tr-dht.c
libtransmission/tr-getopt-test.c
libtransmission/tr-getopt.c
libtransmission/tr-lpd.c
libtransmission/tr-udp.c
libtransmission/tr-utp.c
libtransmission/trevent.c
libtransmission/upnp.c
libtransmission/upnp.h
libtransmission/utils-test.c
libtransmission/utils.c
libtransmission/variant-benc.c
libtransmission/variant-json.c
libtransmission/variant-test.c
libtransmission/variant.c
libtransmission/variant.h
libtransmission/verify.c
libtransmission/web.c
libtransmission/webseed.c
qt/AddData.cc
qt/Application.cc
qt/DetailsDialog.cc
qt/FaviconCache.cc
qt/FileTreeDelegate.cc
qt/FileTreeItem.cc
qt/FileTreeModel.cc
qt/Formatter.cc
qt/MainWindow.cc
qt/MakeDialog.cc
qt/OptionsDialog.cc
qt/Prefs.cc
qt/PrefsDialog.cc
qt/Session.cc
qt/SqueezeLabel.cc
qt/Torrent.cc
qt/TorrentFilter.cc
qt/TorrentModel.cc
qt/TrackerModel.cc
qt/Utils.cc
qt/WatchDir.cc
utils/create.c
utils/edit.c
utils/show.c

index d87cbcc54222329d1f02d84918d34f8959d316fb..38ce1d91744e797cb9dae096e3f44015c6501717 100644 (file)
--- a/cli/cli.c
+++ b/cli/cli.c
@@ -191,7 +191,7 @@ static char const* getConfigDir(int argc, char const** argv)
     char const* optarg;
     int const ind = tr_optind;
 
-    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
     {
         if (c == 'g')
         {
@@ -240,7 +240,7 @@ int tr_main(int argc, char* argv[])
     tr_sessionLoadSettings(&settings, configDir, MY_CONFIG_NAME);
 
     /* the command line overrides defaults */
-    if (parseCommandLine(&settings, argc, (char const**)argv))
+    if (parseCommandLine(&settings, argc, (char const**)argv) != 0)
     {
         return EXIT_FAILURE;
     }
@@ -251,7 +251,7 @@ int tr_main(int argc, char* argv[])
     }
 
     /* Check the options for validity */
-    if (!torrentPath)
+    if (torrentPath == NULL)
     {
         fprintf(stderr, "No torrent specified!\n");
         return EXIT_FAILURE;
@@ -311,7 +311,7 @@ int tr_main(int argc, char* argv[])
     tor = tr_torrentNew(ctor, NULL, NULL);
     tr_ctorFree(ctor);
 
-    if (!tor)
+    if (tor == NULL)
     {
         fprintf(stderr, "Failed opening torrent file `%s'\n", torrentPath);
         tr_sessionClose(h);
@@ -400,7 +400,7 @@ static int parseCommandLine(tr_variant* d, int argc, char const** argv)
     int c;
     char const* optarg;
 
-    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
     {
         switch (c)
         {
index e9c4c5e7bc5fb0ada9328ac74e93f01091e26436..447cbf61a44e9d58c6c6d2fe77e0ee42cd9b1683 100644 (file)
@@ -174,7 +174,7 @@ static char const* getConfigDir(int argc, char const* const* argv)
     char const* optarg;
     int const ind = tr_optind;
 
-    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
     {
         if (c == 'g')
         {
@@ -206,7 +206,7 @@ static tr_watchdir_status onFileAdded(tr_watchdir_t dir, char const* name, void*
     tr_ctor* ctor = tr_ctorNew(session);
     int err = tr_ctorSetMetainfoFromFile(ctor, filename);
 
-    if (!err)
+    if (err == 0)
     {
         tr_torrentNew(ctor, &err, NULL);
 
@@ -259,7 +259,7 @@ static void printMessage(tr_sys_file_t logfile, int level, char const* name, cha
         char timestr[64];
         tr_logGetTimeStr(timestr, sizeof(timestr));
 
-        if (name)
+        if (name != NULL)
         {
             tr_sys_file_write_fmt(logfile, "[%s] %s %s (%s:%d)" TR_NATIVE_EOL_STR, NULL, timestr, name, message, file, line);
         }
@@ -270,6 +270,7 @@ static void printMessage(tr_sys_file_t logfile, int level, char const* name, cha
     }
 
 #ifdef HAVE_SYSLOG
+
     else /* daemon... write to syslog */
     {
         int priority;
@@ -290,7 +291,7 @@ static void printMessage(tr_sys_file_t logfile, int level, char const* name, cha
             break;
         }
 
-        if (name)
+        if (name != NULL)
         {
             syslog(priority, "%s %s (%s:%d)", name, message, file, line);
         }
@@ -301,7 +302,9 @@ static void printMessage(tr_sys_file_t logfile, int level, char const* name, cha
     }
 
 #else
+
     (void)level;
+
 #endif
 }
 
@@ -367,7 +370,7 @@ static bool parse_args(int argc, char const** argv, tr_variant* settings, bool*
 
     tr_optind = 1;
 
-    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
     {
         switch (c)
         {
@@ -566,7 +569,7 @@ struct daemon_data
 
 static void daemon_reconfigure(void* arg UNUSED)
 {
-    if (!mySession)
+    if (mySession == NULL)
     {
         tr_logAddInfo("Deferring reload until session is fully started.");
         seenHUP = true;
@@ -643,7 +646,7 @@ static int daemon_start(void* raw_arg, bool foreground)
     pid_filename = NULL;
     tr_variantDictFindStr(settings, key_pidfile, &pid_filename, NULL);
 
-    if (pid_filename && *pid_filename)
+    if (pid_filename != NULL && *pid_filename != '\0')
     {
         tr_error* error = NULL;
         tr_sys_file_t fp = tr_sys_file_open(pid_filename, TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE | TR_SYS_FILE_TRUNCATE, 0666, &error);
@@ -754,7 +757,7 @@ cleanup:
 
     tr_watchdir_free(watchdir);
 
-    if (status_ev)
+    if (status_ev != NULL)
     {
         event_del(status_ev);
         event_free(status_ev);
index 3648290fff8412f3898079694b8829f13a530706..16b06a7ffd088ae6e94ec8bdfedb522a7ca71f81 100644 (file)
@@ -109,9 +109,9 @@ static char* tr_strltime(char* buf, int seconds, size_t buflen)
     tr_snprintf(s, sizeof(s), "%d %s", seconds, seconds == 1 ? "second" : "seconds");
     tr_snprintf(t, sizeof(t), "%d %s", total_seconds, total_seconds == 1 ? "second" : "seconds");
 
-    if (days)
+    if (days != 0)
     {
-        if (days >= 4 || !hours)
+        if (days >= 4 || hours == 0)
         {
             tr_strlcpy(b, d, sizeof(b));
         }
@@ -120,9 +120,9 @@ static char* tr_strltime(char* buf, int seconds, size_t buflen)
             tr_snprintf(b, sizeof(b), "%s, %s", d, h);
         }
     }
-    else if (hours)
+    else if (hours != 0)
     {
-        if (hours >= 4 || !minutes)
+        if (hours >= 4 || minutes == 0)
         {
             tr_strlcpy(b, h, sizeof(b));
         }
@@ -131,9 +131,9 @@ static char* tr_strltime(char* buf, int seconds, size_t buflen)
             tr_snprintf(b, sizeof(b), "%s, %s", h, m);
         }
     }
-    else if (minutes)
+    else if (minutes != 0)
     {
-        if (minutes >= 4 || !seconds)
+        if (minutes >= 4 || seconds == 0)
         {
             tr_strlcpy(b, m, sizeof(b));
         }
@@ -183,7 +183,7 @@ static char* strlratio(char* buf, int64_t numerator, int64_t denominator, size_t
 
 static char* strlmem(char* buf, int64_t bytes, size_t buflen)
 {
-    if (!bytes)
+    if (bytes == 0)
     {
         tr_strlcpy(buf, "None", buflen);
     }
@@ -347,7 +347,7 @@ static int numarg(char const* arg)
     char* end = NULL;
     long const num = strtol(arg, &end, 10);
 
-    if (*end)
+    if (*end != '\0')
     {
         fprintf(stderr, "Not a number: \"%s\"\n", arg);
         showUsage();
@@ -522,7 +522,7 @@ static char* getEncodedMetainfo(char const* filename)
     char* b64 = NULL;
     uint8_t* buf = tr_loadFile(filename, &len, NULL);
 
-    if (buf)
+    if (buf != NULL)
     {
         b64 = tr_base64_encode(buf, len, NULL);
         tr_free(buf);
@@ -533,11 +533,11 @@ static char* getEncodedMetainfo(char const* filename)
 
 static void addIdArg(tr_variant* args, char const* id, char const* fallback)
 {
-    if (!id || !*id)
+    if (id == NULL || *id == '\0')
     {
         id = fallback;
 
-        if (!id || !*id)
+        if (id == NULL || *id == '\0')
         {
             fprintf(stderr, "No torrent specified!  Please use the -t option first.\n");
             id = "-1"; /* no torrent will have this ID, so will act as a no-op */
@@ -551,10 +551,10 @@ 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, ',') || strchr(id, '-');
+        bool isList = strchr(id, ',') != NULL || strchr(id, '-') != NULL;
         bool isNum = true;
 
-        for (pch = id; isNum && *pch; ++pch)
+        for (pch = id; isNum && *pch != '\0'; ++pch)
         {
             if (!isdigit(*pch))
             {
@@ -578,7 +578,7 @@ static void addTime(tr_variant* args, tr_quark const key, char const* arg)
     int time;
     bool success = false;
 
-    if (arg && (strlen(arg) == 4))
+    if (arg != NULL && strlen(arg) == 4)
     {
         char const hh[3] = { arg[0], arg[1], '\0' };
         char const mm[3] = { arg[2], arg[3], '\0' };
@@ -606,7 +606,7 @@ static void addDays(tr_variant* args, tr_quark const key, char const* arg)
 {
     int days = 0;
 
-    if (arg)
+    if (arg != NULL)
     {
         int i;
         int valueCount;
@@ -632,7 +632,7 @@ static void addDays(tr_variant* args, tr_quark const key, char const* arg)
         tr_free(values);
     }
 
-    if (days)
+    if (days != 0)
     {
         tr_variantDictAddInt(args, key, days);
     }
@@ -646,7 +646,7 @@ static void addFiles(tr_variant* args, tr_quark const key, char const* arg)
 {
     tr_variant* files = tr_variantDictAddList(args, key, 100);
 
-    if (!*arg)
+    if (*arg == '\0')
     {
         fprintf(stderr, "No files specified!\n");
         arg = "-1"; /* no file will have this index, so should be a no-op */
@@ -845,15 +845,15 @@ static char* getStatusString(tr_variant* t, char* buf, size_t buflen)
                 tr_variantDictFindInt(t, TR_KEY_peersGettingFromUs, &fromUs);
                 tr_variantDictFindInt(t, TR_KEY_peersSendingToUs, &toUs);
 
-                if (fromUs && toUs)
+                if (fromUs != 0 && toUs != 0)
                 {
                     tr_strlcpy(buf, "Up & Down", buflen);
                 }
-                else if (toUs)
+                else if (toUs != 0)
                 {
                     tr_strlcpy(buf, "Downloading", buflen);
                 }
-                else if (fromUs)
+                else if (fromUs != 0)
                 {
                     int64_t leftUntilDone = 0;
                     tr_variantDictFindInt(t, TR_KEY_leftUntilDone, &leftUntilDone);
@@ -896,7 +896,7 @@ static void printDetails(tr_variant* top)
 {
     tr_variant* args, * torrents;
 
-    if ((tr_variantDictFindDict(top, TR_KEY_arguments, &args)) && (tr_variantDictFindList(args, TR_KEY_torrents, &torrents)))
+    if (tr_variantDictFindDict(top, TR_KEY_arguments, &args) && tr_variantDictFindList(args, TR_KEY_torrents, &torrents))
     {
         int ti, tCount;
 
@@ -1010,7 +1010,8 @@ static void printDetails(tr_variant* top)
                 printf("  Corrupt DL: %s\n", buf);
             }
 
-            if (tr_variantDictFindStr(t, TR_KEY_errorString, &str, NULL) && str && *str && tr_variantDictFindInt(t, TR_KEY_error, &i) && i)
+            if (tr_variantDictFindStr(t, TR_KEY_errorString, &str, NULL) && str != NULL && *str != '\0' &&
+                tr_variantDictFindInt(t, TR_KEY_error, &i) && i != 0)
             {
                 switch (i)
                 {
@@ -1051,36 +1052,36 @@ static void printDetails(tr_variant* top)
 
             printf("HISTORY\n");
 
-            if (tr_variantDictFindInt(t, TR_KEY_addedDate, &i) && i)
+            if (tr_variantDictFindInt(t, TR_KEY_addedDate, &i) && i != 0)
             {
                 time_t const tt = i;
                 printf("  Date added:       %s", ctime(&tt));
             }
 
-            if (tr_variantDictFindInt(t, TR_KEY_doneDate, &i) && i)
+            if (tr_variantDictFindInt(t, TR_KEY_doneDate, &i) && i != 0)
             {
                 time_t const tt = i;
                 printf("  Date finished:    %s", ctime(&tt));
             }
 
-            if (tr_variantDictFindInt(t, TR_KEY_startDate, &i) && i)
+            if (tr_variantDictFindInt(t, TR_KEY_startDate, &i) && i != 0)
             {
                 time_t const tt = i;
                 printf("  Date started:     %s", ctime(&tt));
             }
 
-            if (tr_variantDictFindInt(t, TR_KEY_activityDate, &i) && i)
+            if (tr_variantDictFindInt(t, TR_KEY_activityDate, &i) && i != 0)
             {
                 time_t const tt = i;
                 printf("  Latest activity:  %s", ctime(&tt));
             }
 
-            if (tr_variantDictFindInt(t, TR_KEY_secondsDownloading, &i) && (i > 0))
+            if (tr_variantDictFindInt(t, TR_KEY_secondsDownloading, &i) && i > 0)
             {
                 printf("  Downloading Time: %s\n", tr_strltime(buf, i, sizeof(buf)));
             }
 
-            if (tr_variantDictFindInt(t, TR_KEY_secondsSeeding, &i) && (i > 0))
+            if (tr_variantDictFindInt(t, TR_KEY_secondsSeeding, &i) && i > 0)
             {
                 printf("  Seeding Time:     %s\n", tr_strltime(buf, i, sizeof(buf)));
             }
@@ -1089,7 +1090,7 @@ static void printDetails(tr_variant* top)
 
             printf("ORIGINS\n");
 
-            if (tr_variantDictFindInt(t, TR_KEY_dateCreated, &i) && i)
+            if (tr_variantDictFindInt(t, TR_KEY_dateCreated, &i) && i != 0)
             {
                 time_t const tt = i;
                 printf("  Date created: %s", ctime(&tt));
@@ -1100,12 +1101,12 @@ static void printDetails(tr_variant* top)
                 printf("  Public torrent: %s\n", (boolVal ? "No" : "Yes"));
             }
 
-            if (tr_variantDictFindStr(t, TR_KEY_comment, &str, NULL) && str && *str)
+            if (tr_variantDictFindStr(t, TR_KEY_comment, &str, NULL) && str != NULL && *str != '\0')
             {
                 printf("  Comment: %s\n", str);
             }
 
-            if (tr_variantDictFindStr(t, TR_KEY_creator, &str, NULL) && str && *str)
+            if (tr_variantDictFindStr(t, TR_KEY_creator, &str, NULL) && str != NULL && *str != '\0')
             {
                 printf("  Creator: %s\n", str);
             }
@@ -1201,7 +1202,7 @@ static void printFileList(tr_variant* top)
 {
     tr_variant* args, * torrents;
 
-    if ((tr_variantDictFindDict(top, TR_KEY_arguments, &args)) && (tr_variantDictFindList(args, TR_KEY_torrents, &torrents)))
+    if (tr_variantDictFindDict(top, TR_KEY_arguments, &args) && tr_variantDictFindList(args, TR_KEY_torrents, &torrents))
     {
         int i, in;
 
@@ -1251,7 +1252,8 @@ static void printFileList(tr_variant* top)
                             break;
                         }
 
-                        printf("%3d: %3.0f%% %-8s %-3s %9s  %s\n", j, floor(100.0 * percent), pristr, (wanted ? "Yes" : "No"), sizestr, filename);
+                        printf("%3d: %3.0f%% %-8s %-3s %9s  %s\n", j, floor(100.0 * percent), pristr, wanted ? "Yes" : "No",
+                            sizestr, filename);
                     }
                 }
             }
@@ -1324,7 +1326,7 @@ static void printPiecesImpl(uint8_t const* raw, size_t rawlen, size_t j)
 
         printf(" ");
 
-        if (!(i % 64))
+        if (i % 64 == 0)
         {
             printf("\n  ");
         }
@@ -1373,7 +1375,7 @@ static void printPortTest(tr_variant* top)
 
         if (tr_variantDictFindBool(args, TR_KEY_port_is_open, &boolVal))
         {
-            printf("Port is open: %s\n", (boolVal ? "Yes" : "No"));
+            printf("Port is open: %s\n", boolVal ? "Yes" : "No");
         }
     }
 }
@@ -1382,7 +1384,7 @@ static void printTorrentList(tr_variant* top)
 {
     tr_variant* args, * list;
 
-    if ((tr_variantDictFindDict(top, TR_KEY_arguments, &args)) && (tr_variantDictFindList(args, TR_KEY_torrents, &list)))
+    if (tr_variantDictFindDict(top, TR_KEY_arguments, &args) && tr_variantDictFindList(args, TR_KEY_torrents, &list))
     {
         int i, n;
         int64_t total_size = 0;
@@ -1413,7 +1415,7 @@ static void printTorrentList(tr_variant* top)
                 int64_t error;
                 char errorMark;
 
-                if (sizeWhenDone)
+                if (sizeWhenDone != 0)
                 {
                     tr_snprintf(doneStr, sizeof(doneStr), "%d%%", (int)(100.0 * (sizeWhenDone - leftUntilDone) / sizeWhenDone));
                 }
@@ -1424,7 +1426,7 @@ static void printTorrentList(tr_variant* top)
 
                 strlsize(haveStr, sizeWhenDone - leftUntilDone, sizeof(haveStr));
 
-                if (leftUntilDone || eta != -1)
+                if (leftUntilDone != 0 || eta != -1)
                 {
                     etaToString(etaStr, sizeof(etaStr), eta);
                 }
@@ -1463,7 +1465,7 @@ static void printTrackersImpl(tr_variant* trackerStats)
     char buf[512];
     tr_variant* t;
 
-    for (i = 0; ((t = tr_variantListChild(trackerStats, i))); ++i)
+    for (i = 0; (t = tr_variantListChild(trackerStats, i)) != NULL; ++i)
     {
         int64_t downloadCount;
         bool hasAnnounced;
@@ -1642,7 +1644,7 @@ static void printSession(tr_variant* top)
 {
     tr_variant* args;
 
-    if ((tr_variantDictFindDict(top, TR_KEY_arguments, &args)))
+    if (tr_variantDictFindDict(top, TR_KEY_arguments, &args))
     {
         int64_t i;
         char buf[64];
@@ -1687,7 +1689,7 @@ static void printSession(tr_variant* top)
 
         if (tr_variantDictFindBool(args, TR_KEY_port_forwarding_enabled, &boolVal))
         {
-            printf("  Portforwarding enabled: %s\n", (boolVal ? "Yes" : "No"));
+            printf("  Portforwarding enabled: %s\n", boolVal ? "Yes" : "No");
         }
 
         if (tr_variantDictFindBool(args, TR_KEY_utp_enabled, &boolVal))
@@ -1697,17 +1699,17 @@ static void printSession(tr_variant* top)
 
         if (tr_variantDictFindBool(args, TR_KEY_dht_enabled, &boolVal))
         {
-            printf("  Distributed hash table enabled: %s\n", (boolVal ? "Yes" : "No"));
+            printf("  Distributed hash table enabled: %s\n", boolVal ? "Yes" : "No");
         }
 
         if (tr_variantDictFindBool(args, TR_KEY_lpd_enabled, &boolVal))
         {
-            printf("  Local peer discovery enabled: %s\n", (boolVal ? "Yes" : "No"));
+            printf("  Local peer discovery enabled: %s\n", boolVal ? "Yes" : "No");
         }
 
         if (tr_variantDictFindBool(args, TR_KEY_pex_enabled, &boolVal))
         {
-            printf("  Peer exchange allowed: %s\n", (boolVal ? "Yes" : "No"));
+            printf("  Peer exchange allowed: %s\n", boolVal ? "Yes" : "No");
         }
 
         if (tr_variantDictFindStr(args, TR_KEY_encryption, &str, NULL))
@@ -1799,37 +1801,37 @@ static void printSession(tr_variant* top)
                     printf("  Turtle schedule: %02d:%02d - %02d:%02d  ", (int)(altBegin / 60), (int)(altBegin % 60), (int)(altEnd / 60),
                         (int)(altEnd % 60));
 
-                    if (altDay & TR_SCHED_SUN)
+                    if ((altDay & TR_SCHED_SUN) != 0)
                     {
                         printf("Sun ");
                     }
 
-                    if (altDay & TR_SCHED_MON)
+                    if ((altDay & TR_SCHED_MON) != 0)
                     {
                         printf("Mon ");
                     }
 
-                    if (altDay & TR_SCHED_TUES)
+                    if ((altDay & TR_SCHED_TUES) != 0)
                     {
                         printf("Tue ");
                     }
 
-                    if (altDay & TR_SCHED_WED)
+                    if ((altDay & TR_SCHED_WED) != 0)
                     {
                         printf("Wed ");
                     }
 
-                    if (altDay & TR_SCHED_THURS)
+                    if ((altDay & TR_SCHED_THURS) != 0)
                     {
                         printf("Thu ");
                     }
 
-                    if (altDay & TR_SCHED_FRI)
+                    if ((altDay & TR_SCHED_FRI) != 0)
                     {
                         printf("Fri ");
                     }
 
-                    if (altDay & TR_SCHED_SAT)
+                    if ((altDay & TR_SCHED_SAT) != 0)
                     {
                         printf("Sat ");
                     }
@@ -1845,12 +1847,12 @@ static void printSession(tr_variant* top)
 
         if (tr_variantDictFindBool(args, TR_KEY_start_added_torrents, &boolVal))
         {
-            printf("  Autostart added torrents: %s\n", (boolVal ? "Yes" : "No"));
+            printf("  Autostart added torrents: %s\n", boolVal ? "Yes" : "No");
         }
 
         if (tr_variantDictFindBool(args, TR_KEY_trash_original_torrent_files, &boolVal))
         {
-            printf("  Delete automatically added torrents: %s\n", (boolVal ? "Yes" : "No"));
+            printf("  Delete automatically added torrents: %s\n", boolVal ? "Yes" : "No");
         }
     }
 }
@@ -1859,7 +1861,7 @@ static void printSessionStats(tr_variant* top)
 {
     tr_variant* args, * d;
 
-    if ((tr_variantDictFindDict(top, TR_KEY_arguments, &args)))
+    if (tr_variantDictFindDict(top, TR_KEY_arguments, &args))
     {
         char buf[512];
         int64_t up, down, secs, sessions;
@@ -1900,7 +1902,7 @@ static int processResponse(char const* rpcurl, void const* response, size_t len)
         fprintf(stderr, "got response (len %d):\n--------\n%*.*s\n--------\n", (int)len, (int)len, (int)len, (char const*)response);
     }
 
-    if (tr_variantFromJson(&top, response, len))
+    if (tr_variantFromJson(&top, response, len) != 0)
     {
         tr_logAddNamedError(MY_NAME, "Unable to parse response \"%*.*s\"", (int)len, (int)len, (char const*)response);
         status |= EXIT_FAILURE;
@@ -2014,12 +2016,12 @@ static CURL* tr_curl_easy_init(struct evbuffer* writebuf)
     curl_easy_setopt(curl, CURLOPT_VERBOSE, debug);
     curl_easy_setopt(curl, CURLOPT_ENCODING, ""); /* "" tells curl to fill in the blanks with what it was compiled to support */
 
-    if (netrc)
+    if (netrc != NULL)
     {
         curl_easy_setopt(curl, CURLOPT_NETRC_FILE, netrc);
     }
 
-    if (auth)
+    if (auth != NULL)
     {
         curl_easy_setopt(curl, CURLOPT_USERPWD, auth);
     }
@@ -2030,7 +2032,7 @@ static CURL* tr_curl_easy_init(struct evbuffer* writebuf)
         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); /* since most certs will be self-signed, do not verify against CA */
     }
 
-    if (sessionId)
+    if (sessionId != NULL)
     {
         char* h = tr_strdup_printf("%s: %s", TR_RPC_SESSION_ID_HEADER, sessionId);
         struct curl_slist* custom_headers = curl_slist_append(NULL, h);
@@ -2060,7 +2062,7 @@ static int flush(char const* rpcurl, tr_variant** benc)
         fprintf(stderr, "posting:\n--------\n%s\n--------\n", json);
     }
 
-    if ((res = curl_easy_perform(curl)))
+    if ((res = curl_easy_perform(curl)) != CURLE_OK)
     {
         tr_logAddNamedError(MY_NAME, " (%s) %s", rpcurl_http, curl_easy_strerror(res));
         status |= EXIT_FAILURE;
@@ -2098,7 +2100,7 @@ static int flush(char const* rpcurl, tr_variant** benc)
     tr_free(json);
     evbuffer_free(buf);
 
-    if (curl != 0)
+    if (curl != NULL)
     {
         curl_easy_cleanup(curl);
     }
@@ -2106,7 +2108,7 @@ static int flush(char const* rpcurl, tr_variant** benc)
     if (benc != NULL)
     {
         tr_variantFree(*benc);
-        *benc = 0;
+        *benc = NULL;
     }
 
     return status;
@@ -2116,7 +2118,7 @@ static tr_variant* ensure_sset(tr_variant** sset)
 {
     tr_variant* args;
 
-    if (*sset)
+    if (*sset != NULL)
     {
         args = tr_variantDictFind(*sset, ARGUMENTS);
     }
@@ -2135,7 +2137,7 @@ static tr_variant* ensure_tset(tr_variant** tset)
 {
     tr_variant* args;
 
-    if (*tset)
+    if (*tset != NULL)
     {
         args = tr_variantDictFind(*tset, ARGUMENTS);
     }
@@ -2155,32 +2157,32 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
     int c;
     int status = EXIT_SUCCESS;
     char const* optarg;
-    tr_variant* sset = 0;
-    tr_variant* tset = 0;
-    tr_variant* tadd = 0;
+    tr_variant* sset = NULL;
+    tr_variant* tset = NULL;
+    tr_variant* tadd = NULL;
 
     *id = '\0';
 
-    while ((c = tr_getopt(getUsage(), argc, argv, opts, &optarg)))
+    while ((c = tr_getopt(getUsage(), argc, argv, opts, &optarg)) != TR_OPT_DONE)
     {
         int const stepMode = getOptMode(c);
 
-        if (!stepMode) /* meta commands */
+        if (stepMode == 0) /* meta commands */
         {
             switch (c)
             {
             case 'a': /* add torrent */
-                if (sset != 0)
+                if (sset != NULL)
                 {
                     status |= flush(rpcurl, &sset);
                 }
 
-                if (tadd != 0)
+                if (tadd != NULL)
                 {
                     status |= flush(rpcurl, &tadd);
                 }
 
-                if (tset != 0)
+                if (tset != NULL)
                 {
                     addIdArg(tr_variantDictFind(tset, ARGUMENTS), id, NULL);
                     status |= flush(rpcurl, &tset);
@@ -2221,12 +2223,12 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
                 break;
 
             case 't': /* set current torrent */
-                if (tadd != 0)
+                if (tadd != NULL)
                 {
                     status |= flush(rpcurl, &tadd);
                 }
 
-                if (tset != 0)
+                if (tset != NULL)
                 {
                     addIdArg(tr_variantDictFind(tset, ARGUMENTS), id, NULL);
                     status |= flush(rpcurl, &tset);
@@ -2247,12 +2249,12 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
                 break;
 
             case TR_OPT_UNK:
-                if (tadd)
+                if (tadd != NULL)
                 {
                     tr_variant* args = tr_variantDictFind(tadd, ARGUMENTS);
                     char* tmp = getEncodedMetainfo(optarg);
 
-                    if (tmp)
+                    if (tmp != NULL)
                     {
                         tr_variantDictAddStr(args, TR_KEY_metainfo, tmp);
                     }
@@ -2283,7 +2285,7 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
             args = tr_variantDictAddDict(top, ARGUMENTS, 0);
             fields = tr_variantDictAddList(args, TR_KEY_fields, 0);
 
-            if (tset != 0)
+            if (tset != NULL)
             {
                 addIdArg(tr_variantDictFind(tset, ARGUMENTS), id, NULL);
                 status |= flush(rpcurl, &tset);
@@ -2508,10 +2510,10 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
         }
         else if (stepMode == (MODE_SESSION_SET | MODE_TORRENT_SET))
         {
-            tr_variant* targs = 0;
-            tr_variant* sargs = 0;
+            tr_variant* targs = NULL;
+            tr_variant* sargs = NULL;
 
-            if (*id)
+            if (*id != '\0')
             {
                 targs = ensure_tset(&tset);
             }
@@ -2523,7 +2525,7 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
             switch (c)
             {
             case 'd':
-                if (targs)
+                if (targs != NULL)
                 {
                     tr_variantDictAddInt(targs, TR_KEY_downloadLimit, numarg(optarg));
                     tr_variantDictAddBool(targs, TR_KEY_downloadLimited, true);
@@ -2537,7 +2539,7 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
                 break;
 
             case 'D':
-                if (targs)
+                if (targs != NULL)
                 {
                     tr_variantDictAddBool(targs, TR_KEY_downloadLimited, false);
                 }
@@ -2549,7 +2551,7 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
                 break;
 
             case 'u':
-                if (targs)
+                if (targs != NULL)
                 {
                     tr_variantDictAddInt(targs, TR_KEY_uploadLimit, numarg(optarg));
                     tr_variantDictAddBool(targs, TR_KEY_uploadLimited, true);
@@ -2563,7 +2565,7 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
                 break;
 
             case 'U':
-                if (targs)
+                if (targs != NULL)
                 {
                     tr_variantDictAddBool(targs, TR_KEY_uploadLimited, false);
                 }
@@ -2575,7 +2577,7 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
                 break;
 
             case 930:
-                if (targs)
+                if (targs != NULL)
                 {
                     tr_variantDictAddInt(targs, TR_KEY_peer_limit, atoi(optarg));
                 }
@@ -2631,7 +2633,7 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
         {
             tr_variant* args;
 
-            if (tadd)
+            if (tadd != NULL)
             {
                 args = tr_variantDictFind(tadd, ARGUMENTS);
             }
@@ -2685,7 +2687,7 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
         }
         else if (c == 961) /* set location */
         {
-            if (tadd)
+            if (tadd != NULL)
             {
                 tr_variant* args = tr_variantDictFind(tadd, ARGUMENTS);
                 tr_variantDictAddStr(args, TR_KEY_download_dir, optarg);
@@ -2720,7 +2722,7 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
 
             case 's': /* start */
                 {
-                    if (tadd)
+                    if (tadd != NULL)
                     {
                         tr_variantDictAddBool(tr_variantDictFind(tadd, TR_KEY_arguments), TR_KEY_paused, false);
                     }
@@ -2738,7 +2740,7 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
 
             case 'S': /* stop */
                 {
-                    if (tadd)
+                    if (tadd != NULL)
                     {
                         tr_variantDictAddBool(tr_variantDictFind(tadd, TR_KEY_arguments), TR_KEY_paused, true);
                     }
@@ -2803,7 +2805,7 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
                 {
                     tr_variant* top;
 
-                    if (tset != 0)
+                    if (tset != NULL)
                     {
                         addIdArg(tr_variantDictFind(tset, ARGUMENTS), id, NULL);
                         status |= flush(rpcurl, &tset);
@@ -2821,7 +2823,7 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
                 {
                     tr_variant* top;
 
-                    if (tset != 0)
+                    if (tset != NULL)
                     {
                         addIdArg(tr_variantDictFind(tset, ARGUMENTS), id, NULL);
                         status |= flush(rpcurl, &tset);
@@ -2873,18 +2875,18 @@ static int processArgs(char const* rpcurl, int argc, char const* const* argv)
         }
     }
 
-    if (tadd != 0)
+    if (tadd != NULL)
     {
         status |= flush(rpcurl, &tadd);
     }
 
-    if (tset != 0)
+    if (tset != NULL)
     {
         addIdArg(tr_variantDictFind(tset, ARGUMENTS), id, NULL);
         status |= flush(rpcurl, &tset);
     }
 
-    if (sset != 0)
+    if (sset != NULL)
     {
         status |= flush(rpcurl, &sset);
     }
@@ -2910,7 +2912,7 @@ static void getHostAndPortAndRpcUrl(int* argc, char** argv, char** host, int* po
             UseSSL = true;
             *rpcurl = tr_strdup_printf("%s/rpc/", s + 8);
         }
-        else if (delim) /* user passed in both host and port */
+        else if (delim != NULL) /* user passed in both host and port */
         {
             *host = tr_strndup(s, delim - s);
             *port = atoi(delim + 1);
@@ -2920,7 +2922,7 @@ static void getHostAndPortAndRpcUrl(int* argc, char** argv, char** host, int* po
             char* end;
             int const i = strtol(s, &end, 10);
 
-            if (!*end) /* user passed in a port */
+            if (*end == '\0') /* user passed in a port */
             {
                 *port = i;
             }
index 3a6c0280e73c8a5bfb41a863e0d349a6c57c0115..30b1c7a504ab698e524c04f6458b69962b442b20 100644 (file)
@@ -160,7 +160,7 @@ static void set_double_spin_if_different(GtkWidget* w, gulong tag, double value)
     GtkSpinButton* spin = GTK_SPIN_BUTTON(w);
     double const currentValue = gtk_spin_button_get_value(spin);
 
-    if (((int)(currentValue * 100) != (int)(value * 100)))
+    if ((int)(currentValue * 100) != (int)(value * 100))
     {
         g_signal_handler_block(spin, tag);
         gtk_spin_button_set_value(spin, value);
@@ -184,7 +184,7 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n)
     ***/
 
     /* honor_limits_check */
-    if (n)
+    if (n != 0)
     {
         int i;
         bool const baseline = tr_torrentUsesSessionLimits(torrents[0]);
@@ -204,7 +204,7 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n)
     }
 
     /* down_limited_check */
-    if (n)
+    if (n != 0)
     {
         int i;
         bool const baseline = tr_torrentUsesSpeedLimit(torrents[0], TR_DOWN);
@@ -224,14 +224,14 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n)
     }
 
     /* down_limit_spin */
-    if (n)
+    if (n != 0)
     {
         int i;
-        unsigned const int baseline = tr_torrentGetSpeedLimit_KBps(torrents[0], TR_DOWN);
+        unsigned int const baseline = tr_torrentGetSpeedLimit_KBps(torrents[0], TR_DOWN);
 
         for (i = 1; i < n; ++i)
         {
-            if (baseline != (tr_torrentGetSpeedLimit_KBps(torrents[i], TR_DOWN)))
+            if (baseline != tr_torrentGetSpeedLimit_KBps(torrents[i], TR_DOWN))
             {
                 break;
             }
@@ -244,7 +244,7 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n)
     }
 
     /* up_limited_check */
-    if (n)
+    if (n != 0)
     {
         int i;
         bool const baseline = tr_torrentUsesSpeedLimit(torrents[0], TR_UP);
@@ -264,14 +264,14 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n)
     }
 
     /* up_limit_sping */
-    if (n)
+    if (n != 0)
     {
         int i;
         unsigned int const baseline = tr_torrentGetSpeedLimit_KBps(torrents[0], TR_UP);
 
         for (i = 1; i < n; ++i)
         {
-            if (baseline != (tr_torrentGetSpeedLimit_KBps(torrents[i], TR_UP)))
+            if (baseline != tr_torrentGetSpeedLimit_KBps(torrents[i], TR_UP))
             {
                 break;
             }
@@ -284,7 +284,7 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n)
     }
 
     /* bandwidth_combo */
-    if (n)
+    if (n != 0)
     {
         int i;
         int const baseline = tr_torrentGetPriority(torrents[0]);
@@ -311,7 +311,7 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n)
     }
 
     /* ratio_combo */
-    if (n)
+    if (n != 0)
     {
         int i;
         int const baseline = tr_torrentGetRatioMode(torrents[0]);
@@ -335,14 +335,14 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n)
     }
 
     /* ratio_spin */
-    if (n)
+    if (n != 0)
     {
         double const baseline = tr_torrentGetRatioLimit(torrents[0]);
         set_double_spin_if_different(di->ratio_spin, di->ratio_spin_tag, baseline);
     }
 
     /* idle_combo */
-    if (n)
+    if (n != 0)
     {
         int i;
         int const baseline = tr_torrentGetIdleMode(torrents[0]);
@@ -366,14 +366,14 @@ static void refreshOptions(struct DetailsImpl* di, tr_torrent** torrents, int n)
     }
 
     /* idle_spin */
-    if (n)
+    if (n != 0)
     {
         int const baseline = tr_torrentGetIdleLimit(torrents[0]);
         set_int_spin_if_different(di->idle_spin, di->idle_spin_tag, baseline);
     }
 
     /* max_peers_spin */
-    if (n)
+    if (n != 0)
     {
         int const baseline = tr_torrentGetPeerLimit(torrents[0]);
         set_int_spin_if_different(di->max_peers_spin, di->max_peers_spin_tag, baseline);
@@ -391,7 +391,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; l = l->next)
+    for (l = di->ids; l != NULL; l = l->next)
     {
         tr_variantListAddInt(ids, GPOINTER_TO_INT(l->data));
     }
@@ -411,7 +411,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; l = l->next)
+    for (l = di->ids; l != NULL; l = l->next)
     {
         tr_variantListAddInt(ids, GPOINTER_TO_INT(l->data));
     }
@@ -431,7 +431,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; l = l->next)
+    for (l = di->ids; l != NULL; l = l->next)
     {
         tr_variantListAddInt(ids, GPOINTER_TO_INT(l->data));
     }
@@ -666,7 +666,7 @@ static char* get_short_date_string(time_t t)
     char buf[64];
     struct tm tm;
 
-    if (!t)
+    if (t == 0)
     {
         return g_strdup(_("N/A"));
     }
@@ -746,7 +746,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n)
             mixed_date |= (date != infos[i]->dateCreated);
         }
 
-        gboolean const empty_creator = !*creator;
+        gboolean const empty_creator = *creator == '\0';
         gboolean const empty_date = date == 0;
 
         if (mixed_date || mixed_creator)
@@ -857,7 +857,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n)
 
             if (!stats[i]->finished)
             {
-                allFinished = FALSE;
+                allFinished = false;
             }
         }
 
@@ -888,7 +888,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n)
         {
             str = mixed;
         }
-        else if ((baseline <= 0) || (stats[0]->activity == TR_STATUS_STOPPED))
+        else if (baseline <= 0 || stats[0]->activity == TR_STATUS_STOPPED)
         {
             str = stateString;
         }
@@ -945,7 +945,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n)
             size += infos[i]->totalSize;
             pieces += infos[i]->pieceCount;
 
-            if (!pieceSize)
+            if (pieceSize == 0)
             {
                 pieceSize = infos[i]->pieceSize;
             }
@@ -957,7 +957,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n)
 
         tr_strlsize(sizebuf, size, sizeof(sizebuf));
 
-        if (!size)
+        if (size == 0)
         {
             str = "";
         }
@@ -965,8 +965,8 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n)
         {
             char piecebuf[128];
             tr_formatter_mem_B(piecebuf, pieceSize, sizeof(piecebuf));
-            g_snprintf(buf, sizeof(buf), ngettext("%1$s (%2$'d piece @ %3$s)", "%1$s (%2$'d pieces @ %3$s)",
-                pieces), sizebuf, pieces, piecebuf);
+            g_snprintf(buf, sizeof(buf), ngettext("%1$s (%2$'d piece @ %3$s)", "%1$s (%2$'d pieces @ %3$s)", pieces), sizebuf,
+                pieces, piecebuf);
             str = buf;
         }
         else
@@ -1010,11 +1010,11 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n)
             tr_strlsize(total, haveUnchecked + haveValid, sizeof(total));
             tr_strlsize(unver, haveUnchecked, sizeof(unver));
 
-            if (!haveUnchecked && !leftUntilDone)
+            if (haveUnchecked == 0 && leftUntilDone == 0)
             {
                 g_snprintf(buf, sizeof(buf), _("%1$s (%2$s%%)"), total, buf2);
             }
-            else if (!haveUnchecked)
+            else if (haveUnchecked == 0)
             {
                 g_snprintf(buf, sizeof(buf), _("%1$s (%2$s%% of %3$s%% Available)"), total, buf2, avail);
             }
@@ -1049,7 +1049,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n)
         tr_strlsize(dbuf, d, sizeof(dbuf));
         tr_strlsize(fbuf, f, sizeof(fbuf));
 
-        if (f)
+        if (f != 0)
         {
             g_snprintf(buf, sizeof(buf), _("%1$s (+%2$s corrupt)"), dbuf, fbuf);
         }
@@ -1132,7 +1132,7 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n)
         }
     }
 
-    if (!str || !*str)
+    if (str == NULL || *str == '\0')
     {
         str = _("No errors");
     }
@@ -1817,7 +1817,7 @@ static gboolean onPeerViewQueryTooltip(GtkWidget* widget, gint x, gint y, gboole
         g_string_append_printf(gstr, "<b>%s</b>\n%s\n \n", markup, addr);
         g_free(markup);
 
-        for (pch = flagstr; pch && *pch; ++pch)
+        for (pch = flagstr; pch != NULL && *pch != '\0'; ++pch)
         {
             char const* s = NULL;
 
@@ -1872,13 +1872,13 @@ static gboolean onPeerViewQueryTooltip(GtkWidget* widget, gint x, gint y, gboole
                 break;
             }
 
-            if (s)
+            if (s != NULL)
             {
                 g_string_append_printf(gstr, "%c: %s\n", *pch, s);
             }
         }
 
-        if (gstr->len) /* remove the last linefeed */
+        if (gstr->len != 0) /* remove the last linefeed */
         {
             g_string_set_size(gstr, gstr->len - 1);
         }
@@ -1945,7 +1945,7 @@ static void setPeerViewColumns(GtkTreeView* peer_view)
     view_columns[n++] = PEER_COL_CLIENT;
 
     /* remove any existing columns */
-    while ((c = gtk_tree_view_get_column(peer_view, 0)))
+    while ((c = gtk_tree_view_get_column(peer_view, 0)) != NULL)
     {
         gtk_tree_view_remove_column(peer_view, c);
     }
@@ -2185,7 +2185,7 @@ static void buildTrackerSummary(GString* gstr, char const* key, tr_tracker_stat
     {
         g_string_append(gstr, st->isBackup ? "<i>" : "<b>");
 
-        if (key)
+        if (key != NULL)
         {
             str = g_markup_printf_escaped("%s - %s", st->host, key);
         }
@@ -2716,7 +2716,7 @@ static void on_add_tracker_response(GtkDialog* dialog, int response, gpointer gd
         char* url = g_strdup(gtk_entry_get_text(GTK_ENTRY(e)));
         g_strstrip(url);
 
-        if (url && *url)
+        if (url != NULL && *url != '\0')
         {
             if (tr_urlIsValidTracker(url))
             {
@@ -2842,8 +2842,7 @@ static GtkWidget* tracker_page_new(struct DetailsImpl* di)
         (GDestroyNotify)gtk_tree_row_reference_free);
 
     di->trackers_filtered = gtk_tree_model_filter_new(GTK_TREE_MODEL(di->tracker_store), NULL);
-    gtk_tree_model_filter_set_visible_func(GTK_TREE_MODEL_FILTER(di->trackers_filtered),
-        trackerVisibleFunc, di, NULL);
+    gtk_tree_model_filter_set_visible_func(GTK_TREE_MODEL_FILTER(di->trackers_filtered), trackerVisibleFunc, di, NULL);
 
     hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, GUI_PAD_BIG);
 
index a3f09d7da82c319635fa39be29af81095479be90..28f3d3a9964271bd2ff343c3689b12f0f32febe6 100644 (file)
@@ -68,7 +68,7 @@ void gtr_confirm_remove(GtkWindow* parent, TrCore* core, GSList* torrent_ids, gb
     int incomplete = 0;
     int const count = g_slist_length(torrent_ids);
 
-    if (!count)
+    if (count == 0)
     {
         return;
     }
@@ -84,12 +84,12 @@ void gtr_confirm_remove(GtkWindow* parent, TrCore* core, GSList* torrent_ids, gb
         tr_torrent* tor = gtr_core_find_torrent(core, id);
         tr_stat const* stat = tr_torrentStat(tor);
 
-        if (stat->leftUntilDone)
+        if (stat->leftUntilDone != 0)
         {
             ++incomplete;
         }
 
-        if (stat->peersConnected)
+        if (stat->peersConnected != 0)
         {
             ++connected;
         }
@@ -109,7 +109,7 @@ void gtr_confirm_remove(GtkWindow* parent, TrCore* core, GSList* torrent_ids, gb
 
     secondary_text = g_string_new(NULL);
 
-    if (!incomplete && !connected)
+    if (incomplete == 0 && connected == 0)
     {
         g_string_assign(secondary_text,
             ngettext("Once removed, continuing the transfer will require the torrent file or magnet link.",
@@ -127,18 +127,18 @@ void gtr_confirm_remove(GtkWindow* parent, TrCore* core, GSList* torrent_ids, gb
     }
     else
     {
-        if (connected)
+        if (connected != 0)
         {
             g_string_append(secondary_text, ngettext("One of these torrents is connected to peers.",
                 "Some of these torrents are connected to peers.", connected));
         }
 
-        if (connected && incomplete)
+        if (connected != 0 && incomplete != 0)
         {
             g_string_append(secondary_text, "\n");
         }
 
-        if (incomplete)
+        if (incomplete != 0)
         {
             g_string_assign(secondary_text, ngettext("One of these torrents has not finished downloading.",
                 "Some of these torrents have not finished downloading.", incomplete));
@@ -148,13 +148,13 @@ void gtr_confirm_remove(GtkWindow* parent, TrCore* core, GSList* torrent_ids, gb
     d = gtk_message_dialog_new_with_markup(parent, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE,
         "<big><b>%s</b></big>", primary_text->str);
 
-    if (secondary_text->len)
+    if (secondary_text->len != 0)
     {
         gtk_message_dialog_format_secondary_markup(GTK_MESSAGE_DIALOG(d), "%s", secondary_text->str);
     }
 
     gtk_dialog_add_buttons(GTK_DIALOG(d), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
-        (delete_files ? GTK_STOCK_DELETE : GTK_STOCK_REMOVE), GTK_RESPONSE_ACCEPT, NULL);
+        delete_files ? GTK_STOCK_DELETE : GTK_STOCK_REMOVE, GTK_RESPONSE_ACCEPT, NULL);
     gtk_dialog_set_default_response(GTK_DIALOG(d), GTK_RESPONSE_CANCEL);
     gtk_dialog_set_alternative_button_order(GTK_DIALOG(d), GTK_RESPONSE_ACCEPT, GTK_RESPONSE_CANCEL, -1);
     g_signal_connect(d, "response", G_CALLBACK(on_remove_dialog_response), dd);
index 7aaf60eacc69d69f250e7423c8c1fe13b4660b4c..a16243ef4aae85f822d456408fc3f4f7d930924e 100644 (file)
@@ -65,7 +65,7 @@ static void clearData(FileData* data)
 {
     data->torrentId = -1;
 
-    if (data->timeout_tag)
+    if (data->timeout_tag != 0)
     {
         g_source_remove(data->timeout_tag);
         data->timeout_tag = 0;
@@ -123,7 +123,7 @@ static gboolean refreshFilesForeach(GtkTreeModel* model, GtkTreePath* path UNUSE
         uint64_t const have = refresh_data->refresh_file_stat[index].bytesCompleted;
         int const prog = size ? (int)((100.0 * have) / size) : 1;
 
-        if ((priority != old_priority) || (enabled != old_enabled) || (have != old_have) || (prog != old_prog))
+        if (priority != old_priority || enabled != old_enabled || have != old_have || prog != old_prog)
         {
             /* Changing a value in the sort column can trigger a resort
              * which breaks this foreach () call. (See #3529)
@@ -131,9 +131,8 @@ static gboolean refreshFilesForeach(GtkTreeModel* model, GtkTreePath* path UNUSE
              * sorting until we finish walking the tree. */
             if (!refresh_data->resort_needed)
             {
-                if ((refresh_data->resort_needed =
-                    ((refresh_data->sort_column_id == FC_PRIORITY) && (priority != old_priority)) ||
-                    ((refresh_data->sort_column_id == FC_ENABLED) && (enabled != old_enabled))))
+                if ((refresh_data->resort_needed = (refresh_data->sort_column_id == FC_PRIORITY && priority != old_priority) ||
+                    (refresh_data->sort_column_id == FC_ENABLED && enabled != old_enabled)))
                 {
                     refresh_data->resort_needed = TRUE;
                     gtk_tree_sortable_set_sort_column_id(GTK_TREE_SORTABLE( data->model),
@@ -203,10 +202,9 @@ static gboolean refreshFilesForeach(GtkTreeModel* model, GtkTreePath* path UNUSE
             while (gtk_tree_model_iter_next(model, &child));
         }
 
-        prog = sub_size ? (int)((100.0 * have) / sub_size) : 1;
+        prog = sub_size != 0 ? (int)(100.0 * have / sub_size) : 1;
 
-        if ((size != sub_size) || (have != old_have) || (priority != old_priority) || (enabled != old_enabled) ||
-            (prog != old_prog))
+        if (size != sub_size || have != old_have || priority != old_priority || enabled != old_enabled || prog != old_prog)
         {
             char size_str[64];
             tr_strlsize(size_str, sub_size, sizeof size_str);
@@ -238,7 +236,7 @@ static void gtr_tree_model_foreach_postorder_subtree(GtkTreeModel* model, GtkTre
         while (gtk_tree_model_iter_next(model, &child));
     }
 
-    if (parent)
+    if (parent != NULL)
     {
         func(model, NULL, parent, data);
     }
@@ -367,7 +365,7 @@ static gboolean getSubtreeForeach(GtkTreeModel* model, GtkTreePath* path, GtkTre
     {
         struct SubtreeForeachData* data = gdata;
 
-        if (!gtk_tree_path_compare(path, data->path) || gtk_tree_path_is_descendant(path, data->path))
+        if (gtk_tree_path_compare(path, data->path) == 0 || gtk_tree_path_is_descendant(path, data->path))
         {
             unsigned int i;
             gtk_tree_model_get(model, iter, FC_INDEX, &i, -1);
@@ -601,7 +599,7 @@ static void renderDownload(GtkTreeViewColumn* column UNUSED, GtkCellRenderer* re
 {
     gboolean enabled;
     gtk_tree_model_get(model, iter, FC_ENABLED, &enabled, -1);
-    g_object_set(renderer, "inconsistent", (enabled == MIXED), "active", (enabled == TRUE), NULL);
+    g_object_set(renderer, "inconsistent", enabled == MIXED, "active", enabled == TRUE, NULL);
 }
 
 static void renderPriority(GtkTreeViewColumn* column UNUSED, GtkCellRenderer* renderer, GtkTreeModel* model, GtkTreeIter* iter,
@@ -674,7 +672,7 @@ static gboolean onRowActivated(GtkTreeView* view, GtkTreePath* path, GtkTreeView
 
             /* if the file's not done, walk up the directory tree until we find
              * an ancestor that exists, and open that instead */
-            if (filename && (prog < 100 || !g_file_test(filename, G_FILE_TEST_EXISTS)))
+            if (filename != NULL && (prog < 100 || !g_file_test(filename, G_FILE_TEST_EXISTS)))
             {
                 do
                 {
@@ -682,10 +680,10 @@ static gboolean onRowActivated(GtkTreeView* view, GtkTreePath* path, GtkTreeView
                     g_free(filename);
                     filename = tmp;
                 }
-                while (filename && *filename && !g_file_test(filename, G_FILE_TEST_EXISTS));
+                while (filename != NULL && *filename != '\0' && !g_file_test(filename, G_FILE_TEST_EXISTS));
             }
 
-            if ((handled = filename && *filename))
+            if ((handled = filename != NULL && *filename != '\0'))
             {
                 gtr_open_file(filename);
             }
@@ -701,7 +699,7 @@ static gboolean onViewPathToggled(GtkTreeView* view, GtkTreeViewColumn* col, Gtk
     tr_torrent* tor;
     gboolean handled = FALSE;
 
-    if (!col || !path)
+    if (col == NULL || path == NULL)
     {
         return FALSE;
     }
@@ -709,7 +707,7 @@ static gboolean onViewPathToggled(GtkTreeView* view, GtkTreeViewColumn* col, Gtk
     cid = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(col), TR_COLUMN_ID_KEY));
     tor = gtr_core_find_torrent(data->core, data->torrentId);
 
-    if ((tor != NULL) && ((cid == FC_PRIORITY) || (cid == FC_ENABLED)))
+    if (tor != NULL && (cid == FC_PRIORITY || cid == FC_ENABLED))
     {
         GtkTreeIter iter;
         GArray* indices = getActiveFilesForPath(view, path);
@@ -787,7 +785,7 @@ static gboolean onViewButtonPressed(GtkWidget* w, GdkEventButton* event, gpointe
     GtkTreeView* treeview = GTK_TREE_VIEW(w);
     FileData* data = gdata;
 
-    if ((event->type == GDK_BUTTON_PRESS) && (event->button == 1) && !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) &&
+    if (event->type == GDK_BUTTON_PRESS && event->button == 1 && (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) == 0 &&
         getAndSelectEventPath(treeview, event, &col, &path))
     {
         handled = onViewPathToggled(treeview, col, path, data);
index c25a9e5a8e7052502dc6bc42b674d5e186972074..80d61d1e2094db307ad6130df9c926514dfe3135 100644 (file)
@@ -63,7 +63,7 @@ static char* get_name_from_host(char const* host)
     {
         name = g_strdup(host);
     }
-    else if (dot)
+    else if (dot != NULL)
     {
         name = g_strndup(host, dot - host);
     }
@@ -494,14 +494,14 @@ static gboolean test_torrent_activity(tr_torrent* tor, int type)
     switch (type)
     {
     case ACTIVITY_FILTER_DOWNLOADING:
-        return (st->activity == TR_STATUS_DOWNLOAD) || (st->activity == TR_STATUS_DOWNLOAD_WAIT);
+        return st->activity == TR_STATUS_DOWNLOAD || st->activity == TR_STATUS_DOWNLOAD_WAIT;
 
     case ACTIVITY_FILTER_SEEDING:
-        return (st->activity == TR_STATUS_SEED) || (st->activity == TR_STATUS_SEED_WAIT);
+        return st->activity == TR_STATUS_SEED || st->activity == TR_STATUS_SEED_WAIT;
 
     case ACTIVITY_FILTER_ACTIVE:
-        return (st->peersSendingToUs > 0) || (st->peersGettingFromUs > 0) || (st->webseedsSendingToUs > 0) ||
-               (st->activity == TR_STATUS_CHECK);
+        return st->peersSendingToUs > 0 || st->peersGettingFromUs > 0 || st->webseedsSendingToUs > 0 ||
+               st->activity == TR_STATUS_CHECK;
 
     case ACTIVITY_FILTER_PAUSED:
         return st->activity == TR_STATUS_STOPPED;
@@ -510,7 +510,7 @@ static gboolean test_torrent_activity(tr_torrent* tor, int type)
         return st->finished == TRUE;
 
     case ACTIVITY_FILTER_VERIFYING:
-        return (st->activity == TR_STATUS_CHECK) || (st->activity == TR_STATUS_CHECK_WAIT);
+        return st->activity == TR_STATUS_CHECK || st->activity == TR_STATUS_CHECK_WAIT;
 
     case ACTIVITY_FILTER_ERROR:
         return st->error != 0;
@@ -712,7 +712,7 @@ static gboolean testText(tr_torrent const* tor, char const* key)
 {
     gboolean ret = FALSE;
 
-    if (!key || !*key)
+    if (key == NULL || *key == '\0')
     {
         ret = TRUE;
     }
@@ -788,7 +788,7 @@ static gboolean is_row_visible(GtkTreeModel* model, GtkTreeIter* iter, gpointer
 
     text = (char const*)g_object_get_qdata(o, TEXT_KEY);
 
-    return (tor != NULL) && test_tracker(tor, data->active_tracker_type, data->active_tracker_host) &&
+    return tor != NULL && test_tracker(tor, data->active_tracker_type, data->active_tracker_host) &&
            test_torrent_activity(tor, data->active_activity_type) && testText(tor, text);
 }
 
index c1e0580d684c2de912a4c01ded27c2d47908f4fd..4e51ab3de1879230926dde6afcd49297a0db464a 100644 (file)
@@ -201,7 +201,7 @@ static void get_selected_torrent_counts_foreach(GtkTreeModel* model, GtkTreePath
 
     gtk_tree_model_get(model, iter, MC_ACTIVITY, &activity, -1);
 
-    if ((activity == TR_STATUS_DOWNLOAD_WAIT) || (activity == TR_STATUS_SEED_WAIT))
+    if (activity == TR_STATUS_DOWNLOAD_WAIT || activity == TR_STATUS_SEED_WAIT)
     {
         ++counts->queued_count;
     }
@@ -278,7 +278,7 @@ static void refresh_actions_soon(gpointer gdata)
 {
     struct cbdata* data = gdata;
 
-    if (!data->is_closing && !data->refresh_actions_tag)
+    if (!data->is_closing && data->refresh_actions_tag == 0)
     {
         data->refresh_actions_tag = gdk_threads_add_idle(refresh_actions, data);
     }
@@ -330,7 +330,7 @@ static void ensure_magnet_handler_exists(void)
 static void on_main_window_size_allocated(GtkWidget* gtk_window, GtkAllocation* alloc UNUSED, gpointer gdata UNUSED)
 {
     GdkWindow* gdk_window = gtk_widget_get_window(gtk_window);
-    gboolean const isMaximized = (gdk_window != NULL) && (gdk_window_get_state(gdk_window) & GDK_WINDOW_STATE_MAXIMIZED);
+    gboolean const isMaximized = gdk_window != NULL && (gdk_window_get_state(gdk_window) & GDK_WINDOW_STATE_MAXIMIZED) != 0;
 
     gtr_pref_int_set(TR_KEY_main_window_is_maximized, isMaximized);
 
@@ -369,7 +369,7 @@ static gboolean on_rpc_changed_idle(gpointer gdata)
         break;
 
     case TR_RPC_TORRENT_ADDED:
-        if ((tor = gtr_core_find_torrent(data->core, data->torrent_id)))
+        if ((tor = gtr_core_find_torrent(data->core, data->torrent_id)) != NULL)
         {
             gtr_core_add_torrent(data->core, tor, true);
         }
@@ -402,7 +402,7 @@ static gboolean on_rpc_changed_idle(gpointer gdata)
                 bool changed;
                 tr_variant* oldval = tr_variantDictFind(oldvals, key);
 
-                if (!oldval)
+                if (oldval == NULL)
                 {
                     changed = true;
                 }
@@ -475,7 +475,7 @@ static void signal_handler(int sig)
         signal(sig, SIG_DFL);
         raise(sig);
     }
-    else if ((sig == SIGINT) || (sig == SIGTERM))
+    else if (sig == SIGINT || sig == SIGTERM)
     {
         g_message(_("Got signal %d; trying to shut down cleanly. Do it again if it gets stuck."), sig);
         gtr_actions_handler("quit", sighandler_cbdata);
@@ -504,12 +504,12 @@ static void on_startup(GApplication* application, gpointer user_data)
     sighandler_cbdata = cbdata;
 
     /* ensure the directories are created */
-    if ((str = gtr_pref_string_get(TR_KEY_download_dir)))
+    if ((str = gtr_pref_string_get(TR_KEY_download_dir)) != NULL)
     {
         g_mkdir_with_parents(str, 0777);
     }
 
-    if ((str = gtr_pref_string_get(TR_KEY_incomplete_dir)))
+    if ((str = gtr_pref_string_get(TR_KEY_incomplete_dir)) != NULL)
     {
         g_mkdir_with_parents(str, 0777);
     }
@@ -564,7 +564,7 @@ static void on_activate(GApplication* app UNUSED, struct cbdata* cbdata)
     /* GApplication emits an 'activate' signal when bootstrapping the primary.
      * Ordinarily we handle that by presenting the main window, but if the user
      * user started Transmission minimized, ignore that initial signal... */
-    if (cbdata->is_iconified && (cbdata->activation_count == 1))
+    if (cbdata->is_iconified && cbdata->activation_count == 1)
     {
         return;
     }
@@ -890,19 +890,19 @@ static gboolean on_session_closed(gpointer gdata)
     g_slist_foreach(tmp, (GFunc)gtk_widget_destroy, NULL);
     g_slist_free(tmp);
 
-    if (cbdata->prefs)
+    if (cbdata->prefs != NULL)
     {
         gtk_widget_destroy(GTK_WIDGET(cbdata->prefs));
     }
 
-    if (cbdata->wind)
+    if (cbdata->wind != NULL)
     {
         gtk_widget_destroy(GTK_WIDGET(cbdata->wind));
     }
 
     g_object_unref(cbdata->core);
 
-    if (cbdata->icon)
+    if (cbdata->icon != NULL)
     {
         g_object_unref(cbdata->icon);
     }
@@ -952,14 +952,14 @@ static void on_app_exit(gpointer vdata)
     cbdata->is_closing = true;
 
     /* stop the update timer */
-    if (cbdata->timer)
+    if (cbdata->timer != 0)
     {
         g_source_remove(cbdata->timer);
         cbdata->timer = 0;
     }
 
     /* stop the refresh-actions timer */
-    if (cbdata->refresh_actions_tag)
+    if (cbdata->refresh_actions_tag != 0)
     {
         g_source_remove(cbdata->refresh_actions_tag);
         cbdata->refresh_actions_tag = 0;
@@ -1037,13 +1037,13 @@ static void show_torrent_errors(GtkWindow* window, char const* primary, GSList**
 
 static void flush_torrent_errors(struct cbdata* cbdata)
 {
-    if (cbdata->error_list)
+    if (cbdata->error_list != NULL)
     {
         show_torrent_errors(cbdata->wind, ngettext("Couldn't add corrupt torrent", "Couldn't add corrupt torrents",
             g_slist_length(cbdata->error_list)), &cbdata->error_list);
     }
 
-    if (cbdata->duplicates_list)
+    if (cbdata->duplicates_list != NULL)
     {
         show_torrent_errors(cbdata->wind, ngettext("Couldn't add duplicate torrent", "Couldn't add duplicate torrents",
             g_slist_length(cbdata->duplicates_list)), &cbdata->duplicates_list);
@@ -1076,7 +1076,7 @@ static gboolean on_main_window_focus_in(GtkWidget* widget UNUSED, GdkEventFocus*
 {
     struct cbdata* cbdata = gdata;
 
-    if (cbdata->wind)
+    if (cbdata->wind != NULL)
     {
         gtk_window_set_urgency_hint(cbdata->wind, FALSE);
     }
@@ -1091,7 +1091,7 @@ static void on_add_torrent(TrCore* core, tr_ctor* ctor, gpointer gdata)
 
     g_signal_connect(w, "focus-in-event", G_CALLBACK(on_main_window_focus_in), cbdata);
 
-    if (cbdata->wind)
+    if (cbdata->wind != NULL)
     {
         gtk_window_set_urgency_hint(cbdata->wind, TRUE);
     }
@@ -1134,11 +1134,11 @@ static void on_prefs_changed(TrCore* core UNUSED, tr_quark const key, gpointer d
         {
             bool const show = gtr_pref_flag_get(key);
 
-            if (show && !cbdata->icon)
+            if (show && cbdata->icon == NULL)
             {
                 cbdata->icon = gtr_icon_new(cbdata->core);
             }
-            else if (!show && cbdata->icon)
+            else if (!show && cbdata->icon != NULL)
             {
                 g_clear_object(&cbdata->icon);
             }
@@ -1341,7 +1341,7 @@ static void update_model_soon(gpointer gdata)
 
 static gboolean update_model_loop(gpointer gdata)
 {
-    gboolean const done = global_sigcount;
+    gboolean const done = global_sigcount != 0;
 
     if (!done)
     {
@@ -1606,7 +1606,7 @@ void gtr_actions_handler(char const* action_name, gpointer user_data)
     }
     else if (g_strcmp0(action_name, "edit-preferences") == 0)
     {
-        if (NULL == data->prefs)
+        if (data->prefs == NULL)
         {
             data->prefs = gtr_prefs_dialog_new(data->wind, G_OBJECT(data->core));
             g_signal_connect(data->prefs, "destroy", G_CALLBACK(gtk_widget_destroyed), &data->prefs);
@@ -1616,7 +1616,7 @@ void gtr_actions_handler(char const* action_name, gpointer user_data)
     }
     else if (g_strcmp0(action_name, "toggle-message-log") == 0)
     {
-        if (!data->msgwin)
+        if (data->msgwin == NULL)
         {
             GtkWidget* win = gtr_message_log_window_new(data->wind, data->core);
             g_signal_connect(win, "destroy", G_CALLBACK(on_message_window_closed), NULL);
index cd1919bc2b978c4fb65b110c49b185f4c6e0a419..597f31132f6205e9e90973a43c24541c0163ba77 100644 (file)
@@ -61,7 +61,7 @@ static gboolean onProgressDialogRefresh(gpointer data)
     tr_metainfo_builder const* b = ui->builder;
     GtkDialog* d = GTK_DIALOG(ui->progress_dialog);
     GtkProgressBar* p = GTK_PROGRESS_BAR(ui->progress_bar);
-    double const fraction = b->pieceCount ? ((double)b->pieceIndex / b->pieceCount) : 0;
+    double const fraction = b->pieceCount != 0 ? (double)b->pieceIndex / b->pieceCount : 0;
     char* base = g_path_get_basename(b->top);
 
     /* progress label */
@@ -101,7 +101,7 @@ static gboolean onProgressDialogRefresh(gpointer data)
     }
 
     /* progress bar */
-    if (!b->pieceIndex)
+    if (b->pieceIndex == 0)
     {
         str = g_strdup("");
     }
@@ -240,18 +240,18 @@ 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];)
+            for (i = 0; tracker_strings[i] != NULL;)
             {
                 ++i;
             }
 
             trackers = g_new0(tr_tracker_info, i);
 
-            for (i = n = tier = 0; tracker_strings[i]; ++i)
+            for (i = n = tier = 0; tracker_strings[i] != NULL; ++i)
             {
                 char const* str = tracker_strings[i];
 
-                if (!*str)
+                if (*str == '\0')
                 {
                     ++tier;
                 }
@@ -298,7 +298,7 @@ static void updatePiecesLabel(MakeMetaUI* ui)
 
     g_string_append(gstr, "<i>");
 
-    if (!filename)
+    if (filename == NULL)
     {
         g_string_append(gstr, _("No source selected"));
     }
@@ -387,7 +387,7 @@ static void on_drag_data_received(GtkWidget* widget UNUSED, GdkDragContext* drag
     MakeMetaUI* ui = user_data;
     char** uris = gtk_selection_data_get_uris(selection_data);
 
-    if (uris && uris[0])
+    if (uris != NULL && uris[0] != NULL)
     {
         char const* uri = uris[0];
         gchar* filename = g_filename_from_uri(uri, NULL, NULL);
index c3fb8f195c1de39f673393ef8c03f65757e92a6f..42897a81b583959f5360545fd93307631acdfc51 100644 (file)
@@ -128,7 +128,7 @@ static char* gtr_localtime(time_t time)
 
     g_strlcpy(buf, asctime(&tm), sizeof(buf));
 
-    if ((eoln = strchr(buf, '\n')))
+    if ((eoln = strchr(buf, '\n')) != NULL)
     {
         *eoln = '\0';
     }
@@ -140,10 +140,10 @@ static void doSave(GtkWindow* parent, struct MsgData* data, char const* filename
 {
     FILE* fp = fopen(filename, "w+");
 
-    if (!fp)
+    if (fp == NULL)
     {
-        GtkWidget* w = gtk_message_dialog_new(parent, 0, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, _(
-            "Couldn't save \"%s\""), filename);
+        GtkWidget* w = gtk_message_dialog_new(parent, 0, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, _("Couldn't save \"%s\""),
+            filename);
         gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(w), "%s", g_strerror(errno));
         g_signal_connect_swapped(w, "response", G_CALLBACK(gtk_widget_destroy), w);
         gtk_widget_show(w);
@@ -179,8 +179,8 @@ static void doSave(GtkWindow* parent, struct MsgData* data, char const* filename
                     break;
                 }
 
-                fprintf(fp, "%s\t%s\t%s\t%s\n", date, levelStr, (node->name ? node->name : ""),
-                    (node->message ? node->message : ""));
+                fprintf(fp, "%s\t%s\t%s\t%s\n", date, levelStr, node->name != NULL ? node->name : "",
+                    node->message != NULL ? node->message : "");
                 g_free(date);
             }
             while (gtk_tree_model_iter_next(model, &iter));
@@ -358,9 +358,9 @@ static tr_log_message* addMessages(GtkListStore* store, struct tr_log_message* h
     static unsigned int sequence = 0;
     char const* default_name = g_get_application_name();
 
-    for (i = head; i && i->next; i = i->next)
+    for (i = head; i != NULL && i->next != NULL; i = i->next)
     {
-        char const* name = i->name ? i->name : default_name;
+        char const* name = i->name != NULL ? i->name : default_name;
 
         gtk_list_store_insert_with_values(store, NULL, 0,
             COL_TR_MSG, i,
@@ -397,13 +397,13 @@ static gboolean onRefresh(gpointer gdata)
     {
         tr_log_message* msgs = tr_logGetQueue();
 
-        if (msgs)
+        if (msgs != NULL)
         {
             /* add the new messages and append them to the end of
              * our persistent list */
             tr_log_message* tail = addMessages(data->store, msgs);
 
-            if (myTail)
+            if (myTail != NULL)
             {
                 myTail->next = msgs;
             }
index 52f4c1f3db9108cacd411802f98956bc5a0e034e..03719715f8d967688c8e89bcdca2c5caf5b77b96 100644 (file)
@@ -34,7 +34,7 @@ static void tr_notification_free(gpointer data)
 {
     TrNotification* n = data;
 
-    if (n->core)
+    if (n->core != NULL)
     {
         g_object_unref(G_OBJECT(n->core));
     }
@@ -50,9 +50,9 @@ static void get_capabilities_callback(GObject* source, GAsyncResult* res, gpoint
 
     result = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, NULL);
 
-    if (!result || !g_variant_is_of_type(result, G_VARIANT_TYPE("(as)")))
+    if (result == NULL || !g_variant_is_of_type(result, G_VARIANT_TYPE("(as)")))
     {
-        if (result)
+        if (result != NULL)
         {
             g_variant_unref(result);
         }
@@ -62,7 +62,7 @@ static void get_capabilities_callback(GObject* source, GAsyncResult* res, gpoint
 
     g_variant_get(result, "(^a&s)", &caps);
 
-    for (i = 0; caps[i]; i++)
+    for (i = 0; caps[i] != NULL; i++)
     {
         if (g_strcmp0(caps[i], "actions") == 0)
         {
@@ -153,9 +153,9 @@ static void notify_callback(GObject* source, GAsyncResult* res, gpointer user_da
 
     result = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, NULL);
 
-    if (!result || !g_variant_is_of_type(result, G_VARIANT_TYPE("(u)")))
+    if (result == NULL || !g_variant_is_of_type(result, G_VARIANT_TYPE("(u)")))
     {
-        if (result)
+        if (result != NULL)
         {
             g_variant_unref(result);
         }
index 6c0b65c623b884baaa18a1664eb66a22b873c440..be0e38056939bb01f80e5a13dbb83e2d58559c3c 100644 (file)
@@ -38,7 +38,7 @@ static GSList* get_recent_destinations(void)
         char const* val;
         g_snprintf(key, sizeof(key), "recent-download-dir-%d", i + 1);
 
-        if ((val = gtr_pref_string_get(tr_quark_new(key, TR_BAD_SIZE))))
+        if ((val = gtr_pref_string_get(tr_quark_new(key, TR_BAD_SIZE))) != NULL)
         {
             list = g_slist_append(list, (void*)val);
         }
@@ -59,7 +59,7 @@ static void save_recent_destination(TrCore* core, char const* dir)
     }
 
     /* if it was already in the list, remove it */
-    if ((l = g_slist_find_custom(list, dir, (GCompareFunc)g_strcmp0)))
+    if ((l = g_slist_find_custom(list, dir, (GCompareFunc)g_strcmp0)) != NULL)
     {
         list = g_slist_delete_link(list, l);
     }
@@ -69,13 +69,13 @@ static void save_recent_destination(TrCore* core, char const* dir)
 
     /* make local copies of the strings that aren't
      * invalidated by gtr_pref_string_set() */
-    for (l = list; l; l = l->next)
+    for (l = list; l != NULL; l = l->next)
     {
         l->data = g_strdup(l->data);
     }
 
     /* save the first N_RECENT directories */
-    for (l = list, i = 0; l && (i < N_RECENT); ++i, l = l->next)
+    for (l = list, i = 0; l != NULL && i < N_RECENT; ++i, l = l->next)
     {
         char key[64];
         g_snprintf(key, sizeof(key), "recent-download-dir-%d", i + 1);
@@ -109,7 +109,7 @@ struct OpenData
 
 static void removeOldTorrent(struct OpenData* o)
 {
-    if (o->tor)
+    if (o->tor != NULL)
     {
         gtr_file_list_clear(o->file_list);
         tr_torrentRemove(o->tor, FALSE, NULL);
@@ -121,7 +121,7 @@ static void addResponseCB(GtkDialog* dialog, gint response, gpointer gdata)
 {
     struct OpenData* o = gdata;
 
-    if (o->tor)
+    if (o->tor != NULL)
     {
         if (response != GTK_RESPONSE_ACCEPT)
         {
@@ -159,7 +159,7 @@ static void updateTorrent(struct OpenData* o)
     gboolean const isLocalFile = tr_ctorGetSourceFile(o->ctor) != NULL;
     gtk_widget_set_sensitive(o->trash_check, isLocalFile);
 
-    if (!o->tor)
+    if (o->tor == NULL)
     {
         gtr_file_list_clear(o->file_list);
         gtk_widget_set_sensitive(o->file_list, FALSE);
@@ -186,26 +186,26 @@ static void sourceChanged(GtkFileChooserButton* b, gpointer gdata)
     char* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(b));
 
     /* maybe instantiate a torrent */
-    if (filename || !o->tor)
+    if (filename != NULL || o->tor == NULL)
     {
         int err = 0;
-        int new_file = 0;
+        bool new_file = false;
         int duplicate_id = 0;
         tr_torrent* torrent;
 
-        if (filename && (!o->filename || !tr_sys_path_is_same(filename, o->filename, NULL)))
+        if (filename != NULL && (o->filename == NULL || !tr_sys_path_is_same(filename, o->filename, NULL)))
         {
             g_free(o->filename);
             o->filename = g_strdup(filename);
             tr_ctorSetMetainfoFromFile(o->ctor, o->filename);
-            new_file = 1;
+            new_file = true;
         }
 
         tr_ctorSetDownloadDir(o->ctor, TR_FORCE, o->downloadDir);
         tr_ctorSetPaused(o->ctor, TR_FORCE, TRUE);
         tr_ctorSetDeleteSource(o->ctor, FALSE);
 
-        if ((torrent = tr_torrentNew(o->ctor, &err, &duplicate_id)))
+        if ((torrent = tr_torrentNew(o->ctor, &err, &duplicate_id)) != NULL)
         {
             removeOldTorrent(o);
             o->tor = torrent;
@@ -214,7 +214,7 @@ static void sourceChanged(GtkFileChooserButton* b, gpointer gdata)
         {
             tr_torrent* tor;
 
-            if (duplicate_id)
+            if (duplicate_id != 0)
             {
                 tor = gtr_core_find_torrent(o->core, duplicate_id);
             }
@@ -237,7 +237,7 @@ static void downloadDirChanged(GtkFileChooserButton* b, gpointer gdata)
     struct OpenData* data = gdata;
     char* fname = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(b));
 
-    if (fname && (!data->downloadDir || !tr_sys_path_is_same(fname, data->downloadDir, NULL)))
+    if (fname != NULL && (data->downloadDir == NULL || !tr_sys_path_is_same(fname, data->downloadDir, NULL)))
     {
         g_free(data->downloadDir);
         data->downloadDir = g_strdup(fname);
@@ -343,7 +343,7 @@ GtkWidget* gtr_torrent_options_dialog_new(GtkWindow* parent, TrCore* core, tr_ct
 
     list = get_recent_destinations();
 
-    for (walk = list; walk; walk = walk->next)
+    for (walk = list; walk != NULL; walk = walk->next)
     {
         gtk_file_chooser_add_shortcut_folder(GTK_FILE_CHOOSER(w), walk->data, NULL);
     }
@@ -403,7 +403,7 @@ GtkWidget* gtr_torrent_options_dialog_new(GtkWindow* parent, TrCore* core, tr_ct
      * so that it creates the tor/gtor objects */
     w = source_chooser;
 
-    if (data->filename)
+    if (data->filename != NULL)
     {
         gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(w), data->filename);
     }
@@ -462,7 +462,7 @@ GtkWidget* gtr_torrent_open_from_file_dialog_new(GtkWindow* parent, TrCore* core
     addTorrentFilters(GTK_FILE_CHOOSER(w));
     g_signal_connect(w, "response", G_CALLBACK(onOpenDialogResponse), core);
 
-    if ((folder = gtr_pref_string_get(TR_KEY_open_dialog_dir)))
+    if ((folder = gtr_pref_string_get(TR_KEY_open_dialog_dir)) != NULL)
     {
         gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(w), folder);
     }
@@ -489,7 +489,7 @@ static void onOpenURLResponse(GtkDialog* dialog, int response, gpointer user_dat
         char* url = g_strdup(gtk_entry_get_text(GTK_ENTRY(e)));
         g_strstrip(url);
 
-        if (url)
+        if (url != NULL)
         {
             handled = gtr_core_add_from_url(user_data, url);
 
@@ -503,7 +503,7 @@ static void onOpenURLResponse(GtkDialog* dialog, int response, gpointer user_dat
     }
     else if (response == GTK_RESPONSE_CANCEL)
     {
-        handled = TRUE;
+        handled = true;
     }
 
     if (handled)
index 174fa13d28e0c9499b6fcbfb30bc7d420705fac7..7bf02704368a11b8184429f5f0413960b1daf05f 100644 (file)
@@ -38,12 +38,12 @@ enum
 
 static void getProgressString(GString* gstr, tr_torrent const* tor, tr_info const* info, tr_stat const* st)
 {
-    int const isDone = st->leftUntilDone == 0;
+    bool const isDone = st->leftUntilDone == 0;
     uint64_t const haveTotal = st->haveUnchecked + st->haveValid;
-    int const isSeed = st->haveValid >= info->totalSize;
+    bool const isSeed = st->haveValid >= info->totalSize;
     char buf1[32], buf2[32], buf3[32], buf4[32], buf5[32], buf6[32];
     double seedRatio;
-    gboolean const hasSeedRatio = tr_torrentGetSeedRatio(tor, &seedRatio);
+    bool const hasSeedRatio = tr_torrentGetSeedRatio(tor, &seedRatio);
 
     if (!isDone) /* downloading */
     {
@@ -120,7 +120,7 @@ static void getProgressString(GString* gstr, tr_torrent const* tor, tr_info cons
     }
 
     /* add time when downloading */
-    if ((st->activity == TR_STATUS_DOWNLOAD) || (hasSeedRatio && (st->activity == TR_STATUS_SEED)))
+    if (st->activity == TR_STATUS_DOWNLOAD || (hasSeedRatio && st->activity == TR_STATUS_SEED))
     {
         int const eta = st->eta;
         g_string_append(gstr, " - ");
@@ -142,9 +142,9 @@ static void getProgressString(GString* gstr, tr_torrent const* tor, tr_info cons
 static char* getShortTransferString(tr_torrent const* tor, tr_stat const* st, double uploadSpeed_KBps,
     double downloadSpeed_KBps, char* buf, size_t buflen)
 {
-    int const haveMeta = tr_torrentHasMetadata(tor);
-    int const haveUp = haveMeta && st->peersGettingFromUs > 0;
-    int const haveDown = haveMeta && ((st->peersSendingToUs > 0) || (st->webseedsSendingToUs > 0));
+    bool const haveMeta = tr_torrentHasMetadata(tor);
+    bool const haveUp = haveMeta && st->peersGettingFromUs > 0;
+    bool const haveDown = haveMeta && (st->peersSendingToUs > 0 || st->webseedsSendingToUs > 0);
 
     if (haveDown)
     {
@@ -222,7 +222,7 @@ static void getShortStatusString(GString* gstr, tr_torrent const* tor, tr_stat c
 static void getStatusString(GString* gstr, tr_torrent const* tor, tr_stat const* st, double const uploadSpeed_KBps,
     double const downloadSpeed_KBps)
 {
-    if (st->error)
+    if (st->error != 0)
     {
         char const* fmt[] =
         {
@@ -256,14 +256,14 @@ static void getStatusString(GString* gstr, tr_torrent const* tor, tr_stat const*
                     g_string_append_printf(gstr, _("Downloading metadata from %1$'d %2$s (%3$d%% done)"), st->peersConnected,
                         ngettext("peer", "peers", st->peersConnected), (int)(100.0 * st->metadataPercentComplete));
                 }
-                else if (st->peersSendingToUs && st->webseedsSendingToUs)
+                else if (st->peersSendingToUs != 0 && st->webseedsSendingToUs != 0)
                 {
                     /* Downloading from 2 of 3 peer (s) and 2 webseed (s) */
                     g_string_append_printf(gstr, _("Downloading from %1$'d of %2$'d %3$s and %4$'d %5$s"), st->peersSendingToUs,
                         st->peersConnected, ngettext("peer", "peers", st->peersConnected), st->webseedsSendingToUs,
                         ngettext("web seed", "web seeds", st->webseedsSendingToUs));
                 }
-                else if (st->webseedsSendingToUs)
+                else if (st->webseedsSendingToUs != 0)
                 {
                     /* Downloading from 3 web seed (s) */
                     g_string_append_printf(gstr, _("Downloading from %1$'d %2$s"), st->webseedsSendingToUs,
@@ -286,14 +286,13 @@ static void getStatusString(GString* gstr, tr_torrent const* tor, tr_stat const*
         }
     }
 
-    if ((st->activity != TR_STATUS_CHECK_WAIT) && (st->activity != TR_STATUS_CHECK) &&
-        (st->activity != TR_STATUS_DOWNLOAD_WAIT) && (st->activity != TR_STATUS_SEED_WAIT) &&
-        (st->activity != TR_STATUS_STOPPED))
+    if (st->activity != TR_STATUS_CHECK_WAIT && st->activity != TR_STATUS_CHECK && st->activity != TR_STATUS_DOWNLOAD_WAIT &&
+        st->activity != TR_STATUS_SEED_WAIT && st->activity != TR_STATUS_STOPPED)
     {
         char buf[256];
         getShortTransferString(tor, st, uploadSpeed_KBps, downloadSpeed_KBps, buf, sizeof(buf));
 
-        if (*buf)
+        if (*buf != '\0')
         {
             g_string_append_printf(gstr, " - %s", buf);
         }
@@ -475,7 +474,7 @@ static void torrent_cell_renderer_get_size(GtkCellRenderer* cell, GtkWidget* wid
 {
     TorrentCellRenderer* self = TORRENT_CELL_RENDERER(cell);
 
-    if (self && self->priv->tor)
+    if (self != NULL && self->priv->tor != NULL)
     {
         int w, h;
         struct TorrentCellRendererPrivate* p = self->priv;
@@ -489,22 +488,22 @@ static void torrent_cell_renderer_get_size(GtkCellRenderer* cell, GtkWidget* wid
             get_size_full(TORRENT_CELL_RENDERER(cell), widget, &w, &h);
         }
 
-        if (width)
+        if (width != NULL)
         {
             *width = w;
         }
 
-        if (height)
+        if (height != NULL)
         {
             *height = h;
         }
 
-        if (x_offset)
+        if (x_offset != NULL)
         {
             *x_offset = cell_area ? cell_area->x : 0;
         }
 
-        if (y_offset)
+        if (y_offset != NULL)
         {
             int xpad, ypad;
             gtk_cell_renderer_get_padding(cell, &xpad, &ypad);
@@ -520,7 +519,7 @@ static void get_text_color(GtkWidget* w, tr_stat const* st, GtrColor* setme)
 {
     static GdkRGBA const red = { 1.0, 0, 0, 0 };
 
-    if (st->error)
+    if (st->error != 0)
     {
         *setme = red;
     }
@@ -538,7 +537,7 @@ static double get_percent_done(tr_torrent const* tor, tr_stat const* st, bool* s
 {
     double d;
 
-    if ((st->activity == TR_STATUS_SEED) && tr_torrentGetSeedRatio(tor, &d))
+    if (st->activity == TR_STATUS_SEED && tr_torrentGetSeedRatio(tor, &d))
     {
         *seed = true;
         d = MAX(0.0, st->seedRatioPercentDone);
@@ -578,8 +577,8 @@ static void render_compact(TorrentCellRenderer* cell, GtrDrawable* window, GtkWi
     struct TorrentCellRendererPrivate* p = cell->priv;
     tr_torrent const* tor = p->tor;
     tr_stat const* st = tr_torrentStatCached((tr_torrent*)tor);
-    gboolean const active = (st->activity != TR_STATUS_STOPPED) && (st->activity != TR_STATUS_DOWNLOAD_WAIT) &&
-        (st->activity != TR_STATUS_SEED_WAIT);
+    gboolean const active = st->activity != TR_STATUS_STOPPED && st->activity != TR_STATUS_DOWNLOAD_WAIT &&
+        st->activity != TR_STATUS_SEED_WAIT;
     double const percentDone = get_percent_done(tor, st, &seed);
     gboolean const sensitive = active || st->error;
     GString* gstr_stat = p->gstr1;
@@ -654,8 +653,8 @@ static void render_full(TorrentCellRenderer* cell, GtrDrawable* window, GtkWidge
     tr_torrent const* tor = p->tor;
     tr_stat const* st = tr_torrentStatCached((tr_torrent*)tor);
     tr_info const* inf = tr_torrentInfo(tor);
-    gboolean const active = (st->activity != TR_STATUS_STOPPED) && (st->activity != TR_STATUS_DOWNLOAD_WAIT) &&
-        (st->activity != TR_STATUS_SEED_WAIT);
+    gboolean const active = st->activity != TR_STATUS_STOPPED && st->activity != TR_STATUS_DOWNLOAD_WAIT &&
+        st->activity != TR_STATUS_SEED_WAIT;
     double const percentDone = get_percent_done(tor, st, &seed);
     gboolean const sensitive = active || st->error;
     GString* gstr_prog = p->gstr1;
@@ -754,7 +753,7 @@ static void torrent_cell_renderer_render(GtkCellRenderer* cell, GtrDrawable* win
     gtk_widget_set_direction(widget, GTK_TEXT_DIR_RTL);
 #endif
 
-    if (self && self->priv->tor)
+    if (self != NULL && self->priv->tor != NULL)
     {
         struct TorrentCellRendererPrivate* p = self->priv;
 
@@ -845,7 +844,7 @@ static void torrent_cell_renderer_dispose(GObject* o)
 {
     TorrentCellRenderer* r = TORRENT_CELL_RENDERER(o);
 
-    if (r && r->priv)
+    if (r != NULL && r->priv != NULL)
     {
         g_string_free(r->priv->gstr1, TRUE);
         g_string_free(r->priv->gstr2, TRUE);
index 671ad391d2ecbe311ff5572013e83b80abbc1134..b504bf41a2a88303bb87b5b751fda2132b1d5087 100644 (file)
@@ -83,7 +83,7 @@ struct TrCorePrivate
 
 static int core_is_disposed(TrCore const* core)
 {
-    return !core || !core->priv->sorted_model;
+    return core == NULL || core->priv->sorted_model == NULL;
 }
 
 G_DEFINE_TYPE(TrCore, tr_core, G_TYPE_OBJECT)
@@ -253,6 +253,7 @@ static void core_inc_busy(TrCore* core)
 {
     core_add_to_busy(core, 1);
 }
+
 static void core_dec_busy(TrCore* core)
 {
     core_add_to_busy(core, -1);
@@ -266,7 +267,7 @@ static void core_dec_busy(TrCore* core)
 
 static gboolean is_valid_eta(int t)
 {
-    return (t != TR_ETA_NOT_AVAIL) && (t != TR_ETA_UNKNOWN);
+    return t != TR_ETA_NOT_AVAIL && t != TR_ETA_UNKNOWN;
 }
 
 static int compare_eta(int a, int b)
@@ -432,12 +433,12 @@ static int compare_by_ratio(GtkTreeModel* m, GtkTreeIter* a, GtkTreeIter* b, gpo
     gtk_tree_model_get(m, b, MC_TORRENT, &tb, -1);
     sb = tr_torrentStatCached(tb);
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_ratio(sa->ratio, sb->ratio);
     }
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_by_queue(m, a, b, user_data);
     }
@@ -456,14 +457,14 @@ static int compare_by_activity(GtkTreeModel* m, GtkTreeIter* a, GtkTreeIter* b,
 
     ret = compare_double(aUp + aDown, bUp + bDown);
 
-    if (!ret)
+    if (ret == 0)
     {
         tr_stat const* const sa = tr_torrentStatCached(ta);
         tr_stat const* const sb = tr_torrentStatCached(tb);
         ret = compare_uint64(sa->peersSendingToUs + sa->peersGettingFromUs, sb->peersSendingToUs + sb->peersGettingFromUs);
     }
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_by_queue(m, a, b, user_data);
     }
@@ -479,12 +480,12 @@ static int compare_by_age(GtkTreeModel* m, GtkTreeIter* a, GtkTreeIter* b, gpoin
     gtk_tree_model_get(m, a, MC_TORRENT, &ta, -1);
     gtk_tree_model_get(m, b, MC_TORRENT, &tb, -1);
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_time(tr_torrentStatCached(ta)->addedDate, tr_torrentStatCached(tb)->addedDate);
     }
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_by_name(m, a, b, u);
     }
@@ -503,12 +504,12 @@ static int compare_by_size(GtkTreeModel* m, GtkTreeIter* a, GtkTreeIter* b, gpoi
     gtk_tree_model_get(m, b, MC_TORRENT, &t, -1);
     ib = tr_torrentInfo(t);
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_uint64(ia->totalSize, ib->totalSize);
     }
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_by_name(m, a, b, u);
     }
@@ -527,17 +528,17 @@ static int compare_by_progress(GtkTreeModel* m, GtkTreeIter* a, GtkTreeIter* b,
     gtk_tree_model_get(m, b, MC_TORRENT, &t, -1);
     sb = tr_torrentStatCached(t);
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_double(sa->percentComplete, sb->percentComplete);
     }
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_double(sa->seedRatioPercentDone, sb->seedRatioPercentDone);
     }
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_by_ratio(m, a, b, u);
     }
@@ -553,12 +554,12 @@ static int compare_by_eta(GtkTreeModel* m, GtkTreeIter* a, GtkTreeIter* b, gpoin
     gtk_tree_model_get(m, a, MC_TORRENT, &ta, -1);
     gtk_tree_model_get(m, b, MC_TORRENT, &tb, -1);
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_eta(tr_torrentStatCached(ta)->eta, tr_torrentStatCached(tb)->eta);
     }
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_by_name(m, a, b, u);
     }
@@ -575,12 +576,12 @@ static int compare_by_state(GtkTreeModel* m, GtkTreeIter* a, GtkTreeIter* b, gpo
     gtk_tree_model_get(m, a, MC_ACTIVITY, &sa, MC_TORRENT, &ta, -1);
     gtk_tree_model_get(m, b, MC_ACTIVITY, &sb, MC_TORRENT, &tb, -1);
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_int(sa, sb);
     }
 
-    if (!ret)
+    if (ret == 0)
     {
         ret = compare_by_queue(m, a, b, u);
     }
@@ -801,7 +802,7 @@ static void core_watchdir_scan(TrCore* core)
     {
         char const* name;
 
-        while ((name = g_dir_read_name(dir)))
+        while ((name = g_dir_read_name(dir)) != NULL)
         {
             char* filename = g_build_filename(dirname, name, NULL);
             GFile* file = g_file_new_for_path(filename);
@@ -820,7 +821,7 @@ static void core_watchdir_update(TrCore* core)
     GFile* dir = g_file_new_for_path(gtr_pref_string_get(TR_KEY_watch_dir));
     struct TrCorePrivate* p = core->priv;
 
-    if (p->monitor && (!is_enabled || !g_file_equal(dir, p->monitor_dir)))
+    if (p->monitor != NULL && (!is_enabled || !g_file_equal(dir, p->monitor_dir)))
     {
         g_signal_handler_disconnect(p->monitor, p->monitor_tag);
         g_file_monitor_cancel(p->monitor);
@@ -832,7 +833,7 @@ static void core_watchdir_update(TrCore* core)
         p->monitor_tag = 0;
     }
 
-    if (is_enabled && !p->monitor)
+    if (is_enabled && p->monitor == NULL)
     {
         GFileMonitor* m = g_file_monitor_directory(dir, 0, NULL, NULL);
         core_watchdir_scan(core);
@@ -910,7 +911,7 @@ tr_session* gtr_core_close(TrCore* core)
 {
     tr_session* session = gtr_core_session(core);
 
-    if (session)
+    if (session != NULL)
     {
         core->priv->session = NULL;
         gtr_pref_save(session);
@@ -942,7 +943,7 @@ static gboolean on_torrent_completeness_changed_idle(gpointer gdata)
    so delegate to the GTK+ thread before calling notify's dbus code... */
 static void on_torrent_completeness_changed(tr_torrent* tor, tr_completeness completeness, bool was_running, void* gcore)
 {
-    if (was_running && (completeness != TR_LEECH) && (tr_torrentStat(tor)->sizeWhenDone != 0))
+    if (was_running && completeness != TR_LEECH && tr_torrentStat(tor)->sizeWhenDone != 0)
     {
         struct notify_callback_data* data = g_new(struct notify_callback_data, 1);
         data->core = gcore;
@@ -1049,7 +1050,7 @@ static unsigned int build_torrent_trackers_hash(tr_torrent* tor)
 
     for (i = 0; i < inf->trackerCount; ++i)
     {
-        for (pch = inf->trackers[i].announce; *pch; ++pch)
+        for (pch = inf->trackers[i].announce; *pch != '\0'; ++pch)
         {
             hash = (hash << 4) ^ (hash >> 28) ^ *pch;
         }
@@ -1060,7 +1061,7 @@ static unsigned int build_torrent_trackers_hash(tr_torrent* tor)
 
 static gboolean is_torrent_active(tr_stat const* st)
 {
-    return (st->peersSendingToUs > 0) || (st->peersGettingFromUs > 0) || (st->activity == TR_STATUS_CHECK);
+    return st->peersSendingToUs > 0 || st->peersGettingFromUs > 0 || st->activity == TR_STATUS_CHECK;
 }
 
 void gtr_core_add_torrent(TrCore* core, tr_torrent* tor, gboolean do_notify)
@@ -1112,7 +1113,7 @@ static tr_torrent* core_create_new_torrent(TrCore* core, tr_ctor* ctor)
     tr_ctorSetDeleteSource(ctor, FALSE);
     tor = tr_torrentNew(ctor, NULL, NULL);
 
-    if (tor && do_trash)
+    if (tor != NULL && do_trash)
     {
         char const* config = tr_sessionGetConfigDir(session);
         char const* source = tr_ctorGetSourceFile(ctor);
@@ -1120,7 +1121,7 @@ static tr_torrent* core_create_new_torrent(TrCore* core, tr_ctor* ctor)
         if (source != NULL)
         {
             /* #1294: don't delete the .torrent file if it's our internal copy */
-            int const is_internal = (strstr(source, config) == source);
+            bool const is_internal = strstr(source, config) == source;
 
             if (!is_internal)
             {
@@ -1147,7 +1148,7 @@ static int core_add_ctor(TrCore* core, tr_ctor* ctor, gboolean do_prompt, gboole
         /* don't complain about .torrent files in the watch directory
          * that have already been added... that gets annoying and we
          * don't want to be nagging users to clean up their watch dirs */
-        if (!tr_ctorGetSourceFile(ctor) || !core->priv->adding_from_watch_dir)
+        if (tr_ctorGetSourceFile(ctor) == NULL || !core->priv->adding_from_watch_dir)
         {
             core_emit_err(core, err, inf.name);
         }
@@ -1230,7 +1231,7 @@ static void add_file_async_callback(GObject* file, GAsyncResult* result, gpointe
         g_message(_("Couldn't read \"%s\": %s"), g_file_get_parse_name(G_FILE(file)), error->message);
         g_error_free(error);
     }
-    else if (!tr_ctorSetMetainfo(data->ctor, (uint8_t const*)contents, length))
+    else if (tr_ctorSetMetainfo(data->ctor, (uint8_t const*)contents, length) == 0)
     {
         core_add_ctor(data->core, data->ctor, data->do_prompt, data->do_notify);
     }
@@ -1507,12 +1508,12 @@ static void update_foreach(GtkTreeModel* model, GtkTreeIter* iter)
 
     /* updating the model triggers off resort/refresh,
        so don't do it unless something's actually changed... */
-    if ((newActive != oldActive) || (newActivity != oldActivity) || (newFinished != oldFinished) ||
-        (newPriority != oldPriority) || (newQueuePosition != oldQueuePosition) || (newError != oldError) ||
-        (newActivePeerCount != oldActivePeerCount) || (newDownloadPeerCount != oldDownloadPeerCount) ||
-        (newUploadPeerCount != oldUploadPeerCount) || (newTrackers != oldTrackers) ||
-        gtr_compare_double(newUpSpeed, oldUpSpeed, 2) || gtr_compare_double(newDownSpeed, oldDownSpeed, 2) ||
-        gtr_compare_double(newRecheckProgress, oldRecheckProgress, 2))
+    if (newActive != oldActive || newActivity != oldActivity || newFinished != oldFinished || newPriority != oldPriority ||
+        newQueuePosition != oldQueuePosition || newError != oldError || newActivePeerCount != oldActivePeerCount ||
+        newDownloadPeerCount != oldDownloadPeerCount || newUploadPeerCount != oldUploadPeerCount ||
+        newTrackers != oldTrackers || gtr_compare_double(newUpSpeed, oldUpSpeed, 2) != 0 ||
+        gtr_compare_double(newDownSpeed, oldDownSpeed, 2) != 0 ||
+        gtr_compare_double(newRecheckProgress, oldRecheckProgress, 2) != 0)
     {
         gtk_list_store_set(GTK_LIST_STORE(model), iter,
             MC_ACTIVE, newActive,
@@ -1583,7 +1584,7 @@ static gboolean gtr_inhibit_hibernation(guint* cookie)
         *cookie = g_variant_get_uint32(g_variant_get_child_value(response, 0));
     }
 
-    success = (response != NULL) && (err == NULL);
+    success = response != NULL && err == NULL;
 
     /* logging */
     if (success)
@@ -1751,7 +1752,7 @@ static gboolean core_read_rpc_response_idle(void* vresponse)
         int const tag = (int)intVal;
         struct pending_request_data* data = g_hash_table_lookup(pendingRequests, &tag);
 
-        if (data)
+        if (data != NULL)
         {
             if (data->response_func)
             {
@@ -1928,7 +1929,7 @@ tr_torrent* gtr_core_find_torrent(TrCore* core, int id)
     tr_session* session;
     tr_torrent* tor = NULL;
 
-    if ((session = gtr_core_session(core)))
+    if ((session = gtr_core_session(core)) != NULL)
     {
         tor = tr_torrentFindFromId(session, id);
     }
index 70d78ef6a028ce82de53767a4f6e53859c7fea7b..810e183c97634415e74d0e7bfaebd2aa036dd04d 100644 (file)
@@ -187,7 +187,7 @@ static GtkWidget* new_entry(tr_quark const key, gpointer core)
     GtkWidget* w = gtk_entry_new();
     char const* value = gtr_pref_string_get(key);
 
-    if (value)
+    if (value != NULL)
     {
         gtk_entry_set_text(GTK_ENTRY(w), value);
     }
@@ -573,7 +573,7 @@ static GtkTreeModel* whitelist_tree_model_new(char const* whitelist)
 
     rules = g_strsplit(whitelist, ",", 0);
 
-    for (i = 0; rules && rules[i]; ++i)
+    for (i = 0; rules != NULL && rules[i] != NULL; ++i)
     {
         GtkTreeIter iter;
         char const* s = rules[i];
@@ -1107,7 +1107,7 @@ static void onPortTest(GtkButton* button UNUSED, gpointer vdata)
     gtk_widget_set_sensitive(data->portSpin, FALSE);
     gtk_label_set_markup(GTK_LABEL(data->portLabel), _("<i>Testing TCP port…</i>"));
 
-    if (!data->portTag)
+    if (data->portTag == 0)
     {
         data->portTag = g_signal_connect(data->core, "port-tested", G_CALLBACK(onPortTested), data);
     }
index ab3a97ff57694ccc904e7a5846dd01c6f8e2959f..9fb797c50fa543d00f99223f169d0c7658b006c3 100644 (file)
@@ -79,7 +79,7 @@ static void on_popup_menu(GtkWidget* self UNUSED, GdkEventButton* event)
 {
     GtkWidget* menu = gtr_action_get_widget("/main-window-popup");
 
-    gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL, (event ? event->button : 0), (event ? event->time : 0));
+    gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL, event != NULL ? event->button : 0, event != NULL ? event->time : 0);
 }
 
 static void view_row_activated(GtkTreeView* tree_view UNUSED, GtkTreePath* path UNUSED, GtkTreeViewColumn* column UNUSED,
@@ -821,7 +821,7 @@ void gtr_window_refresh(GtkWindow* self)
 {
     PrivateData* p = get_private_data(self);
 
-    if (p && p->core && gtr_core_session(p->core))
+    if (p != NULL && p->core != NULL && gtr_core_session(p->core) != NULL)
     {
         updateSpeeds(p);
         updateStats(p);
@@ -837,7 +837,7 @@ void gtr_window_set_busy(GtkWindow* win, gboolean isBusy)
 {
     GtkWidget* w = GTK_WIDGET(win);
 
-    if (w && gtk_widget_get_realized(w))
+    if (w != NULL && gtk_widget_get_realized(w))
     {
         GdkDisplay* display = gtk_widget_get_display(w);
         GdkCursor* cursor = isBusy ? gdk_cursor_new_for_display(display, GDK_WATCH) : NULL;
index db7340767cace8c75ab83353ba045019537f079b..421ea8f984c61ad8d4857528478a811b4e8ac461 100644 (file)
@@ -87,7 +87,7 @@ char* tr_strlpercent(char* buf, double x, size_t buflen)
 
 char* tr_strlsize(char* buf, guint64 bytes, size_t buflen)
 {
-    if (!bytes)
+    if (bytes == 0)
     {
         g_strlcpy(buf, Q_("None"), buflen);
     }
@@ -119,9 +119,9 @@ char* tr_strltime(char* buf, int seconds, size_t buflen)
     g_snprintf(m, sizeof(m), ngettext("%'d minute", "%'d minutes", minutes), minutes);
     g_snprintf(s, sizeof(s), ngettext("%'d second", "%'d seconds", seconds), seconds);
 
-    if (days)
+    if (days != 0)
     {
-        if (days >= 4 || !hours)
+        if (days >= 4 || hours == 0)
         {
             g_strlcpy(buf, d, buflen);
         }
@@ -130,9 +130,9 @@ char* tr_strltime(char* buf, int seconds, size_t buflen)
             g_snprintf(buf, buflen, "%s, %s", d, h);
         }
     }
-    else if (hours)
+    else if (hours != 0)
     {
-        if (hours >= 4 || !minutes)
+        if (hours >= 4 || minutes == 0)
         {
             g_strlcpy(buf, h, buflen);
         }
@@ -141,9 +141,9 @@ char* tr_strltime(char* buf, int seconds, size_t buflen)
             g_snprintf(buf, buflen, "%s, %s", h, m);
         }
     }
-    else if (minutes)
+    else if (minutes != 0)
     {
-        if (minutes >= 4 || !seconds)
+        if (minutes >= 4 || seconds == 0)
         {
             g_strlcpy(buf, m, buflen);
         }
@@ -166,7 +166,7 @@ void gtr_get_host_from_url(char* buf, size_t buflen, char const* url)
     char host[1024];
     char const* pch;
 
-    if ((pch = strstr(url, "://")))
+    if ((pch = strstr(url, "://")) != NULL)
     {
         size_t const hostlen = strcspn(pch + 3, ":/");
         size_t const copylen = MIN(hostlen, sizeof(host) - 1);
@@ -187,7 +187,7 @@ void gtr_get_host_from_url(char* buf, size_t buflen, char const* url)
         char const* first_dot = strchr(host, '.');
         char const* last_dot = strrchr(host, '.');
 
-        if ((first_dot) && (last_dot) && (first_dot != last_dot))
+        if (first_dot != NULL && last_dot != NULL && first_dot != last_dot)
         {
             g_strlcpy(buf, first_dot + 1, buflen);
         }
@@ -200,20 +200,20 @@ void gtr_get_host_from_url(char* buf, size_t buflen, char const* url)
 
 static gboolean gtr_is_supported_url(char const* str)
 {
-    return (str != NULL) && (g_str_has_prefix(str, "ftp://") || g_str_has_prefix(str, "http://") ||
+    return str != NULL && (g_str_has_prefix(str, "ftp://") || g_str_has_prefix(str, "http://") ||
            g_str_has_prefix(str, "https://"));
 }
 
 gboolean gtr_is_magnet_link(char const* str)
 {
-    return (str != NULL) && (g_str_has_prefix(str, "magnet:?"));
+    return str != NULL && g_str_has_prefix(str, "magnet:?");
 }
 
 gboolean gtr_is_hex_hashcode(char const* str)
 {
     int i;
 
-    if (!str || (strlen(str) != 40))
+    if (str == NULL || strlen(str) != 40)
     {
         return FALSE;
     }
@@ -338,7 +338,7 @@ bool gtr_file_trash_or_remove(char const* filename, tr_error** error)
         GError* err = NULL;
         trashed = g_file_trash(file, NULL, &err);
 
-        if (err)
+        if (err != NULL)
         {
             g_message("Unable to trash file \"%s\": %s", filename, err->message);
             tr_error_set_literal(error, err->code, err->message);
@@ -351,7 +351,7 @@ bool gtr_file_trash_or_remove(char const* filename, tr_error** error)
         GError* err = NULL;
         g_file_delete(file, NULL, &err);
 
-        if (err)
+        if (err != NULL)
         {
             g_message("Unable to delete file \"%s\": %s", filename, err->message);
             tr_error_clear(error);
@@ -369,7 +369,7 @@ char const* gtr_get_help_uri(void)
 {
     static char* uri = NULL;
 
-    if (!uri)
+    if (uri == NULL)
     {
         char const* fmt = "https://transmissionbt.com/help/gtk/%d.%dx";
         uri = g_strdup_printf(fmt, MAJOR_VERSION, MINOR_VERSION / 10);
@@ -389,7 +389,7 @@ void gtr_open_file(char const* path)
 
 void gtr_open_uri(char const* uri)
 {
-    if (uri)
+    if (uri != NULL)
     {
         gboolean opened = FALSE;
 
@@ -600,7 +600,7 @@ void gtr_unrecognized_url_dialog(GtkWidget* parent, char const* url)
 
     g_string_append_printf(gstr, _("Transmission doesn't know how to use \"%s\""), url);
 
-    if (gtr_is_magnet_link(url) && (strstr(url, xt) == NULL))
+    if (gtr_is_magnet_link(url) && strstr(url, xt) == NULL)
     {
         g_string_append_printf(gstr, "\n \n");
         g_string_append_printf(gstr, _("This magnet link appears to be intended for something other than BitTorrent. "
@@ -631,7 +631,7 @@ void gtr_paste_clipboard_url_into_entry(GtkWidget* e)
     {
         char* s = text[i];
 
-        if (s && (gtr_is_supported_url(s) || gtr_is_magnet_link(s) || gtr_is_hex_hashcode(s)))
+        if (s != NULL && (gtr_is_supported_url(s) || gtr_is_magnet_link(s) || gtr_is_hex_hashcode(s)))
         {
             gtk_entry_set_text(GTK_ENTRY(e), s);
             break;
index 88caa9e869ffd86edb861bbd7fc6ec3b8768461b..97f12e5541a84b0a10c1250e5d4bb4ec24a99fef 100644 (file)
@@ -80,7 +80,7 @@ static char* announce_url_new(tr_session const* session, tr_announce_request con
         "&compact=1"
         "&supportcrypto=1",
         req->url,
-        strchr(req->url, '?') ? '&' : '?',
+        strchr(req->url, '?') != NULL ? '&' : '?',
         escaped_info_hash,
         PEER_ID_LEN, PEER_ID_LEN, req->peer_id,
         req->port,
@@ -95,21 +95,21 @@ static char* announce_url_new(tr_session const* session, tr_announce_request con
         evbuffer_add_printf(buf, "&requirecrypto=1");
     }
 
-    if (req->corrupt)
+    if (req->corrupt != 0)
     {
         evbuffer_add_printf(buf, "&corrupt=%" PRIu64, req->corrupt);
     }
 
     str = get_event_string(req);
 
-    if (str && *str)
+    if (str != NULL && *str != '\0')
     {
         evbuffer_add_printf(buf, "&event=%s", str);
     }
 
     str = req->tracker_id_str;
 
-    if (str && *str)
+    if (str != NULL && *str != '\0')
     {
         evbuffer_add_printf(buf, "&trackerid=%s", str);
     }
@@ -125,7 +125,7 @@ static char* announce_url_new(tr_session const* session, tr_announce_request con
 
     ipv6 = tr_globalIPv6();
 
-    if (ipv6)
+    if (ipv6 != NULL)
     {
         char ipv6_readable[INET6_ADDRSTRLEN];
         evutil_inet_ntop(AF_INET6, ipv6, ipv6_readable, INET6_ADDRSTRLEN);
@@ -170,7 +170,7 @@ static tr_pex* listToPex(tr_variant* peerList, size_t* setme_len)
             continue;
         }
 
-        if ((port < 0) || (port > USHRT_MAX))
+        if (port < 0 || port > USHRT_MAX)
         {
             continue;
         }
@@ -234,7 +234,7 @@ static void on_announce_done(tr_session* session, bool did_connect, bool did_tim
     else
     {
         tr_variant benc;
-        bool const variant_loaded = !tr_variantFromBenc(&benc, msg, msglen);
+        bool const variant_loaded = tr_variantFromBenc(&benc, msg, msglen) == 0;
 
         if (tr_env_key_exists("TR_CURL_VERBOSE"))
         {
@@ -407,7 +407,7 @@ static void on_scrape_done(tr_session* session, bool did_connect, bool did_timeo
         tr_variant* flags;
         size_t len;
         char const* str;
-        bool const variant_loaded = !tr_variantFromBenc(&top, msg, msglen);
+        bool const variant_loaded = tr_variantFromBenc(&top, msg, msglen) == 0;
 
         if (tr_env_key_exists("TR_CURL_VERBOSE"))
         {
@@ -509,7 +509,7 @@ static char* scrape_url_new(tr_scrape_request const* req)
     struct evbuffer* buf = evbuffer_new();
 
     evbuffer_add_printf(buf, "%s", req->url);
-    delimiter = strchr(req->url, '?') ? '&' : '?';
+    delimiter = strchr(req->url, '?') != NULL ? '&' : '?';
 
     for (i = 0; i < req->info_hash_count; ++i)
     {
index 8f573698aca2eda4fa5986c791a6713c8c2bd7a3..c24bc50f7847870a8bdb5bbdb7565357541da84b 100644 (file)
@@ -256,7 +256,7 @@ static void on_scrape_response(struct tau_scrape_request* request, tau_action_t
         {
             struct tr_scrape_response_row* row;
 
-            if (evbuffer_get_length(buf) < (sizeof(uint32_t) * 3))
+            if (evbuffer_get_length(buf) < sizeof(uint32_t) * 3)
             {
                 break;
             }
@@ -274,7 +274,7 @@ static void on_scrape_response(struct tau_scrape_request* request, tau_action_t
         char* errmsg;
         size_t const buflen = evbuffer_get_length(buf);
 
-        if ((action == TAU_ACTION_ERROR) && (buflen > 0))
+        if (action == TAU_ACTION_ERROR && buflen > 0)
         {
             errmsg = tr_strndup(evbuffer_pullup(buf, -1), buflen);
         }
@@ -410,7 +410,7 @@ static void on_announce_response(struct tau_announce_request* request, tau_actio
     request->response.did_connect = true;
     request->response.did_timeout = false;
 
-    if ((action == TAU_ACTION_ANNOUNCE) && (buflen >= 3 * sizeof(uint32_t)))
+    if (action == TAU_ACTION_ANNOUNCE && buflen >= 3 * sizeof(uint32_t))
     {
         tr_announce_response* resp = &request->response;
         resp->interval = evbuffer_read_ntoh_32(buf);
@@ -424,7 +424,7 @@ static void on_announce_response(struct tau_announce_request* request, tau_actio
     {
         char* errmsg;
 
-        if ((action == TAU_ACTION_ERROR) && (buflen > 0))
+        if (action == TAU_ACTION_ERROR && buflen > 0)
         {
             errmsg = tr_strndup(evbuffer_pullup(buf, -1), buflen);
         }
@@ -473,7 +473,7 @@ static void tau_tracker_free(struct tau_tracker* t)
 {
     assert(t->dns_request == NULL);
 
-    if (t->addr)
+    if (t->addr != NULL)
     {
         evutil_freeaddrinfo(t->addr);
     }
@@ -520,7 +520,7 @@ static void tau_tracker_on_dns(int errcode, struct evutil_addrinfo* addr, void*
 
     tracker->dns_request = NULL;
 
-    if (errcode)
+    if (errcode != 0)
     {
         char* errmsg = tr_strdup_printf(_("DNS Lookup failed: %s"), evutil_gai_strerror(errcode));
         dbgmsg(tracker->key, "%s", errmsg);
@@ -563,7 +563,7 @@ static void tau_tracker_send_reqs(struct tau_tracker* tracker)
     {
         struct tau_announce_request* req = tr_ptrArrayNth(reqs, i);
 
-        if (!req->sent_at)
+        if (req->sent_at == 0)
         {
             dbgmsg(tracker->key, "sending announce req %p", (void*)req);
             req->sent_at = now;
@@ -585,7 +585,7 @@ static void tau_tracker_send_reqs(struct tau_tracker* tracker)
     {
         struct tau_scrape_request* req = tr_ptrArrayNth(reqs, i);
 
-        if (!req->sent_at)
+        if (req->sent_at == 0)
         {
             dbgmsg(tracker->key, "sending scrape req %p", (void*)req);
             req->sent_at = now;
@@ -620,7 +620,7 @@ static void on_tracker_connection_response(struct tau_tracker* tracker, tau_acti
         char* errmsg;
         size_t const buflen = buf ? evbuffer_get_length(buf) : 0;
 
-        if ((action == TAU_ACTION_ERROR) && (buflen > 0))
+        if (action == TAU_ACTION_ERROR && buflen > 0)
         {
             errmsg = tr_strndup(evbuffer_pullup(buf, -1), buflen);
         }
@@ -644,7 +644,7 @@ static void tau_tracker_timeout_reqs(struct tau_tracker* tracker)
     time_t const now = time(NULL);
     bool const cancel_all = tracker->close_at && (tracker->close_at <= now);
 
-    if (tracker->connecting_at && (tracker->connecting_at + TAU_REQUEST_TTL < now))
+    if (tracker->connecting_at != 0 && tracker->connecting_at + TAU_REQUEST_TTL < now)
     {
         on_tracker_connection_response(tracker, TAU_ACTION_ERROR, NULL);
     }
@@ -655,7 +655,7 @@ static void tau_tracker_timeout_reqs(struct tau_tracker* tracker)
     {
         struct tau_announce_request* req = tr_ptrArrayNth(reqs, i);
 
-        if (cancel_all || (req->created_at + TAU_REQUEST_TTL < now))
+        if (cancel_all || req->created_at + TAU_REQUEST_TTL < now)
         {
             dbgmsg(tracker->key, "timeout announce req %p", (void*)req);
             tau_announce_request_fail(req, false, true, NULL);
@@ -672,7 +672,7 @@ static void tau_tracker_timeout_reqs(struct tau_tracker* tracker)
     {
         struct tau_scrape_request* req = tr_ptrArrayNth(reqs, i);
 
-        if (cancel_all || (req->created_at + TAU_REQUEST_TTL < now))
+        if (cancel_all || req->created_at + TAU_REQUEST_TTL < now)
         {
             dbgmsg(tracker->key, "timeout scrape req %p", (void*)req);
             tau_scrape_request_fail(req, false, true, NULL);
@@ -727,7 +727,7 @@ static void tau_tracker_upkeep(struct tau_tracker* tracker)
         (size_t)tracker->connecting_at);
 
     /* also need a valid connection ID... */
-    if (tracker->addr && (tracker->connection_expiration_time <= now) && (!tracker->connecting_at))
+    if (tracker->addr != NULL && tracker->connection_expiration_time <= now && tracker->connecting_at == 0)
     {
         struct evbuffer* buf = evbuffer_new();
         tracker->connecting_at = now;
@@ -743,7 +743,7 @@ static void tau_tracker_upkeep(struct tau_tracker* tracker)
 
     tau_tracker_timeout_reqs(tracker);
 
-    if ((tracker->addr != NULL) && (tracker->connection_expiration_time > now))
+    if (tracker->addr != NULL && tracker->connection_expiration_time > now)
     {
         tau_tracker_send_reqs(tracker);
     }
@@ -915,12 +915,12 @@ bool tau_handle_message(tr_session* session, uint8_t const* msg, size_t msglen)
 
     /*fprintf(stderr, "got an incoming udp message w/len %zu\n", msglen);*/
 
-    if (!session || !session->announcer_udp)
+    if (session == NULL || session->announcer_udp == NULL)
     {
         return false;
     }
 
-    if (msglen < (sizeof(uint32_t) * 2))
+    if (msglen < sizeof(uint32_t) * 2)
     {
         return false;
     }
@@ -948,7 +948,7 @@ bool tau_handle_message(tr_session* session, uint8_t const* msg, size_t msglen)
         struct tau_tracker* tracker = tr_ptrArrayNth(&tau->trackers, i);
 
         /* is it a connection response? */
-        if (tracker->connecting_at && (transaction_id == tracker->connection_transaction_id))
+        if (tracker->connecting_at != 0 && transaction_id == tracker->connection_transaction_id)
         {
             dbgmsg(tracker->key, "%" PRIu32 " is my connection request!", transaction_id);
             on_tracker_connection_response(tracker, action_id, buf);
@@ -963,7 +963,7 @@ bool tau_handle_message(tr_session* session, uint8_t const* msg, size_t msglen)
         {
             struct tau_announce_request* req = tr_ptrArrayNth(reqs, j);
 
-            if (req->sent_at && (transaction_id == req->transaction_id))
+            if (req->sent_at != 0 && transaction_id == req->transaction_id)
             {
                 dbgmsg(tracker->key, "%" PRIu32 " is an announce request!", transaction_id);
                 tr_ptrArrayRemove(reqs, j);
@@ -981,7 +981,7 @@ bool tau_handle_message(tr_session* session, uint8_t const* msg, size_t msglen)
         {
             struct tau_scrape_request* req = tr_ptrArrayNth(reqs, j);
 
-            if (req->sent_at && (transaction_id == req->transaction_id))
+            if (req->sent_at != 0 && transaction_id == req->transaction_id)
             {
                 dbgmsg(tracker->key, "%" PRIu32 " is a scrape request!", transaction_id);
                 tr_ptrArrayRemove(reqs, j);
index 7086b129dbf8c4c92ce259e4bac2776fb33d090e..fbed5663d35e2e3b2dbaca23e8001ce613d1a4a8 100644 (file)
@@ -119,7 +119,7 @@ static int compareStops(void const* va, void const* vb)
     tr_announce_request const* b = vb;
 
     /* primary key: volume of data transferred. */
-    if ((i = compareTransfer(a->up, a->down, b->up, b->down)))
+    if ((i = compareTransfer(a->up, a->down, b->up, b->down)) != 0)
     {
         return i;
     }
@@ -229,7 +229,7 @@ static char* getKey(char const* url)
     int port = 0;
 
     tr_urlParse(url, TR_BAD_SIZE, &scheme, &host, &port, NULL);
-    ret = tr_strdup_printf("%s://%s:%d", (scheme ? scheme : "invalid"), (host ? host : "invalid"), port);
+    ret = tr_strdup_printf("%s://%s:%d", scheme != NULL ? scheme : "invalid", host != NULL ? host : "invalid", port);
 
     tr_free(host);
     tr_free(scheme);
@@ -329,7 +329,7 @@ static time_t get_next_scrape_time(tr_session const* session, tr_tier const* tie
     {
         ret = now + interval;
 
-        while (ret % 10)
+        while (ret % 10 != 0)
         {
             ++ret;
         }
@@ -360,14 +360,14 @@ static void tierDestruct(tr_tier* tier)
 
 static void tier_build_log_name(tr_tier const* tier, char* buf, size_t buflen)
 {
-    tr_snprintf(buf, buflen, "[%s---%s]", (tier && tier->tor) ? tr_torrentName(tier->tor) : "?",
-        (tier && tier->currentTracker) ? tier->currentTracker->key : "?");
+    tr_snprintf(buf, buflen, "[%s---%s]", (tier != NULL && tier->tor != NULL) ? tr_torrentName(tier->tor) : "?",
+        (tier != NULL && tier->currentTracker != NULL) ? tier->currentTracker->key : "?");
 }
 
 static void tierIncrementTracker(tr_tier* tier)
 {
     /* move our index to the next tracker in the tier */
-    int const i = (tier->currentTracker == NULL) ? 0 : (tier->currentTrackerIndex + 1) % tier->tracker_count;
+    int const i = tier->currentTracker == NULL ? 0 : (tier->currentTrackerIndex + 1) % tier->tracker_count;
     tier->currentTrackerIndex = i;
     tier->currentTracker = &tier->trackers[i];
 
@@ -442,12 +442,12 @@ static tr_tier* getTier(tr_announcer* announcer, uint8_t const* info_hash, int t
         tr_session* session = announcer->session;
         tr_torrent* tor = tr_torrentFindFromHash(session, info_hash);
 
-        if (tor && tor->tiers)
+        if (tor != NULL && tor->tiers != NULL)
         {
             int i;
             tr_torrent_tiers* tt = tor->tiers;
 
-            for (i = 0; !tier && i < tt->tier_count; ++i)
+            for (i = 0; tier == NULL && i < tt->tier_count; ++i)
             {
                 if (tt->tiers[i].key == tierId)
                 {
@@ -468,14 +468,14 @@ static tr_tracker_event const TRACKER_EVENT_INIT = { 0, 0, 0, 0, 0, 0 };
 
 static void publishMessage(tr_tier* tier, char const* msg, int type)
 {
-    if (tier && tier->tor && tier->tor->tiers && tier->tor->tiers->callback)
+    if (tier != NULL && tier->tor != NULL && tier->tor->tiers != NULL && tier->tor->tiers->callback != NULL)
     {
         tr_torrent_tiers* tiers = tier->tor->tiers;
         tr_tracker_event event = TRACKER_EVENT_INIT;
         event.messageType = type;
         event.text = msg;
 
-        if (tier->currentTracker)
+        if (tier->currentTracker != NULL)
         {
             event.tracker = tier->currentTracker->announce;
         }
@@ -504,15 +504,14 @@ static int8_t getSeedProbability(tr_tier* tier, int seeds, int leechers, int pex
     /* special case optimization:
        ocelot omits seeds from peer lists sent to seeds on private trackers.
        so check for that case... */
-    if ((leechers == pex_count) && tr_torrentIsPrivate(tier->tor) && tr_torrentIsSeed(tier->tor) &&
-        (seeds + leechers < NUMWANT))
+    if (leechers == pex_count && tr_torrentIsPrivate(tier->tor) && tr_torrentIsSeed(tier->tor) && seeds + leechers < NUMWANT)
     {
         return 0;
     }
 
-    if (seeds >= 0 && leechers >= 0 && (seeds + leechers > 0))
+    if (seeds >= 0 && leechers >= 0 && seeds + leechers > 0)
     {
-        return (int8_t)((100.0 * seeds) / (seeds + leechers));
+        return (int8_t)(100.0 * seeds / (seeds + leechers));
     }
 
     return -1; /* unknown */
@@ -520,7 +519,7 @@ static int8_t getSeedProbability(tr_tier* tier, int seeds, int leechers, int pex
 
 static void publishPeersPex(tr_tier* tier, int seeds, int leechers, tr_pex const* pex, int n)
 {
-    if (tier->tor->tiers->callback)
+    if (tier->tor->tiers->callback != NULL)
     {
         tr_tracker_event e = TRACKER_EVENT_INIT;
         e.messageType = TR_TRACKER_PEERS;
@@ -598,7 +597,7 @@ static tr_tracker_info* filter_trackers(tr_tracker_info* input, int input_count,
              */
             for (j = 0, jn = n; !is_duplicate && j < jn; ++j)
             {
-                is_duplicate = (tmp[j].port == port) && strcmp(tmp[j].scheme, scheme) == 0 && strcmp(tmp[j].host, host) == 0 &&
+                is_duplicate = tmp[j].port == port && strcmp(tmp[j].scheme, scheme) == 0 && strcmp(tmp[j].host, host) == 0 &&
                     strcmp(tmp[j].path, path) == 0;
             }
 
@@ -626,7 +625,7 @@ static tr_tracker_info* filter_trackers(tr_tracker_info* input, int input_count,
     {
         for (j = i + 1, jn = n; j < jn; ++j)
         {
-            if ((tmp[i].info.tier != tmp[j].info.tier) && (tmp[i].port == tmp[j].port) &&
+            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)
             {
                 tmp[j].info.tier = tmp[i].info.tier;
@@ -683,7 +682,7 @@ static void addTorrentToTier(tr_torrent_tiers* tt, tr_torrent* tor)
 
     for (i = 0; i < n; ++i)
     {
-        if (!i || (infos[i].tier != infos[i - 1].tier))
+        if (i == 0 || infos[i].tier != infos[i - 1].tier)
         {
             ++tier_count;
         }
@@ -696,7 +695,7 @@ static void addTorrentToTier(tr_torrent_tiers* tt, tr_torrent* tor)
 
     for (i = 0; i < n; ++i)
     {
-        if (i && (infos[i].tier == infos[i - 1].tier))
+        if (i != 0 && infos[i].tier == infos[i - 1].tier)
         {
             ++tier->tracker_count;
         }
@@ -807,7 +806,7 @@ static void dbgmsg_tier_announce_queue(tr_tier const* tier)
 
 static void tier_announce_remove_trailing(tr_tier* tier, tr_announce_event e)
 {
-    while ((tier->announce_event_count > 0) && (tier->announce_events[tier->announce_event_count - 1] == e))
+    while (tier->announce_event_count > 0 && tier->announce_events[tier->announce_event_count - 1] == e)
     {
         --tier->announce_event_count;
     }
@@ -1061,7 +1060,7 @@ static void on_announce_done(tr_announce_response const* response, void* vdata)
     time_t const now = tr_time();
     tr_announce_event const event = data->event;
 
-    if (announcer)
+    if (announcer != NULL)
     {
         ++announcer->slotsAvailable;
     }
@@ -1091,11 +1090,11 @@ static void on_announce_done(tr_announce_response const* response, void* vdata)
             response->downloads,
             response->interval,
             response->min_interval,
-            response->tracker_id_str ? response->tracker_id_str : "none",
+            response->tracker_id_str != NULL ? response->tracker_id_str : "none",
             response->pex_count,
             response->pex6_count,
-            response->errmsg ? response->errmsg : "none",
-            response->warning ? response->warning : "none");
+            response->errmsg != NULL ? response->errmsg : "none",
+            response->warning != NULL ? response->warning : "none");
 
         tier->lastAnnounceTime = now;
         tier->lastAnnounceTimedOut = response->did_timeout;
@@ -1111,7 +1110,7 @@ static void on_announce_done(tr_announce_response const* response, void* vdata)
         {
             on_announce_error(tier, _("Tracker did not respond"), event);
         }
-        else if (response->errmsg)
+        else if (response->errmsg != NULL)
         {
             /* If the torrent's only tracker returned an error, publish it.
                Don't bother publishing if there are other trackers -- it's
@@ -1136,7 +1135,7 @@ static void on_announce_done(tr_announce_response const* response, void* vdata)
 
             publishErrorClear(tier);
 
-            if ((tracker = tier->currentTracker))
+            if ((tracker = tier->currentTracker) != NULL)
             {
                 tracker->consecutiveFailures = 0;
 
@@ -1158,14 +1157,14 @@ static void on_announce_done(tr_announce_response const* response, void* vdata)
                     ++scrape_fields;
                 }
 
-                if ((str = response->tracker_id_str))
+                if ((str = response->tracker_id_str) != NULL)
                 {
                     tr_free(tracker->tracker_id_str);
                     tracker->tracker_id_str = tr_strdup(str);
                 }
             }
 
-            if ((str = response->warning))
+            if ((str = response->warning) != NULL)
             {
                 tr_strlcpy(tier->lastAnnounceStr, str, sizeof(tier->lastAnnounceStr));
                 dbgmsg(tier, "tracker gave \"%s\"", str);
@@ -1176,12 +1175,12 @@ static void on_announce_done(tr_announce_response const* response, void* vdata)
                 tr_strlcpy(tier->lastAnnounceStr, _("Success"), sizeof(tier->lastAnnounceStr));
             }
 
-            if ((i = response->min_interval))
+            if ((i = response->min_interval) != 0)
             {
                 tier->announceMinIntervalSec = i;
             }
 
-            if ((i = response->interval))
+            if ((i = response->interval) != 0)
             {
                 tier->announceIntervalSec = i;
             }
@@ -1226,7 +1225,7 @@ static void on_announce_done(tr_announce_response const* response, void* vdata)
                 tier->byteCounts[TR_ANN_CORRUPT] = 0;
             }
 
-            if (!isStopped && !tier->announce_event_count)
+            if (!isStopped && tier->announce_event_count == 0)
             {
                 /* the queue is empty, so enqueue a perodic update */
                 i = tier->announceIntervalSec;
@@ -1391,7 +1390,7 @@ static void on_scrape_done(tr_scrape_response const* response, void* vsession)
                     row->downloads,
                     row->downloaders,
                     response->min_request_interval,
-                    response->errmsg ? response->errmsg : "none");
+                    response->errmsg != NULL ? response->errmsg : "none");
 
                 tier->isScraping = false;
                 tier->lastScrapeTime = now;
@@ -1406,7 +1405,7 @@ static void on_scrape_done(tr_scrape_response const* response, void* vsession)
                 {
                     on_scrape_error(session, tier, _("Tracker did not respond"));
                 }
-                else if (response->errmsg)
+                else if (response->errmsg != NULL)
                 {
                     on_scrape_error(session, tier, response->errmsg);
                 }
@@ -1419,7 +1418,7 @@ static void on_scrape_done(tr_scrape_response const* response, void* vsession)
                     tier->scrapeAt = get_next_scrape_time(session, tier, tier->scrapeIntervalSec);
                     tr_logAddTorDbg(tier->tor, "Scrape successful. Rescraping in %d seconds.", tier->scrapeIntervalSec);
 
-                    if ((tracker = tier->currentTracker))
+                    if ((tracker = tier->currentTracker) != NULL)
                     {
                         if (row->seeders >= 0)
                         {
@@ -1508,7 +1507,7 @@ static void multiscrape(tr_announcer* announcer, tr_ptrArray* tiers)
         }
 
         /* otherwise, if there's room for another request, build a new one */
-        if ((j == request_count) && (request_count < max_request_count))
+        if (j == request_count && request_count < max_request_count)
         {
             tr_scrape_request* req = &requests[request_count++];
             req->url = url;
@@ -1545,14 +1544,14 @@ static void flushCloseMessages(tr_announcer* announcer)
 
 static bool tierNeedsToAnnounce(tr_tier const* tier, time_t const now)
 {
-    return !tier->isAnnouncing && !tier->isScraping && (tier->announceAt != 0) && (tier->announceAt <= now) &&
-           (tier->announce_event_count > 0);
+    return !tier->isAnnouncing && !tier->isScraping && tier->announceAt != 0 && tier->announceAt <= now &&
+           tier->announce_event_count > 0;
 }
 
 static bool tierNeedsToScrape(tr_tier const* tier, time_t const now)
 {
-    return (!tier->isScraping) && (tier->scrapeAt != 0) && (tier->scrapeAt <= now) && (tier->currentTracker != NULL) &&
-           (tier->currentTracker->scrape != NULL);
+    return !tier->isScraping && tier->scrapeAt != 0 && tier->scrapeAt <= now && tier->currentTracker != NULL &&
+           tier->currentTracker->scrape != NULL;
 }
 
 static int compareTiers(void const* va, void const* vb)
@@ -1566,7 +1565,7 @@ static int compareTiers(void const* va, void const* vb)
         b->byteCounts[TR_ANN_DOWN]);
 
     /* secondary key: announcements that have been waiting longer go first */
-    if (!ret && (a->announceAt != b->announceAt))
+    if (ret == 0 && a->announceAt != b->announceAt)
     {
         ret = a->announceAt < b->announceAt ? -1 : 1;
     }
@@ -1593,11 +1592,11 @@ static void announceMore(tr_announcer* announcer)
     /* build a list of tiers that need to be announced */
     tor = NULL;
 
-    while ((tor = tr_torrentNext(announcer->session, tor)))
+    while ((tor = tr_torrentNext(announcer->session, tor)) != NULL)
     {
         struct tr_torrent_tiers* tt = tor->tiers;
 
-        for (i = 0; tt && i < tt->tier_count; ++i)
+        for (i = 0; tt != NULL && i < tt->tier_count; ++i)
         {
             tr_tier* tier = &tt->tiers[i];
 
@@ -1708,7 +1707,7 @@ tr_tracker_stat* tr_announcerStats(tr_torrent const* torrent, int* setmeTrackerC
             st->isBackup = tracker != tier->currentTracker;
             st->lastScrapeStartTime = tier->lastScrapeStartTime;
 
-            if (tracker->scrape)
+            if (tracker->scrape != NULL)
             {
                 tr_strlcpy(st->scrape, tracker->scrape, sizeof(st->scrape));
             }
@@ -1742,7 +1741,7 @@ tr_tracker_stat* tr_announcerStats(tr_torrent const* torrent, int* setmeTrackerC
                 {
                     st->scrapeState = TR_TRACKER_ACTIVE;
                 }
-                else if (!tier->scrapeAt)
+                else if (tier->scrapeAt == 0)
                 {
                     st->scrapeState = TR_TRACKER_INACTIVE;
                 }
@@ -1771,7 +1770,7 @@ tr_tracker_stat* tr_announcerStats(tr_torrent const* torrent, int* setmeTrackerC
                 {
                     st->announceState = TR_TRACKER_ACTIVE;
                 }
-                else if (!torrent->isRunning || !tier->announceAt)
+                else if (!torrent->isRunning || tier->announceAt == 0)
                 {
                     st->announceState = TR_TRACKER_INACTIVE;
                 }
index 4a1e809dbbc70c1dc98d7f0c4508687f6bcbc75c..61a096c992780f082babc7a2999f25f72f490dff 100644 (file)
@@ -32,7 +32,7 @@
 
 static unsigned int getSpeed_Bps(struct bratecontrol const* r, unsigned int interval_msec, uint64_t now)
 {
-    if (!now)
+    if (now == 0)
     {
         now = tr_time_msec();
     }
@@ -140,14 +140,14 @@ void tr_bandwidthSetParent(tr_bandwidth* b, tr_bandwidth* parent)
     assert(tr_isBandwidth(b));
     assert(b != parent);
 
-    if (b->parent)
+    if (b->parent != NULL)
     {
         assert(tr_isBandwidth(b->parent));
         tr_ptrArrayRemoveSortedPointer(&b->parent->children, b, compareBandwidth);
         b->parent = NULL;
     }
 
-    if (parent)
+    if (parent != NULL)
     {
         assert(tr_isBandwidth(parent));
         assert(parent->parent != b);
@@ -210,7 +210,7 @@ static void phaseOne(tr_ptrArray* peerArray, tr_direction dir)
      * small chunk of bandwidth. Keep looping until we run out of bandwidth
      * and/or peers that can use it */
     n = peerCount;
-    dbgmsg("%d peers to go round-robin for %s", n, (dir == TR_UP ? "upload" : "download"));
+    dbgmsg("%d peers to go round-robin for %s", n, dir == TR_UP ? "upload" : "download");
 
     while (n > 0)
     {
@@ -304,7 +304,7 @@ void tr_bandwidthAllocate(tr_bandwidth* b, tr_direction dir, unsigned int period
 void tr_bandwidthSetPeer(tr_bandwidth* b, tr_peerIo* peer)
 {
     assert(tr_isBandwidth(b));
-    assert((peer == NULL) || tr_isPeerIo(peer));
+    assert(peer == NULL || tr_isPeerIo(peer));
 
     b->peer = peer;
 }
@@ -318,7 +318,7 @@ static unsigned int bandwidthClamp(tr_bandwidth const* b, uint64_t now, tr_direc
     assert(tr_isBandwidth(b));
     assert(tr_isDirection(dir));
 
-    if (b)
+    if (b != NULL)
     {
         if (b->band[dir].isLimited)
         {
@@ -356,7 +356,7 @@ static unsigned int bandwidthClamp(tr_bandwidth const* b, uint64_t now, tr_direc
             }
         }
 
-        if (b->parent && b->band[dir].honorParentLimits && (byteCount > 0))
+        if (b->parent != NULL && b->band[dir].honorParentLimits && byteCount > 0)
         {
             byteCount = bandwidthClamp(b->parent, now, dir, byteCount);
         }
@@ -402,10 +402,10 @@ void tr_bandwidthUsed(tr_bandwidth* b, tr_direction dir, size_t byteCount, bool
 
 #ifdef DEBUG_DIRECTION
 
-    if ((dir == DEBUG_DIRECTION) && (band->isLimited))
+    if (dir == DEBUG_DIRECTION && band->isLimited)
     {
         fprintf(stderr, "%p consumed %5zu bytes of %5s data... was %6zu, now %6zu left\n", b, byteCount,
-            (isPieceData ? "piece" : "raw"), oldBytesLeft, band->bytesLeft);
+            isPieceData ? "piece" : "raw", oldBytesLeft, band->bytesLeft);
     }
 
 #endif
index d45aa6a8eaf27b7c38868532349324f09795f4fa..d3a3ee3f622d6e9f73b8a5c4db91e8685a7463fe 100644 (file)
@@ -128,7 +128,7 @@ void tr_bandwidthDestruct(tr_bandwidth* bandwidth);
 /** @brief test to see if the pointer refers to a live bandwidth object */
 static inline bool tr_isBandwidth(tr_bandwidth const* b)
 {
-    return (b != NULL) && (b->magicNumber == BANDWIDTH_MAGIC_NUMBER);
+    return b != NULL && b->magicNumber == BANDWIDTH_MAGIC_NUMBER;
 }
 
 /******
index 6b09e180def441027956a2090f6bd2ee3ff7ccc4..a0d1c37800aba97a025f2cfe141d490465dd24f2 100644 (file)
@@ -79,7 +79,7 @@ static int test_bitfields(void)
     /* test tr_bitfieldAdd */
     for (i = 0; i < bitcount; i++)
     {
-        if (!(i % 7))
+        if (i % 7 == 0)
         {
             tr_bitfieldAdd(&field, i);
         }
@@ -87,7 +87,7 @@ static int test_bitfields(void)
 
     for (i = 0; i < bitcount; i++)
     {
-        check(tr_bitfieldHas(&field, i) == (!(i % 7)));
+        check(tr_bitfieldHas(&field, i) == (i % 7 == 0));
     }
 
     /* test tr_bitfieldAddRange */
@@ -101,7 +101,7 @@ static int test_bitfields(void)
     /* test tr_bitfieldRem */
     for (i = 0; i < bitcount; i++)
     {
-        if ((i % 7) != 0)
+        if (i % 7 != 0)
         {
             tr_bitfieldRem(&field, i);
         }
@@ -109,7 +109,7 @@ static int test_bitfields(void)
 
     for (i = 0; i < bitcount; i++)
     {
-        check(tr_bitfieldHas(&field, i) == (!(i % 7)));
+        check(tr_bitfieldHas(&field, i) == (i % 7 == 0));
     }
 
     /* test tr_bitfieldRemRange in the middle of a boundary */
@@ -118,7 +118,7 @@ static int test_bitfields(void)
 
     for (i = 0; i < 64; i++)
     {
-        check(tr_bitfieldHas(&field, i) == ((i < 4) || (i >= 21)));
+        check(tr_bitfieldHas(&field, i) == (i < 4 || i >= 21));
     }
 
     /* test tr_bitfieldRemRange on the boundaries */
@@ -127,7 +127,7 @@ static int test_bitfields(void)
 
     for (i = 0; i < 64; i++)
     {
-        check(tr_bitfieldHas(&field, i) == ((i < 8) || (i >= 24)));
+        check(tr_bitfieldHas(&field, i) == (i < 8 || i >= 24));
     }
 
     /* test tr_bitfieldRemRange when begin & end is on the same word */
@@ -136,7 +136,7 @@ static int test_bitfields(void)
 
     for (i = 0; i < 64; i++)
     {
-        check(tr_bitfieldHas(&field, i) == ((i < 4) || (i >= 5)));
+        check(tr_bitfieldHas(&field, i) == (i < 4 || i >= 5));
     }
 
     /* test tr_bitfieldAddRange */
@@ -145,7 +145,7 @@ static int test_bitfields(void)
 
     for (i = 0; i < 64; i++)
     {
-        check(tr_bitfieldHas(&field, i) == ((4 <= i) && (i < 21)));
+        check(tr_bitfieldHas(&field, i) == (4 <= i && i < 21));
     }
 
     /* test tr_bitfieldAddRange on the boundaries */
@@ -154,7 +154,7 @@ static int test_bitfields(void)
 
     for (i = 0; i < 64; i++)
     {
-        check(tr_bitfieldHas(&field, i) == ((8 <= i) && (i < 24)));
+        check(tr_bitfieldHas(&field, i) == (8 <= i && i < 24));
     }
 
     /* test tr_bitfieldAddRange when begin & end is on the same word */
@@ -163,7 +163,7 @@ static int test_bitfields(void)
 
     for (i = 0; i < 64; i++)
     {
-        check(tr_bitfieldHas(&field, i) == ((4 <= i) && (i < 5)));
+        check(tr_bitfieldHas(&field, i) == (4 <= i && i < 5));
     }
 
     tr_bitfieldDestruct(&field);
@@ -234,7 +234,7 @@ int main(void)
         test_bitfield_has_all_none
     };
 
-    if ((ret = runTests(tests, NUM_TESTS(tests))))
+    if ((ret = runTests(tests, NUM_TESTS(tests))) != 0)
     {
         return ret;
     }
@@ -242,7 +242,7 @@ int main(void)
     /* bitfield count range */
     for (l = 0; l < 10000; ++l)
     {
-        if ((ret = test_bitfield_count_range()))
+        if ((ret = test_bitfield_count_range()) != 0)
         {
             return ret;
         }
index 41ff014f53ab95fa793de2569ef4c69b9f6d10ae..92cf7a583507bdb5190b28d1ce32c439d8aabaa0 100644 (file)
@@ -58,7 +58,7 @@ static size_t countRange(tr_bitfield const* b, size_t begin, size_t end)
     size_t const first_byte = begin >> 3u;
     size_t const last_byte = (end - 1) >> 3u;
 
-    if (!b->bit_count)
+    if (b->bit_count == 0)
     {
         return 0;
     }
@@ -163,8 +163,8 @@ bool tr_bitfieldHas(tr_bitfield const* b, size_t n)
 static bool tr_bitfieldIsValid(tr_bitfield const* b)
 {
     assert(b != NULL);
-    assert((b->alloc_count == 0) == (b->bits == 0));
-    assert(!b->bits || (b->true_count == countArray(b)));
+    assert((b->alloc_count == 0) == (b->bits == NULL));
+    assert(b->bits == NULL || b->true_count == countArray(b));
 
     return true;
 }
@@ -180,7 +180,7 @@ size_t tr_bitfieldCountTrueBits(tr_bitfield const* b)
 
 static size_t get_bytes_needed(size_t bit_count)
 {
-    return (bit_count >> 3) + (bit_count & 7 ? 1 : 0);
+    return (bit_count >> 3) + ((bit_count & 7) != 0 ? 1 : 0);
 }
 
 static void set_all_true(uint8_t* array, size_t bit_count)
@@ -203,7 +203,7 @@ void* tr_bitfieldGetRaw(tr_bitfield const* b, size_t* byte_count)
 
     assert(b->bit_count > 0);
 
-    if (b->alloc_count)
+    if (b->alloc_count != 0)
     {
         assert(b->alloc_count <= n);
         memcpy(bits, b->bits, b->alloc_count);
@@ -423,7 +423,7 @@ void tr_bitfieldAddRange(tr_bitfield* b, size_t begin, size_t end)
 
     end--;
 
-    if ((end >= b->bit_count) || (begin > end))
+    if (end >= b->bit_count || begin > end)
     {
         return;
     }
@@ -474,14 +474,14 @@ void tr_bitfieldRemRange(tr_bitfield* b, size_t begin, size_t end)
     unsigned char sm, em;
     size_t const diff = tr_bitfieldCountRange(b, begin, end);
 
-    if (!diff)
+    if (diff == 0)
     {
         return;
     }
 
     end--;
 
-    if ((end >= b->bit_count) || (begin > end))
+    if (end >= b->bit_count || begin > end)
     {
         return;
     }
index 94746e8f237fa143052ad4205522742e062068ba..71191adb5d8329675e28c4bb921249f44a9200e3 100644 (file)
@@ -87,7 +87,7 @@ static void blocklistLoad(tr_blocklistFile* b)
 
     b->rules = tr_sys_file_map_for_reading(fd, 0, byteCount, &error);
 
-    if (!b->rules)
+    if (b->rules == NULL)
     {
         tr_logAddError(err_fmt, b->filename, error->message);
         tr_sys_file_close(fd, NULL);
@@ -203,7 +203,7 @@ bool tr_blocklistFileHasAddress(tr_blocklistFile* b, tr_address const* addr)
 
     blocklistEnsureLoaded(b);
 
-    if (!b->rules || !b->ruleCount)
+    if (b->rules == NULL || b->ruleCount == 0)
     {
         return false;
     }
@@ -230,7 +230,7 @@ static bool parseLine1(char const* line, struct tr_ipv4_range* range)
 
     walk = strrchr(line, ':');
 
-    if (!walk)
+    if (walk == NULL)
     {
         return false;
     }
@@ -332,7 +332,7 @@ int tr_blocklistFileSetContent(tr_blocklistFile* b, char const* filename)
     size_t ranges_count = 0;
     tr_error* error = NULL;
 
-    if (!filename)
+    if (filename == NULL)
     {
         blocklistDelete(b);
         return 0;
index a8c5377033580110f6f8fc593b8f717ed6bc3122..a43c92f097218dae736d158575c1b6d95d3eff0c 100644 (file)
@@ -206,7 +206,7 @@ static int flushRuns(tr_cache* cache, struct run_info* runs, int n)
     int i;
     int err = 0;
 
-    for (i = 0; !err && i < n; i++)
+    for (i = 0; err == 0 && i < n; i++)
     {
         int j;
 
@@ -363,7 +363,7 @@ int tr_cacheReadBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t pie
     int err = 0;
     struct cache_block* cb = findBlock(cache, torrent, piece, offset);
 
-    if (cb)
+    if (cb != NULL)
     {
         evbuffer_copyout(cb->evbuf, setme, len);
     }
@@ -437,7 +437,7 @@ int tr_cacheFlushFile(tr_cache* cache, tr_torrent* torrent, tr_file_index_t i)
     dbgmsg("flushing file %d from cache to disk: blocks [%zu...%zu]", (int)i, (size_t)first, (size_t)last);
 
     /* flush out all the blocks in that file */
-    while (!err && (pos < tr_ptrArraySize(&cache->blocks)))
+    while (err == 0 && pos < tr_ptrArraySize(&cache->blocks))
     {
         struct cache_block const* b = tr_ptrArrayNth(&cache->blocks, pos);
 
@@ -446,7 +446,7 @@ int tr_cacheFlushFile(tr_cache* cache, tr_torrent* torrent, tr_file_index_t i)
             break;
         }
 
-        if ((b->block < first) || (b->block > last))
+        if (b->block < first || b->block > last)
         {
             break;
         }
@@ -463,7 +463,7 @@ int tr_cacheFlushTorrent(tr_cache* cache, tr_torrent* torrent)
     int const pos = findBlockPos(cache, torrent, 0);
 
     /* flush out all the blocks in that torrent */
-    while (!err && (pos < tr_ptrArraySize(&cache->blocks)))
+    while (err == 0 && pos < tr_ptrArraySize(&cache->blocks))
     {
         struct cache_block const* b = tr_ptrArrayNth(&cache->blocks, pos);
 
index e690157ddcd9963d8feb3adb229c4c8b317cad28..4b6e29c4e3535e0af12d27b598c282f82f7140ea 100644 (file)
@@ -41,7 +41,7 @@ static bool getShadowInt(uint8_t ch, int* setme)
     char const* str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.-";
     char const* pch = strchr(str, ch);
 
-    if (!pch)
+    if (pch == NULL)
     {
         return false;
     }
@@ -175,7 +175,7 @@ char* tr_clientForId(char* buf, size_t buflen, void const* id_in)
 
     *buf = '\0';
 
-    if (!id)
+    if (id == NULL)
     {
         return buf;
     }
@@ -196,7 +196,7 @@ char* tr_clientForId(char* buf, size_t buflen, void const* id_in)
             else /* current client style: -TR111Z- is 1.11+ */
             {
                 tr_snprintf(buf, buflen, "Transmission %d.%02d%s", strint(id + 3, 1), strint(id + 4, 2),
-                    id[6] == 'Z' || id[6] == 'X' ? "+" : "");
+                    (id[6] == 'Z' || id[6] == 'X') ? "+" : "");
             }
         }
         else if (strncmp(chid + 1, "UT", 2) == 0)
@@ -755,11 +755,11 @@ char* tr_clientForId(char* buf, size_t buflen, void const* id_in)
     }
 
     /* Shad0w-style */
-    if (!*buf)
+    if (*buf == '\0')
     {
         int a, b, c;
 
-        if (strchr("AOQRSTU", id[0]) && getShadowInt(id[1], &a) && getShadowInt(id[2], &b) && getShadowInt(id[3], &c))
+        if (strchr("AOQRSTU", id[0]) != NULL && getShadowInt(id[1], &a) && getShadowInt(id[2], &b) && getShadowInt(id[3], &c))
         {
             char const* name = NULL;
 
@@ -794,7 +794,7 @@ char* tr_clientForId(char* buf, size_t buflen, void const* id_in)
                 break;
             }
 
-            if (name)
+            if (name != NULL)
             {
                 tr_snprintf(buf, buflen, "%s %d.%d.%d", name, a, b, c);
                 return buf;
@@ -803,7 +803,7 @@ char* tr_clientForId(char* buf, size_t buflen, void const* id_in)
     }
 
     /* No match */
-    if (!*buf)
+    if (*buf == '\0')
     {
         char out[32], * walk = out;
         char const* in, * in_end;
index 2251a5420ef5657c3f2943c81e9134c5d07e6fbc..159afbd073a3db479d410a8cfc6a0a93b785a74a 100644 (file)
@@ -186,7 +186,7 @@ uint64_t tr_cpSizeWhenDone(tr_completion const* ccp)
                     n = tr_bitfieldCountRange(&cp->blockBitfield, f, l + 1);
                     n *= cp->tor->blockSize;
 
-                    if (l == (cp->tor->blockCount - 1) && tr_bitfieldHas(&cp->blockBitfield, l))
+                    if (l == cp->tor->blockCount - 1 && tr_bitfieldHas(&cp->blockBitfield, l))
                     {
                         n -= (cp->tor->blockSize - cp->tor->lastBlockSize);
                     }
@@ -354,5 +354,5 @@ double tr_cpPercentDone(tr_completion const* cp)
 {
     double const ratio = tr_getRatio(cp->sizeNow, tr_cpSizeWhenDone(cp));
     int const iratio = (int)ratio;
-    return ((iratio == TR_RATIO_NA) || (iratio == TR_RATIO_INF)) ? 0.0 : ratio;
+    return (iratio == TR_RATIO_NA || iratio == TR_RATIO_INF) ? 0.0 : ratio;
 }
index 7bc600946951fcba55c90b08ee6629d63cc7d109..ec335b9cd5f010264e1b7d9e143e8f057c83292b 100644 (file)
@@ -174,7 +174,7 @@ void tr_cryptoSetTorrentHash(tr_crypto* crypto, uint8_t const* hash)
 {
     crypto->torrentHashIsSet = hash != NULL;
 
-    if (hash)
+    if (hash != NULL)
     {
         memcpy(crypto->torrentHash, hash, SHA_DIGEST_LENGTH);
     }
index ab42e019ff1cc29605bcd8d78a4deda4c274691b..2cb43ef64c998ec1f838cd0410f328dac5095c22 100644 (file)
@@ -316,7 +316,7 @@ static void fileset_close_torrent(struct tr_fileset* set, int torrent_id)
     {
         for (o = set->begin; o != set->end; ++o)
         {
-            if ((o->torrent_id == torrent_id) && cached_file_is_open(o))
+            if (o->torrent_id == torrent_id && cached_file_is_open(o))
             {
                 cached_file_close(o);
             }
@@ -332,7 +332,7 @@ static struct tr_cached_file* fileset_lookup(struct tr_fileset* set, int torrent
     {
         for (o = set->begin; o != set->end; ++o)
         {
-            if ((torrent_id == o->torrent_id) && (i == o->file_index) && cached_file_is_open(o))
+            if (torrent_id == o->torrent_id && i == o->file_index && cached_file_is_open(o))
             {
                 return o;
             }
@@ -362,7 +362,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)
         {
-            if (!cull || o->used_at < cull->used_at)
+            if (cull == NULL || o->used_at < cull->used_at)
             {
                 cull = o;
             }
@@ -425,7 +425,7 @@ static void ensureSessionFdInfoExists(tr_session* session)
 
 void tr_fdClose(tr_session* session)
 {
-    if (session && session->fdInfo)
+    if (session != NULL && session->fdInfo != NULL)
     {
         struct tr_fdInfo* i = session->fdInfo;
         fileset_destruct(&i->fileset);
@@ -440,7 +440,7 @@ void tr_fdClose(tr_session* session)
 
 static struct tr_fileset* get_fileset(tr_session* session)
 {
-    if (!session)
+    if (session == NULL)
     {
         return NULL;
     }
@@ -453,7 +453,7 @@ void tr_fdFileClose(tr_session* s, tr_torrent const* tor, tr_file_index_t i)
 {
     struct tr_cached_file* o;
 
-    if ((o = fileset_lookup(get_fileset(s), tr_torrentId(tor), i)))
+    if ((o = fileset_lookup(get_fileset(s), tr_torrentId(tor), i)) != NULL)
     {
         /* flush writable files so that their mtimes will be
          * up-to-date when this function returns to the caller... */
@@ -470,7 +470,7 @@ tr_sys_file_t tr_fdFileGetCached(tr_session* s, int torrent_id, tr_file_index_t
 {
     struct tr_cached_file* o = fileset_lookup(get_fileset(s), torrent_id, i);
 
-    if (!o || (writable && !o->is_writable))
+    if (o == NULL || (writable && !o->is_writable))
     {
         return TR_BAD_SYS_FILE;
     }
@@ -485,7 +485,7 @@ bool tr_fdFileGetCachedMTime(tr_session* s, int torrent_id, tr_file_index_t i, t
     tr_sys_path_info info;
     struct tr_cached_file* o = fileset_lookup(get_fileset(s), torrent_id, i);
 
-    if ((success = (o != NULL) && tr_sys_file_get_info(o->fd, &info, NULL)))
+    if ((success = o != NULL && tr_sys_file_get_info(o->fd, &info, NULL)))
     {
         *mtime = info.last_modified_at;
     }
@@ -507,11 +507,11 @@ tr_sys_file_t tr_fdFileCheckout(tr_session* session, int torrent_id, tr_file_ind
     struct tr_fileset* set = get_fileset(session);
     struct tr_cached_file* o = fileset_lookup(set, torrent_id, i);
 
-    if (o && writable && !o->is_writable)
+    if (o != NULL && writable && !o->is_writable)
     {
         cached_file_close(o); /* close it so we can reopen in rw mode */
     }
-    else if (!o)
+    else if (o == NULL)
     {
         o = fileset_get_empty_slot(set);
     }
@@ -520,7 +520,7 @@ tr_sys_file_t tr_fdFileCheckout(tr_session* session, int torrent_id, tr_file_ind
     {
         int const err = cached_file_open(o, filename, writable, allocation, file_size);
 
-        if (err)
+        if (err != 0)
         {
             errno = err;
             return TR_BAD_SYS_FILE;
@@ -609,7 +609,7 @@ tr_socket_t tr_fdSocketAccept(tr_session* s, tr_socket_t sockfd, tr_address* add
 
     if (fd != TR_BAD_SOCKET)
     {
-        if ((gFd->peerCount < s->peerLimit) && tr_address_from_sockaddr_storage(addr, port, &sock))
+        if (gFd->peerCount < s->peerLimit && tr_address_from_sockaddr_storage(addr, port, &sock))
         {
             ++gFd->peerCount;
         }
index 2a0acb892e98021bc84df2715225c364c1b102ee..dc0c7a66acc726ce0bf92f061b89be8fc5622025 100644 (file)
@@ -186,9 +186,9 @@ static bool buildHandshakeMessage(tr_handshake* handshake, uint8_t* buf)
     tr_torrent* tor;
     bool success;
 
-    if ((torrentHash = tr_cryptoGetTorrentHash(handshake->crypto)))
+    if ((torrentHash = tr_cryptoGetTorrentHash(handshake->crypto)) != NULL)
     {
-        if ((tor = tr_torrentFindFromHash(handshake->session, torrentHash)))
+        if ((tor = tr_torrentFindFromHash(handshake->session, torrentHash)) != NULL)
         {
             peer_id = tr_torrentGetPeerId(tor);
         }
@@ -321,7 +321,7 @@ static void sendYa(tr_handshake* handshake)
     /* add our public key (Ya) */
     public_key = tr_cryptoGetMyPublicKey(handshake->crypto, &len);
     assert(len == KEY_LEN);
-    assert(public_key);
+    assert(public_key != NULL);
     memcpy(walk, public_key, len);
     walk += len;
 
@@ -556,7 +556,7 @@ static ReadState readCryptoSelect(tr_handshake* handshake, struct evbuffer* inbu
     handshake->crypto_select = crypto_select;
     dbgmsg(handshake, "crypto select is %d", (int)crypto_select);
 
-    if (!(crypto_select & getCryptoProvide(handshake)))
+    if ((crypto_select & getCryptoProvide(handshake)) == 0)
     {
         dbgmsg(handshake, "peer selected an encryption option we didn't offer");
         return tr_handshakeDone(handshake, false);
@@ -742,7 +742,7 @@ static ReadState readPeerId(tr_handshake* handshake, struct evbuffer* inbuf)
 
     /* if we've somehow connected to ourselves, don't keep the connection */
     tor = tr_torrentFindFromHash(handshake->session, tr_peerIoGetTorrentHash(handshake->io));
-    connected_to_self = (tor != NULL) && memcmp(peer_id, tr_torrentGetPeerId(tor), PEER_ID_LEN) == 0;
+    connected_to_self = tor != NULL && memcmp(peer_id, tr_torrentGetPeerId(tor), PEER_ID_LEN) == 0;
 
     return tr_handshakeDone(handshake, !connected_to_self);
 }
@@ -938,7 +938,7 @@ static ReadState readIA(tr_handshake* handshake, struct evbuffer* inbuf)
     /* send crypto_select */
     crypto_select = getCryptoSelect(handshake, handshake->crypto_provide);
 
-    if (crypto_select)
+    if (crypto_select != 0)
     {
         dbgmsg(handshake, "selecting crypto mode '%d'", (int)crypto_select);
         evbuffer_add_uint32(outbuf, crypto_select);
@@ -1115,7 +1115,7 @@ static ReadState canRead(struct tr_peerIo* io, void* arg, size_t* piece)
 
 static bool fireDoneFunc(tr_handshake* handshake, bool isConnected)
 {
-    uint8_t const* peer_id = isConnected && handshake->havePeerID ? tr_peerIoGetPeersId(handshake->io) : NULL;
+    uint8_t const* peer_id = (isConnected && handshake->havePeerID) ? tr_peerIoGetPeersId(handshake->io) : NULL;
     bool const success = (*handshake->doneCB)(handshake, handshake->io, handshake->haveReadAnythingFromPeer, isConnected,
         peer_id, handshake->doneUserData);
 
@@ -1124,7 +1124,7 @@ static bool fireDoneFunc(tr_handshake* handshake, bool isConnected)
 
 static void tr_handshakeFree(tr_handshake* handshake)
 {
-    if (handshake->io)
+    if (handshake->io != NULL)
     {
         tr_peerIoUnref(handshake->io); /* balanced by the ref in tr_handshakeNew */
     }
@@ -1160,7 +1160,7 @@ static void gotError(tr_peerIo* io, short what, void* vhandshake)
     int errcode = errno;
     tr_handshake* handshake = vhandshake;
 
-    if (io->utp_socket && !io->isIncoming && handshake->state == AWAITING_YB)
+    if (io->utp_socket != NULL && !io->isIncoming && handshake->state == AWAITING_YB)
     {
         /* This peer probably doesn't speak uTP. */
 
@@ -1194,8 +1194,8 @@ static void gotError(tr_peerIo* io, short what, void* vhandshake)
     /* if the error happened while we were sending a public key, we might
      * have encountered a peer that doesn't do encryption... reconnect and
      * try a plaintext handshake */
-    if (((handshake->state == AWAITING_YB) || (handshake->state == AWAITING_VC)) &&
-        (handshake->encryptionMode != TR_ENCRYPTION_REQUIRED) && (!tr_peerIoReconnect(handshake->io)))
+    if ((handshake->state == AWAITING_YB || handshake->state == AWAITING_VC) &&
+        handshake->encryptionMode != TR_ENCRYPTION_REQUIRED && tr_peerIoReconnect(handshake->io) == 0)
     {
         uint8_t msg[HANDSHAKE_SIZE];
 
index b64e93d41092a56cbe6c875fd93e22e62eaffddf..2aa8b3ee64899dc2b462ed321a6b9a768e145264 100644 (file)
@@ -34,7 +34,7 @@ void tr_historyAdd(tr_recentHistory* h, time_t now, unsigned int n)
 unsigned int tr_historyGet(tr_recentHistory const* h, time_t now, unsigned int sec)
 {
     unsigned int n = 0;
-    time_t const cutoff = (now ? now : tr_time()) - sec;
+    time_t const cutoff = (now != 0 ? now : tr_time()) - sec;
     int i = h->newest;
 
     for (;;)
index a1f13a7bda6dcbaf53a9751ad5c4f39119ce4512..afa2c975b4f02acc179dbb0b863ff7a0b229d7af 100644 (file)
@@ -47,10 +47,10 @@ static int readOrWriteBytes(tr_session* session, tr_torrent* tor, int ioMode, tr
     tr_file const* const file = &info->files[fileIndex];
 
     assert(fileIndex < info->fileCount);
-    assert(!file->length || (fileOffset < file->length));
+    assert(file->length == 0 || fileOffset < file->length);
     assert(fileOffset + buflen <= file->length);
 
-    if (!file->length)
+    if (file->length == 0)
     {
         return 0;
     }
@@ -82,11 +82,11 @@ static int readOrWriteBytes(tr_session* session, tr_torrent* tor, int ioMode, tr
                 tr_strdup(file->name);
         }
 
-        if (!err)
+        if (err == 0)
         {
             /* open (and maybe create) the file */
             char* filename = tr_buildPath(base, subpath, NULL);
-            int const prealloc = file->dnd || !doWrite ? TR_PREALLOCATE_NONE : tor->session->preallocationMode;
+            int const prealloc = (file->dnd || !doWrite) ? TR_PREALLOCATE_NONE : tor->session->preallocationMode;
 
             if ((fd = tr_fdFileCheckout(session, tor->uniqueId, fileIndex, filename, doWrite, prealloc,
                     file->length)) == TR_BAD_SYS_FILE)
@@ -110,7 +110,7 @@ static int readOrWriteBytes(tr_session* session, tr_torrent* tor, int ioMode, tr
     ****  Use the fd
     ***/
 
-    if (!err)
+    if (err == 0)
     {
         tr_error* error = NULL;
 
@@ -211,7 +211,7 @@ static int readOrWritePiece(tr_torrent* tor, int ioMode, tr_piece_index_t pieceI
         fileIndex++;
         fileOffset = 0;
 
-        if ((err != 0) && (ioMode == TR_IO_WRITE) && (tor->error != TR_STAT_LOCAL_ERROR))
+        if (err != 0 && ioMode == TR_IO_WRITE && tor->error != TR_STAT_LOCAL_ERROR)
         {
             char* path = tr_buildPath(tor->downloadDir, file->name, NULL);
             tr_torrentSetLocalError(tor, "%s (%s)", tr_strerror(err), path);
@@ -264,7 +264,7 @@ static bool recalculateHash(tr_torrent* tor, tr_piece_index_t pieceIndex, uint8_
     while (bytesLeft)
     {
         size_t const len = MIN(bytesLeft, buflen);
-        success = !tr_cacheReadBlock(tor->session->cache, tor, pieceIndex, offset, len, buffer);
+        success = tr_cacheReadBlock(tor->session->cache, tor, pieceIndex, offset, len, buffer) == 0;
 
         if (!success)
         {
index 060c5096a5d3973036b0dd793638c7abdbf87b4a..4e3d8c7a9389e4ab216fcac2bf1a6f5c0f10af0a 100644 (file)
@@ -60,7 +60,7 @@ static int test_elements(void)
     check(tr_variantDictFindStr(&top, tr_quark_new("null", 4), &str, NULL));
     check_streq("", str);
 
-    if (!err)
+    if (err == 0)
     {
         tr_variantFree(&top);
     }
@@ -78,24 +78,24 @@ static int test_utf8(void)
     tr_quark const key = tr_quark_new("key", 3);
 
     err = tr_variantFromJson(&top, in, strlen(in));
-    check(!err);
+    check(err == 0);
     check(tr_variantIsDict(&top));
     check(tr_variantDictFindStr(&top, key, &str, NULL));
     check_streq("Letöltések", str);
 
-    if (!err)
+    if (err == 0)
     {
         tr_variantFree(&top);
     }
 
     in = "{ \"key\": \"\\u005C\" }";
     err = tr_variantFromJson(&top, in, strlen(in));
-    check(!err);
+    check(err == 0);
     check(tr_variantIsDict(&top));
     check(tr_variantDictFindStr(&top, key, &str, NULL));
     check_streq("\\", str);
 
-    if (!err)
+    if (err == 0)
     {
         tr_variantFree(&top);
     }
@@ -110,13 +110,13 @@ static int test_utf8(void)
      */
     in = "{ \"key\": \"Let\\u00f6lt\\u00e9sek\" }";
     err = tr_variantFromJson(&top, in, strlen(in));
-    check(!err);
+    check(err == 0);
     check(tr_variantIsDict(&top));
     check(tr_variantDictFindStr(&top, key, &str, NULL));
     check_streq("Letöltések", str);
     json = tr_variantToStr(&top, TR_VARIANT_FMT_JSON, NULL);
 
-    if (!err)
+    if (err == 0)
     {
         tr_variantFree(&top);
     }
@@ -125,12 +125,12 @@ static int test_utf8(void)
     check(strstr(json, "\\u00f6") != NULL);
     check(strstr(json, "\\u00e9") != NULL);
     err = tr_variantFromJson(&top, json, strlen(json));
-    check(!err);
+    check(err == 0);
     check(tr_variantIsDict(&top));
     check(tr_variantDictFindStr(&top, key, &str, NULL));
     check_streq("Letöltések", str);
 
-    if (!err)
+    if (err == 0)
     {
         tr_variantFree(&top);
     }
@@ -160,20 +160,20 @@ static int test1(void)
     int64_t i;
     int const err = tr_variantFromJson(&top, in, strlen(in));
 
-    check(!err);
+    check(err == 0);
     check(tr_variantIsDict(&top));
-    check((headers = tr_variantDictFind(&top, tr_quark_new("headers", 7))));
+    check((headers = tr_variantDictFind(&top, tr_quark_new("headers", 7))) != NULL);
     check(tr_variantIsDict(headers));
     check(tr_variantDictFindStr(headers, tr_quark_new("type", 4), &str, NULL));
     check_streq("request", str);
     check(tr_variantDictFindInt(headers, TR_KEY_tag, &i));
     check_int_eq(666, i);
-    check((body = tr_variantDictFind(&top, tr_quark_new("body", 4))));
+    check((body = tr_variantDictFind(&top, tr_quark_new("body", 4))) != NULL);
     check(tr_variantDictFindStr(body, TR_KEY_name, &str, NULL));
     check_streq("torrent-info", str);
-    check((args = tr_variantDictFind(body, tr_quark_new("arguments", 9))));
+    check((args = tr_variantDictFind(body, tr_quark_new("arguments", 9))) != NULL);
     check(tr_variantIsDict(args));
-    check((ids = tr_variantDictFind(args, TR_KEY_ids)));
+    check((ids = tr_variantDictFind(args, TR_KEY_ids)) != NULL);
     check(tr_variantIsList(ids));
     check_uint_eq(2, tr_variantListSize(ids));
     check(tr_variantGetInt(tr_variantListChild(ids, 0), &i));
@@ -194,7 +194,7 @@ static int test2(void)
     top.type = 0;
     err = tr_variantFromJson(&top, in, strlen(in));
 
-    check(err);
+    check(err != 0);
     check(!tr_variantIsDict(&top));
 
     return 0;
@@ -212,7 +212,7 @@ static int test3(void)
     char const* str;
 
     int const err = tr_variantFromJson(&top, in, strlen(in));
-    check(!err);
+    check(err == 0);
     check(tr_variantDictFindStr(&top, TR_KEY_errorString, &str, NULL));
     check_streq("torrent not registered with this tracker 6UHsVW'*C", str);
 
@@ -261,7 +261,7 @@ int main(void)
     /* run the tests in a locale with a decimal point of '.' */
     setlocale(LC_NUMERIC, "C");
 
-    if ((rv = runTests(tests, NUM_TESTS(tests))))
+    if ((rv = runTests(tests, NUM_TESTS(tests))) != 0)
     {
         return rv;
     }
@@ -282,7 +282,7 @@ int main(void)
         fprintf(stderr, "WARNING: unable to run locale-specific json tests. add a locale like %s or %s\n", comma_locales[0],
             comma_locales[1]);
     }
-    else if ((rv = runTests(tests, NUM_TESTS(tests))))
+    else if ((rv = runTests(tests, NUM_TESTS(tests))) != 0)
     {
         return rv;
     }
index bd9be005e533ef607a0edd04606a3ac08a23036e..90f4be1e5d2c6ee107abbbb92c8055c69eb7d535 100644 (file)
@@ -74,8 +74,8 @@ bool check_streq_impl(char const* file, int line, char const* expected, char con
         }
         else
         {
-            fprintf(stderr, "FAIL %s:%d, expected \"%s\", got \"%s\"\n", file, line, expected ? expected : " (null)",
-                actual ? actual : " (null)");
+            fprintf(stderr, "FAIL %s:%d, expected \"%s\", got \"%s\"\n", file, line, expected != NULL ? expected : "(null)",
+                actual != NULL ? actual : "(null)");
         }
     }
 
@@ -148,7 +148,7 @@ int runTests(testFunc const* const tests, int numTests)
 
     for (i = 0; i < numTests; i++)
     {
-        if ((ret = (*tests[i])()))
+        if ((ret = (*tests[i])()) != 0)
         {
             return ret;
         }
@@ -313,21 +313,21 @@ tr_session* libttest_session_init(tr_variant* settings)
 
     q = TR_KEY_port_forwarding_enabled;
 
-    if (!tr_variantDictFind(settings, q))
+    if (tr_variantDictFind(settings, q) == NULL)
     {
         tr_variantDictAddBool(settings, q, false);
     }
 
     q = TR_KEY_dht_enabled;
 
-    if (!tr_variantDictFind(settings, q))
+    if (tr_variantDictFind(settings, q) == NULL)
     {
         tr_variantDictAddBool(settings, q, false);
     }
 
     q = TR_KEY_message_level;
 
-    if (!tr_variantDictFind(settings, q))
+    if (tr_variantDictFind(settings, q) == NULL)
     {
         tr_variantDictAddInt(settings, q, verbose ? TR_LOG_DEBUG : TR_LOG_ERROR);
     }
@@ -402,7 +402,7 @@ tr_torrent* libttest_zero_torrent_init(tr_session* session)
     /* create the torrent */
     err = 0;
     tor = tr_torrentNew(ctor, &err, NULL);
-    assert(!err);
+    assert(err == 0);
 
     /* cleanup */
     tr_free(metainfo);
@@ -423,7 +423,7 @@ void libttest_zero_torrent_populate(tr_torrent* tor, bool complete)
         char* dirname;
         tr_file const* file = &tor->info.files[i];
 
-        if (!complete && (i == 0))
+        if (!complete && i == 0)
         {
             path = tr_strdup_printf("%s%c%s.part", tor->currentDir, TR_PATH_DELIMITER, file->name);
         }
index 76fb2153fe9b43bec3e3061fee595ac2ac784dce..4453c3e30cc78d99d91cc15fbad6f51fbaeb7f75 100644 (file)
@@ -19,7 +19,7 @@ static tr_lock* getRecycledNodesLock(void)
 {
     static tr_lock* l = NULL;
 
-    if (!l)
+    if (l == NULL)
     {
         l = tr_lockNew();
     }
@@ -71,12 +71,12 @@ static void node_free(tr_list* node)
 
 void tr_list_free(tr_list** list, TrListForeachFunc data_free_func)
 {
-    while (*list)
+    while (*list != NULL)
     {
         tr_list* node = *list;
         *list = (*list)->next;
 
-        if (data_free_func)
+        if (data_free_func != NULL)
         {
             data_free_func(node->data);
         }
@@ -92,7 +92,7 @@ void tr_list_prepend(tr_list** list, void* data)
     node->data = data;
     node->next = *list;
 
-    if (*list)
+    if (*list != NULL)
     {
         (*list)->prev = node;
     }
@@ -106,7 +106,7 @@ void tr_list_append(tr_list** list, void* data)
 
     node->data = data;
 
-    if (!*list)
+    if (*list == NULL)
     {
         *list = node;
     }
@@ -114,7 +114,7 @@ void tr_list_append(tr_list** list, void* data)
     {
         tr_list* l = *list;
 
-        while (l->next)
+        while (l->next != NULL)
         {
             l = l->next;
         }
@@ -126,7 +126,7 @@ void tr_list_append(tr_list** list, void* data)
 
 static tr_list* tr_list_find_data(tr_list* list, void const* data)
 {
-    for (; list; list = list->next)
+    for (; list != NULL; list = list->next)
     {
         if (list->data == data)
         {
@@ -140,15 +140,15 @@ static tr_list* tr_list_find_data(tr_list* list, void const* data)
 static void* tr_list_remove_node(tr_list** list, tr_list* node)
 {
     void* data;
-    tr_list* prev = node ? node->prev : NULL;
-    tr_list* next = node ? node->next : NULL;
+    tr_list* prev = node != NULL ? node->prev : NULL;
+    tr_list* next = node != NULL ? node->next : NULL;
 
-    if (prev)
+    if (prev != NULL)
     {
         prev->next = next;
     }
 
-    if (next)
+    if (next != NULL)
     {
         next->prev = prev;
     }
@@ -167,7 +167,7 @@ void* tr_list_pop_front(tr_list** list)
 {
     void* ret = NULL;
 
-    if (*list)
+    if (*list != NULL)
     {
         ret = (*list)->data;
         tr_list_remove_node(list, *list);
@@ -188,9 +188,9 @@ void* tr_list_remove(tr_list** list, void const* b, TrListCompareFunc compare_fu
 
 tr_list* tr_list_find(tr_list* list, void const* b, TrListCompareFunc func)
 {
-    for (; list; list = list->next)
+    for (; list != NULL; list = list->next)
     {
-        if (!func(list->data, b))
+        if (func(list->data, b) == 0)
         {
             return list;
         }
@@ -237,7 +237,7 @@ int tr_list_size(tr_list const* list)
 {
     int size = 0;
 
-    while (list)
+    while (list != NULL)
     {
         ++size;
         list = list->next;
index 5d34d6dec297cb83cd53e3ff3cd497db6cebee70..bfea61f363fbc9fb08e955811a0f2d65a30d44af 100644 (file)
@@ -56,7 +56,7 @@ static tr_lock* getMessageLock(void)
 {
     static tr_lock* l = NULL;
 
-    if (!l)
+    if (l == NULL)
     {
         l = tr_lockNew();
     }
@@ -125,7 +125,7 @@ void tr_logFreeQueue(tr_log_message* list)
 {
     tr_log_message* next;
 
-    while (NULL != list)
+    while (list != NULL)
     {
         next = list->next;
         tr_free(list->message);
@@ -185,7 +185,7 @@ void tr_logAddDeep(char const* file, int line, char const* name, char const* fmt
 
         evbuffer_add_printf(buf, "[%s] ", tr_logGetTimeStr(timestr, sizeof(timestr)));
 
-        if (name)
+        if (name != NULL)
         {
             evbuffer_add_printf(buf, "%s ", name);
         }
@@ -248,7 +248,7 @@ void tr_logAddMessage(char const* file, int line, tr_log_level level, char const
 
 #endif
 
-    if (*buf)
+    if (*buf != '\0')
     {
         if (tr_logGetQueueEnabled())
         {
@@ -289,7 +289,7 @@ void tr_logAddMessage(char const* file, int line, tr_log_level level, char const
 
             tr_logGetTimeStr(timestr, sizeof(timestr));
 
-            if (name)
+            if (name != NULL)
             {
                 tr_sys_file_write_fmt(fp, "[%s] %s: %s" TR_NATIVE_EOL_STR, NULL, timestr, name, buf);
             }
index 6fc83c851197e3376f3e0f768edf1691a370de8f..39cceac07ab073aa82e00d7e0474c8bc83b0de2a 100644 (file)
@@ -124,7 +124,7 @@ tr_magnet_info* tr_magnetParse(char const* uri)
     {
         char const* walk;
 
-        for (walk = uri + 8; walk && *walk;)
+        for (walk = uri + 8; walk != NULL && *walk != '\0';)
         {
             char const* key = walk;
             char const* delim = strchr(key, '=');
@@ -180,7 +180,7 @@ tr_magnet_info* tr_magnetParse(char const* uri)
                 displayName = tr_http_unescape(val, vallen);
             }
 
-            if ((vallen > 0) && (trCount < MAX_TRACKERS))
+            if (vallen > 0 && trCount < MAX_TRACKERS)
             {
                 int i;
 
@@ -188,7 +188,7 @@ tr_magnet_info* tr_magnetParse(char const* uri)
                 {
                     tr[trCount++] = tr_http_unescape(val, vallen);
                 }
-                else if ((sscanf(key, "tr.%d=", &i) == 1) && (i >= 0)) /* ticket #3341 and #5134 */
+                else if (sscanf(key, "tr.%d=", &i) == 1 && i >= 0) /* ticket #3341 and #5134 */
                 {
                     tr[trCount++] = tr_http_unescape(val, vallen);
                 }
index c0cc8a8698aa2aa6600a88307329e0f156a98966..ffa27de5331068aac494be3a8a79d939f8d148b5 100644 (file)
@@ -91,32 +91,32 @@ static uint32_t bestPieceSize(uint64_t totalSize)
     uint32_t const MiB = 1048576;
     uint32_t const GiB = 1073741824;
 
-    if (totalSize >= (2 * GiB))
+    if (totalSize >= 2 * GiB)
     {
         return 2 * MiB;
     }
 
-    if (totalSize >= (1 * GiB))
+    if (totalSize >= 1 * GiB)
     {
         return 1 * MiB;
     }
 
-    if (totalSize >= (512 * MiB))
+    if (totalSize >= 512 * MiB)
     {
         return 512 * KiB;
     }
 
-    if (totalSize >= (350 * MiB))
+    if (totalSize >= 350 * MiB)
     {
         return 256 * KiB;
     }
 
-    if (totalSize >= (150 * MiB))
+    if (totalSize >= 150 * MiB)
     {
         return 128 * KiB;
     }
 
-    if (totalSize >= (50 * MiB))
+    if (totalSize >= 50 * MiB)
     {
         return 64 * KiB;
     }
@@ -183,7 +183,7 @@ tr_metainfo_builder* tr_metaInfoBuilderCreate(char const* topFileArg)
 
 static bool isValidPieceSize(uint32_t n)
 {
-    bool const isPowerOfTwo = !(n == 0) && !(n & (n - 1));
+    bool const isPowerOfTwo = n != 0 && (n & (n - 1)) == 0;
 
     return isPowerOfTwo;
 }
@@ -203,7 +203,7 @@ bool tr_metaInfoBuilderSetPieceSize(tr_metainfo_builder* b, uint32_t bytes)
     b->pieceSize = bytes;
     b->pieceCount = (int)(b->totalSize / b->pieceSize);
 
-    if (b->totalSize % b->pieceSize)
+    if (b->totalSize % b->pieceSize != 0)
     {
         ++b->pieceCount;
     }
@@ -213,7 +213,7 @@ bool tr_metaInfoBuilderSetPieceSize(tr_metainfo_builder* b, uint32_t bytes)
 
 void tr_metaInfoBuilderFree(tr_metainfo_builder* builder)
 {
-    if (builder)
+    if (builder != NULL)
     {
         int i;
         tr_file_index_t t;
@@ -253,7 +253,7 @@ static uint8_t* getHashInfo(tr_metainfo_builder* b)
     tr_sys_file_t fd;
     tr_error* error = NULL;
 
-    if (!b->totalSize)
+    if (b->totalSize == 0)
     {
         return ret;
     }
@@ -282,7 +282,7 @@ static uint8_t* getHashInfo(tr_metainfo_builder* b)
 
         assert(b->pieceIndex < b->pieceCount);
 
-        while (leftInPiece)
+        while (leftInPiece != 0)
         {
             uint64_t const n_this_pass = MIN(b->files[fileIndex].size - off, leftInPiece);
             uint64_t n_read = 0;
@@ -330,7 +330,7 @@ static uint8_t* getHashInfo(tr_metainfo_builder* b)
         ++b->pieceIndex;
     }
 
-    assert(b->abortFlag || (walk - ret == (int)(SHA_DIGEST_LENGTH * b->pieceCount)));
+    assert(b->abortFlag || walk - ret == (int)(SHA_DIGEST_LENGTH * b->pieceCount));
     assert(b->abortFlag || !totalRemain);
 
     if (fd != TR_BAD_SYS_FILE)
@@ -367,9 +367,9 @@ static void getFileInfo(char const* topFile, tr_metainfo_builder_file const* fil
         char* walk = filename;
         char const* token;
 
-        while ((token = tr_strsep(&walk, TR_PATH_DELIMITER_STR)))
+        while ((token = tr_strsep(&walk, TR_PATH_DELIMITER_STR)) != NULL)
         {
-            if (*token)
+            if (*token != '\0')
             {
                 tr_variantListAddStr(uninitialized_path, token);
             }
@@ -414,7 +414,7 @@ static void makeInfoDict(tr_variant* dict, tr_metainfo_builder* builder)
 
     tr_variantDictAddInt(dict, TR_KEY_piece_length, builder->pieceSize);
 
-    if ((pch = getHashInfo(builder)))
+    if ((pch = getHashInfo(builder)) != NULL)
     {
         tr_variantDictAddRaw(dict, TR_KEY_pieces, pch, SHA_DIGEST_LENGTH * builder->pieceCount);
         tr_free(pch);
@@ -440,7 +440,7 @@ static void tr_realMakeMetaInfo(tr_metainfo_builder* builder)
 
     tr_variantInitDict(&top, 6);
 
-    if (!builder->fileCount || !builder->totalSize || !builder->pieceSize || !builder->pieceCount)
+    if (builder->fileCount == 0 || builder->totalSize == 0 || builder->pieceSize == 0 || builder->pieceCount == 0)
     {
         builder->errfile[0] = '\0';
         builder->my_errno = ENOENT;
@@ -448,7 +448,7 @@ static void tr_realMakeMetaInfo(tr_metainfo_builder* builder)
         builder->isDone = true;
     }
 
-    if (!builder->result && builder->trackerCount)
+    if (builder->result == TR_MAKEMETA_OK && builder->trackerCount != 0)
     {
         int prevTier = -1;
         tr_variant* tier = NULL;
@@ -472,9 +472,9 @@ static void tr_realMakeMetaInfo(tr_metainfo_builder* builder)
         tr_variantDictAddStr(&top, TR_KEY_announce, builder->trackers[0].announce);
     }
 
-    if (!builder->result && !builder->abortFlag)
+    if (builder->result == TR_MAKEMETA_OK && !builder->abortFlag)
     {
-        if (builder->comment && *builder->comment)
+        if (builder->comment != NULL && *builder->comment != '\0')
         {
             tr_variantDictAddStr(&top, TR_KEY_comment, builder->comment);
         }
@@ -486,9 +486,9 @@ static void tr_realMakeMetaInfo(tr_metainfo_builder* builder)
     }
 
     /* save the file */
-    if (!builder->result && !builder->abortFlag)
+    if (builder->result == TR_MAKEMETA_OK && !builder->abortFlag)
     {
-        if (tr_variantToFile(&top, TR_VARIANT_FMT_BENC, builder->outputFile))
+        if (tr_variantToFile(&top, TR_VARIANT_FMT_BENC, builder->outputFile) != 0)
         {
             builder->my_errno = errno;
             tr_strlcpy(builder->errfile, builder->outputFile, sizeof(builder->errfile));
@@ -521,7 +521,7 @@ static tr_lock* getQueueLock(void)
 {
     static tr_lock* lock = NULL;
 
-    if (!lock)
+    if (lock == NULL)
     {
         lock = tr_lockNew();
     }
@@ -539,7 +539,7 @@ static void makeMetaWorkerFunc(void* unused UNUSED)
         tr_lock* lock = getQueueLock();
         tr_lockLock(lock);
 
-        if (queue)
+        if (queue != NULL)
         {
             builder = queue;
             queue = queue->nextBuilder;
@@ -594,7 +594,7 @@ void tr_makeMetaInfo(tr_metainfo_builder* builder, char const* outputFile, tr_tr
     builder->comment = tr_strdup(comment);
     builder->isPrivate = isPrivate;
 
-    if (outputFile && *outputFile)
+    if (outputFile != NULL && *outputFile != '\0')
     {
         builder->outputFile = tr_strdup(outputFile);
     }
@@ -609,7 +609,7 @@ void tr_makeMetaInfo(tr_metainfo_builder* builder, char const* outputFile, tr_tr
     builder->nextBuilder = queue;
     queue = builder;
 
-    if (!workerThread)
+    if (workerThread == NULL)
     {
         workerThread = tr_threadNew(makeMetaWorkerFunc, NULL);
     }
index 8a3b42d10892895d58e7d734fa6c423602b98abf..25c191bcc2a7b25c8c0039178d6e47f467033be2 100644 (file)
@@ -89,7 +89,7 @@ static int test_metainfo(void)
         int const err = tr_ctorSetMetainfo(ctor, metainfo[i].benc, strlen(metainfo[i].benc));
         check_int_eq(metainfo[i].expected_benc_err, err);
 
-        if (!err)
+        if (err == 0)
         {
             tr_parse_result const parse_result = tr_torrentParse(ctor, NULL);
             check_int_eq(metainfo[i].expected_parse_result, parse_result);
index e4d0fe3c1c47646ad79e1c52a40d8b3a4d6ce05f..504b3e5504fefefe698240df11dd8f36831c8217 100644 (file)
@@ -68,8 +68,8 @@ static char* getTorrentFilename(tr_session const* session, tr_info const* inf)
 
 static bool path_component_is_suspicious(char const* component)
 {
-    return (component == NULL) || (strpbrk(component, PATH_DELIMITER_CHARS) != NULL) || (strcmp(component, ".") == 0) ||
-           (strcmp(component, "..") == 0);
+    return component == NULL || strpbrk(component, PATH_DELIMITER_CHARS) != NULL || strcmp(component, ".") == 0 ||
+           strcmp(component, "..") == 0;
 }
 
 static bool getfile(char** setme, char const* root, tr_variant* path, struct evbuffer* buf)
@@ -103,7 +103,7 @@ static bool getfile(char** setme, char const* root, tr_variant* path, struct evb
                 break;
             }
 
-            if (!*str)
+            if (*str == '\0')
             {
                 continue;
             }
@@ -113,7 +113,7 @@ static bool getfile(char** setme, char const* root, tr_variant* path, struct evb
         }
     }
 
-    if (success && (evbuffer_get_length(buf) <= root_len))
+    if (success && evbuffer_get_length(buf) <= root_len)
     {
         success = false;
     }
@@ -225,7 +225,7 @@ static char* tr_convertAnnounceToScrape(char const* announce)
      * it will be taken as a sign that that tracker doesn't support
      * the scrape convention. If it does, substitute 'scrape' for
      * 'announce' to find the scrape page. */
-    if (((s = strrchr(announce, '/')) != NULL) && strncmp(++s, "announce", 8) == 0)
+    if ((s = strrchr(announce, '/')) != NULL && strncmp(++s, "announce", 8) == 0)
     {
         char const* prefix = announce;
         size_t const prefix_len = s - announce;
@@ -312,7 +312,7 @@ static char const* getannounce(tr_info* inf, tr_variant* meta)
         }
 
         /* did we use any of the tiers? */
-        if (!trackerCount)
+        if (trackerCount == 0)
         {
             tr_free(trackers);
             trackers = NULL;
@@ -320,7 +320,7 @@ static char const* getannounce(tr_info* inf, tr_variant* meta)
     }
 
     /* Regular announce value */
-    if (!trackerCount && tr_variantDictFindStr(meta, TR_KEY_announce, &str, &len))
+    if (trackerCount == 0 && tr_variantDictFindStr(meta, TR_KEY_announce, &str, &len))
     {
         char* url = tr_strstrip(tr_strndup(str, len));
 
@@ -369,7 +369,7 @@ static char* fix_webseed_url(tr_info const* inf, char const* url_in)
 
     if (tr_urlIsValid(url, len))
     {
-        if ((inf->fileCount > 1) && (len > 0) && (url[len - 1] != '/'))
+        if (inf->fileCount > 1 && len > 0 && url[len - 1] != '/')
         {
             ret = tr_strdup_printf("%*.*s/", (int)len, (int)len, url);
         }
@@ -475,12 +475,12 @@ static char const* tr_metainfoParseImpl(tr_session const* session, tr_info* inf,
                 inf->originalName = tr_strndup(str, len);
             }
 
-            if (!inf->name)
+            if (inf->name == NULL)
             {
                 inf->name = tr_strdup(inf->hashString);
             }
 
-            if (!inf->originalName)
+            if (inf->originalName == NULL)
             {
                 inf->originalName = tr_strdup(inf->hashString);
             }
@@ -518,7 +518,7 @@ static char const* tr_metainfoParseImpl(tr_session const* session, tr_info* inf,
             }
         }
 
-        if (!str || !*str)
+        if (str == NULL || *str == '\0')
         {
             return "name";
         }
@@ -612,12 +612,12 @@ static char const* tr_metainfoParseImpl(tr_session const* session, tr_info* inf,
     /* files */
     if (!isMagnet)
     {
-        if ((str = parseFiles(inf, tr_variantDictFind(infoDict, TR_KEY_files), tr_variantDictFind(infoDict, TR_KEY_length))))
+        if ((str = parseFiles(inf, tr_variantDictFind(infoDict, TR_KEY_files), tr_variantDictFind(infoDict, TR_KEY_length))) != NULL)
         {
             return str;
         }
 
-        if (!inf->fileCount || !inf->totalSize)
+        if (inf->fileCount == 0 || inf->totalSize == 0)
         {
             return "files";
         }
@@ -629,7 +629,7 @@ static char const* tr_metainfoParseImpl(tr_session const* session, tr_info* inf,
     }
 
     /* get announce or announce-list */
-    if ((str = getannounce(inf, meta)))
+    if ((str = getannounce(inf, meta)) != NULL)
     {
         return str;
     }
@@ -639,7 +639,7 @@ static char const* tr_metainfoParseImpl(tr_session const* session, tr_info* inf,
 
     /* filename of Transmission's copy */
     tr_free(inf->torrent);
-    inf->torrent = session ? getTorrentFilename(session, inf) : NULL;
+    inf->torrent = session != NULL ? getTorrentFilename(session, inf) : NULL;
 
     return NULL;
 }
@@ -650,7 +650,7 @@ bool tr_metainfoParse(tr_session const* session, tr_variant const* meta_in, tr_i
     char const* badTag = tr_metainfoParseImpl(session, inf, hasInfoDict, infoDictLength, meta_in);
     bool const success = badTag == NULL;
 
-    if (badTag)
+    if (badTag != NULL)
     {
         tr_logAddNamedError(inf->name, _("Invalid metadata entry \"%s\""), badTag);
         tr_metainfoFree(inf);
index 8d775efe0239f96a10a14c20620f061a54a4ce11..0706f72d3c2c118b7bf6ed3993912c0cac8a0265 100644 (file)
@@ -130,7 +130,7 @@ static int test_incomplete_dir_impl(char const* incomplete_dir, char const* down
     libttest_blockingTorrentVerify(tor);
     check_uint_eq(0, tr_torrentStat(tor)->leftUntilDone);
 
-    while ((completeness == completeness_unset) && (time(NULL) <= deadline))
+    while (completeness == completeness_unset && time(NULL) <= deadline)
     {
         tr_wait_msec(50);
     }
@@ -153,19 +153,19 @@ static int test_incomplete_dir(void)
     int rv;
 
     /* test what happens when incompleteDir is a subdir of downloadDir*/
-    if ((rv = test_incomplete_dir_impl("Downloads/Incomplete", "Downloads")))
+    if ((rv = test_incomplete_dir_impl("Downloads/Incomplete", "Downloads")) != 0)
     {
         return rv;
     }
 
     /* test what happens when downloadDir is a subdir of incompleteDir */
-    if ((rv = test_incomplete_dir_impl("Downloads", "Downloads/Complete")))
+    if ((rv = test_incomplete_dir_impl("Downloads", "Downloads/Complete")) != 0)
     {
         return rv;
     }
 
     /* test what happens when downloadDir and incompleteDir are siblings */
-    if ((rv = test_incomplete_dir_impl("Incomplete", "Downloads")))
+    if ((rv = test_incomplete_dir_impl("Incomplete", "Downloads")) != 0)
     {
         return rv;
     }
index 00c77adfc4d8715daf2c5b211b67aa3f883e9b8c..d838f0c75072e08aa8d6fe97a06273075c296ac5 100644 (file)
@@ -93,7 +93,7 @@ struct tr_natpmp* tr_natpmpInit(void)
 
 void tr_natpmpClose(tr_natpmp* nat)
 {
-    if (nat)
+    if (nat != NULL)
     {
         closenatpmp(&nat->natpmp);
         tr_free(nat);
@@ -114,7 +114,7 @@ int tr_natpmpPulse(struct tr_natpmp* nat, tr_port private_port, bool is_enabled,
 {
     int ret;
 
-    if (is_enabled && (nat->state == TR_NATPMP_DISCOVER))
+    if (is_enabled && nat->state == TR_NATPMP_DISCOVER)
     {
         int val = initnatpmp(&nat->natpmp, 0, 0);
         logVal("initnatpmp", val);
@@ -125,7 +125,7 @@ int tr_natpmpPulse(struct tr_natpmp* nat, tr_port private_port, bool is_enabled,
         setCommandTime(nat);
     }
 
-    if ((nat->state == TR_NATPMP_RECV_PUB) && canSendCommand(nat))
+    if (nat->state == TR_NATPMP_RECV_PUB && canSendCommand(nat))
     {
         natpmpresp_t response;
         int const val = readnatpmpresponseorretry(&nat->natpmp, &response);
@@ -144,15 +144,15 @@ int tr_natpmpPulse(struct tr_natpmp* nat, tr_port private_port, bool is_enabled,
         }
     }
 
-    if ((nat->state == TR_NATPMP_IDLE) || (nat->state == TR_NATPMP_ERR))
+    if (nat->state == TR_NATPMP_IDLE || nat->state == TR_NATPMP_ERR)
     {
-        if (nat->is_mapped && (!is_enabled || (nat->private_port != private_port)))
+        if (nat->is_mapped && (!is_enabled || nat->private_port != private_port))
         {
             nat->state = TR_NATPMP_SEND_UNMAP;
         }
     }
 
-    if ((nat->state == TR_NATPMP_SEND_UNMAP) && canSendCommand(nat))
+    if (nat->state == TR_NATPMP_SEND_UNMAP && canSendCommand(nat))
     {
         int const val = sendnewportmappingrequest(&nat->natpmp, NATPMP_PROTOCOL_TCP, nat->private_port, nat->public_port, 0);
         logVal("sendnewportmappingrequest", val);
@@ -198,7 +198,7 @@ int tr_natpmpPulse(struct tr_natpmp* nat, tr_port private_port, bool is_enabled,
         }
     }
 
-    if ((nat->state == TR_NATPMP_SEND_MAP) && canSendCommand(nat))
+    if (nat->state == TR_NATPMP_SEND_MAP && canSendCommand(nat))
     {
         int const val = sendnewportmappingrequest(&nat->natpmp, NATPMP_PROTOCOL_TCP, private_port, private_port, LIFETIME_SECS);
         logVal("sendnewportmappingrequest", val);
index 8fc61e5b2f13d238e03e1b30db29607b2a7119e9..5a1e5af9b785ac47c73a5dbdb282945de61f568b 100644 (file)
@@ -261,7 +261,7 @@ tr_socket_t tr_netOpenPeerSocket(tr_session* session, tr_address const* addr, tr
     {
         int n = 8192;
 
-        if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void const*)&n, sizeof(n)))
+        if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void const*)&n, sizeof(n)) != 0)
         {
             tr_logAddInfo("Unable to set SO_RCVBUF on socket %" PRIdMAX ": %s", (intmax_t)s,
                 tr_net_strerror(err_buf, sizeof(err_buf), sockerrno));
@@ -281,7 +281,7 @@ tr_socket_t tr_netOpenPeerSocket(tr_session* session, tr_address const* addr, tr
     assert(source_addr);
     sourcelen = setup_sockaddr(source_addr, 0, &source_sock);
 
-    if (bind(s, (struct sockaddr*)&source_sock, sourcelen))
+    if (bind(s, (struct sockaddr*)&source_sock, sourcelen) != 0)
     {
         tr_logAddError(_("Couldn't set source address %s on %" PRIdMAX ": %s"), tr_address_to_string(source_addr), (intmax_t)s,
             tr_net_strerror(err_buf, sizeof(err_buf), sockerrno));
@@ -289,11 +289,11 @@ tr_socket_t tr_netOpenPeerSocket(tr_session* session, tr_address const* addr, tr
         return TR_BAD_SOCKET; /* -errno */
     }
 
-    if ((connect(s, (struct sockaddr*)&sock, addrlen) < 0) &&
+    if (connect(s, (struct sockaddr*)&sock, addrlen) < 0 &&
 #ifdef _WIN32
-        (sockerrno != WSAEWOULDBLOCK) &&
+        sockerrno != WSAEWOULDBLOCK &&
 #endif
-        (sockerrno != EINPROGRESS))
+        sockerrno != EINPROGRESS)
     {
         int tmperrno;
         tmperrno = sockerrno;
@@ -376,7 +376,7 @@ static tr_socket_t tr_netBindTCPImpl(tr_address const* addr, tr_port port, bool
 
     addrlen = setup_sockaddr(addr, htons(port), &sock);
 
-    if (bind(fd, (struct sockaddr*)&sock, addrlen))
+    if (bind(fd, (struct sockaddr*)&sock, addrlen) != 0)
     {
         int const err = sockerrno;
 
@@ -560,7 +560,7 @@ static int global_unicast_address(struct sockaddr* sa)
     {
         unsigned char const* a = (unsigned char*)&((struct sockaddr_in6*)sa)->sin6_addr;
         /* 2000::/3 */
-        return (a[0] & 0xE0) == 0x20;
+        return (a[0] & 0xE0) == 0x20 ? 1 : 0;
     }
     else
     {
@@ -612,7 +612,7 @@ static int tr_globalAddress(int af, void* addr, int* addr_len)
         return -1;
     }
 
-    if (!global_unicast_address((struct sockaddr*)&ss))
+    if (global_unicast_address((struct sockaddr*)&ss) == 0)
     {
         return -1;
     }
@@ -657,7 +657,7 @@ unsigned char const* tr_globalIPv6(void)
     {
         int addrlen = 16;
         int const rc = tr_globalAddress(AF_INET6, ipv6, &addrlen);
-        have_ipv6 = (rc >= 0) && (addrlen == 16);
+        have_ipv6 = rc >= 0 && addrlen == 16;
         last_time = now;
     }
 
@@ -671,12 +671,12 @@ unsigned char const* tr_globalIPv6(void)
 
 static bool isIPv4MappedAddress(tr_address const* addr)
 {
-    return (addr->type == TR_AF_INET6) && IN6_IS_ADDR_V4MAPPED(&addr->addr.addr6);
+    return addr->type == TR_AF_INET6 && IN6_IS_ADDR_V4MAPPED(&addr->addr.addr6);
 }
 
 static bool isIPv6LinkLocalAddress(tr_address const* addr)
 {
-    return (addr->type == TR_AF_INET6) && IN6_IS_ADDR_LINKLOCAL(&addr->addr.addr6);
+    return addr->type == TR_AF_INET6 && IN6_IS_ADDR_LINKLOCAL(&addr->addr.addr6);
 }
 
 /* isMartianAddr was written by Juliusz Chroboczek,
@@ -692,13 +692,13 @@ static bool isMartianAddr(struct tr_address const* a)
     case TR_AF_INET:
         {
             unsigned char const* address = (unsigned char const*)&a->addr.addr4;
-            return (address[0] == 0) || (address[0] == 127) || ((address[0] & 0xE0) == 0xE0);
+            return address[0] == 0 || address[0] == 127 || (address[0] & 0xE0) == 0xE0;
         }
 
     case TR_AF_INET6:
         {
             unsigned char const* address = (unsigned char const*)&a->addr.addr6;
-            return (address[0] == 0xFF) || (memcmp(address, zeroes, 15) == 0 && (address[15] == 0 || address[15] == 1));
+            return address[0] == 0xFF || (memcmp(address, zeroes, 15) == 0 && (address[15] == 0 || address[15] == 1));
         }
 
     default:
@@ -708,6 +708,6 @@ static bool isMartianAddr(struct tr_address const* a)
 
 bool tr_address_is_valid_for_peers(tr_address const* addr, tr_port port)
 {
-    return (port != 0) && (tr_address_is_valid(addr)) && (!isIPv6LinkLocalAddress(addr)) && (!isIPv4MappedAddress(addr)) &&
-           (!isMartianAddr(addr));
+    return port != 0 && tr_address_is_valid(addr) && !isIPv6LinkLocalAddress(addr) && !isIPv4MappedAddress(addr) &&
+           !isMartianAddr(addr);
 }
index cba35e9c0f33967f615d538b006a0bd3c2c2f39b..9df75042d1d737b9bd9a7ba1a540b6a0c909e2a4 100644 (file)
@@ -122,7 +122,7 @@ static void peer_io_pull_datatype(tr_peerIo* io)
 {
     struct tr_datatype* tmp;
 
-    if ((tmp = io->outbuf_datatypes))
+    if ((tmp = io->outbuf_datatypes) != NULL)
     {
         io->outbuf_datatypes = tmp->next;
         datatype_free(tmp);
@@ -133,7 +133,7 @@ static void peer_io_push_datatype(tr_peerIo* io, struct tr_datatype* datatype)
 {
     struct tr_datatype* tmp;
 
-    if ((tmp = io->outbuf_datatypes))
+    if ((tmp = io->outbuf_datatypes) != NULL)
     {
         while (tmp->next != NULL)
         {
@@ -154,7 +154,7 @@ static void peer_io_push_datatype(tr_peerIo* io, struct tr_datatype* datatype)
 
 static void didWriteWrapper(tr_peerIo* io, unsigned int bytes_transferred)
 {
-    while (bytes_transferred && tr_isPeerIo(io))
+    while (bytes_transferred != 0 && tr_isPeerIo(io))
     {
         struct tr_datatype* next = io->outbuf_datatypes;
 
@@ -170,7 +170,7 @@ static void didWriteWrapper(tr_peerIo* io, unsigned int bytes_transferred)
             tr_bandwidthUsed(&io->bandwidth, TR_UP, overhead, false, now);
         }
 
-        if (io->didWrite)
+        if (io->didWrite != NULL)
         {
             io->didWrite(io, payload, next->isPieceData, io->userData);
         }
@@ -180,7 +180,7 @@ static void didWriteWrapper(tr_peerIo* io, unsigned int bytes_transferred)
             bytes_transferred -= payload;
             next->length -= payload;
 
-            if (!next->length)
+            if (next->length == 0)
             {
                 peer_io_pull_datatype(io);
             }
@@ -201,7 +201,7 @@ static void canReadWrapper(tr_peerIo* io)
     session = io->session;
 
     /* try to consume the input buffer */
-    if (io->canRead)
+    if (io->canRead != NULL)
     {
         uint64_t const now = tr_time_msec();
 
@@ -215,9 +215,9 @@ static void canReadWrapper(tr_peerIo* io)
             size_t const used = oldLen - evbuffer_get_length(io->inbuf);
             unsigned int const overhead = guessPacketOverhead(used);
 
-            if (piece || (piece != used))
+            if (piece != 0 || piece != used)
             {
-                if (piece)
+                if (piece != 0)
                 {
                     tr_bandwidthUsed(&io->bandwidth, TR_DOWN, piece, true, now);
                 }
@@ -236,7 +236,7 @@ static void canReadWrapper(tr_peerIo* io)
             switch (ret)
             {
             case READ_NOW:
-                if (evbuffer_get_length(io->inbuf))
+                if (evbuffer_get_length(io->inbuf) != 0)
                 {
                     continue;
                 }
@@ -381,7 +381,7 @@ static void event_write_cb(evutil_socket_t fd, short event UNUSED, void* vio)
 
     if (res == -1)
     {
-        if (!e || e == EAGAIN || e == EINTR || e == EINPROGRESS)
+        if (e == 0 || e == EAGAIN || e == EINTR || e == EINPROGRESS)
         {
             goto reschedule;
         }
@@ -400,7 +400,7 @@ static void event_write_cb(evutil_socket_t fd, short event UNUSED, void* vio)
         goto error;
     }
 
-    if (evbuffer_get_length(io->outbuf))
+    if (evbuffer_get_length(io->outbuf) != 0)
     {
         tr_peerIoSetEnabled(io, dir, true);
     }
@@ -409,8 +409,7 @@ static void event_write_cb(evutil_socket_t fd, short event UNUSED, void* vio)
     return;
 
 reschedule:
-
-    if (evbuffer_get_length(io->outbuf))
+    if (evbuffer_get_length(io->outbuf) != 0)
     {
         tr_peerIoSetEnabled(io, dir, true);
     }
@@ -433,7 +432,7 @@ error:
 
 static void maybeSetCongestionAlgorithm(tr_socket_t socket, char const* algorithm)
 {
-    if (algorithm && *algorithm)
+    if (algorithm != NULL && *algorithm != '\0')
     {
         tr_netSetCongestionControl(socket, algorithm);
     }
@@ -517,14 +516,14 @@ static void utp_on_state_change(void* closure, int state)
     {
         dbgmsg(io, "utp_on_state_change -- changed to writable");
 
-        if (io->pendingEvents & EV_WRITE)
+        if ((io->pendingEvents & EV_WRITE) != 0)
         {
             utp_on_writable(io);
         }
     }
     else if (state == UTP_STATE_EOF)
     {
-        if (io->gotError)
+        if (io->gotError != NULL)
         {
             io->gotError(io, BEV_EVENT_EOF, io->userData);
         }
@@ -547,14 +546,14 @@ static void utp_on_error(void* closure, int errcode)
 
     dbgmsg(io, "utp_on_error -- errcode is %d", errcode);
 
-    if (io->gotError)
+    if (io->gotError != NULL)
     {
         errno = errcode;
         io->gotError(io, BEV_EVENT_ERROR, io->userData);
     }
 }
 
-static void utp_on_overhead(void* closure, uint8_t send, size_t count, int type UNUSED)
+static void utp_on_overhead(void* closure, uint8_t /* bool */ send, size_t count, int type UNUSED)
 {
     tr_peerIo* io = closure;
     assert(tr_isPeerIo(io));
@@ -599,17 +598,14 @@ static size_t dummy_get_rb_size(void* closure UNUSED)
 
 static void dummy_on_state_change(void* closure UNUSED, int state UNUSED)
 {
-    return;
 }
 
 static void dummy_on_error(void* closure UNUSED, int errcode UNUSED)
 {
-    return;
 }
 
-static void dummy_on_overhead(void* closure UNUSED, uint8_t send UNUSED, size_t count UNUSED, int type UNUSED)
+static void dummy_on_overhead(void* closure UNUSED, uint8_t /* bool */ send UNUSED, size_t count UNUSED, int type UNUSED)
 {
-    return;
 }
 
 static struct UTPFunctionTable dummy_utp_function_table =
@@ -693,7 +689,7 @@ static tr_peerIo* tr_peerIoNew(tr_session* session, tr_bandwidth* parent, tr_add
 tr_peerIo* tr_peerIoNewIncoming(tr_session* session, tr_bandwidth* parent, tr_address const* addr, tr_port port, tr_socket_t fd,
     struct UTPSocket* utp_socket)
 {
-    assert(session);
+    assert(session != NULL);
     assert(tr_address_is_valid(addr));
 
     return tr_peerIoNew(session, parent, addr, port, NULL, true, false, fd, utp_socket);
@@ -705,16 +701,16 @@ tr_peerIo* tr_peerIoNewOutgoing(tr_session* session, tr_bandwidth* parent, tr_ad
     tr_socket_t fd = TR_BAD_SOCKET;
     struct UTPSocket* utp_socket = NULL;
 
-    assert(session);
+    assert(session != NULL);
     assert(tr_address_is_valid(addr));
-    assert(torrentHash);
+    assert(torrentHash != NULL);
 
     if (utp)
     {
         utp_socket = tr_netOpenPeerUTPSocket(session, addr, port, isSeed);
     }
 
-    if (!utp_socket)
+    if (utp_socket == NULL)
     {
         fd = tr_netOpenPeerSocket(session, addr, port, isSeed);
         dbgmsg(NULL, "tr_netOpenPeerSocket returned fd %" PRIdMAX, (intmax_t)fd);
@@ -744,7 +740,7 @@ static void event_enable(tr_peerIo* io, short event)
         assert(event_initialized(io->event_write));
     }
 
-    if ((event & EV_READ) && !(io->pendingEvents & EV_READ))
+    if ((event & EV_READ) != 0 && (io->pendingEvents & EV_READ) == 0)
     {
         dbgmsg(io, "enabling ready-to-read polling");
 
@@ -756,7 +752,7 @@ static void event_enable(tr_peerIo* io, short event)
         io->pendingEvents |= EV_READ;
     }
 
-    if ((event & EV_WRITE) && !(io->pendingEvents & EV_WRITE))
+    if ((event & EV_WRITE) != 0 && (io->pendingEvents & EV_WRITE) == 0)
     {
         dbgmsg(io, "enabling ready-to-write polling");
 
@@ -781,7 +777,7 @@ static void event_disable(struct tr_peerIo* io, short event)
         assert(event_initialized(io->event_write));
     }
 
-    if ((event & EV_READ) && (io->pendingEvents & EV_READ))
+    if ((event & EV_READ) != 0 && (io->pendingEvents & EV_READ) != 0)
     {
         dbgmsg(io, "disabling ready-to-read polling");
 
@@ -793,7 +789,7 @@ static void event_disable(struct tr_peerIo* io, short event)
         io->pendingEvents &= ~EV_READ;
     }
 
-    if ((event & EV_WRITE) && (io->pendingEvents & EV_WRITE))
+    if ((event & EV_WRITE) != 0 && (io->pendingEvents & EV_WRITE) != 0)
     {
         dbgmsg(io, "disabling ready-to-write polling");
 
@@ -851,7 +847,7 @@ static void io_close_socket(tr_peerIo* io)
 
 #ifdef WITH_UTP
 
-    if (io->utp_socket)
+    if (io->utp_socket != NULL)
     {
         UTP_SetCallbacks(io->utp_socket, &dummy_utp_function_table, NULL);
         UTP_Close(io->utp_socket);
@@ -889,7 +885,7 @@ static void io_dtor(void* vio)
 
 static void tr_peerIoFree(tr_peerIo* io)
 {
-    if (io)
+    if (io != NULL)
     {
         dbgmsg(io, "in tr_peerIoFree");
         io->canRead = NULL;
@@ -914,7 +910,7 @@ void tr_peerIoUnrefImpl(char const* file, int line, tr_peerIo* io)
 
     dbgmsg(io, "%s:%d is decrementing the IO's refcount from %d to %d", file, line, io->refCount, io->refCount - 1);
 
-    if (!--io->refCount)
+    if (--io->refCount == 0)
     {
         tr_peerIoFree(io);
     }
@@ -924,7 +920,7 @@ tr_address const* tr_peerIoGetAddress(tr_peerIo const* io, tr_port* port)
 {
     assert(tr_isPeerIo(io));
 
-    if (port)
+    if (port != NULL)
     {
         *port = io->port;
     }
@@ -1262,7 +1258,7 @@ static int tr_peerIoTryRead(tr_peerIo* io, size_t howmuch)
 {
     int res = 0;
 
-    if ((howmuch = tr_bandwidthClamp(&io->bandwidth, TR_DOWN, howmuch)))
+    if ((howmuch = tr_bandwidthClamp(&io->bandwidth, TR_DOWN, howmuch)) != 0)
     {
         if (io->utp_socket != NULL) /* utp peer connection */
         {
@@ -1283,14 +1279,14 @@ static int tr_peerIoTryRead(tr_peerIo* io, size_t howmuch)
             res = evbuffer_read(io->inbuf, io->socket, (int)howmuch);
             e = EVUTIL_SOCKET_ERROR();
 
-            dbgmsg(io, "read %d from peer (%s)", res, (res == -1 ? tr_net_strerror(err_buf, sizeof(err_buf), e) : ""));
+            dbgmsg(io, "read %d from peer (%s)", res, res == -1 ? tr_net_strerror(err_buf, sizeof(err_buf), e) : "");
 
             if (evbuffer_get_length(io->inbuf))
             {
                 canReadWrapper(io);
             }
 
-            if ((res <= 0) && (io->gotError) && (e != EAGAIN) && (e != EINTR) && (e != EINPROGRESS))
+            if (res <= 0 && io->gotError != NULL && e != EAGAIN && e != EINTR && e != EINPROGRESS)
             {
                 short what = BEV_EVENT_READING | BEV_EVENT_ERROR;
 
@@ -1301,6 +1297,7 @@ static int tr_peerIoTryRead(tr_peerIo* io, size_t howmuch)
 
                 dbgmsg(io, "tr_peerIoTryRead got an error. res is %d, what is %hd, errno is %d (%s)", res, what, e,
                     tr_net_strerror(err_buf, sizeof(err_buf), e));
+
                 io->gotError(io, what, io->userData);
             }
         }
@@ -1320,7 +1317,7 @@ static int tr_peerIoTryWrite(tr_peerIo* io, size_t howmuch)
         howmuch = old_len;
     }
 
-    if ((howmuch = tr_bandwidthClamp(&io->bandwidth, TR_UP, howmuch)))
+    if ((howmuch = tr_bandwidthClamp(&io->bandwidth, TR_UP, howmuch)) != 0)
     {
         if (io->utp_socket != NULL) /* utp peer connection */
         {
@@ -1340,7 +1337,7 @@ static int tr_peerIoTryWrite(tr_peerIo* io, size_t howmuch)
                 didWriteWrapper(io, n);
             }
 
-            if ((n < 0) && (io->gotError) && e && (e != EPIPE) && (e != EAGAIN) && (e != EINTR) && (e != EINPROGRESS))
+            if (n < 0 && io->gotError != NULL && e != 0 && e != EPIPE && e != EAGAIN && e != EINTR && e != EINPROGRESS)
             {
                 char errstr[512];
                 short const what = BEV_EVENT_WRITING | BEV_EVENT_ERROR;
@@ -1348,10 +1345,7 @@ static int tr_peerIoTryWrite(tr_peerIo* io, size_t howmuch)
                 dbgmsg(io, "tr_peerIoTryWrite got an error. res is %d, what is %hd, errno is %d (%s)", n, what, e,
                     tr_net_strerror(errstr, sizeof(errstr), e));
 
-                if (io->gotError != NULL)
-                {
-                    io->gotError(io, what, io->userData);
-                }
+                io->gotError(io, what, io->userData);
             }
         }
     }
index 504ee32d8ae85dc6819af9f06bf320328821d352..cd04ac0561918be61434b7954e58808e276c9c97 100644 (file)
@@ -127,8 +127,8 @@ void tr_peerIoUnrefImpl(char const* file, int line, tr_peerIo* io);
 
 static inline bool tr_isPeerIo(tr_peerIo const* io)
 {
-    return (io != NULL) && (io->magicNumber == PEER_IO_MAGIC_NUMBER) && (io->refCount >= 0) &&
-           (tr_isBandwidth(&io->bandwidth)) && (tr_address_is_valid(&io->addr));
+    return io != NULL && io->magicNumber == PEER_IO_MAGIC_NUMBER && io->refCount >= 0 && tr_isBandwidth(&io->bandwidth) &&
+           tr_address_is_valid(&io->addr);
 }
 
 /**
@@ -177,7 +177,7 @@ static inline bool tr_peerIoSupportsUTP(tr_peerIo const* io)
 static inline tr_session* tr_peerIoGetSession(tr_peerIo* io)
 {
     assert(tr_isPeerIo(io));
-    assert(io->session);
+    assert(io->session != NULL);
 
     return io->session;
 }
@@ -249,7 +249,7 @@ void tr_peerIoSetEncryption(tr_peerIo* io, tr_encryption_type encryption_type);
 
 static inline bool tr_peerIoIsEncrypted(tr_peerIo const* io)
 {
-    return (io != NULL) && (io->encryption_type == PEER_ENCRYPTION_RC4);
+    return io != NULL && io->encryption_type == PEER_ENCRYPTION_RC4;
 }
 
 void evbuffer_add_uint8(struct evbuffer* outbuf, uint8_t byte);
index 6c7d5c55326854b3401a23adac65649199fe17c0..98ac95fada86f5e5f30d10569924f997bee1f98a 100644 (file)
@@ -133,15 +133,15 @@ struct peer_atom
 
 static bool tr_isAtom(struct peer_atom const* atom)
 {
-    return (atom != NULL) && (atom->fromFirst < TR_PEER_FROM__MAX) && (atom->fromBest < TR_PEER_FROM__MAX) &&
-           (tr_address_is_valid(&atom->addr));
+    return atom != NULL && atom->fromFirst < TR_PEER_FROM__MAX && atom->fromBest < TR_PEER_FROM__MAX &&
+           tr_address_is_valid(&atom->addr);
 }
 
 #endif
 
 static char const* tr_atomAddrStr(struct peer_atom const* atom)
 {
-    return atom ? tr_peerIoAddrStr(&atom->addr, atom->port) : "[no atom]";
+    return atom != NULL ? tr_peerIoAddrStr(&atom->addr, atom->port) : "[no atom]";
 }
 
 struct block_request
@@ -297,7 +297,7 @@ void tr_peerDestruct(tr_peer* peer)
     tr_bitfieldDestruct(&peer->have);
     tr_bitfieldDestruct(&peer->blame);
 
-    if (peer->atom)
+    if (peer->atom != NULL)
     {
         peer->atom->peer = NULL;
     }
@@ -411,7 +411,7 @@ static bool peerIsInUse(tr_swarm const* cs, struct peer_atom const* atom)
 
     assert(swarmIsLocked(s));
 
-    return (atom->peer != NULL) || getExistingHandshake(&s->outgoingHandshakes, &atom->addr) ||
+    return atom->peer != NULL || getExistingHandshake(&s->outgoingHandshakes, &atom->addr) ||
            getExistingHandshake(&s->manager->incomingHandshakes, &atom->addr);
 }
 
@@ -575,7 +575,7 @@ void tr_peerMgrOnBlocklistChanged(tr_peerMgr* mgr)
 
     /* we cache whether or not a peer is blocklisted...
        since the blocklist has changed, erase that cached value */
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         int i;
         tr_swarm* s = tor->swarm;
@@ -642,7 +642,7 @@ bool tr_peerMgrPeerIsSeed(tr_torrent const* tor, tr_address const* addr)
     tr_swarm const* s = tor->swarm;
     struct peer_atom const* atom = getExistingAtom(s, addr);
 
-    if (atom)
+    if (atom != NULL)
     {
         isSeed = atomIsSeed(atom);
     }
@@ -654,7 +654,7 @@ void tr_peerMgrSetUtpSupported(tr_torrent* tor, tr_address const* addr)
 {
     struct peer_atom* atom = getExistingAtom(tor->swarm, addr);
 
-    if (atom)
+    if (atom != NULL)
     {
         atom->flags |= ADDED_F_UTP_FLAGS;
     }
@@ -664,7 +664,7 @@ void tr_peerMgrSetUtpFailed(tr_torrent* tor, tr_address const* addr, bool failed
 {
     struct peer_atom* atom = getExistingAtom(tor->swarm, addr);
 
-    if (atom)
+    if (atom != NULL)
     {
         atom->utp_failed = failed;
     }
@@ -847,7 +847,7 @@ static bool testForEndgame(tr_swarm const* s)
 {
     /* we consider ourselves to be in endgame if the number of bytes
        we've got requested is >= the number of bytes left to download */
-    return ((uint64_t)s->requestCount * s->tor->blockSize) >= tr_torrentGetLeftUntilDone(s->tor);
+    return (uint64_t)s->requestCount * s->tor->blockSize >= tr_torrentGetLeftUntilDone(s->tor);
 }
 
 static void updateEndgame(tr_swarm* s)
@@ -859,7 +859,7 @@ static void updateEndgame(tr_swarm* s)
         /* not in endgame */
         s->endgame = 0;
     }
-    else if (!s->endgame) /* only recalculate when endgame first begins */
+    else if (s->endgame == 0) /* only recalculate when endgame first begins */
     {
         int i;
         int numDownloading = 0;
@@ -923,10 +923,10 @@ static int comparePieceByWeight(void const* va, void const* vb)
     /* primary key: weight */
     missing = tr_torrentMissingBlocksInPiece(tor, a->index);
     pending = a->requestCount;
-    ia = missing > pending ? missing - pending : (tor->blockCountInPiece + pending);
+    ia = missing > pending ? missing - pending : tor->blockCountInPiece + pending;
     missing = tr_torrentMissingBlocksInPiece(tor, b->index);
     pending = b->requestCount;
-    ib = missing > pending ? missing - pending : (tor->blockCountInPiece + pending);
+    ib = missing > pending ? missing - pending : tor->blockCountInPiece + pending;
 
     if (ia < ib)
     {
@@ -1029,7 +1029,7 @@ static void pieceListSort(tr_swarm* s, enum piece_sort_state state)
 
 static void assertWeightedPiecesAreSorted(Torrent* t)
 {
-    if (!t->endgame)
+    if (t->endgame == 0)
     {
         int i;
         setComparePieceByWeightTorrent(t);
@@ -1171,7 +1171,7 @@ static void pieceListRemovePiece(tr_swarm* s, tr_piece_index_t piece)
 {
     struct weighted_piece* p;
 
-    if ((p = pieceListLookup(s, piece)))
+    if ((p = pieceListLookup(s, piece)) != NULL)
     {
         int const pos = p - s->pieces;
 
@@ -1199,12 +1199,12 @@ static void pieceListResortPiece(tr_swarm* s, struct weighted_piece* p)
     pos = p - s->pieces;
     setComparePieceByWeightTorrent(s);
 
-    if (isSorted && (pos > 0) && (comparePieceByWeight(p - 1, p) > 0))
+    if (isSorted && pos > 0 && comparePieceByWeight(p - 1, p) > 0)
     {
         isSorted = false;
     }
 
-    if (isSorted && (pos < s->pieceCount - 1) && (comparePieceByWeight(p, p + 1) > 0))
+    if (isSorted && pos < s->pieceCount - 1 && comparePieceByWeight(p, p + 1) > 0)
     {
         isSorted = false;
     }
@@ -1238,7 +1238,7 @@ static void pieceListRemoveRequest(tr_swarm* s, tr_block_index_t block)
     struct weighted_piece* p;
     tr_piece_index_t const index = tr_torBlockPiece(s->tor, block);
 
-    if (((p = pieceListLookup(s, index))) && (p->requestCount > 0))
+    if ((p = pieceListLookup(s, index)) != NULL && p->requestCount > 0)
     {
         --p->requestCount;
         pieceListResortPiece(s, p);
@@ -1425,7 +1425,7 @@ void tr_peerMgrGetNextRequests(tr_torrent* tor, tr_peer* peer, int numwant, tr_b
                 if (peerCount != 0)
                 {
                     /* don't make a second block request until the endgame */
-                    if (!s->endgame)
+                    if (s->endgame == 0)
                     {
                         continue;
                     }
@@ -1458,7 +1458,7 @@ void tr_peerMgrGetNextRequests(tr_torrent* tor, tr_peer* peer, int numwant, tr_b
                 }
                 /* if intervals are requested two array entries are necessarry:
                    one for the interval's starting block and one for its end block */
-                else if (got && setme[2 * got - 1] == b - 1 && b != first)
+                else if (got != 0 && setme[2 * got - 1] == b - 1 && b != first)
                 {
                     /* expand the last interval */
                     ++setme[2 * got - 1];
@@ -1535,7 +1535,7 @@ static void refillUpkeep(evutil_socket_t foo UNUSED, short bar UNUSED, void* vmg
     /* alloc the temporary "cancel" buffer */
     tor = NULL;
 
-    while ((tor = tr_torrentNext(mgr->session, tor)))
+    while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
     {
         cancel_buflen = MAX(cancel_buflen, tor->swarm->requestCount);
     }
@@ -1548,7 +1548,7 @@ static void refillUpkeep(evutil_socket_t foo UNUSED, short bar UNUSED, void* vmg
     /* prune requests that are too old */
     tor = NULL;
 
-    while ((tor = tr_torrentNext(mgr->session, tor)))
+    while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
     {
         tr_swarm* s = tor->swarm;
         int const n = s->requestCount;
@@ -1564,7 +1564,7 @@ static void refillUpkeep(evutil_socket_t foo UNUSED, short bar UNUSED, void* vmg
             {
                 tr_peerMsgs* msgs = PEER_MSGS(it->peer);
 
-                if ((msgs != NULL) && (it->sentAt <= too_old) && !tr_peerMsgsIsReadingBlock(msgs, it->block))
+                if (msgs != NULL && it->sentAt <= too_old && !tr_peerMsgsIsReadingBlock(msgs, it->block))
                 {
                     cancel[cancelCount++] = *it;
                 }
@@ -1722,7 +1722,7 @@ static void cancelAllRequestsForBlock(tr_swarm* s, tr_block_index_t block, tr_pe
     {
         tr_peer* p = peers[i];
 
-        if ((p != no_notify) && tr_isPeerMsgs(p))
+        if (p != no_notify && tr_isPeerMsgs(p))
         {
             tr_historyAdd(&p->cancelsSentToPeer, tr_time(), 1);
             tr_peerMsgsCancel(PEER_MSGS(p), block);
@@ -1867,7 +1867,7 @@ static void peerCallbackFunc(tr_peer* peer, tr_peer_event const* e, void* vs)
         break;
 
     case TR_PEER_CLIENT_GOT_PORT:
-        if (peer->atom)
+        if (peer->atom != NULL)
         {
             peer->atom->port = e->port;
         }
@@ -1895,7 +1895,7 @@ static void peerCallbackFunc(tr_peer* peer, tr_peer_event const* e, void* vs)
         }
 
     case TR_PEER_ERROR:
-        if ((e->err == ERANGE) || (e->err == EMSGSIZE) || (e->err == ENOTCONN))
+        if (e->err == ERANGE || e->err == EMSGSIZE || e->err == ENOTCONN)
         {
             /* some protocol error from the peer */
             peer->doPurge = true;
@@ -2040,7 +2040,7 @@ static bool myHandshakeDoneCB(tr_handshake* handshake, tr_peerIo* io, bool readA
     tr_peerMgr* manager = vmanager;
     tr_swarm* s;
 
-    assert(io);
+    assert(io != NULL);
     assert(tr_isBool(ok));
 
     s = tr_peerIoHasTorrentHash(io) ? getExistingSwarm(manager, tr_peerIoGetTorrentHash(io)) : NULL;
@@ -2049,25 +2049,25 @@ static bool myHandshakeDoneCB(tr_handshake* handshake, tr_peerIo* io, bool readA
     {
         tr_ptrArrayRemoveSortedPointer(&manager->incomingHandshakes, handshake, handshakeCompare);
     }
-    else if (s)
+    else if (s != NULL)
     {
         tr_ptrArrayRemoveSortedPointer(&s->outgoingHandshakes, handshake, handshakeCompare);
     }
 
-    if (s)
+    if (s != NULL)
     {
         swarmLock(s);
     }
 
     addr = tr_peerIoGetAddress(io, &port);
 
-    if (!ok || !s || !s->isRunning)
+    if (!ok || s == NULL || !s->isRunning)
     {
-        if (s)
+        if (s != NULL)
         {
             struct peer_atom* atom = getExistingAtom(s, addr);
 
-            if (atom)
+            if (atom != NULL)
             {
                 ++atom->numFails;
 
@@ -2100,23 +2100,23 @@ static bool myHandshakeDoneCB(tr_handshake* handshake, tr_peerIo* io, bool readA
 
         /* In principle, this flag specifies whether the peer groks uTP,
            not whether it's currently connected over uTP. */
-        if (io->utp_socket)
+        if (io->utp_socket != NULL)
         {
             atom->flags |= ADDED_F_UTP_FLAGS;
         }
 
-        if (atom->flags2 & MYFLAG_BANNED)
+        if ((atom->flags2 & MYFLAG_BANNED) != 0)
         {
             tordbg(s, "banned peer %s tried to reconnect", tr_atomAddrStr(atom));
         }
-        else if (tr_peerIoIsIncoming(io) && (getPeerCount(s) >= getMaxPeerCount(s->tor)))
+        else if (tr_peerIoIsIncoming(io) && getPeerCount(s) >= getMaxPeerCount(s->tor))
         {
         }
         else
         {
             tr_peer* peer = atom->peer;
 
-            if (peer)
+            if (peer != NULL)
             {
                 /* we already have this peer */
             }
@@ -2175,7 +2175,7 @@ void tr_peerMgrAddIncoming(tr_peerMgr* manager, tr_address* addr, tr_port port,
             UTP_Close(utp_socket);
         }
     }
-    else if (getExistingHandshake(&manager->incomingHandshakes, addr))
+    else if (getExistingHandshake(&manager->incomingHandshakes, addr) != NULL)
     {
         if (socket != TR_BAD_SOCKET)
         {
@@ -2251,7 +2251,7 @@ tr_pex* tr_peerMgrCompactToPex(void const* compact, size_t compactLen, uint8_t c
         memcpy(&pex[i].port, walk, 2);
         walk += 2;
 
-        if (added_f && (n == added_f_len))
+        if (added_f != NULL && n == added_f_len)
         {
             pex[i].flags = added_f[i];
         }
@@ -2277,7 +2277,7 @@ tr_pex* tr_peerMgrCompact6ToPex(void const* compact, size_t compactLen, uint8_t
         memcpy(&pex[i].port, walk, 2);
         walk += 2;
 
-        if (added_f && (n == added_f_len))
+        if (added_f != NULL && n == added_f_len)
         {
             pex[i].flags = added_f[i];
         }
@@ -2341,7 +2341,7 @@ int tr_pexCompare(void const* va, void const* vb)
     assert(tr_isPex(a));
     assert(tr_isPex(b));
 
-    if ((i = tr_address_compare(&a->addr, &b->addr)))
+    if ((i = tr_address_compare(&a->addr, &b->addr)) != 0)
     {
         return i;
     }
@@ -2398,7 +2398,7 @@ static bool isAtomInteresting(tr_torrent const* tor, struct peer_atom* atom)
         return false;
     }
 
-    if (atom->flags2 & MYFLAG_BANNED)
+    if ((atom->flags2 & MYFLAG_BANNED) != 0)
     {
         return false;
     }
@@ -2625,7 +2625,7 @@ void tr_peerUpdateProgress(tr_torrent* tor, tr_peer* peer)
         peer->progress = 1.0;
     }
 
-    if (peer->atom && (peer->progress >= 1.0))
+    if (peer->atom != NULL && peer->progress >= 1.0)
     {
         atomSetSeed(tor->swarm, peer->atom);
     }
@@ -2682,7 +2682,7 @@ void tr_peerMgrTorrentAvailability(tr_torrent const* tor, int8_t* tab, unsigned
             {
                 tab[i] = -1;
             }
-            else if (peerCount)
+            else if (peerCount != 0)
             {
                 int j;
 
@@ -2732,7 +2732,7 @@ bool tr_peerIsSeed(tr_peer const* peer)
         return true;
     }
 
-    if (peer->atom && atomIsSeed(peer->atom))
+    if (peer->atom != NULL && atomIsSeed(peer->atom))
     {
         return true;
     }
@@ -2783,7 +2783,7 @@ uint64_t tr_peerMgrGetDesiredAvailable(tr_torrent const* tor)
         }
     }
 
-    if (!s->pieceReplication || !s->pieceReplicationSize)
+    if (s->pieceReplication == NULL || s->pieceReplicationSize == 0)
     {
         return 0;
     }
@@ -2794,7 +2794,7 @@ uint64_t tr_peerMgrGetDesiredAvailable(tr_torrent const* tor)
 
     for (i = 0, n = MIN(tor->info.pieceCount, s->pieceReplicationSize); i < n; ++i)
     {
-        if (!tor->info.pieces[i].dnd && (s->pieceReplication[i] > 0))
+        if (!tor->info.pieces[i].dnd && s->pieceReplication[i] > 0)
         {
             desiredAvailable += tr_torrentMissingBytesInPiece(tor, i);
         }
@@ -3100,7 +3100,7 @@ static void rechokeDownloads(tr_swarm* s)
 
         timeSinceCancel = now - s->lastCancel;
 
-        if (timeSinceCancel)
+        if (timeSinceCancel != 0)
         {
             int const maxIncrease = 15;
             time_t const maxHistory = 2 * CANCEL_HISTORY_SEC;
@@ -3154,19 +3154,19 @@ static void rechokeDownloads(tr_swarm* s)
                 int const blocks = tr_historyGet(&peer->blocksSentToClient, now, CANCEL_HISTORY_SEC);
                 int const cancels = tr_historyGet(&peer->cancelsSentToPeer, now, CANCEL_HISTORY_SEC);
 
-                if (!blocks && !cancels)
+                if (blocks == 0 && cancels == 0)
                 {
                     rechoke_state = RECHOKE_STATE_UNTESTED;
                 }
-                else if (!cancels)
+                else if (cancels == 0)
                 {
                     rechoke_state = RECHOKE_STATE_GOOD;
                 }
-                else if (!blocks)
+                else if (blocks == 0)
                 {
                     rechoke_state = RECHOKE_STATE_BAD;
                 }
-                else if ((cancels * 10) < blocks)
+                else if (cancels * 10 < blocks)
                 {
                     rechoke_state = RECHOKE_STATE_GOOD;
                 }
@@ -3243,7 +3243,7 @@ static int compareChoke(void const* va, void const* vb)
 /* is this a new connection? */
 static bool isNew(tr_peerMsgs const* msgs)
 {
-    return (msgs != NULL) && (tr_peerMsgsGetConnectionAge(msgs) < 45);
+    return msgs != NULL && tr_peerMsgsGetConnectionAge(msgs) < 45;
 }
 
 /* get a rate for deciding which peers to choke and unchoke. */
@@ -3369,7 +3369,7 @@ static void rechokeUploads(tr_swarm* s, uint64_t const now)
     }
 
     /* optimistic unchoke */
-    if (!s->optimistic && !isMaxedOut && (i < size))
+    if (s->optimistic == NULL && !isMaxedOut && i < size)
     {
         int n;
         struct ChokeData* c;
@@ -3394,7 +3394,7 @@ static void rechokeUploads(tr_swarm* s, uint64_t const now)
             }
         }
 
-        if ((n = tr_ptrArraySize(&randPool)))
+        if ((n = tr_ptrArraySize(&randPool)) != 0)
         {
             c = tr_ptrArrayNth(&randPool, tr_rand_int_weak(n));
             c->isChoked = false;
@@ -3422,7 +3422,7 @@ static void rechokePulse(evutil_socket_t foo UNUSED, short bar UNUSED, void* vmg
 
     managerLock(mgr);
 
-    while ((tor = tr_torrentNext(mgr->session, tor)))
+    while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
     {
         if (tor->isRunning)
         {
@@ -3461,7 +3461,7 @@ static bool shouldPeerBeClosed(tr_swarm const* s, tr_peer const* peer, int peerC
     /* disconnect if we're both seeds and enough time has passed for PEX */
     if (tr_torrentIsSeed(tor) && tr_peerIsSeed(peer))
     {
-        return !tr_torrentAllowsPex(tor) || (now - atom->time >= 30);
+        return !tr_torrentAllowsPex(tor) || now - atom->time >= 30;
     }
 
     /* disconnect if it's been too long since piece data has been transferred.
@@ -3526,7 +3526,7 @@ static int getReconnectIntervalSecs(struct peer_atom const* atom, time_t const n
     /* if we were recently connected to this peer and transferring piece
      * data, try to reconnect to them sooner rather that later -- we don't
      * want network troubles to get in the way of a good peer. */
-    if (!unreachable && ((now - atom->piece_data_time) <= (MINIMUM_RECONNECT_INTERVAL_SECS * 2)))
+    if (!unreachable && now - atom->piece_data_time <= MINIMUM_RECONNECT_INTERVAL_SECS * 2)
     {
         sec = MINIMUM_RECONNECT_INTERVAL_SECS;
     }
@@ -3583,7 +3583,7 @@ static void removePeer(tr_swarm* s, tr_peer* peer)
     struct peer_atom* atom = peer->atom;
 
     assert(swarmIsLocked(s));
-    assert(atom);
+    assert(atom != NULL);
 
     atom->time = tr_time();
 
@@ -3716,14 +3716,14 @@ static void sortPeersByLivelinessImpl(tr_peer** peers, void** clientData, int n,
         l->time = p->atom->time;
         l->speed = tr_peerGetPieceSpeed_Bps(p, now, TR_UP) + tr_peerGetPieceSpeed_Bps(p, now, TR_DOWN);
 
-        if (clientData)
+        if (clientData != NULL)
         {
             l->clientData = clientData[i];
         }
     }
 
     /* sort 'em */
-    assert(n == (l - lives));
+    assert(n == l - lives);
     qsort(lives, n, sizeof(struct peer_liveliness), compare);
 
     /* build the peer array */
@@ -3731,13 +3731,13 @@ static void sortPeersByLivelinessImpl(tr_peer** peers, void** clientData, int n,
     {
         peers[i] = l->peer;
 
-        if (clientData)
+        if (clientData != NULL)
         {
             clientData[i] = l->clientData;
         }
     }
 
-    assert(n == (l - lives));
+    assert(n == l - lives);
 
     /* cleanup */
     tr_free(lives);
@@ -3775,7 +3775,7 @@ static void enforceSessionPeerLimit(tr_session* session, uint64_t now)
     int const max = tr_sessionGetPeerLimit(session);
 
     /* count the total number of peers */
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         n += tr_ptrArraySize(&tor->swarm->peers);
     }
@@ -3790,7 +3790,7 @@ static void enforceSessionPeerLimit(tr_session* session, uint64_t now)
         n = 0;
         tor = NULL;
 
-        while ((tor = tr_torrentNext(session, tor)))
+        while ((tor = tr_torrentNext(session, tor)) != NULL)
         {
             int i;
             tr_swarm* s = tor->swarm;
@@ -3834,7 +3834,7 @@ static void reconnectPulse(evutil_socket_t foo UNUSED, short bar UNUSED, void* v
     /* if we're over the per-torrent peer limits, cull some peers */
     tor = NULL;
 
-    while ((tor = tr_torrentNext(mgr->session, tor)))
+    while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
     {
         if (tor->isRunning)
         {
@@ -3848,7 +3848,7 @@ static void reconnectPulse(evutil_socket_t foo UNUSED, short bar UNUSED, void* v
     /* remove crappy peers */
     tor = NULL;
 
-    while ((tor = tr_torrentNext(mgr->session, tor)))
+    while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
     {
         if (!tor->swarm->isRunning)
         {
@@ -3874,7 +3874,7 @@ static void pumpAllPeers(tr_peerMgr* mgr)
 {
     tr_torrent* tor = NULL;
 
-    while ((tor = tr_torrentNext(mgr->session, tor)))
+    while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
     {
         int j;
         tr_swarm* s = tor->swarm;
@@ -3932,7 +3932,7 @@ static void bandwidthPulse(evutil_socket_t foo UNUSED, short bar UNUSED, void* v
     /* torrent upkeep */
     tor = NULL;
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         /* possibly stop torrents that have seeded enough */
         tr_torrentCheckSeedLimit(tor);
@@ -4033,7 +4033,7 @@ static void atomPulse(evutil_socket_t foo UNUSED, short bar UNUSED, void* vmgr)
     tr_peerMgr* mgr = vmgr;
     managerLock(mgr);
 
-    while ((tor = tr_torrentNext(mgr->session, tor)))
+    while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
     {
         int atomCount;
         tr_swarm* s = tor->swarm;
@@ -4126,7 +4126,7 @@ static bool isPeerCandidate(tr_torrent const* tor, struct peer_atom* atom, time_
     }
 
     /* not if we just tried them already */
-    if ((now - atom->time) < getReconnectIntervalSecs(atom, now))
+    if (now - atom->time < getReconnectIntervalSecs(atom, now))
     {
         return false;
     }
@@ -4138,7 +4138,7 @@ static bool isPeerCandidate(tr_torrent const* tor, struct peer_atom* atom, time_
     }
 
     /* not if they're banned... */
-    if (atom->flags2 & MYFLAG_BANNED)
+    if ((atom->flags2 & MYFLAG_BANNED) != 0)
     {
         return false;
     }
@@ -4207,7 +4207,7 @@ static uint64_t getPeerCandidateScore(tr_torrent const* tor, struct peer_atom co
     score = addValToKey(score, 1, i);
 
     /* prefer peers that are known to be connectible */
-    i = (atom->flags & ADDED_F_CONNECTABLE) ? 0 : 1;
+    i = (atom->flags & ADDED_F_CONNECTABLE) != 0 ? 0 : 1;
     score = addValToKey(score, 1, i);
 
     /* prefer peers that we might have a chance of uploading to...
@@ -4315,7 +4315,7 @@ static struct peer_candidate* getPeerCandidates(tr_session* session, int* candid
     atomCount = 0;
     peerCount = 0;
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         atomCount += tr_ptrArraySize(&tor->swarm->pool);
         peerCount += tr_ptrArraySize(&tor->swarm->peers);
@@ -4334,7 +4334,7 @@ static struct peer_candidate* getPeerCandidates(tr_session* session, int* candid
     /* populate the candidate array */
     tor = NULL;
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         int i, nAtoms;
         struct peer_atom** atoms;
@@ -4395,7 +4395,7 @@ static void initiateConnection(tr_peerMgr* mgr, tr_swarm* s, struct peer_atom* a
         /* PEX has explicit signalling for uTP support.  If an atom
            originally came from PEX and doesn't have the uTP flag, skip the
            uTP connection attempt.  Are we being optimistic here? */
-        utp = utp && (atom->flags & ADDED_F_UTP_FLAGS);
+        utp = utp && (atom->flags & ADDED_F_UTP_FLAGS) != 0;
     }
 
     tordbg(s, "Starting an OUTGOING%s connection with %s", utp ? " ÂµTP" : "", tr_atomAddrStr(atom));
index 8195756f3c48a0db66741b4b327c56e1a4dd7968..649edc48aaf1d7e63004df7e9cec79d27c3f178c 100644 (file)
@@ -571,12 +571,12 @@ size_t tr_generateAllowedSet(tr_piece_index_t* setmePieces, size_t desiredSetSiz
 {
     size_t setSize = 0;
 
-    assert(setmePieces);
+    assert(setmePieces != NULL);
     assert(desiredSetSize <= pieceCount);
-    assert(desiredSetSize);
-    assert(pieceCount);
-    assert(infohash);
-    assert(addr);
+    assert(desiredSetSize != 0);
+    assert(pieceCount != 0);
+    assert(infohash != NULL);
+    assert(addr != NULL);
 
     if (addr->type == TR_AF_INET)
     {
@@ -626,7 +626,7 @@ size_t tr_generateAllowedSet(tr_piece_index_t* setmePieces, size_t desiredSetSiz
 static void updateFastSet(tr_peerMsgs* msgs UNUSED)
 {
     bool const fext = tr_peerIoSupportsFEXT(msgs->io);
-    int const peerIsNeedy = msgs->peer->progress < 0.10;
+    bool const peerIsNeedy = msgs->peer->progress < 0.10;
 
     if (fext && peerIsNeedy && !msgs->haveFastSet)
     {
@@ -732,7 +732,7 @@ static void sendInterest(tr_peerMsgs* msgs, bool b)
 {
     struct evbuffer* out = msgs->outMessages;
 
-    assert(msgs);
+    assert(msgs != NULL);
     assert(tr_isBool(b));
 
     msgs->client_is_interested = b;
@@ -792,7 +792,7 @@ static bool popNextRequest(tr_peerMsgs* msgs, struct peer_request* setme)
 static void cancelAllRequestsToClient(tr_peerMsgs* msgs)
 {
     struct peer_request req;
-    int const mustSendCancel = tr_peerIoSupportsFEXT(msgs->io);
+    bool const mustSendCancel = tr_peerIoSupportsFEXT(msgs->io);
 
     while (popNextRequest(msgs, &req))
     {
@@ -884,7 +884,7 @@ static void sendLtepHandshake(tr_peerMsgs* msgs)
         return;
     }
 
-    if (!version_quark)
+    if (version_quark == 0)
     {
         version_quark = tr_quark_new(TR_NAME " " USERAGENT_PREFIX, TR_BAD_SIZE);
     }
@@ -924,7 +924,7 @@ static void sendLtepHandshake(tr_peerMsgs* msgs)
         tr_variantDictAddRaw(&val, TR_KEY_ipv6, ipv6, 16);
     }
 
-    if (allow_metadata_xfer && tr_torrentHasMetadata(msgs->torrent) && (msgs->torrent->infoDictLength > 0))
+    if (allow_metadata_xfer && tr_torrentHasMetadata(msgs->torrent) && msgs->torrent->infoDictLength > 0)
     {
         tr_variantDictAddInt(&val, TR_KEY_metadata_size, msgs->torrent->infoDictLength);
     }
@@ -978,7 +978,7 @@ static void parseLtepHandshake(tr_peerMsgs* msgs, uint32_t len, struct evbuffer*
     tr_peerIoReadBytes(msgs->io, inbuf, tmp, len);
     msgs->peerSentLtepHandshake = true;
 
-    if (tr_variantFromBenc(&val, tmp, len) || !tr_variantIsDict(&val))
+    if (tr_variantFromBenc(&val, tmp, len) != 0 || !tr_variantIsDict(&val))
     {
         dbgmsg(msgs, "GET  extended-handshake, couldn't get dictionary");
         tr_free(tmp);
@@ -998,9 +998,9 @@ static void parseLtepHandshake(tr_peerMsgs* msgs, uint32_t len, struct evbuffer*
     /* does the peer prefer encrypted connections? */
     if (tr_variantDictFindInt(&val, TR_KEY_e, &i))
     {
-        msgs->encryption_preference = i ? ENCRYPTION_PREFERENCE_YES : ENCRYPTION_PREFERENCE_NO;
+        msgs->encryption_preference = i != 0 ? ENCRYPTION_PREFERENCE_YES : ENCRYPTION_PREFERENCE_NO;
 
-        if (i)
+        if (i != 0)
         {
             pex.flags |= ADDED_F_ENCRYPTION_FLAG;
         }
@@ -1057,14 +1057,14 @@ static void parseLtepHandshake(tr_peerMsgs* msgs, uint32_t len, struct evbuffer*
         dbgmsg(msgs, "peer's port is now %d", (int)i);
     }
 
-    if (tr_peerIoIsIncoming(msgs->io) && tr_variantDictFindRaw(&val, TR_KEY_ipv4, &addr, &addr_len) && (addr_len == 4))
+    if (tr_peerIoIsIncoming(msgs->io) && tr_variantDictFindRaw(&val, TR_KEY_ipv4, &addr, &addr_len) && addr_len == 4)
     {
         pex.addr.type = TR_AF_INET;
         memcpy(&pex.addr.addr.addr4, addr, 4);
         tr_peerMgrAddPex(msgs->torrent, TR_PEER_FROM_LTEP, &pex, seedProbability);
     }
 
-    if (tr_peerIoIsIncoming(msgs->io) && tr_variantDictFindRaw(&val, TR_KEY_ipv6, &addr, &addr_len) && (addr_len == 16))
+    if (tr_peerIoIsIncoming(msgs->io) && tr_variantDictFindRaw(&val, TR_KEY_ipv6, &addr, &addr_len) && addr_len == 16)
     {
         pex.addr.type = TR_AF_INET6;
         memcpy(&pex.addr.addr.addr6, addr, 16);
@@ -1094,7 +1094,7 @@ static void parseUtMetadata(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer*
     tr_peerIoReadBytes(msgs->io, inbuf, tmp, msglen);
     msg_end = (char*)tmp + msglen;
 
-    if (!tr_variantFromBencFull(&dict, tmp, msglen, NULL, &benc_end))
+    if (tr_variantFromBencFull(&dict, tmp, msglen, NULL, &benc_end) == 0)
     {
         tr_variantDictFindInt(&dict, TR_KEY_msg_type, &msg_type);
         tr_variantDictFindInt(&dict, TR_KEY_piece, &piece);
@@ -1109,8 +1109,8 @@ static void parseUtMetadata(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer*
         /* NOOP */
     }
 
-    if ((msg_type == METADATA_MSG_TYPE_DATA) && (!tr_torrentHasMetadata(msgs->torrent)) &&
-        (msg_end - benc_end <= METADATA_PIECE_SIZE) && (piece * METADATA_PIECE_SIZE + (msg_end - benc_end) <= total_size))
+    if (msg_type == METADATA_MSG_TYPE_DATA && !tr_torrentHasMetadata(msgs->torrent) &&
+        msg_end - benc_end <= METADATA_PIECE_SIZE && piece * METADATA_PIECE_SIZE + (msg_end - benc_end) <= total_size)
     {
         int const pieceLen = msg_end - benc_end;
         tr_torrentSetMetadataPiece(msgs->torrent, piece, benc_end, pieceLen);
@@ -1118,8 +1118,8 @@ static void parseUtMetadata(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer*
 
     if (msg_type == METADATA_MSG_TYPE_REQUEST)
     {
-        if ((piece >= 0) && tr_torrentHasMetadata(msgs->torrent) && !tr_torrentIsPrivate(msgs->torrent) &&
-            (msgs->peerAskedForMetadataCount < METADATA_REQQ))
+        if (piece >= 0 && tr_torrentHasMetadata(msgs->torrent) && !tr_torrentIsPrivate(msgs->torrent) &&
+            msgs->peerAskedForMetadataCount < METADATA_REQQ)
         {
             msgs->peerAskedForMetadata[msgs->peerAskedForMetadataCount++] = piece;
         }
@@ -1154,7 +1154,7 @@ static void parseUtMetadata(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer*
 
 static void parseUtPex(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer* inbuf)
 {
-    int loaded = 0;
+    bool loaded = false;
     uint8_t* tmp = tr_new(uint8_t, msglen);
     tr_variant val;
     tr_torrent* tor = msgs->torrent;
@@ -1163,7 +1163,7 @@ static void parseUtPex(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer* inbu
 
     tr_peerIoReadBytes(msgs->io, inbuf, tmp, msglen);
 
-    if (tr_torrentAllowsPex(tor) && ((loaded = !tr_variantFromBenc(&val, tmp, msglen))))
+    if (tr_torrentAllowsPex(tor) && (loaded = tr_variantFromBenc(&val, tmp, msglen) == 0))
     {
         if (tr_variantDictFindRaw(&val, TR_KEY_added, &added, &added_len))
         {
@@ -1183,7 +1183,7 @@ static void parseUtPex(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer* inbu
 
                 if (i < added_f_len)
                 {
-                    seedProbability = (added_f[i] & ADDED_F_SEED_FLAG) ? 100 : 0;
+                    seedProbability = (added_f[i] & ADDED_F_SEED_FLAG) != 0 ? 100 : 0;
                 }
 
                 tr_peerMgrAddPex(tor, TR_PEER_FROM_PEX, pex + i, seedProbability);
@@ -1210,7 +1210,7 @@ static void parseUtPex(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer* inbu
 
                 if (i < added_f_len)
                 {
-                    seedProbability = (added_f[i] & ADDED_F_SEED_FLAG) ? 100 : 0;
+                    seedProbability = (added_f[i] & ADDED_F_SEED_FLAG) != 0 ? 100 : 0;
                 }
 
                 tr_peerMgrAddPex(tor, TR_PEER_FROM_PEX, pex + i, seedProbability);
@@ -1356,9 +1356,9 @@ static void prefetchPieces(tr_peerMsgs* msgs)
 static void peerMadeRequest(tr_peerMsgs* msgs, struct peer_request const* req)
 {
     bool const fext = tr_peerIoSupportsFEXT(msgs->io);
-    int const reqIsValid = requestIsValid(msgs, req);
-    int const clientHasPiece = reqIsValid && tr_torrentPieceIsComplete(msgs->torrent, req->index);
-    int const peerIsChoked = msgs->peer_is_choked;
+    bool const reqIsValid = requestIsValid(msgs, req);
+    bool const clientHasPiece = reqIsValid && tr_torrentPieceIsComplete(msgs->torrent, req->index);
+    bool const peerIsChoked = msgs->peer_is_choked;
 
     bool allow = false;
 
@@ -1414,7 +1414,7 @@ static bool messageLengthIsCorrect(tr_peerMsgs const* msg, uint8_t id, uint32_t
     case BT_BITFIELD:
         if (tr_torrentHasMetadata(msg->torrent))
         {
-            return len == (msg->torrent->info.pieceCount >> 3) + (msg->torrent->info.pieceCount & 7 ? 1 : 0) + 1u;
+            return len == (msg->torrent->info.pieceCount >> 3) + ((msg->torrent->info.pieceCount & 7) != 0 ? 1 : 0) + 1u;
         }
 
         /* we don't know the piece count yet,
@@ -1454,7 +1454,7 @@ static int readBtPiece(tr_peerMsgs* msgs, struct evbuffer* inbuf, size_t inlen,
     assert(evbuffer_get_length(inbuf) >= inlen);
     dbgmsg(msgs, "In readBtPiece");
 
-    if (!req->length)
+    if (req->length == 0)
     {
         if (inlen < 8)
         {
@@ -1504,7 +1504,7 @@ static int readBtPiece(tr_peerMsgs* msgs, struct evbuffer* inbuf, size_t inlen,
         /* cleanup */
         req->length = 0;
         msgs->state = AWAITING_BT_LENGTH;
-        return err ? READ_ERR : READ_NOW;
+        return err != 0 ? READ_ERR : READ_NOW;
     }
 }
 
@@ -1575,7 +1575,7 @@ static int readBtMessage(tr_peerMsgs* msgs, struct evbuffer* inbuf, size_t inlen
         tr_peerIoReadUint32(msgs->io, inbuf, &ui32);
         dbgmsg(msgs, "got Have: %u", ui32);
 
-        if (tr_torrentHasMetadata(msgs->torrent) && (ui32 >= msgs->torrent->info.pieceCount))
+        if (tr_torrentHasMetadata(msgs->torrent) && ui32 >= msgs->torrent->info.pieceCount)
         {
             fireError(msgs, ERANGE);
             return READ_ERR;
@@ -1628,7 +1628,7 @@ static int readBtMessage(tr_peerMsgs* msgs, struct evbuffer* inbuf, size_t inlen
             {
                 struct peer_request const* req = msgs->peerAskedFor + i;
 
-                if ((req->index == r.index) && (req->offset == r.offset) && (req->length == r.length))
+                if (req->index == r.index && req->offset == r.offset && req->length == r.length)
                 {
                     break;
                 }
@@ -1803,7 +1803,7 @@ static int clientGotBlock(tr_peerMsgs* msgs, struct evbuffer* data, struct peer_
     ***  Save the block
     **/
 
-    if ((err = tr_cacheWriteBlock(getSession(msgs)->cache, tor, req->index, req->offset, req->length, data)))
+    if ((err = tr_cacheWriteBlock(getSession(msgs)->cache, tor, req->index, req->offset, req->length, data)) != 0)
     {
         return err;
     }
@@ -1824,7 +1824,7 @@ static void didWrite(tr_peerIo* io, size_t bytesWritten, bool wasPieceData, void
         firePeerGotPieceData(msgs, bytesWritten);
     }
 
-    if (tr_isPeerIo(io) && io->userData)
+    if (tr_isPeerIo(io) && io->userData != NULL)
     {
         peerPulse(msgs);
     }
@@ -1839,7 +1839,7 @@ static ReadState canRead(tr_peerIo* io, void* vmsgs, size_t* piece)
 
     dbgmsg(msgs, "canRead: inlen is %zu, msgs->state is %d", inlen, msgs->state);
 
-    if (!inlen)
+    if (inlen == 0)
     {
         ret = READ_LATER;
     }
@@ -1972,8 +1972,8 @@ static void updateMetadataRequests(tr_peerMsgs* msgs, time_t now)
 
 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)))
+    if (tr_torrentIsPieceTransferAllowed(msgs->torrent, TR_PEER_TO_CLIENT) && msgs->desiredRequestCount > 0 &&
+        msgs->peer.pendingReqsToPeer <= msgs->desiredRequestCount * 0.66)
     {
         int i;
         int n;
@@ -2009,12 +2009,12 @@ static size_t fillOutputBuffer(tr_peerMsgs* msgs, time_t now)
     ***  Protocol messages
     **/
 
-    if (haveMessages && !msgs->outMessagesBatchedAt) /* fresh batch */
+    if (haveMessages && msgs->outMessagesBatchedAt == 0) /* fresh batch */
     {
         dbgmsg(msgs, "started an outMessages batch (length is %zu)", evbuffer_get_length(msgs->outMessages));
         msgs->outMessagesBatchedAt = now;
     }
-    else if (haveMessages && ((now - msgs->outMessagesBatchedAt) >= msgs->outMessagesBatchPeriod))
+    else if (haveMessages && now - msgs->outMessagesBatchedAt >= msgs->outMessagesBatchPeriod)
     {
         size_t const len = evbuffer_get_length(msgs->outMessages);
         /* flush the protocol messages */
@@ -2030,7 +2030,7 @@ static size_t fillOutputBuffer(tr_peerMsgs* msgs, time_t now)
     ***  Metadata Pieces
     **/
 
-    if ((tr_peerIoGetWriteBufferSpace(msgs->io, now) >= METADATA_PIECE_SIZE) && popNextMetadataRequest(msgs, &piece))
+    if (tr_peerIoGetWriteBufferSpace(msgs->io, now) >= METADATA_PIECE_SIZE && popNextMetadataRequest(msgs, &piece))
     {
         char* data;
         size_t dataLen;
@@ -2096,7 +2096,7 @@ static size_t fillOutputBuffer(tr_peerMsgs* msgs, time_t now)
     ***  Data Blocks
     **/
 
-    if ((tr_peerIoGetWriteBufferSpace(msgs->io, now) >= msgs->torrent->blockSize) && popNextRequest(msgs, &req))
+    if (tr_peerIoGetWriteBufferSpace(msgs->io, now) >= msgs->torrent->blockSize && popNextRequest(msgs, &req))
     {
         --msgs->prefetchCount;
 
@@ -2122,16 +2122,16 @@ static size_t fillOutputBuffer(tr_peerMsgs* msgs, time_t now)
             evbuffer_commit_space(out, iovec, 1);
 
             /* check the piece if it needs checking... */
-            if (!err && tr_torrentPieceNeedsCheck(msgs->torrent, req.index))
+            if (err == 0 && tr_torrentPieceNeedsCheck(msgs->torrent, req.index))
             {
-                if ((err = !tr_torrentCheckPiece(msgs->torrent, req.index)))
+                if ((err = !tr_torrentCheckPiece(msgs->torrent, req.index)) != 0)
                 {
                     tr_torrentSetLocalError(msgs->torrent, _("Please Verify Local Data! Piece #%zu is corrupt."),
                         (size_t)req.index);
                 }
             }
 
-            if (err)
+            if (err != 0)
             {
                 if (fext)
                 {
@@ -2151,7 +2151,7 @@ static size_t fillOutputBuffer(tr_peerMsgs* msgs, time_t now)
 
             evbuffer_free(out);
 
-            if (err)
+            if (err != 0)
             {
                 bytesWritten = 0;
                 msgs = NULL;
@@ -2172,7 +2172,7 @@ static size_t fillOutputBuffer(tr_peerMsgs* msgs, time_t now)
     ***  Keepalive
     **/
 
-    if ((msgs != NULL) && (msgs->clientSentAnythingAt != 0) && ((now - msgs->clientSentAnythingAt) > KEEPALIVE_INTERVAL_SECS))
+    if (msgs != NULL && msgs->clientSentAnythingAt != 0 && now - msgs->clientSentAnythingAt > KEEPALIVE_INTERVAL_SECS)
     {
         dbgmsg(msgs, "sending a keepalive message");
         evbuffer_add_uint32(msgs->outMessages, 0);
@@ -2215,12 +2215,12 @@ void tr_peerMsgsPulse(tr_peerMsgs* msgs)
 
 static void gotError(tr_peerIo* io UNUSED, short what, void* vmsgs)
 {
-    if (what & BEV_EVENT_TIMEOUT)
+    if ((what & BEV_EVENT_TIMEOUT) != 0)
     {
         dbgmsg(vmsgs, "libevent got a timeout, what=%hd", what);
     }
 
-    if (what & (BEV_EVENT_EOF | BEV_EVENT_ERROR))
+    if ((what & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) != 0)
     {
         dbgmsg(vmsgs, "libevent got an error! what=%hd, errno=%d (%s)", what, errno, tr_strerror(errno));
     }
@@ -2355,7 +2355,7 @@ static void tr_set_compare(void const* va, size_t aCount, void const* vb, size_t
         {
             int const val = (*compare)(a, b);
 
-            if (!val)
+            if (val == 0)
             {
                 (*in_both_cb)((void*)a, userData);
                 a += elementSize;
@@ -2406,7 +2406,7 @@ static void sendPex(tr_peerMsgs* msgs)
         dbgmsg(msgs, "pex: old peer count %d+%d, new peer count %d+%d, added %d+%d, removed %d+%d", msgs->pexCount,
             msgs->pexCount6, newCount, newCount6, diffs.addedCount, diffs6.addedCount, diffs.droppedCount, diffs6.droppedCount);
 
-        if (!diffs.addedCount && !diffs.droppedCount && !diffs6.addedCount && !diffs6.droppedCount)
+        if (diffs.addedCount == 0 && diffs.droppedCount == 0 && diffs6.addedCount == 0 && diffs6.droppedCount == 0)
         {
             tr_free(diffs.elements);
             tr_free(diffs6.elements);
@@ -2443,7 +2443,7 @@ static void sendPex(tr_peerMsgs* msgs)
                     walk += 2;
                 }
 
-                assert((walk - tmp) == diffs.addedCount * 6);
+                assert(walk - tmp == diffs.addedCount * 6);
                 tr_variantDictAddRaw(&val, TR_KEY_added, tmp, walk - tmp);
                 tr_free(tmp);
 
@@ -2456,7 +2456,7 @@ static void sendPex(tr_peerMsgs* msgs)
                     *walk++ = diffs.added[i].flags & ~ADDED_F_HOLEPUNCH;
                 }
 
-                assert((walk - tmp) == diffs.addedCount);
+                assert(walk - tmp == diffs.addedCount);
                 tr_variantDictAddRaw(&val, TR_KEY_added_f, tmp, walk - tmp);
                 tr_free(tmp);
             }
@@ -2474,7 +2474,7 @@ static void sendPex(tr_peerMsgs* msgs)
                     walk += 2;
                 }
 
-                assert((walk - tmp) == diffs.droppedCount * 6);
+                assert(walk - tmp == diffs.droppedCount * 6);
                 tr_variantDictAddRaw(&val, TR_KEY_dropped, tmp, walk - tmp);
                 tr_free(tmp);
             }
@@ -2492,7 +2492,7 @@ static void sendPex(tr_peerMsgs* msgs)
                     walk += 2;
                 }
 
-                assert((walk - tmp) == diffs6.addedCount * 18);
+                assert(walk - tmp == diffs6.addedCount * 18);
                 tr_variantDictAddRaw(&val, TR_KEY_added6, tmp, walk - tmp);
                 tr_free(tmp);
 
@@ -2505,7 +2505,7 @@ static void sendPex(tr_peerMsgs* msgs)
                     *walk++ = diffs6.added[i].flags & ~ADDED_F_HOLEPUNCH;
                 }
 
-                assert((walk - tmp) == diffs6.addedCount);
+                assert(walk - tmp == diffs6.addedCount);
                 tr_variantDictAddRaw(&val, TR_KEY_added6_f, tmp, walk - tmp);
                 tr_free(tmp);
             }
@@ -2523,7 +2523,7 @@ static void sendPex(tr_peerMsgs* msgs)
                     walk += 2;
                 }
 
-                assert((walk - tmp) == diffs6.droppedCount * 18);
+                assert(walk - tmp == diffs6.droppedCount * 18);
                 tr_variantDictAddRaw(&val, TR_KEY_dropped6, tmp, walk - tmp);
                 tr_free(tmp);
             }
@@ -2606,7 +2606,7 @@ static void peermsgs_destruct(tr_peer* peer)
         evbuffer_free(msgs->incoming.block);
     }
 
-    if (msgs->io)
+    if (msgs->io != NULL)
     {
         tr_peerIoClear(msgs->io);
         tr_peerIoUnref(msgs->io); /* balanced by the ref in handshakeDoneCB() */
@@ -2694,7 +2694,7 @@ bool tr_peerMsgsIsIncomingConnection(tr_peerMsgs const* msgs)
 bool tr_isPeerMsgs(void const* msgs)
 {
     /* FIXME: this is pretty crude */
-    return (msgs != NULL) && (((struct tr_peerMsgs*)msgs)->magic_number == MAGIC_NUMBER);
+    return msgs != NULL && ((struct tr_peerMsgs*)msgs)->magic_number == MAGIC_NUMBER;
 }
 
 tr_peerMsgs* tr_peerMsgsCast(void* vm)
index ae5f0718bc70c729fd94fa5b6f049eade519ce08..aaa5889cd08f7e424ab76aec80fafeafe5b0531d 100644 (file)
@@ -120,7 +120,7 @@ static char const* getdev(char const* path)
     }
 
     endmntent(fp);
-    return mnt ? mnt->mnt_fsname : NULL;
+    return mnt != NULL ? mnt->mnt_fsname : NULL;
 
 #endif
 
@@ -132,7 +132,7 @@ static char const* getdev(char const* path)
 
     n = getmntinfo(&mnt, MNT_WAIT);
 
-    if (!n)
+    if (n == 0)
     {
         return NULL;
     }
@@ -145,7 +145,7 @@ static char const* getdev(char const* path)
         }
     }
 
-    return (i < n) ? mnt[i].f_mntfromname : NULL;
+    return i < n ? mnt[i].f_mntfromname : NULL;
 
 #endif
 }
@@ -197,7 +197,7 @@ static char const* getfstype(char const* device)
     }
 
     endmntent(fp);
-    return mnt ? mnt->mnt_type : NULL;
+    return mnt != NULL ? mnt->mnt_type : NULL;
 
 #endif
 
@@ -209,7 +209,7 @@ static char const* getfstype(char const* device)
 
     n = getmntinfo(&mnt, MNT_WAIT);
 
-    if (!n)
+    if (n == 0)
     {
         return NULL;
     }
@@ -222,7 +222,7 @@ static char const* getfstype(char const* device)
         }
     }
 
-    return (i < n) ? mnt[i].f_fstypename : NULL;
+    return i < n ? mnt[i].f_fstypename : NULL;
 
 #endif
 }
@@ -260,7 +260,7 @@ static char const* getblkdev(char const* path)
     return device;
 }
 
-#if defined(__NetBSD__) && (__NetBSD_Version__ >= 600000000)
+#if defined(__NetBSD__) && __NetBSD_Version__ >= 600000000
 
 #include <quota.h>
 
@@ -308,7 +308,7 @@ static int64_t getquota(char const* device)
     quota_close(qh);
 
     freespace = limit - spaceused;
-    return (freespace < 0) ? 0 : freespace;
+    return freespace < 0 ? 0 : freespace;
 }
 
 #else
@@ -378,9 +378,9 @@ static int64_t getquota(char const* device)
         freespace = limit - spaceused;
 
 #ifdef __APPLE__
-        return (freespace < 0) ? 0 : freespace;
+        return freespace < 0 ? 0 : freespace;
 #else
-        return (freespace < 0) ? 0 : freespace * 1024;
+        return freespace < 0 ? 0 : freespace * 1024;
 #endif
     }
 
@@ -420,7 +420,7 @@ static int64_t getxfsquota(char* device)
         }
 
         freespace = limit - (dq.d_bcount >> 1);
-        return (freespace < 0) ? 0 : freespace * 1024;
+        return freespace < 0 ? 0 : freespace * 1024;
     }
 
     /* something went wrong */
@@ -437,7 +437,7 @@ static int64_t tr_getQuotaFreeSpace(struct tr_device_info const* info)
 
 #ifndef _WIN32
 
-    if (info->fstype && !evutil_ascii_strcasecmp(info->fstype, "xfs"))
+    if (info->fstype != NULL && evutil_ascii_strcasecmp(info->fstype, "xfs") == 0)
     {
 #ifdef HAVE_XQM
         ret = getxfsquota(info->device);
@@ -524,7 +524,7 @@ int64_t tr_device_info_get_free_space(struct tr_device_info const* info)
 {
     int64_t free_space;
 
-    if ((info == NULL) || (info->path == NULL))
+    if (info == NULL || info->path == NULL)
     {
         errno = EINVAL;
         free_space = -1;
index 60fec97af0d24043c6513ab85de8fb59d64332d2..4466f2a23fbaabdcc69a8644ca3126ab921403f9 100644 (file)
@@ -192,14 +192,14 @@ void tr_lockLock(tr_lock* l)
 #endif
 
     assert(l->depth >= 0);
-    assert(!l->depth || tr_areThreadsEqual(l->lockThread, tr_getCurrentThread()));
+    assert(l->depth == 0 || tr_areThreadsEqual(l->lockThread, tr_getCurrentThread()));
     l->lockThread = tr_getCurrentThread();
     ++l->depth;
 }
 
 bool tr_lockHave(tr_lock const* l)
 {
-    return (l->depth > 0) && (tr_areThreadsEqual(l->lockThread, tr_getCurrentThread()));
+    return l->depth > 0 && tr_areThreadsEqual(l->lockThread, tr_getCurrentThread());
 }
 
 void tr_lockUnlock(tr_lock* l)
@@ -252,11 +252,11 @@ static char const* getHomeDir(void)
 {
     static char* home = NULL;
 
-    if (!home)
+    if (home == NULL)
     {
         home = tr_env_get_string("HOME", NULL);
 
-        if (!home)
+        if (home == NULL)
         {
 #ifdef _WIN32
 
@@ -266,7 +266,7 @@ static char const* getHomeDir(void)
 
             struct passwd* pw = getpwuid(getuid());
 
-            if (pw)
+            if (pw != NULL)
             {
                 home = tr_strdup(pw->pw_dir);
             }
@@ -276,7 +276,7 @@ static char const* getHomeDir(void)
 #endif
         }
 
-        if (!home)
+        if (home == NULL)
         {
             home = tr_strdup("");
         }
@@ -327,12 +327,12 @@ char const* tr_getDefaultConfigDir(char const* appname)
 {
     static char* s = NULL;
 
-    if (!appname || !*appname)
+    if (appname == NULL || *appname == '\0')
     {
         appname = "Transmission";
     }
 
-    if (!s)
+    if (s == NULL)
     {
         s = tr_env_get_string("TRANSMISSION_HOME", NULL);
 
@@ -389,7 +389,7 @@ char const* tr_getDefaultDownloadDir(void)
         /* figure out where to look for user-dirs.dirs */
         config_home = tr_env_get_string("XDG_CONFIG_HOME", NULL);
 
-        if (config_home && *config_home)
+        if (config_home != NULL && *config_home != '\0')
         {
             config_file = tr_buildPath(config_home, "user-dirs.dirs", NULL);
         }
@@ -403,7 +403,7 @@ char const* tr_getDefaultDownloadDir(void)
         /* read in user-dirs.dirs and look for the download dir entry */
         content = (char*)tr_loadFile(config_file, &content_len, NULL);
 
-        if (content && content_len > 0)
+        if (content != NULL && content_len > 0)
         {
             char const* key = "XDG_DOWNLOAD_DIR=\"";
             char* line = strstr(content, key);
@@ -413,7 +413,7 @@ char const* tr_getDefaultDownloadDir(void)
                 char* value = line + strlen(key);
                 char* end = strchr(value, '"');
 
-                if (end)
+                if (end != NULL)
                 {
                     *end = '\0';
 
@@ -476,7 +476,7 @@ char const* tr_getWebClientDir(tr_session const* session UNUSED)
 {
     static char* s = NULL;
 
-    if (!s)
+    if (s == NULL)
     {
         s = tr_env_get_string("CLUTCH_HOME", NULL);
 
@@ -575,7 +575,7 @@ char const* tr_getWebClientDir(tr_session const* session UNUSED)
             /* XDG_DATA_HOME should be the first in the list of candidates */
             tmp = tr_env_get_string("XDG_DATA_HOME", NULL);
 
-            if (tmp && *tmp)
+            if (tmp != NULL && *tmp != '\0')
             {
                 tr_list_append(&candidates, tmp);
             }
@@ -595,20 +595,20 @@ char const* tr_getWebClientDir(tr_session const* session UNUSED)
                 tr_free(xdg);
                 tmp = buf;
 
-                while (tmp && *tmp)
+                while (tmp != NULL && *tmp != '\0')
                 {
                     char const* end = strchr(tmp, ':');
 
-                    if (end)
+                    if (end != NULL)
                     {
-                        if ((end - tmp) > 1)
+                        if (end - tmp > 1)
                         {
                             tr_list_append(&candidates, tr_strndup(tmp, (size_t)(end - tmp)));
                         }
 
                         tmp = (char*)end + 1;
                     }
-                    else if (tmp && *tmp)
+                    else if (tmp != NULL && *tmp != '\0')
                     {
                         tr_list_append(&candidates, tr_strdup(tmp));
                         break;
@@ -619,10 +619,10 @@ char const* tr_getWebClientDir(tr_session const* session UNUSED)
             }
 
             /* walk through the candidates & look for a match */
-            for (l = candidates; l; l = l->next)
+            for (l = candidates; l != NULL; l = l->next)
             {
                 char* path = tr_buildPath(l->data, "transmission", "web", NULL);
-                int const found = isWebClientDir(path);
+                bool const found = isWebClientDir(path);
 
                 if (found)
                 {
index f8f4b7d58615a419065524279fe99778f80d2bb4..6114d7f1453c347e1f14e96d44e3fd34e4a0d595 100644 (file)
@@ -76,7 +76,7 @@ static void natPulse(tr_shared* s, bool do_check)
     int newStatus;
     tr_port public_peer_port;
     tr_port const private_peer_port = s->session->private_peer_port;
-    int const is_enabled = s->isEnabled && !s->isShuttingDown;
+    bool const is_enabled = s->isEnabled && !s->isShuttingDown;
 
     if (s->natpmp == NULL)
     {
@@ -143,8 +143,8 @@ static void onTimer(evutil_socket_t fd UNUSED, short what UNUSED, void* vshared)
 {
     tr_shared* s = vshared;
 
-    assert(s);
-    assert(s->timer);
+    assert(s != NULL);
+    assert(s->timer != NULL);
 
     /* do something */
     natPulse(s, s->doPortCheck);
index 9fe9ba746da1d1d83fb14e0a25902f559a5c105d..8e3e20118ad83e98e905a92919b0acb7b96ca908 100644 (file)
@@ -19,9 +19,9 @@ tr_ptrArray const TR_PTR_ARRAY_INIT = TR_PTR_ARRAY_INIT_STATIC;
 void tr_ptrArrayDestruct(tr_ptrArray* p, PtrArrayForeachFunc func)
 {
     assert(p != NULL);
-    assert(p->items || !p->n_items);
+    assert(p->items != NULL || p->n_items == 0);
 
-    if (func)
+    if (func != NULL)
     {
         tr_ptrArrayForeach(p, func);
     }
@@ -33,9 +33,9 @@ void tr_ptrArrayForeach(tr_ptrArray* t, PtrArrayForeachFunc func)
 {
     int i;
 
-    assert(t);
-    assert(t->items || !t->n_items);
-    assert(func);
+    assert(t != NULL);
+    assert(t->items != NULL || t->n_items == 0);
+    assert(func != NULL);
 
     for (i = 0; i < t->n_items; ++i)
     {
@@ -75,7 +75,7 @@ void* tr_ptrArrayPop(tr_ptrArray* t)
 {
     void* ret = NULL;
 
-    if (t->n_items)
+    if (t->n_items != 0)
     {
         ret = t->items[--t->n_items];
     }
@@ -187,7 +187,7 @@ static void assertIndexIsSortedAndUnique(tr_ptrArray const* t, int pos, int (* c
         assert(compare(t->items[pos - 1], t->items[pos]) < 0);
     }
 
-    if ((pos + 1) < t->n_items)
+    if (pos + 1 < t->n_items)
     {
         assert(compare(t->items[pos], t->items[pos + 1]) < 0);
     }
index bc9e54e22bb08d14f6ddf818ff5a39c37311dffb..60c7af2d2bfd9f6acd2e6bd2c084834ed705c4f8 100644 (file)
@@ -50,7 +50,7 @@ void tr_ptrArrayForeach(tr_ptrArray* array, PtrArrayForeachFunc func);
     @return the nth item in a tr_ptrArray */
 static inline void* tr_ptrArrayNth(tr_ptrArray* array, int i)
 {
-    assert(array);
+    assert(array != NULL);
     assert(i >= 0);
     assert(i < array->n_items);
 
index b2ab651c82e6b1d99051c9d1405e4ecd986f2002..343c659f776a748a47fe95594905a68c614700ec 100644 (file)
@@ -123,7 +123,7 @@ static tr_torrent* create_torrent_from_base64_metainfo(tr_ctor* ctor, char const
     /* create the torrent */
     err = 0;
     tor = tr_torrentNew(ctor, &err, NULL);
-    assert(!err);
+    assert(err == 0);
 
     /* cleanup */
     tr_free(metainfo);
@@ -352,10 +352,10 @@ static int test_multifile_torrent(void)
     check_streq(expected_files[3], files[3].name);
     check(testFileExistsAndConsistsOfThisString(tor, 1, expected_contents[1]));
     check(testFileExistsAndConsistsOfThisString(tor, 2, expected_contents[2]));
-    check(files[0].is_renamed == false);
-    check(files[1].is_renamed == true);
-    check(files[2].is_renamed == true);
-    check(files[3].is_renamed == false);
+    check(!files[0].is_renamed);
+    check(files[1].is_renamed);
+    check(files[2].is_renamed);
+    check(!files[3].is_renamed);
 
     /* (while the branch is renamed: confirm that the .resume file remembers the changes) */
     tr_torrentSaveResume(tor);
@@ -378,10 +378,10 @@ static int test_multifile_torrent(void)
         check(testFileExistsAndConsistsOfThisString(tor, i, expected_contents[i]));
     }
 
-    check(files[0].is_renamed == false);
-    check(files[1].is_renamed == true);
-    check(files[2].is_renamed == true);
-    check(files[3].is_renamed == false);
+    check(!files[0].is_renamed);
+    check(files[1].is_renamed);
+    check(files[2].is_renamed);
+    check(!files[3].is_renamed);
 
     /***
     ****  Test it an incomplete torrent...
@@ -477,18 +477,18 @@ static int test_multifile_torrent(void)
     /* rename prefix of top */
     check_int_eq(EINVAL, torrentRenameAndWait(tor, "Feli", "FelidaeX"));
     check_streq(tor->info.name, "Felidae");
-    check(files[0].is_renamed == false);
-    check(files[1].is_renamed == false);
-    check(files[2].is_renamed == false);
-    check(files[3].is_renamed == false);
+    check(!files[0].is_renamed);
+    check(!files[1].is_renamed);
+    check(!files[2].is_renamed);
+    check(!files[3].is_renamed);
 
     /* rename false path */
     check_int_eq(EINVAL, torrentRenameAndWait(tor, "Felidae/FelinaeX", "Genus Felinae"));
     check_streq(tor->info.name, "Felidae");
-    check(files[0].is_renamed == false);
-    check(files[1].is_renamed == false);
-    check(files[2].is_renamed == false);
-    check(files[3].is_renamed == false);
+    check(!files[0].is_renamed);
+    check(!files[1].is_renamed);
+    check(!files[2].is_renamed);
+    check(!files[3].is_renamed);
 
     /***
     ****
index e36dafca7c31d522d4bc35adf2e1fafd36626567..4495e8d604e8b8e0380bd7d45905fd9b64bf2733 100644 (file)
@@ -132,7 +132,7 @@ static uint64_t loadDND(tr_variant* dict, tr_torrent* tor)
     tr_variant* list = NULL;
     tr_file_index_t const n = tor->info.fileCount;
 
-    if (tr_variantDictFindList(dict, TR_KEY_dnd, &list) && (tr_variantListSize(list) == n))
+    if (tr_variantDictFindList(dict, TR_KEY_dnd, &list) && tr_variantListSize(list) == n)
     {
         int64_t tmp;
         tr_file_index_t* dl = tr_new(tr_file_index_t, n);
@@ -141,7 +141,7 @@ static uint64_t loadDND(tr_variant* dict, tr_torrent* tor)
 
         for (i = 0; i < n; ++i)
         {
-            if (tr_variantGetInt(tr_variantListChild(list, i), &tmp) && tmp)
+            if (tr_variantGetInt(tr_variantListChild(list, i), &tmp) && tmp != 0)
             {
                 dnd[dndCount++] = i;
             }
@@ -151,13 +151,13 @@ static uint64_t loadDND(tr_variant* dict, tr_torrent* tor)
             }
         }
 
-        if (dndCount)
+        if (dndCount != 0)
         {
             tr_torrentInitFileDLs(tor, dnd, dndCount, false);
             tr_logAddTorDbg(tor, "Resume file found %d files listed as dnd", dndCount);
         }
 
-        if (dlCount)
+        if (dlCount != 0)
         {
             tr_torrentInitFileDLs(tor, dl, dlCount, true);
             tr_logAddTorDbg(tor, "Resume file found %d files marked for download", dlCount);
@@ -201,7 +201,7 @@ static uint64_t loadFilePriorities(tr_variant* dict, tr_torrent* tor)
     uint64_t ret = 0;
     tr_file_index_t const n = tor->info.fileCount;
 
-    if (tr_variantDictFindList(dict, TR_KEY_priority, &list) && (tr_variantListSize(list) == n))
+    if (tr_variantDictFindList(dict, TR_KEY_priority, &list) && tr_variantListSize(list) == n)
     {
         int64_t priority;
         tr_file_index_t i;
@@ -422,7 +422,7 @@ static uint64_t loadFilenames(tr_variant* dict, tr_torrent* tor)
             char const* str;
             size_t str_len;
 
-            if (tr_variantGetStr(tr_variantListChild(list, i), &str, &str_len) && str && str_len)
+            if (tr_variantGetStr(tr_variantListChild(list, i), &str, &str_len) && str != NULL && str_len != 0)
             {
                 tr_free(files[i].name);
                 files[i].name = tr_strndup(str, str_len);
@@ -485,7 +485,7 @@ static void saveProgress(tr_variant* dict, tr_torrent* tor)
         /* get the oldest and newest nonzero timestamps for pieces in this file */
         for (p = &inf->pieces[f->firstPiece], pend = &inf->pieces[f->lastPiece]; p != pend; ++p)
         {
-            if (!p->timeChecked)
+            if (p->timeChecked == 0)
             {
                 has_zero = true;
             }
@@ -509,7 +509,7 @@ static void saveProgress(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. */
 
-        if (!has_zero && (mtime <= oldest_nonzero)) /* all checked */
+        if (!has_zero && mtime <= oldest_nonzero) /* all checked */
         {
             tr_variantListAddInt(l, oldest_nonzero);
         }
@@ -525,7 +525,7 @@ static void saveProgress(tr_variant* dict, tr_torrent* tor)
 
             for (p = &inf->pieces[f->firstPiece], pend = &inf->pieces[f->lastPiece] + 1; p != pend; ++p)
             {
-                tr_variantListAddInt(ll, p->timeChecked ? p->timeChecked - offset : 0);
+                tr_variantListAddInt(ll, p->timeChecked != 0 ? p->timeChecked - offset : 0);
             }
         }
     }
@@ -606,7 +606,7 @@ static uint64_t loadProgress(tr_variant* dict, tr_torrent* tor)
                     {
                         int64_t t = 0;
                         tr_variantGetInt(tr_variantListChild(b, i + 1), &t);
-                        inf->pieces[f->firstPiece + i].timeChecked = (time_t)(t ? t + offset : 0);
+                        inf->pieces[f->firstPiece + i].timeChecked = (time_t)(t != 0 ? t + offset : 0);
                     }
                 }
             }
@@ -642,7 +642,7 @@ static uint64_t loadProgress(tr_variant* dict, tr_torrent* tor)
         err = NULL;
         tr_bitfieldConstruct(&blocks, tor->blockCount);
 
-        if ((b = tr_variantDictFind(prog, TR_KEY_blocks)))
+        if ((b = tr_variantDictFind(prog, TR_KEY_blocks)) != NULL)
         {
             size_t buflen;
             uint8_t const* buf;
@@ -751,7 +751,7 @@ void tr_torrentSaveResume(tr_torrent* tor)
 
     filename = getResumeFilename(tor);
 
-    if ((err = tr_variantToFile(&top, TR_VARIANT_FMT_BENC, filename)))
+    if ((err = tr_variantToFile(&top, TR_VARIANT_FMT_BENC, filename)) != 0)
     {
         tr_torrentSetLocalError(tor, "Unable to save resume file: %s", tr_strerror(err));
     }
@@ -788,14 +788,14 @@ static uint64_t loadFromFile(tr_torrent* tor, uint64_t fieldsToLoad)
 
     tr_logAddTorDbg(tor, "Read resume file \"%s\"", filename);
 
-    if ((fieldsToLoad & TR_FR_CORRUPT) && tr_variantDictFindInt(&top, TR_KEY_corrupt, &i))
+    if ((fieldsToLoad & TR_FR_CORRUPT) != 0 && tr_variantDictFindInt(&top, TR_KEY_corrupt, &i))
     {
         tor->corruptPrev = i;
         fieldsLoaded |= TR_FR_CORRUPT;
     }
 
-    if ((fieldsToLoad & (TR_FR_PROGRESS | TR_FR_DOWNLOAD_DIR)) &&
-        (tr_variantDictFindStr(&top, TR_KEY_destination, &str, &len)) && (str && *str))
+    if ((fieldsToLoad & (TR_FR_PROGRESS | TR_FR_DOWNLOAD_DIR)) != 0 &&
+        tr_variantDictFindStr(&top, TR_KEY_destination, &str, &len) && str != NULL && *str != '\0')
     {
         bool const is_current_dir = tor->currentDir == tor->downloadDir;
         tr_free(tor->downloadDir);
@@ -809,8 +809,8 @@ static uint64_t loadFromFile(tr_torrent* tor, uint64_t fieldsToLoad)
         fieldsLoaded |= TR_FR_DOWNLOAD_DIR;
     }
 
-    if ((fieldsToLoad & (TR_FR_PROGRESS | TR_FR_INCOMPLETE_DIR)) &&
-        (tr_variantDictFindStr(&top, TR_KEY_incomplete_dir, &str, &len)) && (str && *str))
+    if ((fieldsToLoad & (TR_FR_PROGRESS | TR_FR_INCOMPLETE_DIR)) != 0 &&
+        tr_variantDictFindStr(&top, TR_KEY_incomplete_dir, &str, &len) && str != NULL && *str != '\0')
     {
         bool const is_current_dir = tor->currentDir == tor->incompleteDir;
         tr_free(tor->incompleteDir);
@@ -824,108 +824,108 @@ static uint64_t loadFromFile(tr_torrent* tor, uint64_t fieldsToLoad)
         fieldsLoaded |= TR_FR_INCOMPLETE_DIR;
     }
 
-    if ((fieldsToLoad & TR_FR_DOWNLOADED) && tr_variantDictFindInt(&top, TR_KEY_downloaded, &i))
+    if ((fieldsToLoad & TR_FR_DOWNLOADED) != 0 && tr_variantDictFindInt(&top, TR_KEY_downloaded, &i))
     {
         tor->downloadedPrev = i;
         fieldsLoaded |= TR_FR_DOWNLOADED;
     }
 
-    if ((fieldsToLoad & TR_FR_UPLOADED) && tr_variantDictFindInt(&top, TR_KEY_uploaded, &i))
+    if ((fieldsToLoad & TR_FR_UPLOADED) != 0 && tr_variantDictFindInt(&top, TR_KEY_uploaded, &i))
     {
         tor->uploadedPrev = i;
         fieldsLoaded |= TR_FR_UPLOADED;
     }
 
-    if ((fieldsToLoad & TR_FR_MAX_PEERS) && tr_variantDictFindInt(&top, TR_KEY_max_peers, &i))
+    if ((fieldsToLoad & TR_FR_MAX_PEERS) != 0 && tr_variantDictFindInt(&top, TR_KEY_max_peers, &i))
     {
         tor->maxConnectedPeers = i;
         fieldsLoaded |= TR_FR_MAX_PEERS;
     }
 
-    if ((fieldsToLoad & TR_FR_RUN) && tr_variantDictFindBool(&top, TR_KEY_paused, &boolVal))
+    if ((fieldsToLoad & TR_FR_RUN) != 0 && tr_variantDictFindBool(&top, TR_KEY_paused, &boolVal))
     {
         tor->isRunning = !boolVal;
         fieldsLoaded |= TR_FR_RUN;
     }
 
-    if ((fieldsToLoad & TR_FR_ADDED_DATE) && tr_variantDictFindInt(&top, TR_KEY_added_date, &i))
+    if ((fieldsToLoad & TR_FR_ADDED_DATE) != 0 && tr_variantDictFindInt(&top, TR_KEY_added_date, &i))
     {
         tor->addedDate = i;
         fieldsLoaded |= TR_FR_ADDED_DATE;
     }
 
-    if ((fieldsToLoad & TR_FR_DONE_DATE) && tr_variantDictFindInt(&top, TR_KEY_done_date, &i))
+    if ((fieldsToLoad & TR_FR_DONE_DATE) != 0 && tr_variantDictFindInt(&top, TR_KEY_done_date, &i))
     {
         tor->doneDate = i;
         fieldsLoaded |= TR_FR_DONE_DATE;
     }
 
-    if ((fieldsToLoad & TR_FR_ACTIVITY_DATE) && tr_variantDictFindInt(&top, TR_KEY_activity_date, &i))
+    if ((fieldsToLoad & TR_FR_ACTIVITY_DATE) != 0 && tr_variantDictFindInt(&top, TR_KEY_activity_date, &i))
     {
         tr_torrentSetActivityDate(tor, i);
         fieldsLoaded |= TR_FR_ACTIVITY_DATE;
     }
 
-    if ((fieldsToLoad & TR_FR_TIME_SEEDING) && tr_variantDictFindInt(&top, TR_KEY_seeding_time_seconds, &i))
+    if ((fieldsToLoad & TR_FR_TIME_SEEDING) != 0 && tr_variantDictFindInt(&top, TR_KEY_seeding_time_seconds, &i))
     {
         tor->secondsSeeding = i;
         fieldsLoaded |= TR_FR_TIME_SEEDING;
     }
 
-    if ((fieldsToLoad & TR_FR_TIME_DOWNLOADING) && tr_variantDictFindInt(&top, TR_KEY_downloading_time_seconds, &i))
+    if ((fieldsToLoad & TR_FR_TIME_DOWNLOADING) != 0 && tr_variantDictFindInt(&top, TR_KEY_downloading_time_seconds, &i))
     {
         tor->secondsDownloading = i;
         fieldsLoaded |= TR_FR_TIME_DOWNLOADING;
     }
 
-    if ((fieldsToLoad & TR_FR_BANDWIDTH_PRIORITY) &&
+    if ((fieldsToLoad & TR_FR_BANDWIDTH_PRIORITY) != 0 &&
         tr_variantDictFindInt(&top, TR_KEY_bandwidth_priority, &i) && tr_isPriority(i))
     {
         tr_torrentSetPriority(tor, i);
         fieldsLoaded |= TR_FR_BANDWIDTH_PRIORITY;
     }
 
-    if (fieldsToLoad & TR_FR_PEERS)
+    if ((fieldsToLoad & TR_FR_PEERS) != 0)
     {
         fieldsLoaded |= loadPeers(&top, tor);
     }
 
-    if (fieldsToLoad & TR_FR_FILE_PRIORITIES)
+    if ((fieldsToLoad & TR_FR_FILE_PRIORITIES) != 0)
     {
         fieldsLoaded |= loadFilePriorities(&top, tor);
     }
 
-    if (fieldsToLoad & TR_FR_PROGRESS)
+    if ((fieldsToLoad & TR_FR_PROGRESS) != 0)
     {
         fieldsLoaded |= loadProgress(&top, tor);
     }
 
-    if (fieldsToLoad & TR_FR_DND)
+    if ((fieldsToLoad & TR_FR_DND) != 0)
     {
         fieldsLoaded |= loadDND(&top, tor);
     }
 
-    if (fieldsToLoad & TR_FR_SPEEDLIMIT)
+    if ((fieldsToLoad & TR_FR_SPEEDLIMIT) != 0)
     {
         fieldsLoaded |= loadSpeedLimits(&top, tor);
     }
 
-    if (fieldsToLoad & TR_FR_RATIOLIMIT)
+    if ((fieldsToLoad & TR_FR_RATIOLIMIT) != 0)
     {
         fieldsLoaded |= loadRatioLimits(&top, tor);
     }
 
-    if (fieldsToLoad & TR_FR_IDLELIMIT)
+    if ((fieldsToLoad & TR_FR_IDLELIMIT) != 0)
     {
         fieldsLoaded |= loadIdleLimits(&top, tor);
     }
 
-    if (fieldsToLoad & TR_FR_FILENAMES)
+    if ((fieldsToLoad & TR_FR_FILENAMES) != 0)
     {
         fieldsLoaded |= loadFilenames(&top, tor);
     }
 
-    if (fieldsToLoad & TR_FR_NAME)
+    if ((fieldsToLoad & TR_FR_NAME) != 0)
     {
         fieldsLoaded |= loadName(&top, tor);
     }
@@ -944,7 +944,7 @@ static uint64_t setFromCtor(tr_torrent* tor, uint64_t fields, tr_ctor const* cto
 {
     uint64_t ret = 0;
 
-    if (fields & TR_FR_RUN)
+    if ((fields & TR_FR_RUN) != 0)
     {
         bool isPaused;
 
@@ -955,7 +955,7 @@ static uint64_t setFromCtor(tr_torrent* tor, uint64_t fields, tr_ctor const* cto
         }
     }
 
-    if (fields & TR_FR_MAX_PEERS)
+    if ((fields & TR_FR_MAX_PEERS) != 0)
     {
         if (tr_ctorGetPeerLimit(ctor, mode, &tor->maxConnectedPeers))
         {
@@ -963,11 +963,11 @@ static uint64_t setFromCtor(tr_torrent* tor, uint64_t fields, tr_ctor const* cto
         }
     }
 
-    if (fields & TR_FR_DOWNLOAD_DIR)
+    if ((fields & TR_FR_DOWNLOAD_DIR) != 0)
     {
         char const* path;
 
-        if (tr_ctorGetDownloadDir(ctor, mode, &path) && path && *path)
+        if (tr_ctorGetDownloadDir(ctor, mode, &path) && path != NULL && *path != '\0')
         {
             ret |= TR_FR_DOWNLOAD_DIR;
             tr_free(tor->downloadDir);
index cfbe256e2a5c7d723c8f9a471f2a00ebd2f574a5..00b3c08b7ff5925ff883f5090c63f4c9af4fb93d 100644 (file)
@@ -98,7 +98,7 @@ static void send_simple_response(struct evhttp_request* req, int code, char cons
 
     evbuffer_add_printf(body, "<h1>%d: %s</h1>", code, code_text);
 
-    if (text)
+    if (text != NULL)
     {
         evbuffer_add_printf(body, "%s", text);
     }
@@ -130,14 +130,14 @@ static void extract_parts_from_multipart(struct evkeyvalq const* headers, struct
     size_t inlen = evbuffer_get_length(body);
 
     char const* boundary_key = "boundary=";
-    char const* boundary_key_begin = content_type ? strstr(content_type, boundary_key) : NULL;
-    char const* boundary_val = boundary_key_begin ? boundary_key_begin + strlen(boundary_key) : "arglebargle";
+    char const* boundary_key_begin = content_type != NULL ? strstr(content_type, boundary_key) : NULL;
+    char const* boundary_val = boundary_key_begin != NULL ? boundary_key_begin + strlen(boundary_key) : "arglebargle";
     char* boundary = tr_strdup_printf("--%s", boundary_val);
     size_t const boundary_len = strlen(boundary);
 
     char const* delim = tr_memmem(in, inlen, boundary, boundary_len);
 
-    while (delim)
+    while (delim != NULL)
     {
         size_t part_len;
         char const* part = delim + boundary_len;
@@ -146,13 +146,13 @@ static void extract_parts_from_multipart(struct evkeyvalq const* headers, struct
         in = part;
 
         delim = tr_memmem(in, inlen, boundary, boundary_len);
-        part_len = delim ? (size_t)(delim - part) : inlen;
+        part_len = delim != NULL ? (size_t)(delim - part) : inlen;
 
-        if (part_len)
+        if (part_len != 0)
         {
             char const* rnrn = tr_memmem(part, part_len, "\r\n\r\n", 4);
 
-            if (rnrn)
+            if (rnrn != NULL)
             {
                 struct tr_mimepart* p = tr_new(struct tr_mimepart, 1);
                 p->headers_len = (size_t)(rnrn - part);
@@ -181,7 +181,7 @@ static void handle_upload(struct evhttp_request* req, struct tr_rpc_server* serv
         tr_ptrArray parts = TR_PTR_ARRAY_INIT;
 
         char const* query = strchr(req->uri, '?');
-        bool const paused = query && strstr(query + 1, "paused=true");
+        bool const paused = query != NULL && strstr(query + 1, "paused=true") != NULL;
 
         extract_parts_from_multipart(req->input_headers, req->input_buffer, &parts);
         n = tr_ptrArraySize(&parts);
@@ -191,7 +191,7 @@ static void handle_upload(struct evhttp_request* req, struct tr_rpc_server* serv
         {
             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)))
+            if (tr_memmem(p->headers, p->headers_len, TR_RPC_SESSION_ID_HEADER, strlen(TR_RPC_SESSION_ID_HEADER)) != NULL)
             {
                 break;
             }
@@ -240,7 +240,7 @@ static void handle_upload(struct evhttp_request* req, struct tr_rpc_server* serv
                     tr_variantDictAddRaw(args, TR_KEY_filename, body, body_len);
                     have_source = true;
                 }
-                else if (!tr_variantFromBenc(&test, body, body_len))
+                else if (tr_variantFromBenc(&test, body, body_len) == 0)
                 {
                     char* b64 = tr_base64_encode(body, body_len, NULL);
                     tr_variantDictAddStr(args, TR_KEY_metainfo, b64);
@@ -296,7 +296,7 @@ static char const* mimetype_guess(char const* path)
     };
     char const* dot = strrchr(path, '.');
 
-    for (i = 0; dot && i < TR_N_ELEMENTS(types); ++i)
+    for (i = 0; dot != NULL && i < TR_N_ELEMENTS(types); ++i)
     {
         if (strcmp(dot + 1, types[i].suffix) == 0)
         {
@@ -312,7 +312,7 @@ static void add_response(struct evhttp_request* req, struct tr_rpc_server* serve
 {
     char const* key = "Accept-Encoding";
     char const* encoding = evhttp_find_header(req->input_headers, key);
-    int const do_compress = encoding && strstr(encoding, "gzip");
+    bool const do_compress = encoding != NULL && strstr(encoding, "gzip") != NULL;
 
     if (!do_compress)
     {
@@ -444,7 +444,7 @@ static void handle_web_client(struct evhttp_request* req, struct tr_rpc_server*
 {
     char const* webClientDir = tr_getWebClientDir(server->session);
 
-    if (!webClientDir || !*webClientDir)
+    if (webClientDir == NULL || *webClientDir == '\0')
     {
         send_simple_response(req, HTTP_NOTFOUND,
             "<p>Couldn't find Transmission's web interface files!</p>"
@@ -463,12 +463,12 @@ static void handle_web_client(struct evhttp_request* req, struct tr_rpc_server*
 
         subpath = tr_strdup(req->uri + strlen(server->url) + 4);
 
-        if ((pch = strchr(subpath, '?')))
+        if ((pch = strchr(subpath, '?')) != NULL)
         {
             *pch = '\0';
         }
 
-        if (strstr(subpath, ".."))
+        if (strstr(subpath, "..") != NULL)
         {
             send_simple_response(req, HTTP_NOTFOUND, "<p>Tsk, tsk.</p>");
         }
@@ -532,7 +532,7 @@ static void handle_rpc(struct evhttp_request* req, struct tr_rpc_server* server)
         handle_rpc_from_json(req, server, (char const*)evbuffer_pullup(req->input_buffer, -1),
             evbuffer_get_length(req->input_buffer));
     }
-    else if ((req->type == EVHTTP_REQ_GET) && ((q = strchr(req->uri, '?'))))
+    else if (req->type == EVHTTP_REQ_GET && (q = strchr(req->uri, '?')) != NULL)
     {
         struct rpc_response_data* data = tr_new0(struct rpc_response_data, 1);
         data->req = req;
@@ -577,7 +577,7 @@ static void handle_request(struct evhttp_request* req, void* arg)
 {
     struct tr_rpc_server* server = arg;
 
-    if (req && req->evcon)
+    if (req != NULL && req->evcon != NULL)
     {
         char const* auth;
         char* user = NULL;
@@ -587,7 +587,7 @@ static void handle_request(struct evhttp_request* req, void* arg)
 
         auth = evhttp_find_header(req->input_headers, "Authorization");
 
-        if (auth && !evutil_ascii_strncasecmp(auth, "basic ", 6))
+        if (auth != NULL && evutil_ascii_strncasecmp(auth, "basic ", 6) == 0)
         {
             size_t plen;
             char* p = tr_base64_decode_str(auth + 6, &plen);
@@ -843,7 +843,7 @@ void tr_rpcSetUrl(tr_rpc_server* server, char const* url)
 
 char const* tr_rpcGetUrl(tr_rpc_server const* server)
 {
-    return server->url ? server->url : "";
+    return server->url != NULL ? server->url : "";
 }
 
 void tr_rpcSetWhitelist(tr_rpc_server* server, char const* whitelistStr)
@@ -857,13 +857,13 @@ void tr_rpcSetWhitelist(tr_rpc_server* server, char const* whitelistStr)
     tr_free(tmp);
 
     /* clear out the old whitelist entries */
-    while ((tmp = tr_list_pop_front(&server->whitelist)))
+    while ((tmp = tr_list_pop_front(&server->whitelist)) != NULL)
     {
         tr_free(tmp);
     }
 
     /* build the new whitelist entries */
-    for (walk = whitelistStr; walk && *walk;)
+    for (walk = whitelistStr; walk != NULL && *walk != '\0';)
     {
         char const* delimiters = " ,;";
         size_t const len = strcspn(walk, delimiters);
@@ -891,7 +891,7 @@ void tr_rpcSetWhitelist(tr_rpc_server* server, char const* whitelistStr)
 
 char const* tr_rpcGetWhitelist(tr_rpc_server const* server)
 {
-    return server->whitelistStr ? server->whitelistStr : "";
+    return server->whitelistStr != NULL ? server->whitelistStr : "";
 }
 
 void tr_rpcSetWhitelistEnabled(tr_rpc_server* server, bool isEnabled)
@@ -920,7 +920,7 @@ void tr_rpcSetUsername(tr_rpc_server* server, char const* username)
 
 char const* tr_rpcGetUsername(tr_rpc_server const* server)
 {
-    return server->username ? server->username : "";
+    return server->username != NULL ? server->username : "";
 }
 
 void tr_rpcSetPassword(tr_rpc_server* server, char const* password)
@@ -941,7 +941,7 @@ void tr_rpcSetPassword(tr_rpc_server* server, char const* password)
 
 char const* tr_rpcGetPassword(tr_rpc_server const* server)
 {
-    return server->password ? server->password : "";
+    return server->password != NULL ? server->password : "";
 }
 
 void tr_rpcSetPasswordEnabled(tr_rpc_server* server, bool isEnabled)
@@ -974,7 +974,7 @@ static void closeServer(void* vserver)
 
     stopServer(s);
 
-    while ((tmp = tr_list_pop_front(&s->whitelist)))
+    while ((tmp = tr_list_pop_front(&s->whitelist)) != NULL)
     {
         tr_free(tmp);
     }
@@ -1072,7 +1072,7 @@ tr_rpc_server* tr_rpcInit(tr_session* session, tr_variant* settings)
 
     key = TR_KEY_rpc_whitelist;
 
-    if (!tr_variantDictFindStr(settings, key, &str, NULL) && str)
+    if (!tr_variantDictFindStr(settings, key, &str, NULL) && str != NULL)
     {
         missing_settings_key(key);
     }
index 5f30591fda9acbfba06863d4be205ec6311ff8b5..2cdcb6ba55c9fdb32bb11c754b158d7e600b9184 100644 (file)
@@ -72,7 +72,7 @@ static tr_rpc_callback_status notify(tr_session* session, int type, tr_torrent*
 {
     tr_rpc_callback_status status = 0;
 
-    if (session->rpc_func)
+    if (session->rpc_func != NULL)
     {
         status = session->rpc_func(session, type, tor, session->rpc_func_user_data);
     }
@@ -161,7 +161,7 @@ static tr_torrent** getTorrents(tr_session* session, tr_variant* args, int* setm
         tr_torrent* tor;
         torrents = tr_new0(tr_torrent*, 1);
 
-        if ((tor = tr_torrentFindFromId(session, id)))
+        if ((tor = tr_torrentFindFromId(session, id)) != NULL)
         {
             torrents[torrentCount++] = tor;
         }
@@ -176,7 +176,7 @@ static tr_torrent** getTorrents(tr_session* session, tr_variant* args, int* setm
             int const n = tr_sessionCountTorrents(session);
             torrents = tr_new0(tr_torrent*, n);
 
-            while ((tor = tr_torrentNext(session, tor)))
+            while ((tor = tr_torrentNext(session, tor)) != NULL)
             {
                 if (tor->anyDate >= now - window)
                 {
@@ -189,7 +189,7 @@ static tr_torrent** getTorrents(tr_session* session, tr_variant* args, int* setm
             tr_torrent* tor;
             torrents = tr_new0(tr_torrent*, 1);
 
-            if ((tor = tr_torrentFindFromHashString(session, str)))
+            if ((tor = tr_torrentFindFromHashString(session, str)) != NULL)
             {
                 torrents[torrentCount++] = tor;
             }
@@ -373,7 +373,7 @@ static char const* torrentRemove(tr_session* session, tr_variant* args_in, tr_va
         tr_torrent* tor = torrents[i];
         tr_rpc_callback_status const status = notify(session, type, tor);
 
-        if (!(status & TR_RPC_NOREMOVE))
+        if ((status & TR_RPC_NOREMOVE) == 0)
         {
             tr_torrentRemove(tor, deleteFlag, NULL);
         }
@@ -946,11 +946,11 @@ static char const* torrentGet(tr_session* session, tr_variant* args_in, tr_varia
         int const interval = RECENTLY_ACTIVE_SECONDS;
         tr_variant* removed_out = tr_variantDictAddList(args_out, TR_KEY_removed, 0);
 
-        while ((d = tr_variantListChild(&session->removedTorrents, n++)))
+        while ((d = tr_variantListChild(&session->removedTorrents, n++)) != NULL)
         {
             int64_t intVal;
 
-            if (tr_variantDictFindInt(d, TR_KEY_date, &intVal) && (intVal >= now - interval))
+            if (tr_variantDictFindInt(d, TR_KEY_date, &intVal) && intVal >= now - interval)
             {
                 tr_variantDictFindInt(d, TR_KEY_id, &intVal);
                 tr_variantListAddInt(removed_out, intVal);
@@ -987,7 +987,7 @@ static char const* setFilePriorities(tr_torrent* tor, int priority, tr_variant*
     char const* errmsg = NULL;
     tr_file_index_t* files = tr_new0(tr_file_index_t, tor->info.fileCount);
 
-    if (n)
+    if (n != 0)
     {
         for (i = 0; i < n; ++i)
         {
@@ -1014,7 +1014,7 @@ static char const* setFilePriorities(tr_torrent* tor, int priority, tr_variant*
         }
     }
 
-    if (fileCount)
+    if (fileCount != 0)
     {
         tr_torrentSetFilePriorities(tor, files, fileCount, priority);
     }
@@ -1032,7 +1032,7 @@ static char const* setFileDLs(tr_torrent* tor, bool do_download, tr_variant* lis
     char const* errmsg = NULL;
     tr_file_index_t* files = tr_new0(tr_file_index_t, tor->info.fileCount);
 
-    if (n) /* if argument list, process them */
+    if (n != 0) /* if argument list, process them */
     {
         for (i = 0; i < n; ++i)
         {
@@ -1137,7 +1137,7 @@ static char const* addTrackerUrls(tr_torrent* tor, tr_variant* urls)
     /* and add the new ones */
     i = 0;
 
-    while ((val = tr_variantListChild(urls, i++)))
+    while ((val = tr_variantListChild(urls, i++)) != NULL)
     {
         char const* announce = NULL;
 
@@ -1181,7 +1181,7 @@ static char const* replaceTrackers(tr_torrent* tor, tr_variant* urls)
     /* make the substitutions... */
     i = 0;
 
-    while (((pair[0] = tr_variantListChild(urls, i))) && ((pair[1] = tr_variantListChild(urls, i + 1))))
+    while ((pair[0] = tr_variantListChild(urls, i)) != NULL && (pair[1] = tr_variantListChild(urls, i + 1)) != NULL)
     {
         size_t len;
         int64_t pos;
@@ -1233,11 +1233,11 @@ static char const* removeTrackers(tr_torrent* tor, tr_variant* ids)
     /* remove the ones specified in the urls list */
     i = 0;
 
-    while ((val = tr_variantListChild(ids, i++)))
+    while ((val = tr_variantListChild(ids, i++)) != NULL)
     {
         int64_t pos;
 
-        if (tr_variantGetInt(val, &pos) && (0 <= pos) && (pos < n))
+        if (tr_variantGetInt(val, &pos) && 0 <= pos && pos < n)
         {
             tids[t++] = pos;
         }
@@ -1246,7 +1246,7 @@ static char const* removeTrackers(tr_torrent* tor, tr_variant* ids)
     /* sort trackerIds and remove from largest to smallest so there is no need to recacluate array indicies */
     qsort(tids, t, sizeof(int), compareInt);
 
-    while (t--)
+    while (t-- != 0)
     {
         /* check for duplicates */
         if (tids[t] == dup)
@@ -1304,12 +1304,12 @@ static char const* torrentSet(tr_session* session, tr_variant* args_in, tr_varia
             }
         }
 
-        if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_files_unwanted, &files))
+        if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_files_unwanted, &files))
         {
             errmsg = setFileDLs(tor, false, files);
         }
 
-        if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_files_wanted, &files))
+        if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_files_wanted, &files))
         {
             errmsg = setFileDLs(tor, true, files);
         }
@@ -1319,17 +1319,17 @@ static char const* torrentSet(tr_session* session, tr_variant* args_in, tr_varia
             tr_torrentSetPeerLimit(tor, tmp);
         }
 
-        if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_priority_high, &files))
+        if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_priority_high, &files))
         {
             errmsg = setFilePriorities(tor, TR_PRI_HIGH, files);
         }
 
-        if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_priority_low, &files))
+        if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_priority_low, &files))
         {
             errmsg = setFilePriorities(tor, TR_PRI_LOW, files);
         }
 
-        if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_priority_normal, &files))
+        if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_priority_normal, &files))
         {
             errmsg = setFilePriorities(tor, TR_PRI_NORMAL, files);
         }
@@ -1384,17 +1384,17 @@ static char const* torrentSet(tr_session* session, tr_variant* args_in, tr_varia
             tr_torrentSetQueuePosition(tor, tmp);
         }
 
-        if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_trackerAdd, &trackers))
+        if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_trackerAdd, &trackers))
         {
             errmsg = addTrackerUrls(tor, trackers);
         }
 
-        if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_trackerRemove, &trackers))
+        if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_trackerRemove, &trackers))
         {
             errmsg = removeTrackers(tor, trackers);
         }
 
-        if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_trackerReplace, &trackers))
+        if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_trackerReplace, &trackers))
         {
             errmsg = replaceTrackers(tor, trackers);
         }
@@ -1513,7 +1513,7 @@ static void portTested(tr_session* session UNUSED, bool did_connect UNUSED, bool
     }
     else /* success */
     {
-        bool const isOpen = response_byte_count && *(char*)response == '1';
+        bool const isOpen = response_byte_count != 0 && *(char*)response == '1';
         tr_variantDictAddBool(data->args_out, TR_KEY_port_is_open, isOpen);
         tr_snprintf(result, sizeof(result), "success");
     }
@@ -1597,7 +1597,7 @@ static void gotNewBlocklist(tr_session* session, bool did_connect UNUSED, bool d
 
             if (err != Z_OK)
             {
-                if ((err != Z_STREAM_END) && (err != Z_DATA_ERROR))
+                if (err != Z_STREAM_END && err != Z_DATA_ERROR)
                 {
                     tr_snprintf(result, sizeof(result), _("Error uncompressing blocklist: %s (%d)"), zError(err), err);
                 }
@@ -1619,7 +1619,7 @@ static void gotNewBlocklist(tr_session* session, bool did_connect UNUSED, bool d
 
         tr_sys_file_close(fd, NULL);
 
-        if (*result)
+        if (*result != '\0')
         {
             tr_logAddError("%s", result);
         }
@@ -1663,7 +1663,7 @@ static void addTorrentImpl(struct tr_rpc_idle_data* data, tr_ctor* ctor)
     tor = tr_torrentNew(ctor, &err, &duplicate_id);
     tr_ctorFree(ctor);
 
-    if (!err)
+    if (err == 0)
     {
         key = TR_KEY_torrent_added;
         result = NULL;
@@ -1680,7 +1680,7 @@ static void addTorrentImpl(struct tr_rpc_idle_data* data, tr_ctor* ctor)
         result = "invalid or corrupt torrent file";
     }
 
-    if (tor && key)
+    if (tor != NULL && key != 0)
     {
         tr_variant fields;
         tr_variantInitList(&fields, 3);
@@ -1773,7 +1773,7 @@ static char const* torrentAdd(tr_session* session, tr_variant* args_in, tr_varia
     tr_variantDictFindStr(args_in, TR_KEY_filename, &filename, NULL);
     tr_variantDictFindStr(args_in, TR_KEY_metainfo, &metainfo_base64, NULL);
 
-    if (!filename && !metainfo_base64)
+    if (filename == NULL && metainfo_base64 == NULL)
     {
         return "no filename or metainfo specified";
     }
@@ -2166,7 +2166,7 @@ static char const* sessionStats(tr_session* session, tr_variant* args_in UNUSED,
 
     assert(idle_data == NULL);
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         ++total;
 
@@ -2719,28 +2719,28 @@ void tr_rpc_request_exec_uri(tr_session* session, void const* request_uri, size_
 
     pch = strchr(request, '?');
 
-    if (!pch)
+    if (pch == NULL)
     {
         pch = request;
     }
 
-    while (pch)
+    while (pch != NULL)
     {
         char const* delim = strchr(pch, '=');
         char const* next = strchr(pch, '&');
 
-        if (delim)
+        if (delim != NULL)
         {
             char* key = tr_strndup(pch, (size_t)(delim - pch));
             bool isArg = strcmp(key, "method") != 0 && strcmp(key, "tag") != 0;
             tr_variant* parent = isArg ? args : &top;
 
             tr_rpc_parse_list_str(tr_variantDictAdd(parent, tr_quark_new(key, (size_t)(delim - pch))), delim + 1,
-                next ? (size_t)(next - (delim + 1)) : strlen(delim + 1));
+                next != NULL ? (size_t)(next - (delim + 1)) : strlen(delim + 1));
             tr_free(key);
         }
 
-        pch = next ? next + 1 : NULL;
+        pch = next != NULL ? next + 1 : NULL;
     }
 
     tr_rpc_request_exec_json(session, &top, callback, callback_user_data);
index 42eb798d2cef27e6124f281a68f5eda410b2945d..af9ffc6166e0c656dea52a2ed063421cbdf3b675 100644 (file)
@@ -39,7 +39,7 @@ static int testPeerId(void)
             val += strtoul(tmp, NULL, 36);
         }
 
-        check((val % 36) == 0);
+        check(val % 36 == 0);
     }
 
     return 0;
index c2049cb66842a56443d33b7f21aa338398c686ef..2f8035e9fe54dc0c995c26c63a1ad351966c4d99 100644 (file)
@@ -109,7 +109,7 @@ void tr_peerIdInit(uint8_t* buf)
         buf[i] = pool[val];
     }
 
-    val = total % base ? base - (total % base) : 0;
+    val = total % base != 0 ? base - (total % base) : 0;
     buf[19] = pool[val];
     buf[20] = '\0';
 }
@@ -120,14 +120,14 @@ void tr_peerIdInit(uint8_t* buf)
 
 tr_encryption_mode tr_sessionGetEncryption(tr_session* session)
 {
-    assert(session);
+    assert(session != NULL);
 
     return session->encryptionMode;
 }
 
 void tr_sessionSetEncryption(tr_session* session, tr_encryption_mode mode)
 {
-    assert(session);
+    assert(session != NULL);
     assert(mode == TR_ENCRYPTION_PREFERRED || mode == TR_ENCRYPTION_REQUIRED || mode == TR_CLEAR_PREFERRED);
 
     session->encryptionMode = mode;
@@ -146,7 +146,7 @@ struct tr_bindinfo
 
 static void close_bindinfo(struct tr_bindinfo* b)
 {
-    if ((b != NULL) && (b->socket != TR_BAD_SOCKET))
+    if (b != NULL && b->socket != TR_BAD_SOCKET)
     {
         event_free(b->ev);
         b->ev = NULL;
@@ -239,12 +239,12 @@ tr_address const* tr_sessionGetPublicAddress(tr_session const* session, int tr_a
         break;
     }
 
-    if (is_default_value && bindinfo)
+    if (is_default_value != NULL && bindinfo != NULL)
     {
         *is_default_value = tr_strcmp0(default_value, tr_address_to_string(&bindinfo->addr)) == 0;
     }
 
-    return bindinfo ? &bindinfo->addr : NULL;
+    return bindinfo != NULL ? &bindinfo->addr : NULL;
 }
 
 /***
@@ -262,44 +262,44 @@ static int parse_tos(char const* str)
     char* p;
     int value;
 
-    if (!evutil_ascii_strcasecmp(str, ""))
+    if (evutil_ascii_strcasecmp(str, "") == 0)
     {
         return 0;
     }
 
-    if (!evutil_ascii_strcasecmp(str, "default"))
+    if (evutil_ascii_strcasecmp(str, "default") == 0)
     {
         return 0;
     }
 
-    if (!evutil_ascii_strcasecmp(str, "lowcost"))
+    if (evutil_ascii_strcasecmp(str, "lowcost") == 0)
     {
         return 0x10;
     }
 
-    if (!evutil_ascii_strcasecmp(str, "mincost"))
+    if (evutil_ascii_strcasecmp(str, "mincost") == 0)
     {
         return 0x10;
     }
 
-    if (!evutil_ascii_strcasecmp(str, "throughput"))
+    if (evutil_ascii_strcasecmp(str, "throughput") == 0)
     {
         return 0x08;
     }
 
-    if (!evutil_ascii_strcasecmp(str, "reliability"))
+    if (evutil_ascii_strcasecmp(str, "reliability") == 0)
     {
         return 0x04;
     }
 
-    if (!evutil_ascii_strcasecmp(str, "lowdelay"))
+    if (evutil_ascii_strcasecmp(str, "lowdelay") == 0)
     {
         return 0x02;
     }
 
     value = strtol(str, &p, 0);
 
-    if (!p || (p == str))
+    if (p == NULL || p == str)
     {
         return 0;
     }
@@ -494,7 +494,7 @@ bool tr_sessionLoadSettings(tr_variant* dict, char const* configDir, char const*
     tr_variantFree(&oldDict);
 
     /* if caller didn't specify a config dir, use the default */
-    if (!configDir || !*configDir)
+    if (configDir == NULL || *configDir == '\0')
     {
         configDir = tr_getDefaultConfigDir(appName);
     }
@@ -573,12 +573,12 @@ static void onSaveTimer(evutil_socket_t foo UNUSED, short bar UNUSED, void* vses
     tr_torrent* tor = NULL;
     tr_session* session = vsession;
 
-    if (tr_cacheFlushDone(session->cache))
+    if (tr_cacheFlushDone(session->cache) != 0)
     {
         tr_logAddError("Error while flushing completed pieces from cache");
     }
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         tr_torrentSave(tor);
     }
@@ -679,7 +679,7 @@ static void onNowTimer(evutil_socket_t foo UNUSED, short bar UNUSED, void* vsess
         turtleCheckClock(session, &session->turtle);
     }
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         if (tor->isRunning)
         {
@@ -974,7 +974,7 @@ static void sessionSetImpl(void* vdata)
 
     tr_variantDictFindStr(settings, TR_KEY_bind_address_ipv4, &str, NULL);
 
-    if (!tr_address_from_string(&b.addr, str) || (b.addr.type != TR_AF_INET))
+    if (!tr_address_from_string(&b.addr, str) || b.addr.type != TR_AF_INET)
     {
         b.addr = tr_inaddr_any;
     }
@@ -984,7 +984,7 @@ static void sessionSetImpl(void* vdata)
 
     tr_variantDictFindStr(settings, TR_KEY_bind_address_ipv6, &str, NULL);
 
-    if (!tr_address_from_string(&b.addr, str) || (b.addr.type != TR_AF_INET6))
+    if (!tr_address_from_string(&b.addr, str) || b.addr.type != TR_AF_INET6)
     {
         b.addr = tr_in6addr_any;
     }
@@ -1178,7 +1178,7 @@ char const* tr_sessionGetDownloadDir(tr_session const* session)
 
     assert(tr_isSession(session));
 
-    if ((session != NULL) && (session->downloadDir != NULL))
+    if (session != NULL && session->downloadDir != NULL)
     {
         dir = session->downloadDir->path;
     }
@@ -1296,7 +1296,7 @@ static void peerPortChanged(void* session)
     open_incoming_peer_port(session);
     tr_sharedPortChanged(session);
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         tr_torrentChangeMyPort(tor);
     }
@@ -1312,7 +1312,7 @@ static void setPeerPort(tr_session* session, tr_port port)
 
 void tr_sessionSetPeerPort(tr_session* session, tr_port port)
 {
-    if (tr_isSession(session) && (session->private_peer_port != port))
+    if (tr_isSession(session) && session->private_peer_port != port)
     {
         setPeerPort(session, port);
     }
@@ -1458,7 +1458,7 @@ static void updateBandwidth(tr_session* session, tr_direction dir)
 {
     unsigned int limit_Bps = 0;
     bool const isLimited = tr_sessionGetActiveSpeedLimit_Bps(session, dir, &limit_Bps);
-    bool const zeroCase = isLimited && !limit_Bps;
+    bool const zeroCase = isLimited && limit_Bps == 0;
 
     tr_bandwidthSetLimited(&session->bandwidth, dir, isLimited && !zeroCase);
 
@@ -1481,7 +1481,7 @@ static void turtleUpdateTable(struct tr_turtle_info* t)
 
     for (day = 0; day < 7; ++day)
     {
-        if (t->days & (1 << day))
+        if ((t->days & (1 << day)) != 0)
         {
             int i;
             time_t const begin = t->beginMinute;
@@ -1567,11 +1567,11 @@ static void turtleCheckClock(tr_session* s, struct tr_turtle_info* t)
 
     enabled = getInTurtleTime(t);
     newAutoTurtleState = autoSwitchState(enabled);
-    alreadySwitched = (t->autoTurtleState == newAutoTurtleState);
+    alreadySwitched = t->autoTurtleState == newAutoTurtleState;
 
     if (!alreadySwitched)
     {
-        tr_logAddInfo("Time to turn %s turtle mode!", (enabled ? "on" : "off"));
+        tr_logAddInfo("Time to turn %s turtle mode!", enabled ? "on" : "off");
         t->autoTurtleState = newAutoTurtleState;
         useAltSpeed(s, t, enabled, false);
     }
@@ -1721,7 +1721,7 @@ bool tr_sessionUsesAltSpeedTime(tr_session const* s)
 void tr_sessionSetAltSpeedBegin(tr_session* s, int minute)
 {
     assert(tr_isSession(s));
-    assert(0 <= minute && minute < (60 * 24));
+    assert(0 <= minute && minute < 60 * 24);
 
     if (s->turtle.beginMinute != minute)
     {
@@ -1740,7 +1740,7 @@ int tr_sessionGetAltSpeedBegin(tr_session const* s)
 void tr_sessionSetAltSpeedEnd(tr_session* s, int minute)
 {
     assert(tr_isSession(s));
-    assert(0 <= minute && minute < (60 * 24));
+    assert(0 <= minute && minute < 60 * 24);
 
     if (s->turtle.endMinute != minute)
     {
@@ -2067,7 +2067,8 @@ void tr_sessionClose(tr_session* session)
      * so we need to keep the transmission thread alive
      * for a bit while they tell the router & tracker
      * that we're closing now */
-    while ((session->shared || session->web || session->announcer || session->announcer_udp) && !deadlineReached(deadline))
+    while ((session->shared != NULL || session->web != NULL || session->announcer != NULL || session->announcer_udp != NULL) &&
+        !deadlineReached(deadline))
     {
         dbgmsg("waiting on port unmap (%p) or announcer (%p)... now %zu deadline %zu", (void*)session->shared,
             (void*)session->announcer, (size_t)time(NULL), (size_t)deadline);
@@ -2106,7 +2107,7 @@ void tr_sessionClose(tr_session* session)
     tr_session_id_free(session->session_id);
     tr_lockFree(session->lock);
 
-    if (session->metainfoLookup)
+    if (session->metainfoLookup != NULL)
     {
         tr_variantFree(session->metainfoLookup);
         tr_free(session->metainfoLookup);
@@ -2160,7 +2161,7 @@ static void sessionLoadTorrents(void* vdata)
                 char* path = tr_buildPath(dirname, name, NULL);
                 tr_ctorSetMetainfoFromFile(data->ctor, path);
 
-                if ((tor = tr_torrentNew(data->ctor, NULL, NULL)))
+                if ((tor = tr_torrentNew(data->ctor, NULL, NULL)) != NULL)
                 {
                     tr_list_prepend(&list, tor);
                     ++n;
@@ -2184,12 +2185,12 @@ static void sessionLoadTorrents(void* vdata)
 
     tr_list_free(&list, NULL);
 
-    if (n)
+    if (n != 0)
     {
         tr_logAddInfo(_("Loaded %d torrents"), n);
     }
 
-    if (data->setmeCount)
+    if (data->setmeCount != NULL)
     {
         *data->setmeCount = n;
     }
@@ -2554,7 +2555,7 @@ int tr_blocklistGetRuleCount(tr_session const* session)
 
     assert(tr_isSession(session));
 
-    for (l = session->blocklists; l; l = l->next)
+    for (l = session->blocklists; l != NULL; l = l->next)
     {
         n += tr_blocklistFileGetRuleCount(l->data);
     }
@@ -2599,7 +2600,7 @@ int tr_blocklistSetContent(tr_session* session, char const* contentFilename)
     char const* defaultName = DEFAULT_BLOCKLIST_FILENAME;
     tr_sessionLock(session);
 
-    for (b = NULL, l = session->blocklists; !b && l; l = l->next)
+    for (b = NULL, l = session->blocklists; b == NULL && l != NULL; l = l->next)
     {
         if (tr_stringEndsWith(tr_blocklistFileGetFilename(l->data), defaultName))
         {
@@ -2607,7 +2608,7 @@ int tr_blocklistSetContent(tr_session* session, char const* contentFilename)
         }
     }
 
-    if (!b)
+    if (b == NULL)
     {
         char* path = tr_buildPath(session->configDir, "blocklists", defaultName, NULL);
         b = tr_blocklistFileNew(path, session->isBlocklistEnabled);
@@ -2626,7 +2627,7 @@ bool tr_sessionIsAddressBlocked(tr_session const* session, tr_address const* add
 
     assert(tr_isSession(session));
 
-    for (l = session->blocklists; l; l = l->next)
+    for (l = session->blocklists; l != NULL; l = l->next)
     {
         if (tr_blocklistFileHasAddress(l->data, addr))
         {
@@ -2685,7 +2686,7 @@ static void metainfoLookupInit(tr_session* session)
                 char* path = tr_buildPath(dirname, name, NULL);
                 tr_ctorSetMetainfoFromFile(ctor, path);
 
-                if (!tr_torrentParse(ctor, &inf))
+                if (tr_torrentParse(ctor, &inf) == TR_PARSE_OK)
                 {
                     ++n;
                     tr_variantDictAddStr(lookup, tr_quark_new(inf.hashString, TR_BAD_SIZE), path);
@@ -2708,7 +2709,7 @@ char const* tr_sessionFindTorrentFile(tr_session const* session, char const* has
 {
     char const* filename = NULL;
 
-    if (!session->metainfoLookup)
+    if (session->metainfoLookup == NULL)
     {
         metainfoLookupInit((tr_session*)session);
     }
@@ -2724,7 +2725,7 @@ void tr_sessionSetTorrentFile(tr_session* session, char const* hashString, char
      * and tr_sessionSetTorrentFile() is just to tell us there's a new file
      * in that same directory, we don't need to do anything here if the
      * lookup table hasn't been built yet */
-    if (session->metainfoLookup)
+    if (session->metainfoLookup != NULL)
     {
         tr_variantDictAddStr(session->metainfoLookup, tr_quark_new(hashString, TR_BAD_SIZE), filename);
     }
@@ -3009,7 +3010,7 @@ void tr_sessionGetNextQueuedTorrents(tr_session* session, tr_direction direction
     i = 0;
     tor = NULL;
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         if (!tr_torrentIsQueued(tor))
         {
@@ -3061,7 +3062,7 @@ int tr_sessionCountQueueFreeSlots(tr_session* session, tr_direction dir)
     tor = NULL;
     active_count = 0;
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         if (!tr_torrentIsStalled(tor))
         {
index 9dd8bf45db3c7c02b27bd6c50f080ccce4b5da0a..f73d3af304ab0cc4126c3ad8ed9b1d39d4dff4e6 100644 (file)
@@ -266,22 +266,22 @@ enum
 
 static inline bool tr_isSession(tr_session const* session)
 {
-    return (session != NULL) && (session->magicNumber == SESSION_MAGIC_NUMBER);
+    return session != NULL && session->magicNumber == SESSION_MAGIC_NUMBER;
 }
 
 static inline bool tr_isPreallocationMode(tr_preallocation_mode m)
 {
-    return (m == TR_PREALLOCATE_NONE) || (m == TR_PREALLOCATE_SPARSE) || (m == TR_PREALLOCATE_FULL);
+    return m == TR_PREALLOCATE_NONE || m == TR_PREALLOCATE_SPARSE || m == TR_PREALLOCATE_FULL;
 }
 
 static inline bool tr_isEncryptionMode(tr_encryption_mode m)
 {
-    return (m == TR_CLEAR_PREFERRED) || (m == TR_ENCRYPTION_PREFERRED) || (m == TR_ENCRYPTION_REQUIRED);
+    return m == TR_CLEAR_PREFERRED || m == TR_ENCRYPTION_PREFERRED || m == TR_ENCRYPTION_REQUIRED;
 }
 
 static inline bool tr_isPriority(tr_priority_t p)
 {
-    return (p == TR_PRI_LOW) || (p == TR_PRI_NORMAL) || (p == TR_PRI_HIGH);
+    return p == TR_PRI_LOW || p == TR_PRI_NORMAL || p == TR_PRI_HIGH;
 }
 
 /***
index 3ebc02259b1d62e3762b7152c7a0d263743cf083..c3ebae9034f171251801f57b4cda9234447f1fe4 100644 (file)
@@ -132,7 +132,7 @@ void tr_statsSaveDirty(tr_session* session)
 {
     struct tr_stats_handle* h = getStats(session);
 
-    if ((h != NULL) && h->isDirty)
+    if (h != NULL && h->isDirty)
     {
         tr_session_stats cumulative = STATS_INIT;
         tr_sessionGetCumulativeStats(session, &cumulative);
@@ -172,7 +172,7 @@ void tr_sessionGetStats(tr_session const* session, tr_session_stats* setme)
 {
     struct tr_stats_handle const* stats = getStats(session);
 
-    if (stats)
+    if (stats != NULL)
     {
         *setme = stats->single;
         setme->secondsActive = tr_time() - stats->startTime;
@@ -185,7 +185,7 @@ void tr_sessionGetCumulativeStats(tr_session const* session, tr_session_stats* s
     struct tr_stats_handle const* stats = getStats(session);
     tr_session_stats current = STATS_INIT;
 
-    if (stats)
+    if (stats != NULL)
     {
         tr_sessionGetStats(session, &current);
         addStats(setme, &stats->old, &current);
@@ -216,7 +216,7 @@ void tr_statsAddUploaded(tr_session* session, uint32_t bytes)
 {
     struct tr_stats_handle* s;
 
-    if ((s = getStats(session)))
+    if ((s = getStats(session)) != NULL)
     {
         s->single.uploadedBytes += bytes;
         s->isDirty = true;
@@ -227,7 +227,7 @@ void tr_statsAddDownloaded(tr_session* session, uint32_t bytes)
 {
     struct tr_stats_handle* s;
 
-    if ((s = getStats(session)))
+    if ((s = getStats(session)) != NULL)
     {
         s->single.downloadedBytes += bytes;
         s->isDirty = true;
@@ -238,7 +238,7 @@ void tr_statsFileCreated(tr_session* session)
 {
     struct tr_stats_handle* s;
 
-    if ((s = getStats(session)))
+    if ((s = getStats(session)) != NULL)
     {
         s->single.filesAdded++;
     }
index f968124b3145c15d79b570aad199c231cb66cfb3..0cb3e8a5bcf3875273e78b5b262a7e79af95844b 100644 (file)
@@ -129,7 +129,7 @@ int tr_ctorSetMetainfoFromFile(tr_ctor* ctor, char const* filename)
 
     metainfo = tr_loadFile(filename, &len, NULL);
 
-    if (metainfo && len)
+    if (metainfo != NULL && len != 0)
     {
         err = tr_ctorSetMetainfo(ctor, metainfo, len);
     }
@@ -158,7 +158,7 @@ int tr_ctorSetMetainfoFromFile(tr_ctor* ctor, char const* filename)
                 }
             }
 
-            if (!name || !*name)
+            if (name == NULL || *name == '\0')
             {
                 char* base = tr_sys_path_basename(filename, NULL);
 
@@ -182,7 +182,7 @@ int tr_ctorSetMetainfoFromHash(tr_ctor* ctor, char const* hashString)
 
     filename = tr_sessionFindTorrentFile(ctor->session, hashString);
 
-    if (!filename)
+    if (filename == NULL)
     {
         err = EINVAL;
     }
@@ -258,12 +258,12 @@ void tr_ctorSetFilesWanted(tr_ctor* ctor, tr_file_index_t const* files, tr_file_
 
 void tr_ctorInitTorrentWanted(tr_ctor const* ctor, tr_torrent* tor)
 {
-    if (ctor->notWantSize)
+    if (ctor->notWantSize != 0)
     {
         tr_torrentInitFileDLs(tor, ctor->notWant, ctor->notWantSize, false);
     }
 
-    if (ctor->wantSize)
+    if (ctor->wantSize != 0)
     {
         tr_torrentInitFileDLs(tor, ctor->want, ctor->wantSize, true);
     }
@@ -289,7 +289,7 @@ bool tr_ctorGetDeleteSource(tr_ctor const* ctor, bool* setme)
     {
         ret = false;
     }
-    else if (setme)
+    else if (setme != NULL)
     {
         *setme = ctor->doDelete;
     }
@@ -318,7 +318,7 @@ void tr_ctorSetPaused(tr_ctor* ctor, tr_ctorMode mode, bool isPaused)
     struct optional_args* args;
 
     assert(ctor != NULL);
-    assert((mode == TR_FALLBACK) || (mode == TR_FORCE));
+    assert(mode == TR_FALLBACK || mode == TR_FORCE);
     assert(tr_isBool(isPaused));
 
     args = &ctor->optionalArgs[mode];
@@ -331,7 +331,7 @@ void tr_ctorSetPeerLimit(tr_ctor* ctor, tr_ctorMode mode, uint16_t peerLimit)
     struct optional_args* args;
 
     assert(ctor != NULL);
-    assert((mode == TR_FALLBACK) || (mode == TR_FORCE));
+    assert(mode == TR_FALLBACK || mode == TR_FORCE);
 
     args = &ctor->optionalArgs[mode];
     args->isSet_connected = true;
@@ -343,14 +343,14 @@ void tr_ctorSetDownloadDir(tr_ctor* ctor, tr_ctorMode mode, char const* director
     struct optional_args* args;
 
     assert(ctor != NULL);
-    assert((mode == TR_FALLBACK) || (mode == TR_FORCE));
+    assert(mode == TR_FALLBACK || mode == TR_FORCE);
 
     args = &ctor->optionalArgs[mode];
     tr_free(args->downloadDir);
     args->downloadDir = NULL;
     args->isSet_downloadDir = false;
 
-    if (directory && *directory)
+    if (directory != NULL && *directory != '\0')
     {
         args->isSet_downloadDir = true;
         args->downloadDir = tr_strdup(directory);
@@ -372,7 +372,7 @@ bool tr_ctorGetPeerLimit(tr_ctor const* ctor, tr_ctorMode mode, uint16_t* setmeC
     {
         ret = false;
     }
-    else if (setmeCount)
+    else if (setmeCount != NULL)
     {
         *setmeCount = args->peerLimit;
     }
@@ -389,7 +389,7 @@ bool tr_ctorGetPaused(tr_ctor const* ctor, tr_ctorMode mode, bool* setmeIsPaused
     {
         ret = false;
     }
-    else if (setmeIsPaused)
+    else if (setmeIsPaused != NULL)
     {
         *setmeIsPaused = args->isPaused;
     }
@@ -406,7 +406,7 @@ bool tr_ctorGetDownloadDir(tr_ctor const* ctor, tr_ctorMode mode, char const** s
     {
         ret = false;
     }
-    else if (setmeDownloadDir)
+    else if (setmeDownloadDir != NULL)
     {
         *setmeDownloadDir = args->downloadDir;
     }
@@ -438,7 +438,7 @@ bool tr_ctorGetMetainfo(tr_ctor const* ctor, tr_variant const** setme)
     {
         ret = false;
     }
-    else if (setme)
+    else if (setme != NULL)
     {
         *setme = &ctor->metainfo;
     }
@@ -457,7 +457,7 @@ tr_session* tr_ctorGetSession(tr_ctor const* ctor)
 
 static bool isPriority(int i)
 {
-    return (i == TR_PRI_LOW) || (i == TR_PRI_NORMAL) || (i == TR_PRI_HIGH);
+    return i == TR_PRI_LOW || i == TR_PRI_NORMAL || i == TR_PRI_HIGH;
 }
 
 void tr_ctorSetBandwidthPriority(tr_ctor* ctor, tr_priority_t priority)
index c1bacbf1ef46a86612e9b26c06ac989db7dfb6ce..87e991f06491e148a738ce359d3daac87642bd74 100644 (file)
@@ -125,11 +125,11 @@ static size_t findInfoDictOffset(tr_torrent const* tor)
     size_t offset = 0;
 
     /* load the file, and find the info dict's offset inside the file */
-    if ((fileContents = tr_loadFile(tor->info.torrent, &fileLen, NULL)))
+    if ((fileContents = tr_loadFile(tor->info.torrent, &fileLen, NULL)) != NULL)
     {
         tr_variant top;
 
-        if (!tr_variantFromBenc(&top, fileContents, fileLen))
+        if (tr_variantFromBenc(&top, fileContents, fileLen) == 0)
         {
             tr_variant* infoDict;
 
@@ -290,7 +290,7 @@ void tr_torrentSetMetadataPiece(tr_torrent* tor, int piece, void const* data, in
             int const err = tr_variantFromBenc(&infoDict, m->metadata, m->metadata_size);
             dbgmsg(tor, "err is %d", err);
 
-            if ((metainfoParsed = !err))
+            if ((metainfoParsed = err == 0))
             {
                 /* yay we have bencoded metainfo... merge it into our .torrent file */
                 tr_variant newMetainfo;
@@ -375,7 +375,7 @@ bool tr_torrentGetNextMetadataRequest(tr_torrent* tor, time_t now, int* setme_pi
 
     m = tor->incompleteMetadata;
 
-    if ((m != NULL) && (m->piecesNeededCount > 0) && (m->piecesNeeded[0].requestedAt + MIN_REPEAT_INTERVAL_SECS < now))
+    if (m != NULL && m->piecesNeededCount > 0 && m->piecesNeeded[0].requestedAt + MIN_REPEAT_INTERVAL_SECS < now)
     {
         int i;
         int const piece = m->piecesNeeded[0].piece;
@@ -406,7 +406,7 @@ double tr_torrentGetMetadataPercent(tr_torrent const* tor)
     {
         struct tr_incomplete_metadata const* m = tor->incompleteMetadata;
 
-        if (!m || !m->pieceCount)
+        if (m == NULL || m->pieceCount == 0)
         {
             ret = 0.0;
         }
@@ -430,7 +430,7 @@ char* tr_torrentInfoGetMagnetLink(tr_info const* inf)
 
     name = inf->name;
 
-    if (name && *name)
+    if (name != NULL && *name != '\0')
     {
         evbuffer_add_printf(s, "%s", "&dn=");
         tr_http_escape(s, name, TR_BAD_SIZE, true);
index 33c5de2390477fa2d34de3c9c5e8d86d6090f06e..ade2c8c413a138aa7621585c78c5acd03d14b365 100644 (file)
 
 char const* tr_torrentName(tr_torrent const* tor)
 {
-    return tor ? tor->info.name : "";
+    return tor != NULL ? tor->info.name : "";
 }
 
 int tr_torrentId(tr_torrent const* tor)
 {
-    return tor ? tor->uniqueId : -1;
+    return tor != NULL ? tor->uniqueId : -1;
 }
 
 tr_torrent* tr_torrentFindFromId(tr_session* session, int id)
 {
     tr_torrent* tor = NULL;
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         if (tor->uniqueId == id)
         {
@@ -99,7 +99,7 @@ tr_torrent* tr_torrentFindFromHashString(tr_session* session, char const* str)
 {
     tr_torrent* tor = NULL;
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         if (!evutil_ascii_strcasecmp(str, tor->info.hashString))
         {
@@ -114,7 +114,7 @@ tr_torrent* tr_torrentFindFromHash(tr_session* session, uint8_t const* torrentHa
 {
     tr_torrent* tor = NULL;
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         if (*tor->info.hash == *torrentHash)
         {
@@ -133,7 +133,7 @@ tr_torrent* tr_torrentFindFromMagnetLink(tr_session* session, char const* magnet
     tr_magnet_info* info;
     tr_torrent* tor = NULL;
 
-    if ((info = tr_magnetParse(magnet)))
+    if ((info = tr_magnetParse(magnet)) != NULL)
     {
         tor = tr_torrentFindFromHash(session, info->hash);
         tr_magnetFree(info);
@@ -146,7 +146,7 @@ tr_torrent* tr_torrentFindFromObfuscatedHash(tr_session* session, uint8_t const*
 {
     tr_torrent* tor = NULL;
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         if (memcmp(tor->obfuscatedHash, obfuscatedTorrentHash, SHA_DIGEST_LENGTH) == 0)
         {
@@ -201,7 +201,7 @@ static int peerIdTTL(tr_torrent const* tor)
 {
     int ttl;
 
-    if (!tor->peer_id_creation_time)
+    if (tor->peer_id_creation_time == 0)
     {
         ttl = 0;
     }
@@ -217,7 +217,7 @@ unsigned char const* tr_torrentGetPeerId(tr_torrent* tor)
 {
     bool needs_new_peer_id = false;
 
-    if (!*tor->peer_id)
+    if (*tor->peer_id == '\0')
     {
         needs_new_peer_id = true;
     }
@@ -371,7 +371,7 @@ bool tr_torrentGetSeedRatio(tr_torrent const* tor, double* ratio)
     case TR_RATIOLIMIT_SINGLE:
         isLimited = true;
 
-        if (ratio)
+        if (ratio != NULL)
         {
             *ratio = tr_torrentGetRatioLimit(tor);
         }
@@ -381,7 +381,7 @@ bool tr_torrentGetSeedRatio(tr_torrent const* tor, double* ratio)
     case TR_RATIOLIMIT_GLOBAL:
         isLimited = tr_sessionIsRatioLimited(tor->session);
 
-        if (isLimited && ratio)
+        if (isLimited && ratio != NULL)
         {
             *ratio = tr_sessionGetRatioLimit(tor->session);
         }
@@ -412,12 +412,12 @@ static bool tr_torrentGetSeedRatioBytes(tr_torrent const* tor, uint64_t* setmeLe
         uint64_t const baseline = d ? d : tr_cpSizeWhenDone(&tor->completion);
         uint64_t const goal = baseline * seedRatio;
 
-        if (setmeLeft)
+        if (setmeLeft != NULL)
         {
             *setmeLeft = goal > u ? goal - u : 0;
         }
 
-        if (setmeGoal)
+        if (setmeGoal != NULL)
         {
             *setmeGoal = goal;
         }
@@ -496,7 +496,7 @@ bool tr_torrentGetSeedIdle(tr_torrent const* tor, uint16_t* idleMinutes)
     case TR_IDLELIMIT_GLOBAL:
         isLimited = tr_sessionIsIdleLimited(tor->session);
 
-        if (isLimited && idleMinutes)
+        if (isLimited && idleMinutes != NULL)
         {
             *idleMinutes = tr_sessionGetIdleLimit(tor->session);
         }
@@ -652,7 +652,7 @@ static tr_piece_index_t getBytePiece(tr_info const* info, uint64_t byteOffset)
 {
     tr_piece_index_t piece;
 
-    assert(info);
+    assert(info != NULL);
     assert(info->pieceSize != 0);
 
     piece = byteOffset / info->pieceSize;
@@ -683,7 +683,7 @@ static void initFilePieces(tr_info* info, tr_file_index_t fileIndex)
 
 static bool pieceHasFile(tr_piece_index_t piece, tr_file const* file)
 {
-    return (file->firstPiece <= piece) && (piece <= file->lastPiece);
+    return file->firstPiece <= piece && piece <= file->lastPiece;
 }
 
 static tr_priority_t calculatePiecePriority(tr_torrent const* tor, tr_piece_index_t piece, int fileHint)
@@ -820,7 +820,7 @@ uint32_t tr_getBlockSize(uint32_t pieceSize)
         b /= 2u;
     }
 
-    if (!b || (pieceSize % b)) /* not cleanly divisible */
+    if (b == 0 || pieceSize % b != 0) /* not cleanly divisible */
     {
         return 0;
     }
@@ -837,34 +837,34 @@ static void torrentInitFromInfo(tr_torrent* tor)
 
     tor->blockSize = tr_getBlockSize(info->pieceSize);
 
-    if (info->pieceSize)
+    if (info->pieceSize != 0)
     {
         tor->lastPieceSize = (uint32_t)(info->totalSize % info->pieceSize);
     }
 
-    if (!tor->lastPieceSize)
+    if (tor->lastPieceSize == 0)
     {
         tor->lastPieceSize = info->pieceSize;
     }
 
-    if (tor->blockSize)
+    if (tor->blockSize != 0)
     {
         tor->lastBlockSize = info->totalSize % tor->blockSize;
     }
 
-    if (!tor->lastBlockSize)
+    if (tor->lastBlockSize == 0)
     {
         tor->lastBlockSize = tor->blockSize;
     }
 
-    tor->blockCount = tor->blockSize ? (info->totalSize + tor->blockSize - 1) / tor->blockSize : 0;
-    tor->blockCountInPiece = tor->blockSize ? info->pieceSize / tor->blockSize : 0;
-    tor->blockCountInLastPiece = tor->blockSize ? (tor->lastPieceSize + tor->blockSize - 1) / tor->blockSize : 0;
+    tor->blockCount = tor->blockSize != 0 ? (info->totalSize + tor->blockSize - 1) / tor->blockSize : 0;
+    tor->blockCountInPiece = tor->blockSize != 0 ? info->pieceSize / tor->blockSize : 0;
+    tor->blockCountInLastPiece = tor->blockSize != 0 ? (tor->lastPieceSize + tor->blockSize - 1) / tor->blockSize : 0;
 
     /* check our work */
     if (tor->blockSize != 0)
     {
-        assert((info->pieceSize % tor->blockSize) == 0);
+        assert(info->pieceSize % tor->blockSize == 0);
     }
 
     t = info->pieceCount - 1;
@@ -915,7 +915,7 @@ static bool hasAnyLocalData(tr_torrent const* tor)
 
 static bool setLocalErrorIfFilesDisappeared(tr_torrent* tor)
 {
-    bool const disappeared = (tr_torrentHaveTotal(tor) > 0) && !hasAnyLocalData(tor);
+    bool const disappeared = tr_torrentHaveTotal(tor) > 0 && !hasAnyLocalData(tor);
 
     if (disappeared)
     {
@@ -971,8 +971,8 @@ static void torrentInit(tr_torrent* tor, tr_ctor const* ctor)
 
     tr_peerMgrAddTorrent(session->peerMgr, tor);
 
-    assert(!tor->downloadedCur);
-    assert(!tor->uploadedCur);
+    assert(tor->downloadedCur == 0);
+    assert(tor->uploadedCur == 0);
 
     tr_torrentSetAddedDate(tor, tr_time()); /* this is a default value to be overwritten by the resume file */
 
@@ -989,7 +989,7 @@ static void torrentInit(tr_torrent* tor, tr_ctor const* ctor)
     doStart = tor->isRunning;
     tor->isRunning = false;
 
-    if (!(loaded & TR_FR_SPEEDLIMIT))
+    if ((loaded & TR_FR_SPEEDLIMIT) == 0)
     {
         tr_torrentUseSpeedLimit(tor, TR_UP, false);
         tr_torrentSetSpeedLimit_Bps(tor, TR_UP, tr_sessionGetSpeedLimit_Bps(tor->session, TR_UP));
@@ -998,13 +998,13 @@ static void torrentInit(tr_torrent* tor, tr_ctor const* ctor)
         tr_torrentUseSessionLimits(tor, true);
     }
 
-    if (!(loaded & TR_FR_RATIOLIMIT))
+    if ((loaded & TR_FR_RATIOLIMIT) == 0)
     {
         tr_torrentSetRatioMode(tor, TR_RATIOLIMIT_GLOBAL);
         tr_torrentSetRatioLimit(tor, tr_sessionGetRatioLimit(tor->session));
     }
 
-    if (!(loaded & TR_FR_IDLELIMIT))
+    if ((loaded & TR_FR_IDLELIMIT) == 0)
     {
         tr_torrentSetIdleMode(tor, TR_IDLELIMIT_GLOBAL);
         tr_torrentSetIdleLimit(tor, tr_sessionGetIdleLimit(tor->session));
@@ -1042,7 +1042,7 @@ static void torrentInit(tr_torrent* tor, tr_ctor const* ctor)
             char const* path = tor->info.torrent;
             int const err = tr_variantToFile(val, TR_VARIANT_FMT_BENC, path);
 
-            if (err)
+            if (err != 0)
             {
                 tr_torrentSetLocalError(tor, "Unable to save torrent file: %s", tr_strerror(err));
             }
@@ -1102,7 +1102,7 @@ static tr_parse_result torrentParseImpl(tr_ctor const* ctor, tr_info* setmeInfo,
         result = TR_PARSE_ERR;
     }
 
-    if (didParse && session && (result == TR_PARSE_OK))
+    if (didParse && session != NULL && result == TR_PARSE_OK)
     {
         tr_torrent const* const tor = tr_torrentFindFromHash(session, setmeInfo->hash);
 
@@ -1239,7 +1239,7 @@ void tr_torrentManualUpdate(tr_torrent* tor)
 
 bool tr_torrentCanManualUpdate(tr_torrent const* tor)
 {
-    return (tr_isTorrent(tor)) && (tor->isRunning) && (tr_announcerCanManualAnnounce(tor));
+    return tr_isTorrent(tor) && tor->isRunning && tr_announcerCanManualAnnounce(tor);
 }
 
 tr_info const* tr_torrentInfo(tr_torrent const* tor)
@@ -1251,7 +1251,7 @@ tr_stat const* tr_torrentStatCached(tr_torrent* tor)
 {
     time_t const now = tr_time();
 
-    return tr_isTorrent(tor) && (now == tor->lastStatTime) ? &tor->stats : tr_torrentStat(tor);
+    return (tr_isTorrent(tor) && now == tor->lastStatTime) ? &tor->stats : tr_torrentStat(tor);
 }
 
 void tr_torrentSetVerifyState(tr_torrent* tor, tr_verify_state state)
@@ -1316,7 +1316,7 @@ static time_t torrentGetIdleSecs(tr_torrent const* tor)
 bool tr_torrentIsStalled(tr_torrent const* tor)
 {
     return tr_sessionGetQueueStalledEnabled(tor->session) &&
-           (torrentGetIdleSecs(tor) > (tr_sessionGetQueueStalledMinutes(tor->session) * 60));
+           torrentGetIdleSecs(tor) > tr_sessionGetQueueStalledMinutes(tor->session) * 60;
 }
 
 static double getVerifyProgress(tr_torrent const* tor)
@@ -1330,7 +1330,7 @@ static double getVerifyProgress(tr_torrent const* tor)
 
         for (i = 0, n = tor->info.pieceCount; i != n; ++i)
         {
-            if (tor->info.pieces[i].timeChecked)
+            if (tor->info.pieces[i].timeChecked != 0)
             {
                 ++checked;
             }
@@ -1427,15 +1427,15 @@ tr_stat const* tr_torrentStat(tr_torrent* tor)
      * so, etaXLSpeed is a smoothed-out version of the piece speed
      * to dampen the effect of fluctuations */
     case TR_STATUS_DOWNLOAD:
-        if ((tor->etaDLSpeedCalculatedAt + 800) < now)
+        if (tor->etaDLSpeedCalculatedAt + 800 < now)
         {
             tor->etaDLSpeedCalculatedAt = now;
-            tor->etaDLSpeed_Bps = ((tor->etaDLSpeedCalculatedAt + 4000) < now) ?
+            tor->etaDLSpeed_Bps = tor->etaDLSpeedCalculatedAt + 4000 < now ?
                 pieceDownloadSpeed_Bps : /* if no recent previous speed, no need to smooth */
-                ((tor->etaDLSpeed_Bps * 4.0) + pieceDownloadSpeed_Bps) / 5.0; /* smooth across 5 readings */
+                (tor->etaDLSpeed_Bps * 4.0 + pieceDownloadSpeed_Bps) / 5.0; /* smooth across 5 readings */
         }
 
-        if ((s->leftUntilDone > s->desiredAvailable) && (tor->info.webseedCount < 1))
+        if (s->leftUntilDone > s->desiredAvailable && tor->info.webseedCount < 1)
         {
             s->eta = TR_ETA_NOT_AVAIL;
         }
@@ -1458,12 +1458,12 @@ tr_stat const* tr_torrentStat(tr_torrent* tor)
         }
         else
         {
-            if ((tor->etaULSpeedCalculatedAt + 800) < now)
+            if (tor->etaULSpeedCalculatedAt + 800 < now)
             {
                 tor->etaULSpeedCalculatedAt = now;
-                tor->etaULSpeed_Bps = ((tor->etaULSpeedCalculatedAt + 4000) < now) ?
+                tor->etaULSpeed_Bps = tor->etaULSpeedCalculatedAt + 4000 < now ?
                     pieceUploadSpeed_Bps : /* if no recent previous speed, no need to smooth */
-                    ((tor->etaULSpeed_Bps * 4.0) + pieceUploadSpeed_Bps) / 5.0; /* smooth across 5 readings */
+                    (tor->etaULSpeed_Bps * 4.0 + pieceUploadSpeed_Bps) / 5.0; /* smooth across 5 readings */
             }
 
             if (tor->etaULSpeed_Bps == 0)
@@ -1495,13 +1495,13 @@ tr_stat const* tr_torrentStat(tr_torrent* tor)
 
     /* s->haveValid is here to make sure a torrent isn't marked 'finished'
      * when the user hits "uncheck all" prior to starting the torrent... */
-    s->finished = tor->finishedSeedingByIdle || (seedRatioApplies && !seedRatioBytesLeft && s->haveValid);
+    s->finished = tor->finishedSeedingByIdle || (seedRatioApplies && seedRatioBytesLeft == 0 && s->haveValid != 0);
 
     if (!seedRatioApplies || s->finished)
     {
         s->seedRatioPercentDone = 1;
     }
-    else if (!seedRatioBytesGoal) /* impossible? safeguard for div by zero */
+    else if (seedRatioBytesGoal == 0) /* impossible? safeguard for div by zero */
     {
         s->seedRatioPercentDone = 0;
     }
@@ -1527,7 +1527,7 @@ static uint64_t countFileBytesCompleted(tr_torrent const* tor, tr_file_index_t i
     uint64_t total = 0;
     tr_file const* f = &tor->info.files[index];
 
-    if (f->length)
+    if (f->length != 0)
     {
         tr_block_index_t first;
         tr_block_index_t last;
@@ -1581,7 +1581,7 @@ tr_file_stat* tr_torrentFiles(tr_torrent const* tor, tr_file_index_t* fileCount)
     {
         uint64_t const b = isSeed ? tor->info.files[i].length : countFileBytesCompleted(tor, i);
         walk->bytesCompleted = b;
-        walk->progress = tor->info.files[i].length > 0 ? ((float)b / tor->info.files[i].length) : 1.0f;
+        walk->progress = tor->info.files[i].length > 0 ? (float)b / tor->info.files[i].length : 1.0f;
     }
 
     if (fileCount != NULL)
@@ -1729,7 +1729,7 @@ static void freeTorrent(tr_torrent* tor)
     /* resequence the queue positions */
     t = NULL;
 
-    while ((t = tr_torrentNext(session, t)))
+    while ((t = tr_torrentNext(session, t)) != NULL)
     {
         if (t->queuePosition > tor->queuePosition)
         {
@@ -2167,9 +2167,9 @@ static char const* getCompletionString(int type)
 
 static void fireCompletenessChange(tr_torrent* tor, tr_completeness status, bool wasRunning)
 {
-    assert((status == TR_LEECH) || (status == TR_SEED) || (status == TR_PARTIAL_SEED));
+    assert(status == TR_LEECH || status == TR_SEED || status == TR_PARTIAL_SEED);
 
-    if (tor->completeness_func)
+    if (tor->completeness_func != NULL)
     {
         tor->completeness_func(tor, status, wasRunning, tor->completeness_func_user_data);
     }
@@ -2244,7 +2244,7 @@ static void torrentCallScript(tr_torrent const* tor, char const* script)
         *newlinePos = '\0';
     }
 
-    if (script && *script)
+    if (script != NULL && *script != '\0')
     {
         size_t i;
         char* cmd[] =
@@ -2325,7 +2325,7 @@ static void torrentCallScript(tr_torrent const* tor, char const* script)
 
         signal(SIGCHLD, onSigCHLD);
 
-        if (!fork())
+        if (fork() == 0)
         {
             for (i = 0; env[i] != NULL; ++i)
             {
@@ -2539,7 +2539,7 @@ static void setFileDND(tr_torrent* tor, tr_file_index_t fileIndex, int doDownloa
 
             firstPieceDND = tor->info.files[i].dnd;
 
-            if (!i)
+            if (i == 0)
             {
                 break;
             }
@@ -2698,7 +2698,7 @@ bool tr_torrentReqIsValid(tr_torrent const* tor, tr_piece_index_t index, uint32_
     {
         err = 2;
     }
-    else if ((offset + length) > tr_torPieceCountBytes(tor, index))
+    else if (offset + length > tr_torPieceCountBytes(tor, index))
     {
         err = 3;
     }
@@ -2711,7 +2711,7 @@ bool tr_torrentReqIsValid(tr_torrent const* tor, tr_piece_index_t index, uint32_
         err = 5;
     }
 
-    if (err)
+    if (err != 0)
     {
         tr_logAddTorDbg(tor, "index %lu offset %lu length %lu err %d\n", (unsigned long)index, (unsigned long)offset,
             (unsigned long)length, err);
@@ -2740,7 +2740,7 @@ void tr_torGetFileBlockRange(tr_torrent const* tor, tr_file_index_t const file,
 
     *first = offset / tor->blockSize;
 
-    if (!f->length)
+    if (f->length == 0)
     {
         *last = *first;
     }
@@ -2817,7 +2817,7 @@ bool tr_torrentPieceNeedsCheck(tr_torrent const* tor, tr_piece_index_t p)
     tr_info const* inf = tr_torrentInfo(tor);
 
     /* if we've never checked this piece, then it needs to be checked */
-    if (!inf->pieces[p].timeChecked)
+    if (inf->pieces[p].timeChecked == 0)
     {
         return true;
     }
@@ -2944,7 +2944,7 @@ bool tr_torrentSetAnnounceList(tr_torrent* tor, tr_tracker_info const* trackers_
         /* if we had a tracker-related error on this torrent,
          * and that tracker's been removed,
          * then clear the error */
-        if ((tor->error == TR_STAT_TRACKER_WARNING) || (tor->error == TR_STAT_TRACKER_ERROR))
+        if (tor->error == TR_STAT_TRACKER_WARNING || tor->error == TR_STAT_TRACKER_ERROR)
         {
             bool clear = true;
 
@@ -3493,7 +3493,7 @@ static void tr_torrentPieceCompleted(tr_torrent* tor, tr_piece_index_t pieceInde
     {
         tr_file const* file = &tor->info.files[i];
 
-        if ((file->firstPiece <= pieceIndex) && (pieceIndex <= file->lastPiece))
+        if (file->firstPiece <= pieceIndex && pieceIndex <= file->lastPiece)
         {
             if (tr_cpFileIsComplete(&tor->completion, i))
             {
@@ -3577,7 +3577,7 @@ bool tr_torrentFindFile2(tr_torrent const* tor, tr_file_index_t fileNum, char co
     }
 
     /* look in the incomplete dir... */
-    if ((b == NULL) && (tor->incompleteDir != NULL))
+    if (b == NULL && tor->incompleteDir != NULL)
     {
         char* filename = tr_buildPath(tor->incompleteDir, file->name, NULL);
 
@@ -3596,7 +3596,7 @@ bool tr_torrentFindFile2(tr_torrent const* tor, tr_file_index_t fileNum, char co
     }
 
     /* look for a .part file in the incomplete dir... */
-    if ((b == NULL) && (tor->incompleteDir != NULL))
+    if (b == NULL && tor->incompleteDir != NULL)
     {
         char* filename = tr_buildPath(tor->incompleteDir, part, NULL);
 
@@ -3678,7 +3678,7 @@ static void refreshCurrentDir(tr_torrent* tor)
     }
 
     assert(dir != NULL);
-    assert((dir == tor->downloadDir) || (dir == tor->incompleteDir));
+    assert(dir == tor->downloadDir || dir == tor->incompleteDir);
     tor->currentDir = dir;
 }
 
@@ -3763,11 +3763,11 @@ void tr_torrentSetQueuePosition(tr_torrent* tor, int pos)
 
     walk = NULL;
 
-    while ((walk = tr_torrentNext(tor->session, walk)))
+    while ((walk = tr_torrentNext(tor->session, walk)) != NULL)
     {
         if (old_pos < pos)
         {
-            if ((old_pos <= walk->queuePosition) && (walk->queuePosition <= pos))
+            if (old_pos <= walk->queuePosition && walk->queuePosition <= pos)
             {
                 walk->queuePosition--;
                 walk->anyDate = now;
@@ -3776,7 +3776,7 @@ void tr_torrentSetQueuePosition(tr_torrent* tor, int pos)
 
         if (old_pos > pos)
         {
-            if ((pos <= walk->queuePosition) && (walk->queuePosition < old_pos))
+            if (pos <= walk->queuePosition && walk->queuePosition < old_pos)
             {
                 walk->queuePosition++;
                 walk->anyDate = now;
@@ -3884,8 +3884,8 @@ void tr_torrentSetQueueStartCallback(tr_torrent* torrent, void (* callback)(tr_t
 
 static bool renameArgsAreValid(char const* oldpath, char const* newname)
 {
-    return (oldpath && *oldpath) && (newname && *newname) && (strcmp(newname, ".") != 0) && (strcmp(newname, "..") != 0) &&
-           (strchr(newname, TR_PATH_DELIMITER) == NULL);
+    return oldpath != NULL && *oldpath != '\0' && newname != NULL && *newname != '\0' && strcmp(newname, ".") != 0 &&
+           strcmp(newname, "..") != 0 && strchr(newname, TR_PATH_DELIMITER) == NULL;
 }
 
 static tr_file_index_t* renameFindAffectedFiles(tr_torrent* tor, char const* oldpath, size_t* setme_n)
@@ -3919,7 +3919,7 @@ static int renamePath(tr_torrent* tor, char const* oldpath, char const* newname)
     char const* base;
     int err = 0;
 
-    if (!tr_torrentIsSeed(tor) && (tor->incompleteDir != NULL))
+    if (!tr_torrentIsSeed(tor) && tor->incompleteDir != NULL)
     {
         base = tor->incompleteDir;
     }
@@ -4075,7 +4075,7 @@ static void torrentRenamePath(void* vdata)
 
             error = renamePath(tor, oldpath, newname);
 
-            if (!error)
+            if (error == 0)
             {
                 /* update tr_info.files */
                 for (i = 0; i < n; ++i)
@@ -4084,7 +4084,7 @@ static void torrentRenamePath(void* vdata)
                 }
 
                 /* update tr_info.name if user changed the toplevel */
-                if ((n == tor->info.fileCount) && (strchr(oldpath, '/') == NULL))
+                if (n == tor->info.fileCount && strchr(oldpath, '/') == NULL)
                 {
                     tr_free(tor->info.name);
                     tor->info.name = tr_strdup(newname);
index dc9d4b3b4be6251afeac6429f1f26c5afc44bfc9..97e2ef263ee1ac813316506106c35880a7a83947 100644 (file)
@@ -243,7 +243,7 @@ struct tr_torrent
 
 static inline tr_torrent* tr_torrentNext(tr_session* session, tr_torrent* current)
 {
-    return current ? current->next : session->torrentList;
+    return current != NULL ? current->next : session->torrentList;
 }
 
 /* what piece index is this block in? */
@@ -296,22 +296,22 @@ static inline bool tr_torrentIsSeed(tr_torrent const* tor)
 
 static inline bool tr_torrentIsPrivate(tr_torrent const* tor)
 {
-    return (tor != NULL) && tor->info.isPrivate;
+    return tor != NULL && tor->info.isPrivate;
 }
 
 static inline bool tr_torrentAllowsPex(tr_torrent const* tor)
 {
-    return (tor != NULL) && (tor->session->isPexEnabled) && (!tr_torrentIsPrivate(tor));
+    return tor != NULL && tor->session->isPexEnabled && !tr_torrentIsPrivate(tor);
 }
 
 static inline bool tr_torrentAllowsDHT(tr_torrent const* tor)
 {
-    return (tor != NULL) && (tr_sessionAllowsDHT(tor->session)) && (!tr_torrentIsPrivate(tor));
+    return tor != NULL && tr_sessionAllowsDHT(tor->session) && !tr_torrentIsPrivate(tor);
 }
 
 static inline bool tr_torrentAllowsLPD(tr_torrent const* tor)
 {
-    return (tor != NULL) && (tr_sessionAllowsLPD(tor->session)) && (!tr_torrentIsPrivate(tor));
+    return tor != NULL && tr_sessionAllowsLPD(tor->session) && !tr_torrentIsPrivate(tor);
 }
 
 /***
@@ -325,7 +325,7 @@ enum
 
 static inline bool tr_isTorrent(tr_torrent const* tor)
 {
-    return (tor != NULL) && (tor->magicNumber == TORRENT_MAGIC_NUMBER) && (tr_isSession(tor->session));
+    return tor != NULL && tor->magicNumber == TORRENT_MAGIC_NUMBER && tr_isSession(tor->session);
 }
 
 /* set a flag indicating that the torrent's .resume file
index 077009921e9c4679776e3d30a061f03df9fa5322..662d7a4b112a7a5768a3dffb587067c91a06e5c0 100644 (file)
@@ -135,7 +135,7 @@ static void bootstrap_from_name(char const* name, tr_port port, int af)
 
     infop = info;
 
-    while (infop)
+    while (infop != NULL)
     {
         dht_ping_node(infop->ai_addr, infop->ai_addrlen);
 
@@ -226,7 +226,7 @@ static void dht_bootstrap(void* closure)
 
         bootstrap_file = tr_buildPath(cl->session->configDir, "dht.bootstrap", NULL);
 
-        if (bootstrap_file)
+        if (bootstrap_file != NULL)
         {
             f = tr_sys_file_open(bootstrap_file, TR_SYS_FILE_READ, 0, NULL);
         }
@@ -299,12 +299,12 @@ static void dht_bootstrap(void* closure)
         }
     }
 
-    if (cl->nodes)
+    if (cl->nodes != NULL)
     {
         tr_free(cl->nodes);
     }
 
-    if (cl->nodes6)
+    if (cl->nodes6 != NULL)
     {
         tr_free(cl->nodes6);
     }
@@ -324,7 +324,7 @@ int tr_dhtInit(tr_session* ss)
     size_t len, len6;
     struct bootstrap_closure* cl;
 
-    if (session) /* already initialized */
+    if (session != NULL) /* already initialized */
     {
         return -1;
     }
@@ -349,14 +349,12 @@ int tr_dhtInit(tr_session* ss)
             memcpy(myid, raw, len);
         }
 
-        if (ss->udp_socket != TR_BAD_SOCKET &&
-            tr_variantDictFindRaw(&benc, TR_KEY_nodes, &raw, &len) && !(len % 6))
+        if (ss->udp_socket != TR_BAD_SOCKET && tr_variantDictFindRaw(&benc, TR_KEY_nodes, &raw, &len) && len % 6 == 0)
         {
             nodes = tr_memdup(raw, len);
         }
 
-        if (ss->udp6_socket != TR_BAD_SOCKET &&
-            tr_variantDictFindRaw(&benc, TR_KEY_nodes6, &raw, &len6) && !(len6 % 18))
+        if (ss->udp6_socket != TR_BAD_SOCKET && tr_variantDictFindRaw(&benc, TR_KEY_nodes6, &raw, &len6) && len6 % 18 == 0)
         {
             nodes6 = tr_memdup(raw, len6);
         }
@@ -433,7 +431,7 @@ void tr_dhtUninit(tr_session* ss)
 
     /* Since we only save known good nodes, avoid erasing older data if we
        don't know enough nodes. */
-    if ((tr_dhtStatus(ss, AF_INET, NULL) < TR_DHT_FIREWALLED) && (tr_dhtStatus(ss, AF_INET6, NULL) < TR_DHT_FIREWALLED))
+    if (tr_dhtStatus(ss, AF_INET, NULL) < TR_DHT_FIREWALLED && tr_dhtStatus(ss, AF_INET6, NULL) < TR_DHT_FIREWALLED)
     {
         tr_logAddNamedInfo("DHT", "Not saving nodes, DHT not ready");
     }
@@ -494,7 +492,7 @@ void tr_dhtUninit(tr_session* ss)
 
 bool tr_dhtEnabled(tr_session const* ss)
 {
-    return ss && (ss == session);
+    return ss != NULL && ss == session;
 }
 
 struct getstatus_closure
@@ -538,7 +536,7 @@ int tr_dhtStatus(tr_session* session, int af, int* nodes_return)
     if (!tr_dhtEnabled(session) || (af == AF_INET && session->udp_socket == TR_BAD_SOCKET) ||
         (af == AF_INET6 && session->udp6_socket == TR_BAD_SOCKET))
     {
-        if (nodes_return)
+        if (nodes_return != NULL)
         {
             *nodes_return = 0;
         }
@@ -553,7 +551,7 @@ int tr_dhtStatus(tr_session* session, int af, int* nodes_return)
         tr_wait_msec(50 /*msec*/);
     }
 
-    if (nodes_return)
+    if (nodes_return != NULL)
     {
         *nodes_return = closure.count;
     }
@@ -642,7 +640,7 @@ static void callback(void* ignore UNUSED, int event, unsigned char const* info_h
         tr_sessionLock(session);
         tor = tr_torrentFindFromHash(session, info_hash);
 
-        if (tor && tr_torrentAllowsDHT(tor))
+        if (tor != NULL && tr_torrentAllowsDHT(tor))
         {
             size_t i, n;
             tr_pex* pex;
@@ -671,7 +669,7 @@ static void callback(void* ignore UNUSED, int event, unsigned char const* info_h
     {
         tr_torrent* tor = tr_torrentFindFromHash(session, info_hash);
 
-        if (tor)
+        if (tor != NULL)
         {
             if (event == DHT_EVENT_SEARCH_DONE)
             {
@@ -744,7 +742,7 @@ void tr_dhtUpkeep(tr_session* session)
     tr_torrent* tor = NULL;
     time_t const now = tr_time();
 
-    while ((tor = tr_torrentNext(session, tor)))
+    while ((tor = tr_torrentNext(session, tor)) != NULL)
     {
         if (!tor->isRunning || !tr_torrentAllowsDHT(tor))
         {
index 58272f3318649ce78e45b3de253ac2ef4a2209ac..52026b87a79bdaabc9e12f9cf99ac496424d226d 100644 (file)
@@ -32,7 +32,7 @@ static int run_test(int argc, char const** argv, int expected_n, int* expected_c
     n = 0;
     tr_optind = 1;
 
-    while ((c = tr_getopt("summary", argc, argv, options, &optarg)))
+    while ((c = tr_getopt("summary", argc, argv, options, &optarg)) != TR_OPT_DONE)
     {
         check(n < expected_n);
         check_int_eq(expected_c[n], c);
index 08cdc3bae9d4ff7969c898f0fa4bbcbdec711e25..25214de64904186f9e019f5345601ff481183316 100644 (file)
@@ -27,7 +27,7 @@ static char const* getArgName(tr_option const* opt)
     {
         arg = "";
     }
-    else if (opt->argName)
+    else if (opt->argName != NULL)
     {
         arg = opt->argName;
     }
@@ -51,27 +51,27 @@ static int get_next_line_len(char const* description, int maxlen)
 
     end = maxlen < len ? maxlen : len;
 
-    while ((end > 0) && !isspace(description[end]))
+    while (end > 0 && !isspace(description[end]))
     {
         --end;
     }
 
-    return end ? end : len;
+    return end != 0 ? end : len;
 }
 
 static void getopts_usage_line(tr_option const* opt, int longWidth, int shortWidth, int argWidth)
 {
     int len;
-    char const* longName = opt->longName ? opt->longName : "";
-    char const* shortName = opt->shortName ? opt->shortName : "";
+    char const* longName = opt->longName != NULL ? opt->longName : "";
+    char const* shortName = opt->shortName != NULL ? opt->shortName : "";
     char const* arg = getArgName(opt);
 
     int const d_indent = shortWidth + longWidth + argWidth + 7;
     int const d_width = 80 - d_indent;
     char const* d = opt->description;
 
-    printf(" %s%-*s %s%-*s %-*s ", (shortName && *shortName ? "-" : " "), shortWidth, shortName,
-        (longName && *longName ? "--" : "  "), longWidth, longName, argWidth, arg);
+    printf(" %s%-*s %s%-*s %-*s ", (shortName != NULL && *shortName != '\0') ? "-" : " ", shortWidth, shortName,
+        (longName != NULL && *longName != '\0') ? "--" : "  ", longWidth, longName, argWidth, arg);
     len = get_next_line_len(d, d_width);
     printf("%*.*s\n", len, len, d);
 
@@ -82,7 +82,7 @@ static void getopts_usage_line(tr_option const* opt, int longWidth, int shortWid
         ++d;
     }
 
-    while ((len = get_next_line_len(d, d_width)))
+    while ((len = get_next_line_len(d, d_width)) != 0)
     {
         printf("%*.*s%*.*s\n", d_indent, d_indent, "", len, len, d);
         d += len;
@@ -98,17 +98,17 @@ static void maxWidth(struct tr_option const* o, int* longWidth, int* shortWidth,
 {
     char const* arg;
 
-    if (o->longName)
+    if (o->longName != NULL)
     {
         *longWidth = MAX(*longWidth, (int)strlen(o->longName));
     }
 
-    if (o->shortName)
+    if (o->shortName != NULL)
     {
         *shortWidth = MAX(*shortWidth, (int)strlen(o->shortName));
     }
 
-    if ((arg = getArgName(o)))
+    if ((arg = getArgName(o)) != NULL)
     {
         *argWidth = MAX(*argWidth, (int)strlen(arg));
     }
@@ -122,7 +122,7 @@ void tr_getopt_usage(char const* progName, char const* description, struct tr_op
     struct tr_option help;
     struct tr_option const* o;
 
-    for (o = opts; o->val; ++o)
+    for (o = opts; o->val != 0; ++o)
     {
         maxWidth(o, &longWidth, &shortWidth, &argWidth);
     }
@@ -143,7 +143,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; ++o)
+    for (o = opts; o->val != 0; ++o)
     {
         getopts_usage_line(o, longWidth, shortWidth, argWidth);
     }
@@ -157,11 +157,11 @@ static tr_option const* findOption(tr_option const* opts, char const* str, char
     tr_option const* match = NULL;
 
     /* find the longest matching option */
-    for (o = opts; o->val; ++o)
+    for (o = opts; o->val != 0; ++o)
     {
-        size_t len = o->longName ? strlen(o->longName) : 0;
+        size_t len = o->longName != NULL ? strlen(o->longName) : 0;
 
-        if ((matchlen < len) && (str[0] == '-') && (str[1] == '-') && strncmp(str + 2, o->longName, len) == 0 &&
+        if (matchlen < len && str[0] == '-' && str[1] == '-' && strncmp(str + 2, o->longName, len) == 0 &&
             (str[len + 2] == '\0' || (o->has_arg && str[len + 2] == '=')))
         {
             matchlen = len;
@@ -169,10 +169,9 @@ static tr_option const* findOption(tr_option const* opts, char const* str, char
             arg = str[len + 2] == '=' ? str + len + 3 : NULL;
         }
 
-        len = o->shortName ? strlen(o->shortName) : 0;
+        len = o->shortName != NULL ? strlen(o->shortName) : 0;
 
-        if ((matchlen < len) && (str[0] == '-') && strncmp(str + 1, o->shortName, len) == 0 &&
-            (str[len + 1] == '\0' || o->has_arg))
+        if (matchlen < len && str[0] == '-' && strncmp(str + 1, o->shortName, len) == 0 && (str[len + 1] == '\0' || o->has_arg))
         {
             matchlen = len;
             match = o;
@@ -194,7 +193,7 @@ static tr_option const* findOption(tr_option const* opts, char const* str, char
         }
     }
 
-    if (setme_arg)
+    if (setme_arg != NULL)
     {
         *setme_arg = arg;
     }
@@ -228,7 +227,7 @@ int tr_getopt(char const* usage, int argc, char const* const* argv, tr_option co
 
     o = findOption(opts, argv[tr_optind], &arg);
 
-    if (!o)
+    if (o == NULL)
     {
         /* let the user know we got an unknown option... */
         *setme_optarg = argv[tr_optind++];
@@ -238,7 +237,7 @@ int tr_getopt(char const* usage, int argc, char const* const* argv, tr_option co
     if (!o->has_arg)
     {
         /* no argument needed for this option, so we're done */
-        if (arg)
+        if (arg != NULL)
         {
             return TR_OPT_ERR;
         }
@@ -249,7 +248,7 @@ int tr_getopt(char const* usage, int argc, char const* const* argv, tr_option co
     }
 
     /* option needed an argument, and it was embedded in this string */
-    if (arg)
+    if (arg != NULL)
     {
         *setme_optarg = arg;
         ++tr_optind;
@@ -262,7 +261,7 @@ int tr_getopt(char const* usage, int argc, char const* const* argv, tr_option co
         return TR_OPT_ERR;
     }
 
-    if (findOption(opts, argv[tr_optind], NULL))
+    if (findOption(opts, argv[tr_optind], NULL) != NULL)
     {
         return TR_OPT_ERR;
     }
index c7313433b1344b7335efd1b2316952ec353ecffe..0d6921d4b53f29178fcc1df22358d5e77ee183eb 100644 (file)
@@ -296,7 +296,7 @@ int tr_lpdInit(tr_session* ss, tr_address* tr_addr UNUSED)
     struct ip_mreq mcastReq;
     int const opt_on = 1, opt_off = 0;
 
-    if (session) /* already initialized */
+    if (session != NULL) /* already initialized */
     {
         return -1;
     }
@@ -444,7 +444,7 @@ void tr_lpdUninit(tr_session* ss)
 
 bool tr_lpdEnabled(tr_session const* ss)
 {
-    return ss && (ss == session);
+    return ss != NULL && ss == session;
 }
 
 /**
@@ -499,7 +499,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 (i = 0; i < sizeof(hashString); i++)
     {
         hashString[i] = toupper(t->info.hashString[i]);
     }
@@ -629,7 +629,7 @@ static int tr_lpdAnnounceMore(time_t const now, int const interval)
         return -1;
     }
 
-    while ((tor = tr_torrentNext(session, tor)) && tr_sessionAllowsLPD(session))
+    while ((tor = tr_torrentNext(session, tor)) != NULL && tr_sessionAllowsLPD(session))
     {
         if (tr_isTorrent(tor))
         {
index 25aa326f9ca629a1fa7ebfd9f0d923514fa4fd55..6764814dd34dfa67fbf41f1c0788cd4911760c86 100644 (file)
@@ -50,7 +50,7 @@ THE SOFTWARE.
 #define SEND_BUFFER_SIZE (1 * 1024 * 1024)
 #define SMALL_BUFFER_SIZE (32 * 1024)
 
-static void set_socket_buffers(tr_socket_t fd, int large)
+static void set_socket_buffers(tr_socket_t fd, bool large)
 {
     int size, rbuf, sbuf, rc;
     socklen_t rbuf_len = sizeof(rbuf), sbuf_len = sizeof(sbuf);
@@ -138,7 +138,7 @@ static void rebind_ipv6(tr_session* ss, bool force)
        No way to fix that without some surgery to the DHT code itself. */
     if (ipv6 == NULL || (!force && ss->udp6_socket == TR_BAD_SOCKET))
     {
-        if (ss->udp6_bound)
+        if (ss->udp6_bound != NULL)
         {
             free(ss->udp6_bound);
             ss->udp6_bound = NULL;
@@ -168,7 +168,7 @@ static void rebind_ipv6(tr_session* ss, bool force)
     memset(&sin6, 0, sizeof(sin6));
     sin6.sin6_family = AF_INET6;
 
-    if (ipv6)
+    if (ipv6 != NULL)
     {
         memcpy(&sin6.sin6_addr, ipv6, 16);
     }
@@ -176,7 +176,7 @@ static void rebind_ipv6(tr_session* ss, bool force)
     sin6.sin6_port = htons(ss->udp_port);
     public_addr = tr_sessionGetPublicAddress(ss, TR_AF_INET6, &is_default);
 
-    if (public_addr && !is_default)
+    if (public_addr != NULL && !is_default)
     {
         sin6.sin6_addr = public_addr->addr.addr6;
     }
@@ -210,7 +210,7 @@ static void rebind_ipv6(tr_session* ss, bool force)
         ss->udp6_bound = malloc(16);
     }
 
-    if (ss->udp6_bound)
+    if (ss->udp6_bound != NULL)
     {
         memcpy(ss->udp6_bound, ipv6, 16);
     }
@@ -227,7 +227,7 @@ fail:
         tr_netCloseSocket(s);
     }
 
-    if (ss->udp6_bound)
+    if (ss->udp6_bound != NULL)
     {
         free(ss->udp6_bound);
         ss->udp6_bound = NULL;
@@ -269,7 +269,7 @@ static void event_callback(evutil_socket_t s, short type UNUSED, void* sv)
         {
             rc = tau_handle_message(ss, buf, rc);
 
-            if (!rc)
+            if (rc == 0)
             {
                 tr_logAddNamedDbg("UDP", "Couldn't parse UDP tracker packet.");
             }
@@ -280,7 +280,7 @@ static void event_callback(evutil_socket_t s, short type UNUSED, void* sv)
             {
                 rc = tr_utpPacket(buf, rc, (struct sockaddr*)&from, fromlen, ss);
 
-                if (!rc)
+                if (rc == 0)
                 {
                     tr_logAddNamedDbg("UDP", "Unexpected UDP packet");
                 }
@@ -318,7 +318,7 @@ void tr_udpInit(tr_session* ss)
     sin.sin_family = AF_INET;
     public_addr = tr_sessionGetPublicAddress(ss, TR_AF_INET, &is_default);
 
-    if (public_addr && !is_default)
+    if (public_addr != NULL && !is_default)
     {
         memcpy(&sin.sin_addr, &public_addr->addr.addr4, sizeof(struct in_addr));
     }
@@ -365,12 +365,12 @@ ipv6:
         tr_dhtInit(ss);
     }
 
-    if (ss->udp_event)
+    if (ss->udp_event != NULL)
     {
         event_add(ss->udp_event, NULL);
     }
 
-    if (ss->udp6_event)
+    if (ss->udp6_event != NULL)
     {
         event_add(ss->udp6_event, NULL);
     }
@@ -386,7 +386,7 @@ void tr_udpUninit(tr_session* ss)
         ss->udp_socket = TR_BAD_SOCKET;
     }
 
-    if (ss->udp_event)
+    if (ss->udp_event != NULL)
     {
         event_free(ss->udp_event);
         ss->udp_event = NULL;
@@ -398,13 +398,13 @@ void tr_udpUninit(tr_session* ss)
         ss->udp6_socket = TR_BAD_SOCKET;
     }
 
-    if (ss->udp6_event)
+    if (ss->udp6_event != NULL)
     {
         event_free(ss->udp6_event);
         ss->udp6_event = NULL;
     }
 
-    if (ss->udp6_bound)
+    if (ss->udp6_bound != NULL)
     {
         free(ss->udp6_bound);
         ss->udp6_bound = NULL;
index 3b65dea5a60a490d40177fbc0cf06d48ef7047d0..3ab795ec2cab15dd71f745a718b5bf2188cae2ce 100644 (file)
@@ -176,7 +176,7 @@ static void timer_callback(evutil_socket_t s UNUSED, short type UNUSED, void* cl
 
 int tr_utpPacket(unsigned char const* buf, size_t buflen, struct sockaddr const* from, socklen_t fromlen, tr_session* ss)
 {
-    if (!ss->isClosed && !utp_timer)
+    if (!ss->isClosed && utp_timer == NULL)
     {
         utp_timer = evtimer_new(ss->event_base, timer_callback, ss);
 
@@ -193,7 +193,7 @@ int tr_utpPacket(unsigned char const* buf, size_t buflen, struct sockaddr const*
 
 void tr_utpClose(tr_session* session UNUSED)
 {
-    if (utp_timer)
+    if (utp_timer != NULL)
     {
         evtimer_del(utp_timer);
         utp_timer = NULL;
index 1e4c8d3f24f38cdee7aae0131f6e6932fe038743..9f67eab19d40d1c39a65e353ed5879ffe34d8e68 100644 (file)
@@ -150,7 +150,7 @@ typedef int tr_pipe_end_t;
 
 typedef struct tr_event_handle
 {
-    uint8_t die;
+    bool die;
     tr_pipe_end_t fds[2];
     tr_lock* lock;
     tr_session* session;
@@ -203,7 +203,7 @@ static void readFromPipe(evutil_socket_t fd, short eventType, void* veh)
             size_t const nwant = sizeof(data);
             ev_ssize_t const ngot = piperead(fd, &data, nwant);
 
-            if (!eh->die && (ngot == (ev_ssize_t)nwant))
+            if (!eh->die && ngot == (ev_ssize_t)nwant)
             {
                 dbgmsg("invoking function in libevent thread");
                 (data.func)(data.user_data);
@@ -363,7 +363,7 @@ void tr_runInEventThread(tr_session* session, void (* func)(void*), void* user_d
 
         tr_lockUnlock(e->lock);
 
-        if ((res_1 == -1) || (res_2 == -1))
+        if (res_1 == -1 || res_2 == -1)
         {
             tr_logAddError("Unable to write to libtransmisison event queue: %s", tr_strerror(errno));
         }
index ddab9e3598bd91322b21ac239fc3bef45c648615..893cdd148b7be700ebfbd86f147f0b09e249d9b6 100644 (file)
@@ -46,7 +46,7 @@ struct tr_upnp
     struct IGDdatas data;
     int port;
     char lanaddr[16];
-    unsigned int isMapped;
+    bool isMapped;
     tr_upnp_state state;
 };
 
@@ -66,7 +66,7 @@ tr_upnp* tr_upnpInit(void)
 void tr_upnpClose(tr_upnp* handle)
 {
     assert(!handle->isMapped);
-    assert((handle->state == TR_UPNP_IDLE) || (handle->state == TR_UPNP_ERR) || (handle->state == TR_UPNP_DISCOVER));
+    assert(handle->state == TR_UPNP_IDLE || handle->state == TR_UPNP_ERR || handle->state == TR_UPNP_DISCOVER);
 
     if (handle->hasDiscovered)
     {
@@ -151,7 +151,7 @@ static int tr_upnpAddPortMapping(tr_upnp const* handle, char const* proto, tr_po
         proto, NULL);
 #endif
 
-    if (err)
+    if (err != 0)
     {
         tr_logAddNamedDbg(getKey(), "%s Port forwarding failed with error %d (errno %d - %s)", proto, err, errno,
             tr_strerror(errno));
@@ -182,11 +182,11 @@ enum
     UPNP_IGD_INVALID = 3
 };
 
-int tr_upnpPulse(tr_upnp* handle, int port, int isEnabled, int doPortCheck)
+int tr_upnpPulse(tr_upnp* handle, int port, bool isEnabled, bool doPortCheck)
 {
     int ret;
 
-    if (isEnabled && (handle->state == TR_UPNP_DISCOVER))
+    if (isEnabled && handle->state == TR_UPNP_DISCOVER)
     {
         struct UPNPDev* devlist;
 
@@ -214,7 +214,7 @@ int tr_upnpPulse(tr_upnp* handle, int port, int isEnabled, int doPortCheck)
 
     if (handle->state == TR_UPNP_IDLE)
     {
-        if (handle->isMapped && (!isEnabled || (handle->port != port)))
+        if (handle->isMapped && (!isEnabled || handle->port != port))
         {
             handle->state = TR_UPNP_UNMAP;
         }
@@ -222,8 +222,8 @@ int tr_upnpPulse(tr_upnp* handle, int port, int isEnabled, int doPortCheck)
 
     if (isEnabled && handle->isMapped && doPortCheck)
     {
-        if ((tr_upnpGetSpecificPortMappingEntry(handle, "TCP") != UPNPCOMMAND_SUCCESS) ||
-            (tr_upnpGetSpecificPortMappingEntry(handle, "UDP") != UPNPCOMMAND_SUCCESS))
+        if (tr_upnpGetSpecificPortMappingEntry(handle, "TCP") != UPNPCOMMAND_SUCCESS ||
+            tr_upnpGetSpecificPortMappingEntry(handle, "UDP") != UPNPCOMMAND_SUCCESS)
         {
             tr_logAddNamedInfo(getKey(), _("Port %d isn't forwarded"), handle->port);
             handle->isMapped = false;
@@ -238,7 +238,7 @@ int tr_upnpPulse(tr_upnp* handle, int port, int isEnabled, int doPortCheck)
         tr_logAddNamedInfo(getKey(), _("Stopping port forwarding through \"%s\", service \"%s\""), handle->urls.controlURL,
             handle->data.first.servicetype);
 
-        handle->isMapped = 0;
+        handle->isMapped = false;
         handle->state = TR_UPNP_IDLE;
         handle->port = -1;
     }
@@ -257,7 +257,7 @@ int tr_upnpPulse(tr_upnp* handle, int port, int isEnabled, int doPortCheck)
         int err_udp = -1;
         errno = 0;
 
-        if (!handle->urls.controlURL)
+        if (handle->urls.controlURL == NULL)
         {
             handle->isMapped = 0;
         }
@@ -269,7 +269,7 @@ int tr_upnpPulse(tr_upnp* handle, int port, int isEnabled, int doPortCheck)
             err_tcp = tr_upnpAddPortMapping(handle, "TCP", port, desc);
             err_udp = tr_upnpAddPortMapping(handle, "UDP", port, desc);
 
-            handle->isMapped = !err_tcp | !err_udp;
+            handle->isMapped = err_tcp == 0 || err_udp == 0;
         }
 
         tr_logAddNamedInfo(getKey(), _("Port forwarding through \"%s\", service \"%s\". (local address: %s:%d)"),
index 207b513067e19e3e2ed998515e3ca7ac50986fa5..ace7f1de86d6f6b352fe17005a306f00b2511c0b 100644 (file)
@@ -23,6 +23,6 @@ tr_upnp* tr_upnpInit(void);
 
 void tr_upnpClose(tr_upnp*);
 
-int tr_upnpPulse(tr_upnp*, int port, int isEnabled, int doPortCheck);
+int tr_upnpPulse(tr_upnp*, int port, bool isEnabled, bool doPortCheck);
 
 /* @} */
index 213c5435bf9c779a426e2871dfccc1cb048cb52a..5201f287ae725d48a190acee7d79ce283a807283 100644 (file)
@@ -113,7 +113,7 @@ static int test_utf8(void)
     in = "\x92\xE0\xE3\xA4\xAD\xAE \xA1\xEB\xE2\xEC \x81\xAE\xA3\xAE\xAC";
     out = tr_utf8clean(in, 17);
     check(out != NULL);
-    check((strlen(out) == 17) || (strlen(out) == 33));
+    check(strlen(out) == 17 || strlen(out) == 33);
     check(tr_utf8_validate(out, TR_BAD_SIZE, NULL));
     tr_free(out);
 
@@ -128,14 +128,14 @@ static int test_utf8(void)
     in = "\xF4\x00\x81\x82";
     out = tr_utf8clean(in, 4);
     check(out != NULL);
-    check((strlen(out) == 1) || (strlen(out) == 2));
+    check(strlen(out) == 1 || strlen(out) == 2);
     check(tr_utf8_validate(out, TR_BAD_SIZE, NULL));
     tr_free(out);
 
     in = "\xF4\x33\x81\x82";
     out = tr_utf8clean(in, 4);
     check(out != NULL);
-    check((strlen(out) == 4) || (strlen(out) == 7));
+    check(strlen(out) == 4 || strlen(out) == 7);
     check(tr_utf8_validate(out, TR_BAD_SIZE, NULL));
     tr_free(out);
 
@@ -322,14 +322,14 @@ static int test_array(void)
 
     for (i = 0; i < n; ++i)
     {
-        check_int_eq((i < 5 ? i : i + 1), array[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)
     {
-        check_int_eq((i < 4 ? i + 1 : i + 2), array[i]);
+        check_int_eq(i < 4 ? i + 1 : i + 2, array[i]);
     }
 
     tr_removeElementFromArray(array, n - 1, sizeof(size_t), n);
@@ -337,7 +337,7 @@ static int test_array(void)
 
     for (i = 0; i < n; ++i)
     {
-        check_int_eq((i < 4 ? i + 1 : i + 2), array[i]);
+        check_int_eq(i < 4 ? i + 1 : i + 2, array[i]);
     }
 
     return 0;
index 65f55814b128246cc52fcb3141e41d959c722f6a..499dc64474d5eb4f04260d39abe1a99f129f1d71 100644 (file)
@@ -72,7 +72,7 @@ struct tm* tr_localtime_r(time_t const* _clock, struct tm* _result)
 
     struct tm* p = localtime(_clock);
 
-    if (p)
+    if (p != NULL)
     {
         *(_result) = *p;
     }
@@ -124,12 +124,12 @@ int tr_gettimeofday(struct timeval* tv)
 
 void* tr_malloc(size_t size)
 {
-    return size ? malloc(size) : NULL;
+    return size != 0 ? malloc(size) : NULL;
 }
 
 void* tr_malloc0(size_t size)
 {
-    return size ? calloc(1, size) : NULL;
+    return size != 0 ? calloc(1, size) : NULL;
 }
 
 void* tr_realloc(void* p, size_t size)
@@ -167,9 +167,9 @@ char const* tr_strip_positional_args(char const* str)
     static size_t bufsize = 0;
     static char* buf = NULL;
     char const* in = str;
-    size_t const len = str ? strlen(str) : 0;
+    size_t const len = str != NULL ? strlen(str) : 0;
 
-    if (!buf || (bufsize < len))
+    if (buf == NULL || bufsize < len)
     {
         bufsize = len * 2 + 1;
         buf = tr_renew(char, buf, bufsize);
@@ -179,7 +179,7 @@ char const* tr_strip_positional_args(char const* str)
     {
         *out++ = *str;
 
-        if ((*str == '%') && isdigit(str[1]))
+        if (*str == '%' && isdigit(str[1]))
         {
             char const* tmp = str + 1;
 
@@ -194,7 +194,7 @@ char const* tr_strip_positional_args(char const* str)
             }
         }
 
-        if ((*str == '%') && (str[1] == '\''))
+        if (*str == '%' && str[1] == '\'')
         {
             str = str + 1;
         }
@@ -300,7 +300,7 @@ char* tr_buildPath(char const* first_element, ...)
     va_start(vl, first_element);
     element = first_element;
 
-    while (element)
+    while (element != NULL)
     {
         bufLen += strlen(element) + 1;
         element = va_arg(vl, char const*);
@@ -318,7 +318,7 @@ char* tr_buildPath(char const* first_element, ...)
     va_start(vl, first_element);
     element = first_element;
 
-    while (element)
+    while (element != NULL)
     {
         size_t const elementLen = strlen(element);
         memcpy(pch, element, elementLen);
@@ -346,7 +346,7 @@ int64_t tr_getDirFreeSpace(char const* dir)
 {
     int64_t free_space;
 
-    if (!dir || !*dir)
+    if (dir == NULL || *dir == '\0')
     {
         errno = EINVAL;
         free_space = -1;
@@ -395,7 +395,7 @@ char* tr_strndup(void const* in, size_t len)
     {
         out = tr_strdup(in);
     }
-    else if (in)
+    else if (in != NULL)
     {
         out = tr_malloc(len + 1);
 
@@ -416,14 +416,15 @@ char const* tr_memmem(char const* haystack, size_t haystacklen, char const* need
     return memmem(haystack, haystacklen, needle, needlelen);
 
 #else
+
     size_t i;
 
-    if (!needlelen)
+    if (needlelen == 0)
     {
         return haystack;
     }
 
-    if (needlelen > haystacklen || !haystack || !needle)
+    if (needlelen > haystacklen || haystack == NULL || needle == NULL)
     {
         return NULL;
     }
@@ -474,17 +475,17 @@ char const* tr_strerror(int i)
 
 int tr_strcmp0(char const* str1, char const* str2)
 {
-    if (str1 && str2)
+    if (str1 != NULL && str2 != NULL)
     {
         return strcmp(str1, str2);
     }
 
-    if (str1)
+    if (str1 != NULL)
     {
         return 1;
     }
 
-    if (str2)
+    if (str2 != NULL)
     {
         return -1;
     }
@@ -541,7 +542,7 @@ char* tr_strstrip(char* str)
         size_t pos;
         size_t len = strlen(str);
 
-        while (len && isspace(str[len - 1]))
+        while (len != 0 && isspace(str[len - 1]))
         {
             --len;
         }
@@ -564,12 +565,12 @@ bool tr_str_has_suffix(char const* str, char const* suffix)
     size_t str_len;
     size_t suffix_len;
 
-    if (!str)
+    if (str == NULL)
     {
         return false;
     }
 
-    if (!suffix)
+    if (suffix == NULL)
     {
         return true;
     }
@@ -668,7 +669,7 @@ size_t tr_strlcpy(char* dst, void const* src, size_t siz)
             *d = '\0'; /* NUL-terminate dst */
         }
 
-        while (*s++)
+        while (*s++ != '\0')
         {
         }
     }
@@ -1141,7 +1142,7 @@ static char* to_utf8(const char* in, size_t inlen)
     size_t const buflen = inlen * 4 + 10;
     char* out = tr_new(char, buflen);
 
-    for (i = 0; !ret && i < encoding_count; ++i)
+    for (i = 0; ret == NULL && i < encoding_count; ++i)
     {
 #ifdef ICONV_SECOND_ARGUMENT_IS_CONST
         char const* inbuf = in;
@@ -1401,7 +1402,7 @@ static bool parseNumberSection(char const* str, size_t len, struct number_range*
     errno = 0;
     a = b = strtol(tmp, &end, 10);
 
-    if (errno || (end == tmp))
+    if (errno != 0 || end == tmp)
     {
         success = false;
     }
@@ -1414,11 +1415,11 @@ static bool parseNumberSection(char const* str, size_t len, struct number_range*
         char const* pch = end + 1;
         b = strtol(pch, &end, 10);
 
-        if (errno || (pch == end))
+        if (errno != 0 || pch == end)
         {
             success = false;
         }
-        else if (*end) /* trailing data */
+        else if (*end != '\0') /* trailing data */
         {
             success = false;
         }
@@ -1462,12 +1463,12 @@ int* tr_parseNumberRange(char const* str_in, size_t len, int* setmeCount)
 
     walk = str;
 
-    while (walk && *walk && success)
+    while (walk != NULL && *walk != '\0' && success)
     {
         struct number_range range;
         char const* pch = strchr(walk, ',');
 
-        if (pch)
+        if (pch != NULL)
         {
             success = parseNumberSection(walk, (size_t)(pch - walk), &range);
             walk = pch + 1;
@@ -1539,7 +1540,7 @@ int* tr_parseNumberRange(char const* str_in, size_t len, int* setmeCount)
             {
                 for (i = n = 0; i < n2; ++i)
                 {
-                    if (!n || uniq[n - 1] != sorted[i])
+                    if (n == 0 || uniq[n - 1] != sorted[i])
                     {
                         uniq[n++] = sorted[i];
                     }
@@ -1570,9 +1571,9 @@ double tr_truncd(double x, int precision)
     int const max_precision = (int)log10(1.0 / DBL_EPSILON) - 1;
     tr_snprintf(buf, sizeof(buf), "%.*f", max_precision, x);
 
-    if ((pt = strstr(buf, localeconv()->decimal_point)))
+    if ((pt = strstr(buf, localeconv()->decimal_point)) != NULL)
     {
-        pt[precision ? precision + 1 : 0] = '\0';
+        pt[precision != 0 ? precision + 1 : 0] = '\0';
     }
 
     return atof(buf);
@@ -1737,7 +1738,7 @@ void* tr_valloc(size_t bufLen)
     void* buf = NULL;
     static size_t pageSize = 0;
 
-    if (!pageSize)
+    if (pageSize == 0)
     {
 #if defined(HAVE_GETPAGESIZE) && !defined(_WIN32)
         pageSize = (size_t)getpagesize();
@@ -1755,9 +1756,9 @@ void* tr_valloc(size_t bufLen)
 
 #ifdef HAVE_POSIX_MEMALIGN
 
-    if (!buf)
+    if (buf == NULL)
     {
-        if (posix_memalign(&buf, pageSize, allocLen))
+        if (posix_memalign(&buf, pageSize, allocLen) != 0)
         {
             buf = NULL; /* just retry with valloc/malloc */
         }
@@ -1767,14 +1768,14 @@ void* tr_valloc(size_t bufLen)
 
 #ifdef HAVE_VALLOC
 
-    if (!buf)
+    if (buf == NULL)
     {
         buf = valloc(allocLen);
     }
 
 #endif
 
-    if (!buf)
+    if (buf == NULL)
     {
         buf = tr_malloc(allocLen);
     }
index eda4c59973c2a9900067b6e7f485a24497155b3f..eff009634356d2884b697ea2814478db1d4c25e4 100644 (file)
@@ -65,12 +65,12 @@ int tr_bencParseInt(uint8_t const* buf, uint8_t const* bufend, uint8_t const** s
     errno = 0;
     val = evutil_strtoll(begin, &endptr, 10);
 
-    if (errno || (endptr != end)) /* incomplete parse */
+    if (errno != 0 || endptr != end) /* incomplete parse */
     {
         return EILSEQ;
     }
 
-    if (val && *(char const*)begin == '0') /* no leading zeroes! */
+    if (val != 0 && *(char const*)begin == '0') /* no leading zeroes! */
     {
         return EILSEQ;
     }
@@ -115,7 +115,7 @@ int tr_bencParseStr(uint8_t const* buf, uint8_t const* bufend, uint8_t const** s
     errno = 0;
     len = strtoul((char const*)buf, &ulend, 10);
 
-    if (errno || ulend != end)
+    if (errno != 0 || ulend != end)
     {
         goto err;
     }
@@ -123,7 +123,7 @@ int tr_bencParseStr(uint8_t const* buf, uint8_t const* bufend, uint8_t const** s
     strbegin = (uint8_t const*)end + 1;
     strend = strbegin + len;
 
-    if ((strend < strbegin) || (strend > bufend))
+    if (strend < strbegin || strend > bufend)
     {
         goto err;
     }
@@ -156,7 +156,7 @@ static tr_variant* get_node(tr_ptrArray* stack, tr_quark* key, tr_variant* top,
         {
             node = tr_variantListAdd(parent);
         }
-        else if (*key && tr_variantIsDict(parent))
+        else if (*key != 0 && tr_variantIsDict(parent))
         {
             node = tr_variantDictAdd(parent, *key);
             *key = 0;
@@ -192,7 +192,7 @@ int tr_variantParseBenc(void const* buf_in, void const* bufend_in, tr_variant* t
             err = EILSEQ;
         }
 
-        if (err)
+        if (err != 0)
         {
             break;
         }
@@ -203,14 +203,14 @@ int tr_variantParseBenc(void const* buf_in, void const* bufend_in, tr_variant* t
             uint8_t const* end;
             tr_variant* v;
 
-            if ((err = tr_bencParseInt(buf, bufend, &end, &val)))
+            if ((err = tr_bencParseInt(buf, bufend, &end, &val)) != 0)
             {
                 break;
             }
 
             buf = end;
 
-            if ((v = get_node(&stack, &key, top, &err)))
+            if ((v = get_node(&stack, &key, top, &err)) != NULL)
             {
                 tr_variantInitInt(v, val);
             }
@@ -221,7 +221,7 @@ int tr_variantParseBenc(void const* buf_in, void const* bufend_in, tr_variant* t
 
             ++buf;
 
-            if ((v = get_node(&stack, &key, top, &err)))
+            if ((v = get_node(&stack, &key, top, &err)) != NULL)
             {
                 tr_variantInitList(v, 0);
                 tr_ptrArrayAppend(&stack, v);
@@ -233,7 +233,7 @@ int tr_variantParseBenc(void const* buf_in, void const* bufend_in, tr_variant* t
 
             ++buf;
 
-            if ((v = get_node(&stack, &key, top, &err)))
+            if ((v = get_node(&stack, &key, top, &err)) != NULL)
             {
                 tr_variantInitDict(v, 0);
                 tr_ptrArrayAppend(&stack, v);
@@ -243,7 +243,7 @@ int tr_variantParseBenc(void const* buf_in, void const* bufend_in, tr_variant* t
         {
             ++buf;
 
-            if (tr_ptrArrayEmpty(&stack) || (key != 0))
+            if (tr_ptrArrayEmpty(&stack) || key != 0)
             {
                 err = EILSEQ;
                 break;
@@ -265,18 +265,18 @@ int tr_variantParseBenc(void const* buf_in, void const* bufend_in, tr_variant* t
             uint8_t const* str;
             size_t str_len;
 
-            if ((err = tr_bencParseStr(buf, bufend, &end, &str, &str_len)))
+            if ((err = tr_bencParseStr(buf, bufend, &end, &str, &str_len)) != 0)
             {
                 break;
             }
 
             buf = end;
 
-            if (!key && !tr_ptrArrayEmpty(&stack) && tr_variantIsDict(tr_ptrArrayBack(&stack)))
+            if (key == 0 && !tr_ptrArrayEmpty(&stack) && tr_variantIsDict(tr_ptrArrayBack(&stack)))
             {
                 key = tr_quark_new(str, str_len);
             }
-            else if ((v = get_node(&stack, &key, top, &err)))
+            else if ((v = get_node(&stack, &key, top, &err)) != NULL)
             {
                 tr_variantInitStr(v, str, str_len);
             }
index 009467ee30df57dcb73637a6f35bf23056dbc17a..ce62f813b795e86f38f8cbd10e5c9c34112b9ca7 100644 (file)
@@ -54,7 +54,7 @@ static tr_variant* get_node(struct jsonsl_st* jsn)
 
     parent = tr_ptrArrayEmpty(&data->stack) ? NULL : tr_ptrArrayBack(&data->stack);
 
-    if (!parent)
+    if (parent == NULL)
     {
         node = data->top;
     }
@@ -62,7 +62,7 @@ static tr_variant* get_node(struct jsonsl_st* jsn)
     {
         node = tr_variantListAdd(parent);
     }
-    else if (tr_variantIsDict(parent) && (data->key != NULL))
+    else if (tr_variantIsDict(parent) && data->key != NULL)
     {
         node = tr_variantDictAdd(parent, tr_quark_new(data->key, data->keylen));
 
@@ -77,7 +77,7 @@ static void error_handler(jsonsl_t jsn, jsonsl_error_t error, struct jsonsl_stat
 {
     struct json_wrapper_data* data = jsn->data;
 
-    if (data->source)
+    if (data->source != NULL)
     {
         tr_logAddError("JSON parse failed in %s at pos %zu: %s -- remaining text \"%.16s\"", data->source, jsn->pos,
             jsonsl_strerror(error), buf);
@@ -139,15 +139,15 @@ static bool decode_hex_string(char const* in, unsigned int* setme)
     {
         val <<= 4;
 
-        if (('0' <= *in) && (*in <= '9'))
+        if ('0' <= *in && *in <= '9')
         {
             val += (*in - '0');
         }
-        else if (('a' <= *in) && (*in <= 'f'))
+        else if ('a' <= *in && *in <= 'f')
         {
             val += (*in - 'a') + 10u;
         }
-        else if (('A' <= *in) && (*in <= 'F'))
+        else if ('A' <= *in && *in <= 'F')
         {
             val += (*in - 'A') + 10u;
         }
@@ -314,31 +314,31 @@ static void action_callback_POP(jsonsl_t jsn, jsonsl_action_t action UNUSED, str
         data->has_content = true;
         data->key = extract_string(jsn, state, &data->keylen, data->keybuf);
     }
-    else if ((state->type == JSONSL_T_LIST) || (state->type == JSONSL_T_OBJECT))
+    else if (state->type == JSONSL_T_LIST || state->type == JSONSL_T_OBJECT)
     {
         tr_ptrArrayPop(&data->stack);
     }
     else if (state->type == JSONSL_T_SPECIAL)
     {
-        if (state->special_flags & JSONSL_SPECIALf_NUMNOINT)
+        if ((state->special_flags & JSONSL_SPECIALf_NUMNOINT) != 0)
         {
             char const* begin = jsn->base + state->pos_begin;
             data->has_content = true;
             tr_variantInitReal(get_node(jsn), strtod(begin, NULL));
         }
-        else if (state->special_flags & JSONSL_SPECIALf_NUMERIC)
+        else if ((state->special_flags & JSONSL_SPECIALf_NUMERIC) != 0)
         {
             char const* begin = jsn->base + state->pos_begin;
             data->has_content = true;
             tr_variantInitInt(get_node(jsn), evutil_strtoll(begin, NULL, 10));
         }
-        else if (state->special_flags & JSONSL_SPECIALf_BOOLEAN)
+        else if ((state->special_flags & JSONSL_SPECIALf_BOOLEAN) != 0)
         {
             bool const b = (state->special_flags & JSONSL_SPECIALf_TRUE) != 0;
             data->has_content = true;
             tr_variantInitBool(get_node(jsn), b);
         }
-        else if (state->special_flags & JSONSL_SPECIALf_NULL)
+        else if ((state->special_flags & JSONSL_SPECIALf_NULL) != 0)
         {
             data->has_content = true;
             tr_variantInitQuark(get_node(jsn), TR_KEY_NONE);
@@ -372,13 +372,13 @@ int tr_jsonParse(char const* source, void const* vbuf, size_t len, tr_variant* s
     jsonsl_feed(jsn, vbuf, len);
 
     /* EINVAL if there was no content */
-    if (!data.error && !data.has_content)
+    if (data.error == 0 && !data.has_content)
     {
         data.error = EINVAL;
     }
 
     /* maybe set the end ptr */
-    if (setme_end)
+    if (setme_end != NULL)
     {
         *setme_end = ((char const*)vbuf) + jsn->pos;
     }
@@ -414,7 +414,7 @@ static void jsonIndent(struct jsonWalk* data)
 {
     static char buf[1024] = { '\0' };
 
-    if (!*buf)
+    if (*buf == '\0')
     {
         memset(buf, ' ', sizeof(buf));
         buf[0] = '\n';
@@ -428,7 +428,7 @@ static void jsonIndent(struct jsonWalk* data)
 
 static void jsonChildFunc(struct jsonWalk* data)
 {
-    if (data->parents && data->parents->data)
+    if (data->parents != NULL && data->parents->data != NULL)
     {
         struct ParentState* pstate = data->parents->data;
 
@@ -438,7 +438,7 @@ static void jsonChildFunc(struct jsonWalk* data)
             {
                 int const i = pstate->childIndex++;
 
-                if (!(i % 2))
+                if (i % 2 == 0)
                 {
                     evbuffer_add(data->out, ": ", data->doIndent ? 2 : 1);
                 }
@@ -609,7 +609,7 @@ static void jsonStringFunc(tr_variant const* val, void* vdata)
                 UTF32* u32 = buf;
                 ConversionResult result = ConvertUTF8toUTF32(&tmp, end, &u32, buf + 1, 0);
 
-                if (((result == conversionOK) || (result == targetExhausted)) && (tmp != it))
+                if ((result == conversionOK || result == targetExhausted) && tmp != it)
                 {
                     outwalk += tr_snprintf(outwalk, outend - outwalk, "\\u%04x", (unsigned int)buf[0]);
                     it = tmp - 1;
@@ -634,7 +634,7 @@ static void jsonDictBeginFunc(tr_variant const* val, void* vdata)
     jsonPushParent(data, val);
     evbuffer_add(data->out, "{", 1);
 
-    if (val->val.l.count)
+    if (val->val.l.count != 0)
     {
         jsonIndent(data);
     }
@@ -648,7 +648,7 @@ static void jsonListBeginFunc(tr_variant const* val, void* vdata)
     jsonPushParent(data, val);
     evbuffer_add(data->out, "[", 1);
 
-    if (nChildren)
+    if (nChildren != 0)
     {
         jsonIndent(data);
     }
@@ -699,7 +699,7 @@ void tr_variantToBufJson(tr_variant const* top, struct evbuffer* buf, bool lean)
 
     tr_variantWalk(top, &walk_funcs, &data, true);
 
-    if (evbuffer_get_length(buf))
+    if (evbuffer_get_length(buf) != 0)
     {
         evbuffer_add_printf(buf, "\n");
     }
index 125db0229e278bc308ef6e7f52fa76cd2c0b0aae..dfab86c41b15461aec41cc2e47cad41b84b96e0c 100644 (file)
@@ -38,7 +38,7 @@ static int testInt(void)
     err = tr_bencParseInt(buf, buf + 4, &end, &val);
     check_int_eq(0, err);
     check_int_eq(64, val);
-    check((buf + 4) == end);
+    check(buf + 4 == end);
 
     /* missing 'e' */
     end = NULL;
@@ -66,14 +66,14 @@ static int testInt(void)
     err = tr_bencParseInt(buf, buf + 4, &end, &val);
     check_int_eq(0, err);
     check_int_eq(-3, val);
-    check((buf + 4) == end);
+    check(buf + 4 == end);
 
     /* zero */
     tr_snprintf((char*)buf, sizeof(buf), "i0e");
     err = tr_bencParseInt(buf, buf + 4, &end, &val);
     check_int_eq(0, err);
     check_int_eq(0, val);
-    check((buf + 3) == end);
+    check(buf + 3 == end);
 
     /* no leading zeroes allowed */
     val = 0;
@@ -103,7 +103,7 @@ static int testStr(void)
     check_uint_eq(0, len);
     check(str == NULL);
     check(end == NULL);
-    check(!len);
+    check(len == 0);
 
     /* good string */
     n = tr_snprintf((char*)buf, sizeof(buf), "4:boat");
@@ -122,14 +122,14 @@ static int testStr(void)
     check_uint_eq(0, len);
     check(str == NULL);
     check(end == NULL);
-    check(!len);
+    check(len == 0);
 
     /* empty string */
     n = tr_snprintf((char*)buf, sizeof(buf), "0:");
     err = tr_bencParseStr(buf, buf + n, &end, &str, &len);
     check_int_eq(0, err);
     check_uint_eq(0, len);
-    check(!*str);
+    check(*str == '\0');
     check(end == buf + 2);
     str = NULL;
     end = NULL;
@@ -162,11 +162,11 @@ static int testString(char const* str, bool isGood)
 
     if (!isGood)
     {
-        check(err);
+        check(err != 0);
     }
     else
     {
-        check(!err);
+        check(err == 0);
 #if 0
         fprintf(stderr, "in: [%s]\n", str);
         fprintf(stderr, "out:\n%s", tr_variantToStr(&val, TR_VARIANT_FMT_JSON, NULL));
@@ -196,7 +196,7 @@ static int testParse(void)
 
     tr_snprintf((char*)buf, sizeof(buf), "i64e");
     err = tr_variantFromBencFull(&val, buf, sizeof(buf), NULL, &end);
-    check(!err);
+    check(err == 0);
     check(tr_variantGetInt(&val, &i));
     check_int_eq(64, i);
     check(end == buf + 4);
@@ -204,7 +204,7 @@ static int testParse(void)
 
     tr_snprintf((char*)buf, sizeof(buf), "li64ei32ei16ee");
     err = tr_variantFromBencFull(&val, buf, sizeof(buf), NULL, &end);
-    check(!err);
+    check(err == 0);
     check(end == buf + strlen((char*)buf));
     check(val.val.l.count == 3);
     check(tr_variantGetInt(&val.val.l.vals[0], &i));
@@ -221,60 +221,60 @@ static int testParse(void)
     end = NULL;
     tr_snprintf((char*)buf, sizeof(buf), "lllee");
     err = tr_variantFromBencFull(&val, buf, sizeof(buf), NULL, &end);
-    check(err);
+    check(err != 0);
     check(end == NULL);
 
     end = NULL;
     tr_snprintf((char*)buf, sizeof(buf), "le");
     err = tr_variantFromBencFull(&val, buf, sizeof(buf), NULL, &end);
-    check(!err);
+    check(err == 0);
     check(end == buf + 2);
     saved = tr_variantToStr(&val, TR_VARIANT_FMT_BENC, &len);
     check_streq("le", saved);
     tr_free(saved);
     tr_variantFree(&val);
 
-    if ((err = testString("llleee", true)))
+    if ((err = testString("llleee", true)) != 0)
     {
         return err;
     }
 
-    if ((err = testString("d3:cow3:moo4:spam4:eggse", true)))
+    if ((err = testString("d3:cow3:moo4:spam4:eggse", true)) != 0)
     {
         return err;
     }
 
-    if ((err = testString("d4:spaml1:a1:bee", true)))
+    if ((err = testString("d4:spaml1:a1:bee", true)) != 0)
     {
         return err;
     }
 
-    if ((err = testString("d5:greenli1ei2ei3ee4:spamd1:ai123e3:keyi214eee", true)))
+    if ((err = testString("d5:greenli1ei2ei3ee4:spamd1:ai123e3:keyi214eee", true)) != 0)
     {
         return err;
     }
 
-    if ((err = testString("d9:publisher3:bob17:publisher-webpage15:www.example.com18:publisher.location4:homee", true)))
+    if ((err = testString("d9:publisher3:bob17:publisher-webpage15:www.example.com18:publisher.location4:homee", true)) != 0)
     {
         return err;
     }
 
-    if ((err = testString("d8:completei1e8:intervali1800e12:min intervali1800e5:peers0:e", true)))
+    if ((err = testString("d8:completei1e8:intervali1800e12:min intervali1800e5:peers0:e", true)) != 0)
     {
         return err;
     }
 
-    if ((err = testString("d1:ai0e1:be", false))) /* odd number of children */
+    if ((err = testString("d1:ai0e1:be", false)) != 0) /* odd number of children */
     {
         return err;
     }
 
-    if ((err = testString("", false)))
+    if ((err = testString("", false)) != 0)
     {
         return err;
     }
 
-    if ((err = testString(" ", false)))
+    if ((err = testString(" ", false)) != 0)
     {
         return err;
     }
@@ -285,10 +285,10 @@ static int testParse(void)
     end = NULL;
     tr_snprintf((char*)buf, sizeof(buf), "lld1:bi32e1:ai64eeee");
     err = tr_variantFromBencFull(&val, buf, sizeof(buf), NULL, &end);
-    check(!err);
+    check(err == 0);
     check(end == buf + strlen((char const*)buf));
-    check((child = tr_variantListChild(&val, 0)));
-    check((child2 = tr_variantListChild(child, 0)));
+    check((child = tr_variantListChild(&val, 0)) != NULL);
+    check((child2 = tr_variantListChild(child, 0)) != NULL);
     saved = tr_variantToStr(&val, TR_VARIANT_FMT_BENC, &len);
     check_streq("lld1:ai64e1:bi32eeee", saved);
     tr_free(saved);
@@ -298,7 +298,7 @@ static int testParse(void)
     end = NULL;
     tr_snprintf((char*)buf, sizeof(buf), "leee");
     err = tr_variantFromBencFull(&val, buf, sizeof(buf), NULL, &end);
-    check(!err);
+    check(err == 0);
     check(end == buf + 2);
     saved = tr_variantToStr(&val, TR_VARIANT_FMT_BENC, &len);
     check_streq("le", saved);
@@ -309,13 +309,13 @@ static int testParse(void)
     end = NULL;
     tr_snprintf((char*)buf, sizeof(buf), "l1:a1:b1:c");
     err = tr_variantFromBencFull(&val, buf, strlen(buf), NULL, &end);
-    check(err);
+    check(err != 0);
 
     /* incomplete string */
     end = NULL;
     tr_snprintf((char*)buf, sizeof(buf), "1:");
     err = tr_variantFromBencFull(&val, buf, strlen(buf), NULL, &end);
-    check(err);
+    check(err != 0);
 
     return 0;
 }
@@ -324,7 +324,7 @@ static void stripWhitespace(char* in)
 {
     char* out;
 
-    for (out = in; in && *in; ++in)
+    for (out = in; in != NULL && *in != '\0'; ++in)
     {
         if (!isspace(*in))
         {
@@ -365,7 +365,7 @@ static int testJSON(void)
     benc_str = "i6e";
     expected = "6";
 
-    if ((val = testJSONSnippet(benc_str, expected)))
+    if ((val = testJSONSnippet(benc_str, expected)) != 0)
     {
         return val;
     }
@@ -373,7 +373,7 @@ static int testJSON(void)
     benc_str = "d5:helloi1e5:worldi2ee";
     expected = "{\"hello\":1,\"world\":2}";
 
-    if ((val = testJSONSnippet(benc_str, expected)))
+    if ((val = testJSONSnippet(benc_str, expected)) != 0)
     {
         return val;
     }
@@ -381,7 +381,7 @@ static int testJSON(void)
     benc_str = "d5:helloi1e5:worldi2e3:fooli1ei2ei3eee";
     expected = "{\"foo\":[1,2,3],\"hello\":1,\"world\":2}";
 
-    if ((val = testJSONSnippet(benc_str, expected)))
+    if ((val = testJSONSnippet(benc_str, expected)) != 0)
     {
         return val;
     }
@@ -389,7 +389,7 @@ static int testJSON(void)
     benc_str = "d5:helloi1e5:worldi2e3:fooli1ei2ei3ed1:ai0eeee";
     expected = "{\"foo\":[1,2,3,{\"a\":0}],\"hello\":1,\"world\":2}";
 
-    if ((val = testJSONSnippet(benc_str, expected)))
+    if ((val = testJSONSnippet(benc_str, expected)) != 0)
     {
         return val;
     }
@@ -397,7 +397,7 @@ static int testJSON(void)
     benc_str = "d4:argsd6:statusle7:status2lee6:result7:successe";
     expected = "{\"args\":{\"status\":[],\"status2\":[]},\"result\":\"success\"}";
 
-    if ((val = testJSONSnippet(benc_str, expected)))
+    if ((val = testJSONSnippet(benc_str, expected)) != 0)
     {
         return val;
     }
@@ -488,7 +488,7 @@ static int testStackSmash(void)
     in[depth * 2] = '\0';
     err = tr_variantFromBencFull(&val, in, depth * 2, NULL, &end);
     check_int_eq(0, err);
-    check(end == in + (depth * 2));
+    check(end == in + depth * 2);
     saved = tr_variantToStr(&val, TR_VARIANT_FMT_BENC, &len);
     check_streq((char*)in, saved);
     tr_free(in);
@@ -523,13 +523,13 @@ static int testBool(void)
     check(tr_variantDictFindBool(&top, key4, &boolVal));
     check(boolVal);
     check(tr_variantDictFindInt(&top, key1, &intVal));
-    check(!intVal);
+    check(intVal == 0);
     check(tr_variantDictFindInt(&top, key2, &intVal));
-    check(!intVal);
+    check(intVal == 0);
     check(tr_variantDictFindInt(&top, key3, &intVal));
-    check(intVal);
+    check(intVal != 0);
     check(tr_variantDictFindInt(&top, key4, &intVal));
-    check(intVal);
+    check(intVal != 0);
 
     tr_variantFree(&top);
     return 0;
@@ -561,7 +561,7 @@ static int testParse2(void)
     benc = tr_variantToStr(&top, TR_VARIANT_FMT_BENC, &len);
     check_streq("d14:this-is-a-booli1e14:this-is-a-real8:0.50000016:this-is-a-string16:this-is-a-string14:this-is-an-int"
         "i1234ee", benc);
-    check(!tr_variantFromBencFull(&top2, benc, len, NULL, &end));
+    check(tr_variantFromBencFull(&top2, benc, len, NULL, &end) == 0);
     check(end == benc + len);
     check(tr_variantIsDict(&top2));
     check(tr_variantDictFindInt(&top, key_int, &intVal));
index 23b8d47d04efefefece9afd6e5f7c5ab6c741c76..7cb241978721c37bead133d2142e553286b042b3 100644 (file)
@@ -265,7 +265,7 @@ tr_variant* tr_variantListChild(tr_variant* v, size_t i)
 {
     tr_variant* ret = NULL;
 
-    if (tr_variantIsList(v) && (i < v->val.l.count))
+    if (tr_variantIsList(v) && i < v->val.l.count)
     {
         ret = v->val.l.vals + i;
     }
@@ -277,7 +277,7 @@ bool tr_variantListRemove(tr_variant* list, size_t i)
 {
     bool removed = false;
 
-    if (tr_variantIsList(list) && (i < list->val.l.count))
+    if (tr_variantIsList(list) && i < list->val.l.count)
     {
         removed = true;
         tr_variantFree(&list->val.l.vals[i]);
@@ -291,17 +291,17 @@ bool tr_variantGetInt(tr_variant const* v, int64_t* setme)
 {
     bool success = false;
 
-    if (!success && ((success = tr_variantIsInt(v))))
+    if (!success && (success = tr_variantIsInt(v)))
     {
-        if (setme)
+        if (setme != NULL)
         {
             *setme = v->val.i;
         }
     }
 
-    if (!success && ((success = tr_variantIsBool(v))))
+    if (!success && (success = tr_variantIsBool(v)))
     {
-        if (setme)
+        if (setme != NULL)
         {
             *setme = v->val.b ? 1 : 0;
         }
@@ -352,7 +352,7 @@ bool tr_variantGetBool(tr_variant const* v, bool* setme)
 
     if (!success && tr_variantIsInt(v))
     {
-        if ((success = (v->val.i == 0 || v->val.i == 1)))
+        if ((success = v->val.i == 0 || v->val.i == 1))
         {
             *setme = v->val.i != 0;
         }
@@ -360,7 +360,7 @@ bool tr_variantGetBool(tr_variant const* v, bool* setme)
 
     if (!success && tr_variantGetStr(v, &str, NULL))
     {
-        if ((success = (strcmp(str, "true") == 0 || strcmp(str, "false") == 0)))
+        if ((success = strcmp(str, "true") == 0 || strcmp(str, "false") == 0))
         {
             *setme = strcmp(str, "true") == 0;
         }
@@ -373,12 +373,12 @@ bool tr_variantGetReal(tr_variant const* v, double* setme)
 {
     bool success = false;
 
-    if (!success && ((success = tr_variantIsReal(v))))
+    if (!success && (success = tr_variantIsReal(v)))
     {
         *setme = v->val.d;
     }
 
-    if (!success && ((success = tr_variantIsInt(v))))
+    if (!success && (success = tr_variantIsInt(v)))
     {
         *setme = v->val.i;
     }
@@ -394,7 +394,7 @@ bool tr_variantGetReal(tr_variant const* v, double* setme)
         d = strtod(getStr(v), &endptr);
         restore_locale(&locale_ctx);
 
-        if ((success = (getStr(v) != endptr) && !*endptr))
+        if ((success = getStr(v) != endptr && *endptr == '\0'))
         {
             *setme = d;
         }
@@ -498,7 +498,7 @@ static void containerReserve(tr_variant* v, size_t count)
     if (needed > v->val.l.alloc)
     {
         /* scale the alloc size in powers-of-2 */
-        size_t n = v->val.l.alloc ? v->val.l.alloc : 8;
+        size_t n = v->val.l.alloc != 0 ? v->val.l.alloc : 8;
 
         while (n < needed)
         {
@@ -617,7 +617,7 @@ static tr_variant* dictFindOrAdd(tr_variant* dict, tr_quark const key, int type)
     tr_variant* child;
 
     /* see if it already exists, and if so, try to reuse it */
-    if ((child = tr_variantDictFind(dict, key)))
+    if ((child = tr_variantDictFind(dict, key)) != NULL)
     {
         if (!tr_variantIsType(child, type))
         {
@@ -825,7 +825,7 @@ void tr_variantWalk(tr_variant const* v, struct VariantWalkFuncs const* walkFunc
             v = node->v;
             node->isVisited = true;
         }
-        else if (tr_variantIsContainer(node->v) && (node->childIndex < node->v->val.l.count))
+        else if (tr_variantIsContainer(node->v) && node->childIndex < node->v->val.l.count)
         {
             int const index = node->childIndex++;
             v = node->v->val.l.vals + index;
@@ -849,7 +849,7 @@ void tr_variantWalk(tr_variant const* v, struct VariantWalkFuncs const* walkFunc
             continue;
         }
 
-        if (v)
+        if (v != NULL)
         {
             switch (v->type)
             {
@@ -962,7 +962,7 @@ static void tr_variantListCopy(tr_variant* target, tr_variant const* src)
     int i = 0;
     tr_variant const* val;
 
-    while ((val = tr_variantListChild((tr_variant*)src, i++)))
+    while ((val = tr_variantListChild((tr_variant*)src, i++)) != NULL)
     {
         if (tr_variantIsBool(val))
         {
@@ -1015,7 +1015,7 @@ bool tr_variantDictChild(tr_variant* dict, size_t n, tr_quark* key, tr_variant**
 
     assert(tr_variantIsDict(dict));
 
-    if (tr_variantIsDict(dict) && (n < dict->val.l.count))
+    if (tr_variantIsDict(dict) && n < dict->val.l.count)
     {
         *key = dict->val.l.vals[n].key;
         *val = dict->val.l.vals + n;
index ffa1f0fad57aa3b745aff3cb6418a480b1b3c13d..0f552545ebeb5da258b4b9b19e4ff548c7c5f0c4 100644 (file)
@@ -150,7 +150,7 @@ static inline int tr_variantFromJson(tr_variant* setme, void const* buf, size_t
 
 static inline bool tr_variantIsType(tr_variant const* b, int type)
 {
-    return (b != NULL) && (b->type == type);
+    return b != NULL && b->type == type;
 }
 
 /***
@@ -159,7 +159,7 @@ static inline bool tr_variantIsType(tr_variant const* b, int type)
 
 static inline bool tr_variantIsString(tr_variant const* b)
 {
-    return (b != NULL) && (b->type == TR_VARIANT_TYPE_STR);
+    return b != NULL && b->type == TR_VARIANT_TYPE_STR;
 }
 
 bool tr_variantGetStr(tr_variant const* variant, char const** setme_str, size_t* setme_len);
@@ -176,7 +176,7 @@ bool tr_variantGetRaw(tr_variant const* variant, uint8_t const** raw_setme, size
 
 static inline bool tr_variantIsReal(tr_variant const* v)
 {
-    return (v != NULL) && (v->type == TR_VARIANT_TYPE_REAL);
+    return v != NULL && v->type == TR_VARIANT_TYPE_REAL;
 }
 
 void tr_variantInitReal(tr_variant* initme, double value);
@@ -188,7 +188,7 @@ bool tr_variantGetReal(tr_variant const* variant, double* value_setme);
 
 static inline bool tr_variantIsBool(tr_variant const* v)
 {
-    return (v != NULL) && (v->type == TR_VARIANT_TYPE_BOOL);
+    return v != NULL && v->type == TR_VARIANT_TYPE_BOOL;
 }
 
 void tr_variantInitBool(tr_variant* initme, bool value);
@@ -200,7 +200,7 @@ bool tr_variantGetBool(tr_variant const* variant, bool* setme);
 
 static inline bool tr_variantIsInt(tr_variant const* v)
 {
-    return (v != NULL) && (v->type == TR_VARIANT_TYPE_INT);
+    return v != NULL && v->type == TR_VARIANT_TYPE_INT;
 }
 
 void tr_variantInitInt(tr_variant* variant, int64_t value);
@@ -212,7 +212,7 @@ bool tr_variantGetInt(tr_variant const* val, int64_t* setme);
 
 static inline bool tr_variantIsList(tr_variant const* v)
 {
-    return (v != NULL) && (v->type == TR_VARIANT_TYPE_LIST);
+    return v != NULL && v->type == TR_VARIANT_TYPE_LIST;
 }
 
 void tr_variantInitList(tr_variant* list, size_t reserve_count);
@@ -238,7 +238,7 @@ size_t tr_variantListSize(tr_variant const* list);
 
 static inline bool tr_variantIsDict(tr_variant const* v)
 {
-    return (v != NULL) && (v->type == TR_VARIANT_TYPE_DICT);
+    return v != NULL && v->type == TR_VARIANT_TYPE_DICT;
 }
 
 void tr_variantInitDict(tr_variant* initme, size_t reserve_count);
index 279d2f42c74ed87e66a50fbb9fce3f13bcc5499a..854b659403d07ef341ece3ee0ce39df8f1d8d616 100644 (file)
@@ -60,7 +60,7 @@ static bool verifyTorrent(tr_torrent* tor, bool* stopFlag)
     tr_logAddTorDbg(tor, "%s", "verifying torrent...");
     tr_torrentSetChecked(tor, 0);
 
-    while (!*stopFlag && (pieceIndex < tor->info.pieceCount))
+    while (!*stopFlag && pieceIndex < tor->info.pieceCount)
     {
         uint64_t leftInPiece;
         uint64_t bytesThisPass;
@@ -207,13 +207,13 @@ static void verifyThreadFunc(void* unused UNUSED)
 {
     for (;;)
     {
-        int changed = 0;
+        bool changed = false;
         tr_torrent* tor;
         struct verify_node* node;
 
         tr_lockLock(getVerifyLock());
         stopCurrent = false;
-        node = (struct verify_node*)verifyList ? verifyList->data : NULL;
+        node = verifyList != NULL ? verifyList->data : NULL;
 
         if (node == NULL)
         {
@@ -238,7 +238,7 @@ static void verifyThreadFunc(void* unused UNUSED)
             tr_torrentSetDirty(tor);
         }
 
-        if (currentNode.callback_func)
+        if (currentNode.callback_func != NULL)
         {
             (*currentNode.callback_func)(tor, stopCurrent, currentNode.callback_data);
         }
index b6cf1120b125ceda1d1bcc2c6d2c5b2026dd2bbc..01d0f6ade0948405131db0e9725e493d95a57fe0 100644 (file)
@@ -90,7 +90,7 @@ struct tr_web_task
 
 static void task_free(struct tr_web_task* task)
 {
-    if (task->freebuf)
+    if (task->freebuf != NULL)
     {
         evbuffer_free(task->freebuf);
     }
@@ -132,7 +132,7 @@ static size_t writeFunc(void* ptr, size_t size, size_t nmemb, void* vtask)
     {
         tr_torrent* tor = tr_torrentFindFromId(task->session, task->torrentId);
 
-        if (tor && !tr_bandwidthClamp(&tor->bandwidth, TR_DOWN, nmemb))
+        if (tor != NULL && tr_bandwidthClamp(&tor->bandwidth, TR_DOWN, nmemb) == 0)
         {
             tr_list_append(&paused_easy_handles, task->curl_easy);
             return CURL_WRITEFUNC_PAUSE;
@@ -172,7 +172,7 @@ static long getTimeoutFromURL(struct tr_web_task const* task)
     long timeout;
     tr_session const* session = task->session;
 
-    if (!session || session->isClosed)
+    if (session == NULL || session->isClosed)
     {
         timeout = 20L;
     }
@@ -229,11 +229,11 @@ static CURL* createEasy(tr_session* s, struct tr_web* web, struct tr_web_task* t
     curl_easy_setopt(e, CURLOPT_WRITEDATA, task);
     curl_easy_setopt(e, CURLOPT_WRITEFUNCTION, writeFunc);
 
-    if (((addr = tr_sessionGetPublicAddress(s, TR_AF_INET, &is_default_value))) && !is_default_value)
+    if ((addr = tr_sessionGetPublicAddress(s, TR_AF_INET, &is_default_value)) != NULL && !is_default_value)
     {
         curl_easy_setopt(e, CURLOPT_INTERFACE, tr_address_to_string(addr));
     }
-    else if (((addr = tr_sessionGetPublicAddress(s, TR_AF_INET6, &is_default_value))) && !is_default_value)
+    else if ((addr = tr_sessionGetPublicAddress(s, TR_AF_INET6, &is_default_value)) != NULL && !is_default_value)
     {
         curl_easy_setopt(e, CURLOPT_INTERFACE, tr_address_to_string(addr));
     }
@@ -307,8 +307,8 @@ static struct tr_web_task* tr_webRunImpl(tr_session* session, int torrentId, cha
         task->cookies = tr_strdup(cookies);
         task->done_func = done_func;
         task->done_func_user_data = done_func_user_data;
-        task->response = buffer ? buffer : evbuffer_new();
-        task->freebuf = buffer ? NULL : task->response;
+        task->response = buffer != NULL ? buffer : evbuffer_new();
+        task->freebuf = buffer != NULL ? NULL : task->response;
 
         tr_lockLock(session->web->taskLock);
         task->next = session->web->tasks;
@@ -350,13 +350,13 @@ static void tr_select(int nfds, fd_set* r_fd_set, fd_set* w_fd_set, fd_set* c_fd
 
     (void)nfds;
 
-    if (!r_fd_set->fd_count && !w_fd_set->fd_count && !c_fd_set->fd_count)
+    if (r_fd_set->fd_count == 0 && w_fd_set->fd_count == 0 && c_fd_set->fd_count == 0)
     {
         long int const msec = t->tv_sec * 1000 + t->tv_usec / 1000;
         tr_wait_msec(msec);
     }
-    else if (select(0, r_fd_set->fd_count ? r_fd_set : NULL, w_fd_set->fd_count ? w_fd_set : NULL,
-        c_fd_set->fd_count ? c_fd_set : NULL, t) < 0)
+    else if (select(0, r_fd_set->fd_count != 0 ? r_fd_set : NULL, w_fd_set->fd_count != 0 ? w_fd_set : NULL,
+        c_fd_set->fd_count != 0 ? c_fd_set : NULL, t) < 0)
     {
         char errstr[512];
         int const e = EVUTIL_SOCKET_ERROR();
@@ -382,7 +382,7 @@ static void tr_webThreadFunc(void* vsession)
 
     /* try to enable ssl for https support; but if that fails,
      * try a plain vanilla init */
-    if (curl_global_init(CURL_GLOBAL_SSL))
+    if (curl_global_init(CURL_GLOBAL_SSL) != CURLE_OK)
     {
         curl_global_init(0);
     }
@@ -427,7 +427,7 @@ static void tr_webThreadFunc(void* vsession)
             break;
         }
 
-        if ((web->close_mode == TR_WEB_CLOSE_WHEN_IDLE) && (web->tasks == NULL))
+        if (web->close_mode == TR_WEB_CLOSE_WHEN_IDLE && web->tasks == NULL)
         {
             break;
         }
@@ -461,7 +461,7 @@ static void tr_webThreadFunc(void* vsession)
             tmp = paused_easy_handles;
             paused_easy_handles = NULL;
 
-            while ((handle = tr_list_pop_front(&tmp)))
+            while ((handle = tr_list_pop_front(&tmp)) != NULL)
             {
                 curl_easy_pause(handle, CURLPAUSE_CONT);
             }
@@ -513,9 +513,9 @@ static void tr_webThreadFunc(void* vsession)
         while (mcode == CURLM_CALL_MULTI_PERFORM);
 
         /* pump completed tasks from the multi */
-        while ((msg = curl_multi_info_read(multi, &unused)))
+        while ((msg = curl_multi_info_read(multi, &unused)) != NULL)
         {
-            if ((msg->msg == CURLMSG_DONE) && (msg->easy_handle != NULL))
+            if (msg->msg == CURLMSG_DONE && msg->easy_handle != NULL)
             {
                 double total_time;
                 struct tr_web_task* task;
@@ -527,7 +527,7 @@ static void tr_webThreadFunc(void* vsession)
                 curl_easy_getinfo(e, CURLINFO_REQUEST_SIZE, &req_bytes_sent);
                 curl_easy_getinfo(e, CURLINFO_TOTAL_TIME, &total_time);
                 task->did_connect = task->code > 0 || req_bytes_sent > 0;
-                task->did_timeout = !task->code && (total_time >= task->timeout_secs);
+                task->did_timeout = task->code == 0 && total_time >= task->timeout_secs;
                 curl_multi_remove_handle(multi, e);
                 tr_list_remove_data(&paused_easy_handles, e);
                 curl_easy_cleanup(e);
@@ -729,8 +729,8 @@ void tr_http_escape(struct evbuffer* out, char const* str, size_t len, bool esca
 
     for (char const* end = str + len; str != end; ++str)
     {
-        if ((*str == ',') || (*str == '-') || (*str == '.') || (('0' <= *str) && (*str <= '9')) ||
-            (('A' <= *str) && (*str <= 'Z')) || (('a' <= *str) && (*str <= 'z')) || ((*str == '/') && (!escape_slashes)))
+        if (*str == ',' || *str == '-' || *str == '.' || ('0' <= *str && *str <= '9') || ('A' <= *str && *str <= 'Z') ||
+            ('a' <= *str && *str <= 'z') || (*str == '/' && !escape_slashes))
         {
             evbuffer_add_printf(out, "%c", *str);
         }
index 67726894a5ac9e818a7a22d9c54c1d3a9b786a01..cfbe787c8ca84e6508d9c25350bdf2cbb91457ce 100644 (file)
@@ -196,13 +196,13 @@ static void connection_succeeded(void* vdata)
     struct connection_succeeded_data* data = vdata;
     struct tr_webseed* w = data->webseed;
 
-    if (++w->active_transfers >= w->retry_challenge && w->retry_challenge)
+    if (++w->active_transfers >= w->retry_challenge && w->retry_challenge != 0)
     {
         /* the server seems to be accepting more connections now */
         w->consecutive_failures = w->retry_tickcount = w->retry_challenge = 0;
     }
 
-    if (data->real_url && (tor = tr_torrentFindFromId(w->session, w->torrent_id)))
+    if (data->real_url != NULL && (tor = tr_torrentFindFromId(w->session, w->torrent_id)) != NULL)
     {
         uint64_t file_offset;
         tr_file_index_t file_index;
@@ -229,7 +229,7 @@ static void on_content_changed(struct evbuffer* buf, struct evbuffer_cb_info con
 
     tr_sessionLock(session);
 
-    if (!task->dead && (n_added > 0))
+    if (!task->dead && n_added > 0)
     {
         uint32_t len;
         struct tr_webseed* w = task->webseed;
@@ -238,7 +238,7 @@ static void on_content_changed(struct evbuffer* buf, struct evbuffer_cb_info con
         fire_client_got_piece_data(w, n_added);
         len = evbuffer_get_length(buf);
 
-        if (!task->response_code)
+        if (task->response_code == 0)
         {
             tr_webGetTaskInfo(task->web_task, TR_WEB_GET_CODE, &task->response_code);
 
@@ -262,7 +262,7 @@ static void on_content_changed(struct evbuffer* buf, struct evbuffer_cb_info con
             }
         }
 
-        if ((task->response_code == 206) && (len >= task->block_size))
+        if (task->response_code == 206 && len >= task->block_size)
         {
             /* once we've got at least one full block, save it */
 
@@ -318,7 +318,7 @@ static void on_idle(tr_webseed* w)
         w->retry_challenge = running_tasks + w->idle_connections + 1;
     }
 
-    if (tor && tor->isRunning && !tr_torrentIsSeed(tor) && (want > 0))
+    if (tor != NULL && tor->isRunning && !tr_torrentIsSeed(tor) && want > 0)
     {
         int i;
         int got = 0;
@@ -390,16 +390,16 @@ static void web_response_func(tr_session* session, bool did_connect UNUSED, bool
         {
             tr_block_index_t const blocks_remain = (t->length + tor->blockSize - 1) / tor->blockSize - t->blocks_done;
 
-            if (blocks_remain)
+            if (blocks_remain != 0)
             {
                 fire_client_got_rejs(tor, w, t->block + t->blocks_done, blocks_remain);
             }
 
-            if (t->blocks_done)
+            if (t->blocks_done != 0)
             {
                 ++w->idle_connections;
             }
-            else if (++w->consecutive_failures >= MAX_CONSECUTIVE_FAILURES && !w->retry_tickcount)
+            else if (++w->consecutive_failures >= MAX_CONSECUTIVE_FAILURES && w->retry_tickcount == 0)
             {
                 /* now wait a while until retrying to establish a connection */
                 ++w->retry_tickcount;
@@ -423,7 +423,7 @@ static void web_response_func(tr_session* session, bool did_connect UNUSED, bool
             }
             else
             {
-                if (buf_len && !tr_torrentPieceIsComplete(tor, t->piece_index))
+                if (buf_len != 0 && !tr_torrentPieceIsComplete(tor, t->piece_index))
                 {
                     /* on_content_changed() will not write a block if it is smaller than
                        the torrent's block size, i.e. the torrent's very last block */
@@ -451,7 +451,7 @@ static struct evbuffer* make_url(tr_webseed* w, tr_file const* file)
     evbuffer_add(buf, w->base_url, w->base_url_len);
 
     /* if url ends with a '/', add the torrent name */
-    if (w->base_url[w->base_url_len - 1] == '/' && file->name)
+    if (w->base_url[w->base_url_len - 1] == '/' && file->name != NULL)
     {
         tr_http_escape(buf, file->name, strlen(file->name), false);
     }
@@ -504,7 +504,7 @@ static void webseed_timer_func(evutil_socket_t foo UNUSED, short bar UNUSED, voi
 {
     tr_webseed* w = vw;
 
-    if (w->retry_tickcount)
+    if (w->retry_tickcount != 0)
     {
         ++w->retry_tickcount;
     }
index 5bb9174e1c61ec338f26e271925489cc1934e9f2..765fd67139223053b7094dc42947eead8d319f24 100644 (file)
@@ -47,7 +47,7 @@ int AddData::set(QString const& key)
         size_t len;
         void* raw = tr_base64_decode(key.toUtf8().constData(), key.toUtf8().size(), &len);
 
-        if (raw)
+        if (raw != nullptr)
         {
             metainfo.append(static_cast<char const*>(raw), int(len));
             tr_free(raw);
index 66c353c89295b1f0716e683fd00f038c6a19d729..14e49df00189ae431bc43554e0d8152163c0ae38 100644 (file)
@@ -138,7 +138,7 @@ Application::Application(int& argc, char** argv) :
     QString configDir;
     QStringList filenames;
 
-    while ((c = tr_getopt(getUsage(), argc, const_cast<char const**>(argv), opts, &optarg)))
+    while ((c = tr_getopt(getUsage(), argc, const_cast<char const**>(argv), opts, &optarg)) != TR_OPT_DONE)
     {
         switch (c)
         {
@@ -443,7 +443,7 @@ void Application::onTorrentCompleted(int id)
 {
     Torrent* tor = myModel->getTorrentFromId(id);
 
-    if (tor)
+    if (tor != nullptr)
     {
         if (myPrefs->getBool(Prefs::SHOW_NOTIFICATION_ON_COMPLETE))
         {
@@ -467,7 +467,7 @@ void Application::onNewTorrentChanged(int id)
 {
     Torrent* tor = myModel->getTorrentFromId(id);
 
-    if (tor && !tor->name().isEmpty())
+    if (tor != nullptr && !tor->name().isEmpty())
     {
         int const age_secs = tor->dateAdded().secsTo(QDateTime::currentDateTime());
 
index 7753ab900a142bb9707d457c11b07fd908c685f9..cded80dd2172b3638365e905d797af52b75819d5 100644 (file)
@@ -122,7 +122,7 @@ public:
     {
         PeerItem const* i = dynamic_cast<PeerItem const*>(&other);
         QTreeWidget* tw(treeWidget());
-        int const column = tw ? tw->sortColumn() : 0;
+        int const column = tw != nullptr ? tw->sortColumn() : 0;
 
         assert(i != nullptr);
 
@@ -262,7 +262,7 @@ void DetailsDialog::setIds(QSet<int> const& ids)
     {
         Torrent const* tor = myModel.getTorrentFromId(id);
 
-        if (tor)
+        if (tor != nullptr)
         {
             disconnect(tor, SIGNAL(torrentChanged(int)), this, SLOT(onTorrentChanged()));
         }
@@ -277,7 +277,7 @@ void DetailsDialog::setIds(QSet<int> const& ids)
     {
         Torrent const* tor = myModel.getTorrentFromId(id);
 
-        if (tor)
+        if (tor != nullptr)
         {
             connect(tor, SIGNAL(torrentChanged(int)), this, SLOT(onTorrentChanged()));
         }
@@ -412,7 +412,7 @@ void DetailsDialog::refresh()
     {
         Torrent const* tor = myModel.getTorrentFromId(id);
 
-        if (tor)
+        if (tor != nullptr)
         {
             torrents << tor;
         }
@@ -511,16 +511,16 @@ void DetailsDialog::refresh()
             }
         }
 
-        double const d = 100.0 * (sizeWhenDone ? (sizeWhenDone - leftUntilDone) / sizeWhenDone : 1);
+        double const d = 100.0 * (sizeWhenDone != 0 ? (sizeWhenDone - leftUntilDone) / sizeWhenDone : 1);
         QString pct = Formatter::percentToString(d);
 
-        if (!haveUnverified && !leftUntilDone)
+        if (haveUnverified == 0 && leftUntilDone == 0)
         {
             //: Text following the "Have:" label in torrent properties dialog;
             //: %1 is amount of downloaded and verified data
             string = tr("%1 (100%)").arg(Formatter::sizeToString(haveVerified));
         }
-        else if (!haveUnverified)
+        else if (haveUnverified == 0)
         {
             //: Text following the "Have:" label in torrent properties dialog;
             //: %1 is amount of downloaded and verified data,
@@ -578,7 +578,7 @@ void DetailsDialog::refresh()
         QString const dstr = Formatter::sizeToString(d);
         QString const fstr = Formatter::sizeToString(f);
 
-        if (f)
+        if (f != 0)
         {
             string = tr("%1 (%2 corrupt)").arg(dstr).arg(fstr);
         }
@@ -775,7 +775,7 @@ void DetailsDialog::refresh()
             }
         }
 
-        if (!size)
+        if (size == 0)
         {
             string = none;
         }
@@ -1022,7 +1022,7 @@ void DetailsDialog::refresh()
         }
 
         setIfIdle(ui.ratioCombo, uniform ? ui.ratioCombo->findData(baselineInt) : -1);
-        ui.ratioSpin->setVisible(uniform && (baselineInt == TR_RATIOLIMIT_SINGLE));
+        ui.ratioSpin->setVisible(uniform && baselineInt == TR_RATIOLIMIT_SINGLE);
 
         setIfIdle(ui.ratioSpin, baseline.seedRatioLimit());
 
@@ -1040,7 +1040,7 @@ void DetailsDialog::refresh()
         }
 
         setIfIdle(ui.idleCombo, uniform ? ui.idleCombo->findData(baselineInt) : -1);
-        ui.idleSpin->setVisible(uniform && (baselineInt == TR_RATIOLIMIT_SINGLE));
+        ui.idleSpin->setVisible(uniform && baselineInt == TR_RATIOLIMIT_SINGLE);
 
         setIfIdle(ui.idleSpin, baseline.seedIdleLimit());
         onIdleLimitChanged();
@@ -1245,7 +1245,7 @@ void DetailsDialog::onSpinBoxEditingFinished()
     tr_quark const key = spin->property(PREF_KEY).toInt();
     QDoubleSpinBox const* d = qobject_cast<QDoubleSpinBox const*>(spin);
 
-    if (d)
+    if (d != nullptr)
     {
         mySession.torrentSet(myIds, key, d->value());
     }
index 54cb5a5162fd127d3ce95902b9731dad36dc0dd9..ca92204050519e8ec5590aaa548779a6ca62663d 100644 (file)
@@ -72,7 +72,7 @@ QString FaviconCache::getHost(QUrl const& url)
     int const first_dot = host.indexOf(QLatin1Char('.'));
     int const last_dot = host.lastIndexOf(QLatin1Char('.'));
 
-    if ((first_dot != -1) && (last_dot != -1) && (first_dot != last_dot))
+    if (first_dot != -1 && last_dot != -1 && first_dot != last_dot)
     {
         host.remove(0, first_dot + 1);
     }
@@ -128,7 +128,7 @@ void FaviconCache::onRequestFinished(QNetworkReply* reply)
 
     QByteArray const content = reply->readAll();
 
-    if (!reply->error())
+    if (reply->error() == QNetworkReply::NoError)
     {
         pixmap.loadFromData(content);
     }
index 3c52214e93c6379e7fbdd4210287be5da43d23db..999dcc65bd26b1b2868bafbb8e97c21b8269776d 100644 (file)
@@ -35,7 +35,7 @@ void FileTreeDelegate::paint(QPainter* painter, QStyleOptionViewItem const& opti
 {
     int const column(index.column());
 
-    if ((column != FileTreeModel::COL_PROGRESS) && (column != FileTreeModel::COL_WANTED))
+    if (column != FileTreeModel::COL_PROGRESS && column != FileTreeModel::COL_WANTED)
     {
         QItemDelegate::paint(painter, option, index);
         return;
index 5fe530de3c06d81742e905f5e1c1b7471037815f..cb6ca7ad38bc64c68d3d2b93153ab417a538bb40 100644 (file)
@@ -40,7 +40,7 @@ FileTreeItem::~FileTreeItem()
     if (myParent != nullptr)
     {
         int const pos = row();
-        assert((pos >= 0) && "couldn't find child in parent's lookup");
+        assert(pos >= 0 && "couldn't find child in parent's lookup");
         myParent->myChildren.removeAt(pos);
         myParent->myChildRows.remove(name());
         myParent->myFirstUnhashedRow = pos;
@@ -74,7 +74,7 @@ int FileTreeItem::row() const
 {
     int i(-1);
 
-    if (myParent)
+    if (myParent != nullptr)
     {
         i = myParent->getMyChildRows().value(name(), -1);
         assert(this == myParent->myChildren[i]);
@@ -200,7 +200,7 @@ double FileTreeItem::progress() const
 
     getSubtreeWantedSize(have, total);
 
-    if (total)
+    if (total != 0)
     {
         d = have / double(total);
     }
@@ -233,7 +233,7 @@ std::pair<int, int> FileTreeItem::update(QString const& name, bool wanted, int p
 
     if (myName != name)
     {
-        if (myParent)
+        if (myParent != nullptr)
         {
             myParent->myFirstUnhashedRow = row();
         }
index 0d156c34834ebf7ecb5f5eda559b878477764519..f9696900e1980c1faa65784bb82fb4df0b71a44a 100644 (file)
@@ -168,7 +168,7 @@ Qt::ItemFlags FileTreeModel::flags(QModelIndex const& index) const
 {
     int i(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
 
-    if (myIsEditable && (index.column() == COL_NAME))
+    if (myIsEditable && index.column() == COL_NAME)
     {
         i |= Qt::ItemIsEditable;
     }
@@ -248,7 +248,7 @@ QModelIndex FileTreeModel::index(int row, int column, QModelIndex const& parent)
 
         FileTreeItem* childItem = parentItem->child(row);
 
-        if (childItem)
+        if (childItem != nullptr)
         {
             i = createIndex(row, column, childItem);
         }
@@ -299,7 +299,7 @@ int FileTreeModel::columnCount(QModelIndex const& parent) const
 
 QModelIndex FileTreeModel::indexOf(FileTreeItem* item, int column) const
 {
-    if (!item || item == myRootItem)
+    if (item == nullptr || item == myRootItem)
     {
         return QModelIndex();
     }
@@ -352,7 +352,7 @@ void FileTreeModel::addFile(int fileIndex, QString const& filename, bool wanted,
 
     item = findItemForFileIndex(fileIndex);
 
-    if (item) // this file is already in the tree, we've added this
+    if (item != nullptr) // this file is already in the tree, we've added this
     {
         QModelIndex indexWithChangedParents;
         ForwardPathIterator filenameIt(filename);
@@ -394,7 +394,7 @@ void FileTreeModel::addFile(int fileIndex, QString const& filename, bool wanted,
             QString const& token = filenameIt.next();
             FileTreeItem* child(item->child(token));
 
-            if (!child)
+            if (child == nullptr)
             {
                 added = true;
                 QModelIndex parentIndex(indexOf(item, 0));
@@ -471,7 +471,7 @@ void FileTreeModel::emitSubtreeChanged(QModelIndex const& index, int firstColumn
 
     int const childCount = rowCount(index);
 
-    if (!childCount)
+    if (childCount == 0)
     {
         return;
     }
index de1e74cb63dbb43de80afe12f62dea39b1f488dc..fb2a0d416988fccd05352e4accebe723c4cd11c3 100644 (file)
@@ -82,7 +82,7 @@ QString Formatter::memToString(int64_t bytes)
         return tr("Unknown");
     }
 
-    if (!bytes)
+    if (bytes == 0)
     {
         return tr("None");
     }
@@ -99,7 +99,7 @@ QString Formatter::sizeToString(int64_t bytes)
         return tr("Unknown");
     }
 
-    if (!bytes)
+    if (bytes == 0)
     {
         return tr("None");
     }
@@ -163,9 +163,9 @@ QString Formatter::timeToString(int seconds)
     m = tr("%Ln minute(s)", nullptr, minutes);
     s = tr("%Ln second(s)", nullptr, seconds);
 
-    if (days)
+    if (days != 0)
     {
-        if (days >= 4 || !hours)
+        if (days >= 4 || hours == 0)
         {
             str = d;
         }
@@ -174,9 +174,9 @@ QString Formatter::timeToString(int seconds)
             str = tr("%1, %2").arg(d).arg(h);
         }
     }
-    else if (hours)
+    else if (hours != 0)
     {
-        if (hours >= 4 || !minutes)
+        if (hours >= 4 || minutes == 0)
         {
             str = h;
         }
@@ -185,9 +185,9 @@ QString Formatter::timeToString(int seconds)
             str = tr("%1, %2").arg(h).arg(m);
         }
     }
-    else if (minutes)
+    else if (minutes != 0)
     {
-        if (minutes >= 4 || !seconds)
+        if (minutes >= 4 || seconds == 0)
         {
             str = m;
         }
index 09bca55d2fa8acd63fe10d20d06db12d29acd778..a0573e913a1de0a09c5b2acd06347bf4880be1af 100644 (file)
@@ -81,7 +81,7 @@ QIcon MainWindow::getStockIcon(QString const& name, int fallback)
 {
     QIcon icon = QIcon::fromTheme(name);
 
-    if (icon.isNull() && (fallback >= 0))
+    if (icon.isNull() && fallback >= 0)
     {
         icon = style()->standardIcon(QStyle::StandardPixmap(fallback), 0, this);
     }
@@ -376,7 +376,7 @@ void MainWindow::onModelReset()
 void MainWindow::onSetPrefs()
 {
     QVariantList const p = sender()->property(PREF_VARIANTS_KEY).toList();
-    assert((p.size() % 2) == 0);
+    assert(p.size() % 2 == 0);
 
     for (int i = 0, n = p.size(); i < n; i += 2)
     {
@@ -720,15 +720,15 @@ void MainWindow::refreshTrayIcon()
     {
         tip = tr("Network Error");
     }
-    else if (!upCount && !downCount)
+    else if (upCount == 0 && downCount == 0)
     {
         tip = tr("Idle");
     }
-    else if (downCount)
+    else if (downCount != 0)
     {
         tip = Formatter::downloadSpeedToString(downSpeed) + QLatin1String("   ") + Formatter::uploadSpeedToString(upSpeed);
     }
-    else if (upCount)
+    else if (upCount != 0)
     {
         tip = Formatter::uploadSpeedToString(upSpeed);
     }
@@ -821,7 +821,7 @@ void MainWindow::refreshActionSensitivity()
         assert(model == modelIndex.model());
         Torrent const* tor(model->data(modelIndex, TorrentModel::TorrentRole).value<Torrent const*>());
 
-        if (tor)
+        if (tor != nullptr)
         {
             bool const isSelected(selectionModel->isSelected(modelIndex));
             bool const isPaused(tor->isPaused());
@@ -1058,7 +1058,7 @@ void MainWindow::toggleWindows(bool doShow)
 
 void MainWindow::trayActivated(QSystemTrayIcon::ActivationReason reason)
 {
-    if ((reason == QSystemTrayIcon::Trigger) || (reason == QSystemTrayIcon::DoubleClick))
+    if (reason == QSystemTrayIcon::Trigger || reason == QSystemTrayIcon::DoubleClick)
     {
         if (isMinimized())
         {
@@ -1342,46 +1342,46 @@ void MainWindow::removeTorrents(bool const deleteFiles)
 
     if (!deleteFiles)
     {
-        primary_text = (count == 1) ? tr("Remove torrent?") : tr("Remove %Ln torrent(s)?", nullptr, count);
+        primary_text = count == 1 ? tr("Remove torrent?") : tr("Remove %Ln torrent(s)?", nullptr, count);
     }
     else
     {
-        primary_text = (count == 1) ? tr("Delete this torrent's downloaded files?") :
+        primary_text = count == 1 ? tr("Delete this torrent's downloaded files?") :
             tr("Delete these %Ln torrent(s)' downloaded files?", nullptr, count);
     }
 
     if (!incomplete && !connected)
     {
-        secondary_text = (count == 1) ?
+        secondary_text = count == 1 ?
             tr("Once removed, continuing the transfer will require the torrent file or magnet link.") :
             tr("Once removed, continuing the transfers will require the torrent files or magnet links.");
     }
     else if (count == incomplete)
     {
-        secondary_text = (count == 1) ? tr("This torrent has not finished downloading.") :
+        secondary_text = count == 1 ? tr("This torrent has not finished downloading.") :
             tr("These torrents have not finished downloading.");
     }
     else if (count == connected)
     {
-        secondary_text = (count == 1) ? tr("This torrent is connected to peers.") :
+        secondary_text = count == 1 ? tr("This torrent is connected to peers.") :
             tr("These torrents are connected to peers.");
     }
     else
     {
-        if (connected)
+        if (connected != 0)
         {
-            secondary_text = (connected == 1) ? tr("One of these torrents is connected to peers.") :
+            secondary_text = connected == 1 ? tr("One of these torrents is connected to peers.") :
                 tr("Some of these torrents are connected to peers.");
         }
 
-        if (connected && incomplete)
+        if (connected != 0 && incomplete != 0)
         {
             secondary_text += QLatin1Char('\n');
         }
 
-        if (incomplete)
+        if (incomplete != 0)
         {
-            secondary_text += (incomplete == 1) ? tr("One of these torrents has not finished downloading.") :
+            secondary_text += incomplete == 1 ? tr("One of these torrents has not finished downloading.") :
                 tr("Some of these torrents have not finished downloading.");
         }
     }
@@ -1452,7 +1452,7 @@ void MainWindow::updateNetworkIcon()
     QString tip;
     QString const url = mySession.getRemoteUrl().host();
 
-    if (!myLastReadTime)
+    if (myLastReadTime == 0)
     {
         tip = tr("%1 has not responded yet").arg(url);
     }
@@ -1464,7 +1464,7 @@ void MainWindow::updateNetworkIcon()
     {
         tip = tr("%1 is responding").arg(url);
     }
-    else if (secondsSinceLastRead < (60 * 2))
+    else if (secondsSinceLastRead < 60 * 2)
     {
         tip = tr("%1 last responded %2 ago").arg(url).arg(Formatter::timeToString(secondsSinceLastRead));
     }
@@ -1486,19 +1486,19 @@ void MainWindow::dataReadProgress()
 {
     if (!myNetworkError)
     {
-        myLastReadTime = time(NULL);
+        myLastReadTime = time(nullptr);
     }
 }
 
 void MainWindow::dataSendProgress()
 {
-    myLastSendTime = time(NULL);
+    myLastSendTime = time(nullptr);
 }
 
 void MainWindow::onNetworkResponse(QNetworkReply::NetworkError code, QString const& message)
 {
     bool const hadError = myNetworkError;
-    bool const haveError = (code != QNetworkReply::NoError) && (code != QNetworkReply::UnknownContentError);
+    bool const haveError = code != QNetworkReply::NoError && code != QNetworkReply::UnknownContentError;
 
     myNetworkError = haveError;
     myErrorMessage = message;
index c673df71711136982f954f4f85cdf513ca6048cb..746c481af8304661ec6efb0f82668fca1561de75 100644 (file)
@@ -86,7 +86,7 @@ void MakeProgressDialog::onProgress()
 {
     // progress bar
     tr_metainfo_builder const& b = myBuilder;
-    double const denom = b.pieceCount ? b.pieceCount : 1;
+    double const denom = b.pieceCount != 0 ? b.pieceCount : 1;
     ui.progressBar->setValue(static_cast<int>((100.0 * b.pieceIndex) / denom));
 
     // progress label
index 1f6ac7e63b2571c31557d535d07a611661356fd2..aa5d66bf18fe8f60bec0f003c5b299c96ff77f27 100644 (file)
@@ -170,7 +170,7 @@ void OptionsDialog::reload()
     }
 
     int const err = tr_torrentParse(ctor, &myInfo);
-    myHaveInfo = !err;
+    myHaveInfo = err == 0;
     tr_ctorFree(ctor);
 
     ui.filesView->clear();
@@ -410,7 +410,7 @@ void OptionsDialog::onTimeout()
 
     tr_file const* file = &myInfo.files[myVerifyFileIndex];
 
-    if (!myVerifyFilePos && !myVerifyFile.isOpen())
+    if (myVerifyFilePos == 0 && !myVerifyFile.isOpen())
     {
         QFileInfo const fileInfo(myLocalDestination, QString::fromUtf8(file->name));
         myVerifyFile.setFileName(fileInfo.absoluteFilePath());
@@ -482,7 +482,7 @@ void OptionsDialog::onTimeout()
             have += f.have;
         }
 
-        if (!have) // everything failed
+        if (have == 0) // everything failed
         {
             // did the user accidentally specify the child directory instead of the parent?
             QStringList const tokens = QString::fromUtf8(file->name).split(QLatin1Char('/'));
index 1442c53687278c232e87411f4c9495df8b3a304c..273e42aca99dd915cd03bd27164c8e1de3b58665 100644 (file)
@@ -216,7 +216,7 @@ Prefs::Prefs(QString const& configDir) :
             break;
 
         default:
-            assert("unhandled type" && 0);
+            assert(false && "unhandled type");
             break;
         }
     }
@@ -284,7 +284,7 @@ Prefs::~Prefs()
             break;
 
         default:
-            assert("unhandled type" && 0);
+            assert(false && "unhandled type");
             break;
         }
     }
index ca0722339c4eb2fc64b3da86c15c123595e14e64..fe538d2a81402fbaa0db576aaaf8fbe4be4182ae 100644 (file)
@@ -123,7 +123,7 @@ int qtDayToTrDay(int day)
         return TR_SCHED_SUN;
 
     default:
-        assert(0 && "Invalid day of week");
+        assert(false && "Invalid day of week");
         return 0;
     }
 }
@@ -154,7 +154,7 @@ QString qtDayName(int day)
         return PrefsDialog::tr("Sunday");
 
     default:
-        assert(0 && "Invalid day of week");
+        assert(false && "Invalid day of week");
         return QString();
     }
 }
index 3fada6631c30b608dd56d418546aa12ec351c279..fbf5dfbc5d2e6a0140df95d5dc341681ec74bc6d 100644 (file)
@@ -241,7 +241,7 @@ void Session::updatePref(int key)
             }
 
         case Prefs::RPC_AUTH_REQUIRED:
-            if (mySession)
+            if (mySession != nullptr)
             {
                 tr_sessionSetRPCPasswordEnabled(mySession, myPrefs.getBool(key));
             }
@@ -249,7 +249,7 @@ void Session::updatePref(int key)
             break;
 
         case Prefs::RPC_ENABLED:
-            if (mySession)
+            if (mySession != nullptr)
             {
                 tr_sessionSetRPCEnabled(mySession, myPrefs.getBool(key));
             }
@@ -257,7 +257,7 @@ void Session::updatePref(int key)
             break;
 
         case Prefs::RPC_PASSWORD:
-            if (mySession)
+            if (mySession != nullptr)
             {
                 tr_sessionSetRPCPassword(mySession, myPrefs.getString(key).toUtf8().constData());
             }
@@ -265,7 +265,7 @@ void Session::updatePref(int key)
             break;
 
         case Prefs::RPC_PORT:
-            if (mySession)
+            if (mySession != nullptr)
             {
                 tr_sessionSetRPCPort(mySession, myPrefs.getInt(key));
             }
@@ -273,7 +273,7 @@ void Session::updatePref(int key)
             break;
 
         case Prefs::RPC_USERNAME:
-            if (mySession)
+            if (mySession != nullptr)
             {
                 tr_sessionSetRPCUsername(mySession, myPrefs.getString(key).toUtf8().constData());
             }
@@ -281,7 +281,7 @@ void Session::updatePref(int key)
             break;
 
         case Prefs::RPC_WHITELIST_ENABLED:
-            if (mySession)
+            if (mySession != nullptr)
             {
                 tr_sessionSetRPCWhitelistEnabled(mySession, myPrefs.getBool(key));
             }
@@ -289,7 +289,7 @@ void Session::updatePref(int key)
             break;
 
         case Prefs::RPC_WHITELIST:
-            if (mySession)
+            if (mySession != nullptr)
             {
                 tr_sessionSetRPCWhitelist(mySession, myPrefs.getString(key).toUtf8().constData());
             }
@@ -342,7 +342,7 @@ void Session::stop()
 {
     myRpc.stop();
 
-    if (mySession)
+    if (mySession != nullptr)
     {
         tr_sessionClose(mySession);
         mySession = nullptr;
@@ -799,7 +799,7 @@ void Session::updateInfo(tr_variant* d)
     {
         tr_variant const* b(tr_variantDictFind(d, myPrefs.getKey(i)));
 
-        if (!b)
+        if (b == nullptr)
         {
             continue;
         }
@@ -914,7 +914,7 @@ void Session::updateInfo(tr_variant* d)
         setBlocklistSize(i);
     }
 
-    if (tr_variantDictFindStr(d, TR_KEY_version, &str, nullptr) && (mySessionVersion != QString::fromUtf8(str)))
+    if (tr_variantDictFindStr(d, TR_KEY_version, &str, nullptr) && mySessionVersion != QString::fromUtf8(str))
     {
         mySessionVersion = QString::fromUtf8(str);
     }
@@ -1091,7 +1091,7 @@ void Session::launchWebInterface()
 {
     QUrl url;
 
-    if (!mySession) // remote session
+    if (mySession == nullptr) // remote session
     {
         url = myRpc.url();
         url.setPath(QLatin1String("/transmission/web/"));
index 11acc3b7c97b50f3b7c4e3e99ecdf01e7019f089..4788ea2711268c4c92d404424e18c945e165d6cd 100644 (file)
@@ -57,7 +57,7 @@ SqueezeLabel::SqueezeLabel(QWidget* parent) :
 
 void SqueezeLabel::paintEvent(QPaintEvent* paintEvent)
 {
-    if (hasFocus() && (textInteractionFlags() & (Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse)))
+    if (hasFocus() && (textInteractionFlags() & (Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse)) != 0)
     {
         return QLabel::paintEvent(paintEvent);
     }
index eba089594199f544c38dce4c0191fcf05bef8fd4..1040a31bf6d163f46396b5d36a4960dffe792fcd 100644 (file)
@@ -627,7 +627,7 @@ void Torrent::update(tr_variant* d)
 
         default:
             std::cerr << __FILE__ << ':' << __LINE__ << "unhandled type: " << tr_quark_get_string(key, nullptr) << std::endl;
-            assert(0 && "unhandled type");
+            assert(false && "unhandled type");
         }
     }
 
@@ -643,7 +643,7 @@ void Torrent::update(tr_variant* d)
         myFiles.clear();
         myFiles.reserve(tr_variantListSize(files));
 
-        while ((child = tr_variantListChild(files, i)))
+        while ((child = tr_variantListChild(files, i)) != nullptr)
         {
             TorrentFile file;
             size_t len;
@@ -706,7 +706,7 @@ void Torrent::update(tr_variant* d)
         QStringList list;
         tr_variant* child;
 
-        while ((child = tr_variantListChild(trackers, i++)))
+        while ((child = tr_variantListChild(trackers, i++)) != nullptr)
         {
             if (tr_variantDictFindStr(child, TR_KEY_announce, &str, &len))
             {
@@ -745,7 +745,7 @@ void Torrent::update(tr_variant* d)
         TrackerStatsList trackerStatsList;
         int childNum = 0;
 
-        while ((child = tr_variantListChild(trackerStats, childNum++)))
+        while ((child = tr_variantListChild(trackerStats, childNum++)) != nullptr)
         {
             bool b;
             int64_t i;
@@ -894,7 +894,7 @@ void Torrent::update(tr_variant* d)
         PeerList peerList;
         int childNum = 0;
 
-        while ((child = tr_variantListChild(peers, childNum++)))
+        while ((child = tr_variantListChild(peers, childNum++)) != nullptr)
         {
             double d;
             bool b;
@@ -990,7 +990,7 @@ void Torrent::update(tr_variant* d)
         emit torrentChanged(id());
     }
 
-    if (!was_seed && isSeed() && (old_verified_size > 0))
+    if (!was_seed && isSeed() && old_verified_size > 0)
     {
         emit torrentCompleted(id());
     }
index b792cd5293cd55fa2a2f81acd2718ed877fba3e9..07e4ca1168f8744fe80a3c6744d24527162c6d29 100644 (file)
@@ -90,7 +90,7 @@ bool TorrentFilter::lessThan(QModelIndex const& left, QModelIndex const& right)
     switch (myPrefs.get<SortMode>(Prefs::SORT_MODE).mode())
     {
     case SortMode::SORT_BY_QUEUE:
-        if (!val)
+        if (val == 0)
         {
             val = -compare(a->queuePosition(), b->queuePosition());
         }
@@ -98,7 +98,7 @@ bool TorrentFilter::lessThan(QModelIndex const& left, QModelIndex const& right)
         break;
 
     case SortMode::SORT_BY_SIZE:
-        if (!val)
+        if (val == 0)
         {
             val = compare(a->sizeWhenDone(), b->sizeWhenDone());
         }
@@ -110,7 +110,7 @@ bool TorrentFilter::lessThan(QModelIndex const& left, QModelIndex const& right)
         break;
 
     case SortMode::SORT_BY_ID:
-        if (!val)
+        if (val == 0)
         {
             val = compare(a->id(), b->id());
         }
@@ -118,12 +118,12 @@ bool TorrentFilter::lessThan(QModelIndex const& left, QModelIndex const& right)
         break;
 
     case SortMode::SORT_BY_ACTIVITY:
-        if (!val)
+        if (val == 0)
         {
             val = compare(a->downloadSpeed() + a->uploadSpeed(), b->downloadSpeed() + b->uploadSpeed());
         }
 
-        if (!val)
+        if (val == 0)
         {
             val = compare(a->peersWeAreUploadingTo() + a->webseedsWeAreDownloadingFrom(),
                 b->peersWeAreUploadingTo() + b->webseedsWeAreDownloadingFrom());
@@ -132,22 +132,22 @@ bool TorrentFilter::lessThan(QModelIndex const& left, QModelIndex const& right)
     // fall through
 
     case SortMode::SORT_BY_STATE:
-        if (!val)
+        if (val == 0)
         {
             val = -compare(a->isPaused(), b->isPaused());
         }
 
-        if (!val)
+        if (val == 0)
         {
             val = compare(a->getActivity(), b->getActivity());
         }
 
-        if (!val)
+        if (val == 0)
         {
             val = -compare(a->queuePosition(), b->queuePosition());
         }
 
-        if (!val)
+        if (val == 0)
         {
             val = compare(a->hasError(), b->hasError());
         }
@@ -155,17 +155,17 @@ bool TorrentFilter::lessThan(QModelIndex const& left, QModelIndex const& right)
     // fall through
 
     case SortMode::SORT_BY_PROGRESS:
-        if (!val)
+        if (val == 0)
         {
             val = compare(a->percentComplete(), b->percentComplete());
         }
 
-        if (!val)
+        if (val == 0)
         {
             val = a->compareSeedRatio(*b);
         }
 
-        if (!val)
+        if (val == 0)
         {
             val = -compare(a->queuePosition(), b->queuePosition());
         }
@@ -173,7 +173,7 @@ bool TorrentFilter::lessThan(QModelIndex const& left, QModelIndex const& right)
     // fall through
 
     case SortMode::SORT_BY_RATIO:
-        if (!val)
+        if (val == 0)
         {
             val = a->compareRatio(*b);
         }
@@ -181,7 +181,7 @@ bool TorrentFilter::lessThan(QModelIndex const& left, QModelIndex const& right)
         break;
 
     case SortMode::SORT_BY_ETA:
-        if (!val)
+        if (val == 0)
         {
             val = a->compareETA(*b);
         }
index a34419bd343320acb85398ef79eecd2f45d4c11c..4eda1ae3ade209b47cb17cc40cb7f405e3e9e880 100644 (file)
@@ -173,7 +173,7 @@ void TorrentModel::removeTorrents(tr_variant* torrents)
     int i = 0;
     tr_variant* child;
 
-    while ((child = tr_variantListChild(torrents, i++)))
+    while ((child = tr_variantListChild(torrents, i++)) != nullptr)
     {
         int64_t intVal;
 
@@ -201,7 +201,7 @@ void TorrentModel::updateTorrents(tr_variant* torrents, bool isCompleteList)
         size_t i(0);
         tr_variant* child;
 
-        while ((child = tr_variantListChild(torrents, i++)))
+        while ((child = tr_variantListChild(torrents, i++)) != nullptr)
         {
             int64_t id;
 
index 23997bdb9b5b1ddecbddedbfd8f3d23686ce56e8..4d3e7cff4f0d13a9e101a8b8ec673f48da8f3f24 100644 (file)
@@ -27,7 +27,7 @@ QVariant TrackerModel::data(QModelIndex const& index, int role) const
 
     int const row = index.row();
 
-    if ((0 <= row) && (row < myRows.size()))
+    if (0 <= row && row < myRows.size())
     {
         TrackerInfo const& trackerInfo = myRows.at(row);
 
@@ -148,7 +148,7 @@ int TrackerModel::find(int torrentId, QString const& url) const
     {
         TrackerInfo const& inf = myRows.at(i);
 
-        if ((inf.torrentId == torrentId) && (url == inf.st.announce))
+        if (inf.torrentId == torrentId && url == inf.st.announce)
         {
             return i;
         }
index 3ba7532170d588d3a97e73bdfcb61a19289f8b16..7559a5bbb3a9a33fb36f9ee5dabd9a980559e97b 100644 (file)
@@ -141,7 +141,7 @@ bool Utils::isValidUtf8(char const* s)
 {
     int n; // number of bytes in a UTF-8 sequence
 
-    for (char const* c = s; *c; c += n)
+    for (char const* c = s; *c != '\0'; c += n)
     {
         if ((*c & 0x80) == 0x00)
         {
index ba91accecde844c06ed478c0251f9d56ddee45b7..adef9e08a84cfcfdaade6b11fc7e505e4a76ad63 100644 (file)
@@ -46,7 +46,7 @@ int WatchDir::metainfoTest(QString const& filename) const
     tr_ctorSetMetainfoFromFile(ctor, filename.toUtf8().constData());
     int const err = tr_torrentParse(ctor, &inf);
 
-    if (err)
+    if (err != 0)
     {
         ret = ERROR;
     }
@@ -60,7 +60,7 @@ int WatchDir::metainfoTest(QString const& filename) const
     }
 
     // cleanup
-    if (!err)
+    if (err == 0)
     {
         tr_metainfoFree(&inf);
     }
index 14594b2592a3a6953b68a32dd3d73b7a9557d12f..675a2d29a0a65dcaec78cf40293ef50ccb3a71dc 100644 (file)
@@ -53,7 +53,7 @@ static int parseCommandLine(int argc, char const* const* argv)
     int c;
     char const* optarg;
 
-    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
     {
         switch (c)
         {
@@ -84,12 +84,12 @@ static int parseCommandLine(int argc, char const* const* argv)
             break;
 
         case 's':
-            if (optarg)
+            if (optarg != NULL)
             {
                 char* endptr = NULL;
                 piecesize_kib = strtoul(optarg, &endptr, 10);
 
-                if (endptr && *endptr == 'M')
+                if (endptr != NULL && *endptr == 'M')
                 {
                     piecesize_kib *= KiB;
                 }
@@ -136,7 +136,7 @@ int tr_main(int argc, char* argv[])
     tr_formatter_size_init(DISK_K, DISK_K_STR, DISK_M_STR, DISK_G_STR, DISK_T_STR);
     tr_formatter_speed_init(SPEED_K, SPEED_K_STR, SPEED_M_STR, SPEED_G_STR, SPEED_T_STR);
 
-    if (parseCommandLine(argc, (char const* const*)argv))
+    if (parseCommandLine(argc, (char const* const*)argv) != 0)
     {
         return EXIT_FAILURE;
     }
@@ -147,7 +147,7 @@ int tr_main(int argc, char* argv[])
         return EXIT_SUCCESS;
     }
 
-    if (!infile)
+    if (infile == NULL)
     {
         fprintf(stderr, "ERROR: No input file or directory specified.\n");
         tr_getopt_usage(MY_NAME, getUsage(), options);
@@ -174,7 +174,7 @@ int tr_main(int argc, char* argv[])
         tr_free(base);
     }
 
-    if (!trackerCount)
+    if (trackerCount == 0)
     {
         if (isPrivate)
         {
index f2ca1949d2f1c94c842d177629f59954444760f5..8f3a25de3418cf23cca628fc7d2f6562ffe324e0 100644 (file)
@@ -47,7 +47,7 @@ static int parseCommandLine(int argc, char const* const* argv)
     int c;
     char const* optarg;
 
-    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
     {
         switch (c)
         {
@@ -105,12 +105,12 @@ static bool removeURL(tr_variant* metainfo, char const* url)
         tr_variant* tier;
         int tierIndex = 0;
 
-        while ((tier = tr_variantListChild(announce_list, tierIndex)))
+        while ((tier = tr_variantListChild(announce_list, tierIndex)) != NULL)
         {
             tr_variant* node;
             int nodeIndex = 0;
 
-            while ((node = tr_variantListChild(tier, nodeIndex)))
+            while ((node = tr_variantListChild(tier, nodeIndex)) != NULL)
             {
                 if (tr_variantGetStr(node, &str, NULL) && strcmp(str, url) == 0)
                 {
@@ -149,9 +149,9 @@ static bool removeURL(tr_variant* metainfo, char const* url)
         tr_variant* tier;
         tr_variant* node;
 
-        if ((tier = tr_variantListChild(announce_list, 0)))
+        if ((tier = tr_variantListChild(announce_list, 0)) != NULL)
         {
-            if ((node = tr_variantListChild(tier, 0)))
+            if ((node = tr_variantListChild(tier, 0)) != NULL)
             {
                 if (tr_variantGetStr(node, &str, NULL))
                 {
@@ -172,7 +172,7 @@ static char* replaceSubstr(char const* str, char const* in, char const* out)
     size_t const inlen = strlen(in);
     size_t const outlen = strlen(out);
 
-    while ((walk = strstr(str, in)))
+    while ((walk = strstr(str, in)) != NULL)
     {
         evbuffer_add(buf, str, walk - str);
         evbuffer_add(buf, out, outlen);
@@ -190,7 +190,7 @@ static bool replaceURL(tr_variant* metainfo, char const* in, char const* out)
     tr_variant* announce_list;
     bool changed = false;
 
-    if (tr_variantDictFindStr(metainfo, TR_KEY_announce, &str, NULL) && strstr(str, in))
+    if (tr_variantDictFindStr(metainfo, TR_KEY_announce, &str, NULL) && strstr(str, in) != NULL)
     {
         char* newstr = replaceSubstr(str, in, out);
         printf("\tReplaced in \"announce\": \"%s\" --> \"%s\"\n", str, newstr);
@@ -204,14 +204,14 @@ static bool replaceURL(tr_variant* metainfo, char const* in, char const* out)
         tr_variant* tier;
         int tierCount = 0;
 
-        while ((tier = tr_variantListChild(announce_list, tierCount++)))
+        while ((tier = tr_variantListChild(announce_list, tierCount++)) != NULL)
         {
             tr_variant* node;
             int nodeCount = 0;
 
-            while ((node = tr_variantListChild(tier, nodeCount++)))
+            while ((node = tr_variantListChild(tier, nodeCount++)) != NULL)
             {
-                if (tr_variantGetStr(node, &str, NULL) && strstr(str, in))
+                if (tr_variantGetStr(node, &str, NULL) && strstr(str, in) != NULL)
                 {
                     char* newstr = replaceSubstr(str, in, out);
                     printf("\tReplaced in \"announce-list\" tier %d: \"%s\" --> \"%s\"\n", tierCount, str, newstr);
@@ -232,13 +232,13 @@ static bool announce_list_has_url(tr_variant* announce_list, char const* url)
     tr_variant* tier;
     int tierCount = 0;
 
-    while ((tier = tr_variantListChild(announce_list, tierCount++)))
+    while ((tier = tr_variantListChild(announce_list, tierCount++)) != NULL)
     {
         tr_variant* node;
         char const* str;
         int nodeCount = 0;
 
-        while ((node = tr_variantListChild(tier, nodeCount++)))
+        while ((node = tr_variantListChild(tier, nodeCount++)) != NULL)
         {
             if (tr_variantGetStr(node, &str, NULL) && strcmp(str, url) == 0)
             {
@@ -303,7 +303,7 @@ int tr_main(int argc, char* argv[])
 
     tr_logSetLevel(TR_LOG_ERROR);
 
-    if (parseCommandLine(argc, (char const* const*)argv))
+    if (parseCommandLine(argc, (char const* const*)argv) != 0)
     {
         return EXIT_FAILURE;
     }
@@ -322,7 +322,7 @@ int tr_main(int argc, char* argv[])
         return EXIT_FAILURE;
     }
 
-    if (!add && !deleteme && !replace[0])
+    if (add == NULL && deleteme == NULL && replace[0] == 0)
     {
         fprintf(stderr, "ERROR: Must specify -a, -d or -r\n");
         tr_getopt_usage(MY_NAME, getUsage(), options);
@@ -356,7 +356,7 @@ int tr_main(int argc, char* argv[])
             changed = addURL(&top, add);
         }
 
-        if (replace[0] && replace[1])
+        if (replace[0] != NULL && replace[1] != NULL)
         {
             changed |= replaceURL(&top, replace[0], replace[1]);
         }
index 33d0375cd81c4c27501c7ed016577f51cb8a73bc..2611c5f1aed0063d4268136c339a30f90f29ebe5 100644 (file)
@@ -51,7 +51,7 @@ static int parseCommandLine(int argc, char const* const* argv)
     int c;
     char const* optarg;
 
-    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+    while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
     {
         switch (c)
         {
@@ -109,7 +109,7 @@ static void showInfo(tr_info const* inf)
     printf("  Hash: %s\n", inf->hashString);
     printf("  Created by: %s\n", inf->creator ? inf->creator : "Unknown");
 
-    if (!inf->dateCreated)
+    if (inf->dateCreated == 0)
     {
         printf("  Created on: Unknown\n");
     }
@@ -119,7 +119,7 @@ static void showInfo(tr_info const* inf)
         printf("  Created on: %s", asctime(&tm));
     }
 
-    if (inf->comment && *inf->comment)
+    if (inf->comment != NULL && *inf->comment != '\0')
     {
         printf("  Comment: %s\n", inf->comment);
     }
@@ -221,7 +221,7 @@ static void doScrape(tr_info const* inf)
 
         tr_http_escape_sha1(escaped, inf->hash);
 
-        url = tr_strdup_printf("%s%cinfo_hash=%s", scrape, strchr(scrape, '?') ? '&' : '?', escaped);
+        url = tr_strdup_printf("%s%cinfo_hash=%s", scrape, strchr(scrape, '?') != NULL ? '&' : '?', escaped);
 
         printf("%s ... ", url);
         fflush(stdout);
@@ -231,7 +231,7 @@ static void doScrape(tr_info const* inf)
         curl_easy_setopt(curl, CURLOPT_URL, url);
         curl_easy_setopt(curl, CURLOPT_TIMEOUT, TIMEOUT_SECS);
 
-        if ((res = curl_easy_perform(curl)))
+        if ((res = curl_easy_perform(curl)) != CURLE_OK)
         {
             printf("error: %s\n", curl_easy_strerror(res));
         }
@@ -251,7 +251,7 @@ static void doScrape(tr_info const* inf)
                 bool matched = false;
                 char const* begin = (char const*)evbuffer_pullup(buf, -1);
 
-                if (!tr_variantFromBenc(&top, begin, evbuffer_get_length(buf)))
+                if (tr_variantFromBenc(&top, begin, evbuffer_get_length(buf)) == 0)
                 {
                     if (tr_variantDictFindDict(&top, TR_KEY_files, &files))
                     {
@@ -300,7 +300,7 @@ int tr_main(int argc, char* argv[])
     tr_formatter_size_init(DISK_K, DISK_K_STR, DISK_M_STR, DISK_G_STR, DISK_T_STR);
     tr_formatter_speed_init(SPEED_K, SPEED_K_STR, SPEED_M_STR, SPEED_G_STR, SPEED_T_STR);
 
-    if (parseCommandLine(argc, (char const* const*)argv))
+    if (parseCommandLine(argc, (char const* const*)argv) != 0)
     {
         return EXIT_FAILURE;
     }
@@ -312,7 +312,7 @@ int tr_main(int argc, char* argv[])
     }
 
     /* make sure the user specified a filename */
-    if (!filename)
+    if (filename == NULL)
     {
         fprintf(stderr, "ERROR: No .torrent file specified.\n");
         tr_getopt_usage(MY_NAME, getUsage(), options);
@@ -326,7 +326,7 @@ int tr_main(int argc, char* argv[])
     err = tr_torrentParse(ctor, &inf);
     tr_ctorFree(ctor);
 
-    if (err)
+    if (err != TR_PARSE_OK)
     {
         fprintf(stderr, "Error parsing .torrent file \"%s\"\n", filename);
         return EXIT_FAILURE;