C++ modernize: Replace MIN/MAX with type safe std::min/std::max (#1806)

* C++ modernize: Replace MIN/MAX with type safe std::min/std::max

* Template std::min/max invocations now explicitly use largest integer type

* torrent.cc did not have <algorithm> included

* MIN/MAX Changes for subprocess-win32.cc

* Using type{} style cast instead of template parameter in std::min/max

* 32-bit type cast errors with uint64_t versus size_t

* 32-bit type cast errors inout.cc and file.cc

* Missing include in windows code; Type cast error fixed

* Missing macro in win32 daemon; Replaced MIN in commented code with std::min

* Update libtransmission/tr-getopt.cc

Co-authored-by: Mike Gelfand <mikedld@users.noreply.github.com>

* Update libtransmission/file-posix.cc

Co-authored-by: Mike Gelfand <mikedld@users.noreply.github.com>

* Update tests/libtransmission/copy-test.cc

Co-authored-by: Mike Gelfand <mikedld@users.noreply.github.com>

* Update libtransmission/peer-mgr.cc

Co-authored-by: Mike Gelfand <mikedld@users.noreply.github.com>

* Strlen returns size_t, remove cast

Co-authored-by: Charles Kerr <charles@charleskerr.com>
Co-authored-by: Mike Gelfand <mikedld@users.noreply.github.com>
This commit is contained in:
Dmytro Lytovchenko 2021-09-19 22:41:35 +02:00 committed by GitHub
parent 6aba12888a
commit 312d18281d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 198 additions and 189 deletions

View File

@ -108,6 +108,8 @@ static void update_service_status(
}
}
#define TR_MAX(a, b) (((a) > (b)) ? (a) : (b))
static unsigned int __stdcall service_stop_thread_main(void* param)
{
callbacks->on_stop(callback_arg);
@ -118,7 +120,7 @@ static unsigned int __stdcall service_stop_thread_main(void* param)
for (DWORD checkpoint = 2; WaitForSingleObject(service_thread, sleep_time) == WAIT_TIMEOUT; ++checkpoint)
{
wait_time = wait_time >= sleep_time ? wait_time - sleep_time : 0;
update_service_status(SERVICE_STOP_PENDING, NO_ERROR, 0, checkpoint, MAX(wait_time, sleep_time * 2));
update_service_status(SERVICE_STOP_PENDING, NO_ERROR, 0, checkpoint, TR_MAX(wait_time, sleep_time * 2));
}
return 0;

View File

@ -6,11 +6,11 @@
*
*/
#include <algorithm> // std::partial_sort
#include <limits.h> /* INT_MAX */
#include <stdio.h>
#include <stdlib.h> /* qsort() */
#include <string.h> /* strcmp(), memcpy(), strncmp() */
#include <algorithm>
#include <climits> /* INT_MAX */
#include <cstdio>
#include <cstdlib> /* qsort() */
#include <cstring> /* strcmp(), memcpy(), strncmp() */
#include <vector>
#include <event2/buffer.h>
@ -797,7 +797,7 @@ time_t tr_announcerNextManualAnnounce(tr_torrent const* tor)
{
if (tt->tiers[i].isRunning)
{
ret = MIN(ret, tt->tiers[i].manualAnnounceAllowedAt);
ret = std::min(ret, tt->tiers[i].manualAnnounceAllowedAt);
}
}
@ -834,7 +834,7 @@ static void tier_update_announce_priority(tr_tier* tier)
for (int i = 0; i < tier->announce_event_count; ++i)
{
priority = MAX(priority, (int)tier->announce_events[i]);
priority = std::max(priority, int{ tier->announce_events[i] });
}
tier->announce_event_priority = priority;
@ -1475,7 +1475,7 @@ static void on_scrape_done(tr_scrape_response const* response, void* vsession)
else
{
tier->lastScrapeSucceeded = true;
tier->scrapeIntervalSec = MAX(DEFAULT_SCRAPE_INTERVAL_SEC, response->min_request_interval);
tier->scrapeIntervalSec = std::max(int{ DEFAULT_SCRAPE_INTERVAL_SEC }, response->min_request_interval);
tier->scrapeAt = get_next_scrape_time(session, tier, tier->scrapeIntervalSec);
tr_logAddTorDbg(tier->tor, "Scrape successful. Rescraping in %d seconds.", tier->scrapeIntervalSec);
@ -1524,7 +1524,7 @@ static void on_scrape_done(tr_scrape_response const* response, void* vsession)
error out, lower the value once for that batch, not N times. */
if (*multiscrape_max >= response->row_count)
{
int const n = MAX(1, *multiscrape_max - TR_MULTISCRAPE_STEP);
int const n = std::max(1, int{ *multiscrape_max - TR_MULTISCRAPE_STEP });
if (*multiscrape_max != n)
{
char* scheme = nullptr;

View File

@ -6,7 +6,8 @@
*
*/
#include <string.h> /* memset() */
#include <algorithm>
#include <cstring> /* memset() */
#include "transmission.h"
#include "bandwidth.h"
@ -159,7 +160,7 @@ static void allocateBandwidth(
TR_ASSERT(tr_isBandwidth(b));
TR_ASSERT(tr_isDirection(dir));
tr_priority_t const priority = MAX(parent_priority, b->priority);
tr_priority_t const priority = std::max(parent_priority, b->priority);
/* set the available bandwidth */
if (b->band[dir].isLimited)
@ -307,7 +308,7 @@ static unsigned int bandwidthClamp(tr_bandwidth const* b, uint64_t now, tr_direc
{
if (b->band[dir].isLimited)
{
byteCount = MIN(byteCount, b->band[dir].bytesLeft);
byteCount = std::min(byteCount, b->band[dir].bytesLeft);
/* if we're getting close to exceeding the speed limit,
* clamp down harder on the bytes available */
@ -380,7 +381,7 @@ void tr_bandwidthUsed(tr_bandwidth* b, tr_direction dir, size_t byteCount, bool
if (band->isLimited && isPieceData)
{
band->bytesLeft -= MIN(band->bytesLeft, byteCount);
band->bytesLeft -= std::min(size_t{ band->bytesLeft }, byteCount);
}
#ifdef DEBUG_DIRECTION

View File

@ -6,7 +6,8 @@
*
*/
#include <string.h> /* memset */
#include <algorithm>
#include <cstring> /* memset */
#include "transmission.h"
#include "bitfield.h"
@ -85,7 +86,7 @@ static size_t countRange(tr_bitfield const* b, size_t begin, size_t end)
else
{
uint8_t val;
size_t const walk_end = MIN(b->alloc_count, last_byte);
size_t const walk_end = std::min(b->alloc_count, last_byte);
/* first byte */
size_t const first_shift = begin - (first_byte * 8);
@ -220,7 +221,7 @@ static void tr_bitfieldEnsureBitsAlloced(tr_bitfield* b, size_t n)
if (has_all)
{
bytes_needed = get_bytes_needed(MAX(n, b->true_count));
bytes_needed = get_bytes_needed(std::max(n, b->true_count));
}
else
{
@ -353,7 +354,7 @@ void tr_bitfieldSetRaw(tr_bitfield* b, void const* bits, size_t byte_count, bool
if (bounded)
{
byte_count = MIN(byte_count, get_bytes_needed(b->bit_count));
byte_count = std::min(byte_count, get_bytes_needed(b->bit_count));
}
b->bits = static_cast<uint8_t*>(tr_memdup(bits, byte_count));

View File

@ -6,9 +6,10 @@
*
*/
#include <errno.h>
#include <inttypes.h>
#include <string.h>
#include <algorithm>
#include <cerrno>
#include <cinttypes>
#include <cstring>
#include "transmission.h"
#include "error.h"
@ -90,7 +91,7 @@ static bool preallocate_file_full(tr_sys_file_t fd, uint64_t length, tr_error**
/* fallback: the old-fashioned way */
while (success && length > 0)
{
uint64_t const thisPass = MIN(length, sizeof(buf));
uint64_t const thisPass = std::min(length, uint64_t{ sizeof(buf) });
uint64_t bytes_written;
success = tr_sys_file_write(fd, buf, thisPass, &bytes_written, &my_error);
length -= bytes_written;

View File

@ -9,19 +9,20 @@
#undef _GNU_SOURCE
#define _GNU_SOURCE
#include <algorithm>
#include <cerrno>
#include <climits> /* PATH_MAX */
#include <cstdint> /* SIZE_MAX */
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h> /* O_LARGEFILE, posix_fadvise(), [posix_]fallocate(), fcntl() */
#include <libgen.h> /* basename(), dirname() */
#include <limits.h> /* PATH_MAX */
#include <stdint.h> /* SIZE_MAX */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/file.h> /* flock() */
#include <sys/mman.h> /* mmap(), munmap() */
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h> /* lseek(), write(), ftruncate(), pread(), pwrite(), pathconf(), etc */
#include <vector>
@ -487,7 +488,7 @@ bool tr_sys_path_copy(char const* src_path, char const* dst_path, tr_error** err
while (file_size > 0)
{
size_t const chunk_size = MIN(file_size, SSIZE_MAX);
size_t const chunk_size = std::min(file_size, uint64_t{ SSIZE_MAX });
ssize_t const copied =
#ifdef USE_COPY_FILE_RANGE
copy_file_range(in, nullptr, out, nullptr, chunk_size, 0);
@ -518,7 +519,7 @@ bool tr_sys_path_copy(char const* src_path, char const* dst_path, tr_error** err
while (file_size > 0)
{
uint64_t const chunk_size = MIN(file_size, buflen);
uint64_t const chunk_size = std::min(file_size, uint64_t{ buflen });
uint64_t bytes_read;
uint64_t bytes_written;

View File

@ -6,7 +6,8 @@
*
*/
#include <string.h> /* strlen() */
#include <algorithm>
#include <cstring> /* strlen() */
#include "transmission.h"
#include "error.h"
@ -26,7 +27,7 @@ bool tr_sys_file_read_line(tr_sys_file_t handle, char* buffer, size_t buffer_siz
while (buffer_size > 0)
{
size_t const bytes_needed = MIN(buffer_size, 1024u);
size_t const bytes_needed = std::min(buffer_size, size_t{ 1024 });
ret = tr_sys_file_read(handle, buffer + offset, bytes_needed, &bytes_read, error);

View File

@ -6,9 +6,10 @@
*
*/
#include <errno.h>
#include <stdlib.h> /* bsearch() */
#include <string.h> /* memcmp() */
#include <algorithm>
#include <cerrno>
#include <cstdlib> /* bsearch() */
#include <cstring> /* memcmp() */
#include "transmission.h"
#include "cache.h" /* tr_cacheReadBlock() */
@ -217,7 +218,7 @@ static int readOrWritePiece(
while (buflen != 0 && err == 0)
{
tr_file const* file = &info->files[fileIndex];
uint64_t const bytesThisPass = MIN(buflen, file->length - fileOffset);
uint64_t const bytesThisPass = std::min(uint64_t{ buflen }, uint64_t{ file->length - fileOffset });
err = readOrWriteBytes(tor->session, tor, ioMode, fileIndex, fileOffset, buf, bytesThisPass);
buf += bytesThisPass;
@ -278,7 +279,7 @@ static bool recalculateHash(tr_torrent* tor, tr_piece_index_t pieceIndex, uint8_
while (bytesLeft != 0)
{
size_t const len = MIN(bytesLeft, buflen);
size_t const len = std::min(bytesLeft, buflen);
success = tr_cacheReadBlock(tor->session->cache, tor, pieceIndex, offset, len, static_cast<uint8_t*>(buffer)) == 0;
if (!success)

View File

@ -6,9 +6,10 @@
*
*/
#include <errno.h>
#include <stdlib.h> /* qsort */
#include <string.h> /* strcmp, strlen */
#include <algorithm>
#include <cerrno>
#include <cstdlib> /* qsort */
#include <cstring> /* strcmp, strlen */
#include <event2/util.h> /* evutil_ascii_strcasecmp() */
@ -283,12 +284,12 @@ static uint8_t* getHashInfo(tr_metainfo_builder* b)
TR_ASSERT(b->pieceIndex < b->pieceCount);
uint8_t* bufptr = buf;
uint32_t const thisPieceSize = (uint32_t)MIN(b->pieceSize, totalRemain);
uint32_t const thisPieceSize = std::min(uint64_t{ b->pieceSize }, totalRemain);
uint64_t leftInPiece = thisPieceSize;
while (leftInPiece != 0)
{
uint64_t const n_this_pass = MIN(b->files[fileIndex].size - off, leftInPiece);
uint64_t const n_this_pass = std::min(b->files[fileIndex].size - off, leftInPiece);
uint64_t n_read = 0;
(void)tr_sys_file_read(fd, bufptr, n_this_pass, &n_read, nullptr);
bufptr += n_read;

View File

@ -6,14 +6,15 @@
*
*/
#include <errno.h>
#include <string.h>
#include <algorithm>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <stdint.h>
#include <libutp/utp.h>
#include "transmission.h"
@ -158,7 +159,7 @@ static void didWriteWrapper(tr_peerIo* io, unsigned int bytes_transferred)
{
struct tr_datatype* next = io->outbuf_datatypes;
unsigned int const payload = MIN(next->length, bytes_transferred);
unsigned int const payload = std::min(uint64_t{ next->length }, uint64_t{ bytes_transferred });
/* For uTP sockets, the overhead is computed in utp_on_overhead. */
unsigned int const overhead = io->socket.type == TR_PEER_SOCKET_TYPE_TCP ? guessPacketOverhead(payload) : 0;
uint64_t const now = tr_time_msec();
@ -1096,8 +1097,8 @@ static unsigned int getDesiredOutputBufferSize(tr_peerIo const* io, uint64_t now
unsigned int const currentSpeed_Bps = tr_bandwidthGetPieceSpeed_Bps(&io->bandwidth, now, TR_UP);
unsigned int const period = 15U; /* arbitrary */
/* the 3 is arbitrary; the .5 is to leave room for messages */
static unsigned int const ceiling = (unsigned int)(MAX_BLOCK_SIZE * 3.5);
return MAX(ceiling, currentSpeed_Bps * period);
static auto const ceiling = (unsigned int)(MAX_BLOCK_SIZE * 3.5);
return std::max(ceiling, currentSpeed_Bps * period);
}
size_t tr_peerIoGetWriteBufferSpace(tr_peerIo const* io, uint64_t now)
@ -1301,7 +1302,7 @@ void tr_peerIoDrain(tr_peerIo* io, struct evbuffer* inbuf, size_t byteCount)
while (byteCount > 0)
{
size_t const thisPass = MIN(byteCount, buflen);
size_t const thisPass = std::min(byteCount, buflen);
tr_peerIoReadBytes(io, inbuf, buf, thisPass);
byteCount -= thisPass;
}

View File

@ -6,15 +6,15 @@
*
*/
#include <algorithm> // std::partial_sort
#include <errno.h> /* error codes ERANGE, ... */
#include <limits.h> /* INT_MAX */
#include <string.h> /* memcpy, memcmp, strstr */
#include <stdlib.h> /* qsort */
#include <algorithm>
#include <cerrno> /* error codes ERANGE, ... */
#include <climits> /* INT_MAX */
#include <cstdlib> /* qsort */
#include <cstring> /* memcpy, memcmp, strstr */
#include <event2/event.h>
#include <stdint.h>
#include <cstdint>
#include <libutp/utp.h>
#include "transmission.h"
@ -833,7 +833,7 @@ static void updateEndgame(tr_swarm* s)
numDownloading += countActiveWebseeds(s);
/* average number of pending requests per downloading peer */
s->endgame = s->requestCount / MAX(numDownloading, 1);
s->endgame = s->requestCount / std::max(numDownloading, 1);
}
}
@ -1504,7 +1504,7 @@ static void refillUpkeep(evutil_socket_t fd, short what, void* vmgr)
while ((tor = tr_torrentNext(mgr->session, tor)) != nullptr)
{
cancel_buflen = MAX(cancel_buflen, tor->swarm->requestCount);
cancel_buflen = std::max(cancel_buflen, tor->swarm->requestCount);
}
if (cancel_buflen > 0)
@ -2432,7 +2432,7 @@ int tr_peerMgrGetPeers(tr_torrent const* tor, tr_pex** setme_pex, uint8_t af, ui
*** add the first N of them into our return list
**/
n = MIN(atomCount, maxCount);
n = std::min(atomCount, maxCount);
pex = walk = tr_new0(tr_pex, n);
for (int i = 0; i < atomCount && count < n; ++i)
@ -2754,7 +2754,7 @@ uint64_t tr_peerMgrGetDesiredAvailable(tr_torrent const* tor)
uint64_t desiredAvailable = 0;
for (size_t i = 0, n = MIN(tor->info.pieceCount, s->pieceReplicationSize); i < n; ++i)
for (size_t i = 0, n = std::min(size_t{ tor->info.pieceCount }, s->pieceReplicationSize); i < n; ++i)
{
if (!tor->info.pieces[i].dnd && s->pieceReplication[i] > 0)
{
@ -3041,7 +3041,7 @@ static void rechokeDownloads(tr_swarm* s)
/* cancelRate: of the block requests we've recently made, the percentage we cancelled.
* higher values indicate more congestion. */
double const cancelRate = cancels / (double)(cancels + blocks);
double const mult = 1 - MIN(cancelRate, 0.5);
double const mult = 1 - std::min(cancelRate, 0.5);
maxPeers = s->interestedCount * mult;
tordbg(
s,
@ -3057,7 +3057,7 @@ static void rechokeDownloads(tr_swarm* s)
{
int const maxIncrease = 15;
time_t const maxHistory = 2 * CANCEL_HISTORY_SEC;
double const mult = MIN(timeSinceCancel, maxHistory) / (double)maxHistory;
double const mult = std::min(timeSinceCancel, maxHistory) / (double)maxHistory;
int const inc = maxIncrease * mult;
maxPeers = s->maxPeers + inc;
tordbg(
@ -3153,7 +3153,7 @@ static void rechokeDownloads(tr_swarm* s)
/* now that we know which & how many peers to be interested in... update the peer interest */
s->interestedCount = MIN(maxPeers, rechoke_count);
s->interestedCount = std::min(maxPeers, rechoke_count);
for (int i = 0; i < rechoke_count; ++i)
{
@ -3437,7 +3437,7 @@ static bool shouldPeerBeClosed(tr_swarm const* s, tr_peer const* peer, int peerC
int const lo = MIN_UPLOAD_IDLE_SECS;
int const hi = MAX_UPLOAD_IDLE_SECS;
int const limit = hi - (hi - lo) * strictness;
int const idleTime = now - MAX(atom->time, atom->piece_data_time);
int const idleTime = now - std::max(atom->time, atom->piece_data_time);
if (idleTime > limit)
{
@ -3975,7 +3975,7 @@ static int compareAtomPtrsByShelfDate(void const* va, void const* vb)
static int getMaxAtomCount(tr_torrent const* tor)
{
return MIN(50, tor->maxConnectedPeers * 3);
return std::min(50, tor->maxConnectedPeers * 3);
}
static void atomPulse(evutil_socket_t fd, short what, void* vmgr)
@ -4182,7 +4182,7 @@ static uint64_t getPeerCandidateScore(tr_torrent const* tor, struct peer_atom co
static bool checkBestScoresComeFirst(struct peer_candidate const* candidates, int n, int k)
{
uint64_t worstFirstScore = 0;
int const x = MIN(n, k) - 1;
int const x = std::min(n, k) - 1;
for (int i = 0; i < x; i++)
{

View File

@ -6,10 +6,11 @@
*
*/
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <cerrno>
#include <cstdarg>
#include <cstdlib>
#include <cstring>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
@ -636,7 +637,7 @@ static void updateFastSet(tr_peerMsgs* msgs)
{
struct tr_address const* addr = tr_peerIoGetAddress(msgs->io, nullptr);
tr_info const* inf = &msgs->torrent->info;
size_t const numwant = MIN(MAX_FAST_SET_SIZE, inf->pieceCount);
size_t const numwant = std::min(MAX_FAST_SET_SIZE, inf->pieceCount);
/* build the fast set */
msgs->fastsetSize = tr_generateAllowedSet(msgs->fastset, numwant, inf->pieceCount, inf->hash, addr);
@ -1170,7 +1171,7 @@ static void parseUtPex(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer* inbu
}
pex = tr_peerMgrCompactToPex(added, added_len, added_f, added_f_len, &n);
n = MIN(n, MAX_PEX_PEER_COUNT);
n = std::min(n, size_t{ MAX_PEX_PEER_COUNT });
tr_peerMgrAddPex(tor, TR_PEER_FROM_PEX, pex, n);
tr_free(pex);
@ -1190,7 +1191,7 @@ static void parseUtPex(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer* inbu
}
pex = tr_peerMgrCompact6ToPex(added, added_len, added_f, added_f_len, &n);
n = MIN(n, MAX_PEX_PEER_COUNT);
n = std::min(n, size_t{ MAX_PEX_PEER_COUNT });
tr_peerMgrAddPex(tor, TR_PEER_FROM_PEX, pex, n);
tr_free(pex);
@ -1452,7 +1453,7 @@ static ReadState readBtPiece(tr_peerMsgs* msgs, struct evbuffer* inbuf, size_t i
/* read in another chunk of data */
nLeft = req->length - evbuffer_get_length(block_buffer);
n = MIN(nLeft, inlen);
n = std::min(nLeft, inlen);
tr_peerIoReadBytesToBuf(msgs->io, inbuf, block_buffer, n);
@ -1892,20 +1893,20 @@ static void updateDesiredRequestCount(tr_peerMsgs* msgs)
if (tr_torrentUsesSpeedLimit(torrent, TR_PEER_TO_CLIENT))
{
rate_Bps = MIN(rate_Bps, tr_torrentGetSpeedLimit_Bps(torrent, TR_PEER_TO_CLIENT));
rate_Bps = std::min(rate_Bps, tr_torrentGetSpeedLimit_Bps(torrent, TR_PEER_TO_CLIENT));
}
/* honor the session limits, if enabled */
if (tr_torrentUsesSessionLimits(torrent) &&
tr_sessionGetActiveSpeedLimit_Bps(torrent->session, TR_PEER_TO_CLIENT, &irate_Bps))
{
rate_Bps = MIN(rate_Bps, irate_Bps);
rate_Bps = std::min(rate_Bps, irate_Bps);
}
/* use this desired rate to figure out how
* many requests we should send to this peer */
estimatedBlocksInPeriod = (rate_Bps * seconds) / torrent->blockSize;
msgs->desiredRequestCount = MAX(floor, estimatedBlocksInPeriod);
msgs->desiredRequestCount = std::max(floor, estimatedBlocksInPeriod);
/* honor the peer's maximum request count, if specified */
if ((msgs->reqq > 0) && (msgs->desiredRequestCount > msgs->reqq))

View File

@ -6,8 +6,8 @@
*
*/
#include <stdio.h>
#include <algorithm>
#include <cstdio>
#include <sys/types.h>
#include <event2/event.h>
@ -262,5 +262,5 @@ bool tr_sharedTraversalIsEnabled(tr_shared const* s)
int tr_sharedTraversalStatus(tr_shared const* s)
{
return MAX(s->natpmpStatus, s->upnpStatus);
return std::max(s->natpmpStatus, s->upnpStatus);
}

View File

@ -6,7 +6,8 @@
*
*/
#include <string.h> /* memmove */
#include <algorithm>
#include <cstring> /* memmove */
#include "ptrarray.h"
#include "tr-assert.h"
@ -50,7 +51,7 @@ int tr_ptrArrayInsert(tr_ptrArray* t, void* ptr, int pos)
{
if (t->n_items >= t->n_alloc)
{
t->n_alloc = MAX(FLOOR, t->n_alloc * 2);
t->n_alloc = std::max(FLOOR, t->n_alloc * 2);
t->items = tr_renew(void*, t->items, t->n_alloc);
}

View File

@ -6,8 +6,9 @@
*
*/
#include <stdlib.h> /* bsearch() */
#include <string.h> /* memcmp() */
#include <algorithm>
#include <cstdlib> /* bsearch() */
#include <cstring> /* memcmp() */
#include "transmission.h"
#include "ptrarray.h"
@ -424,7 +425,7 @@ static int compareKeys(void const* va, void const* vb)
auto const* a = static_cast<struct tr_key_struct const*>(va);
auto const* b = static_cast<struct tr_key_struct const*>(vb);
int ret = memcmp(a->str, b->str, MIN(a->len, b->len));
int ret = memcmp(a->str, b->str, std::min(a->len, b->len));
if (ret == 0 && a->len != b->len)
{

View File

@ -6,7 +6,8 @@
*
*/
#include <string.h>
#include <algorithm>
#include <cstring>
#include "transmission.h"
#include "completion.h"
@ -69,7 +70,7 @@ static void savePeers(tr_variant* dict, tr_torrent const* tor)
static size_t addPeers(tr_torrent* tor, uint8_t const* buf, size_t buflen)
{
size_t const n_in = buflen / sizeof(tr_pex);
size_t const n_pex = MIN(n_in, MAX_REMEMBERED_PEERS);
size_t const n_pex = std::min(n_in, size_t{ MAX_REMEMBERED_PEERS });
tr_pex pex[MAX_REMEMBERED_PEERS];
memcpy(pex, buf, sizeof(tr_pex) * n_pex);

View File

@ -6,8 +6,9 @@
*
*/
#include <errno.h>
#include <string.h> /* memcpy */
#include <algorithm>
#include <cerrno>
#include <cstring> /* memcpy */
#include <zlib.h>
@ -802,7 +803,7 @@ static void rpc_server_on_start_retry(evutil_socket_t fd, short type, void* cont
static int rpc_server_start_retry(tr_rpc_server* server)
{
int retry_delay = (server->start_retry_counter / SERVER_START_RETRY_DELAY_STEP + 1) * SERVER_START_RETRY_DELAY_INCREMENT;
retry_delay = MIN(retry_delay, SERVER_START_RETRY_MAX_DELAY);
retry_delay = std::min(retry_delay, int{ SERVER_START_RETRY_MAX_DELAY });
if (server->start_retry_timer == nullptr)
{

View File

@ -6,10 +6,11 @@
*
*/
#include <ctype.h> /* isdigit */
#include <errno.h>
#include <stdlib.h> /* strtol */
#include <string.h> /* strcmp */
#include <algorithm>
#include <cctype> /* isdigit */
#include <cerrno>
#include <cstdlib> /* strtol */
#include <cstring> /* strcmp */
#ifndef ZLIB_CONST
#define ZLIB_CONST
@ -1246,7 +1247,7 @@ static int copyTrackers(tr_tracker_info* tgt, tr_tracker_info const* src, int n)
{
tgt[i].tier = src[i].tier;
tgt[i].announce = tr_strdup(src[i].announce);
maxTier = MAX(maxTier, src[i].tier);
maxTier = std::max(maxTier, src[i].tier);
}
return maxTier;

View File

@ -6,15 +6,15 @@
*
*/
#include <algorithm> // std::partial_sort
#include <errno.h> /* ENOENT */
#include <limits.h> /* INT_MAX */
#include <stdlib.h>
#include <string.h> /* memcpy */
#include <algorithm> // std::partial_sort, min, max
#include <cerrno> /* ENOENT */
#include <climits> /* INT_MAX */
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <cstring> /* memcpy */
#include <vector>
#include <signal.h>
#ifndef _WIN32
#include <sys/types.h> /* umask() */
#include <sys/stat.h> /* umask() */
@ -23,7 +23,6 @@
#include <event2/dns.h> /* evdns_base_free() */
#include <event2/event.h>
#include <stdint.h>
#include <libutp/utp.h>
// #define TR_SHOW_DEPRECATED
@ -3082,7 +3081,7 @@ int tr_sessionCountQueueFreeSlots(tr_session* session, tr_direction dir)
/* is it stalled? */
if (stalled_enabled)
{
int const idle_secs = (int)difftime(now, MAX(tor->startDate, tor->activityDate));
int const idle_secs = (int)difftime(now, std::max(tor->startDate, tor->activityDate));
if (idle_secs >= stalled_if_idle_for_n_seconds)
continue;
}

View File

@ -6,10 +6,11 @@
*
*/
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <algorithm>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <windows.h>
@ -94,7 +95,7 @@ static bool parse_env_block_part(wchar_t const* part, size_t* full_len, size_t*
static int compare_wide_strings_ci(wchar_t const* lhs, size_t lhs_len, wchar_t const* rhs, size_t rhs_len)
{
int diff = wcsnicmp(lhs, rhs, MIN(lhs_len, rhs_len));
int diff = wcsnicmp(lhs, rhs, std::min(lhs_len, rhs_len));
if (diff == 0)
{

View File

@ -6,8 +6,14 @@
*
*/
#include <errno.h> /* EINVAL */
#include <signal.h> /* signal() */
#include <algorithm> /* EINVAL */
#include <cerrno> /* EINVAL */
#include <climits> /* INT_MAX */
#include <cmath>
#include <csignal> /* signal() */
#include <cstdarg>
#include <cstdlib> /* qsort */
#include <cstring> /* memcmp */
#ifndef _WIN32
#include <sys/wait.h> /* wait() */
@ -16,12 +22,6 @@
#include <windows.h> /* CreateProcess(), GetLastError() */
#endif
#include <math.h>
#include <stdarg.h>
#include <string.h> /* memcmp */
#include <stdlib.h> /* qsort */
#include <limits.h> /* INT_MAX */
#include <event2/util.h> /* evutil_vsnprintf() */
#include "transmission.h"
@ -478,7 +478,7 @@ static bool tr_torrentIsSeedIdleLimitDone(tr_torrent* tor)
{
uint16_t idleMinutes;
return tr_torrentGetSeedIdle(tor, &idleMinutes) &&
difftime(tr_time(), MAX(tor->startDate, tor->activityDate)) >= idleMinutes * 60U;
difftime(tr_time(), std::max(tor->startDate, tor->activityDate)) >= idleMinutes * 60U;
}
/***
@ -641,7 +641,7 @@ static tr_priority_t calculatePiecePriority(tr_torrent const* tor, tr_piece_inde
{
// safeguard against a bad arg
tr_info const* const inf = tr_torrentInfo(tor);
file_hint = MIN(file_hint, inf->fileCount - 1);
file_hint = std::min(file_hint, inf->fileCount - 1);
// find the first file with data in this piece
tr_file_index_t first = file_hint;
@ -661,7 +661,7 @@ static tr_priority_t calculatePiecePriority(tr_torrent const* tor, tr_piece_inde
break;
}
priority = MAX(priority, file->priority);
priority = std::max(priority, file->priority);
/* When dealing with multimedia files, getting the first and
last pieces can sometimes allow you to preview it a bit
@ -1245,7 +1245,7 @@ tr_torrent_activity tr_torrentGetActivity(tr_torrent const* tor)
static int torrentGetIdleSecs(tr_torrent const* tor, tr_torrent_activity activity)
{
return ((activity == TR_STATUS_DOWNLOAD || activity == TR_STATUS_SEED) && tor->startDate != 0) ?
(int)difftime(tr_time(), MAX(tor->startDate, tor->activityDate)) :
(int)difftime(tr_time(), std::max(tor->startDate, tor->activityDate)) :
-1;
}
@ -2851,7 +2851,7 @@ void tr_torrentSetDateAdded(tr_torrent* tor, time_t t)
TR_ASSERT(tr_isTorrent(tor));
tor->addedDate = t;
tor->anyDate = MAX(tor->anyDate, tor->addedDate);
tor->anyDate = std::max(tor->anyDate, tor->addedDate);
}
void tr_torrentSetDateActive(tr_torrent* tor, time_t t)
@ -2859,7 +2859,7 @@ void tr_torrentSetDateActive(tr_torrent* tor, time_t t)
TR_ASSERT(tr_isTorrent(tor));
tor->activityDate = t;
tor->anyDate = MAX(tor->anyDate, tor->activityDate);
tor->anyDate = std::max(tor->anyDate, tor->activityDate);
}
void tr_torrentSetDateDone(tr_torrent* tor, time_t t)
@ -2867,7 +2867,7 @@ void tr_torrentSetDateDone(tr_torrent* tor, time_t t)
TR_ASSERT(tr_isTorrent(tor));
tor->doneDate = t;
tor->anyDate = MAX(tor->anyDate, tor->doneDate);
tor->anyDate = std::max(tor->anyDate, tor->doneDate);
}
/**
@ -3441,7 +3441,7 @@ void tr_torrentGotBlock(tr_torrent* tor, tr_block_index_t block)
uint32_t const n = tr_torPieceCountBytes(tor, p);
tr_logAddTorErr(tor, _("Piece %" PRIu32 ", which was just downloaded, failed its checksum test"), p);
tor->corruptCur += n;
tor->downloadedCur -= MIN(tor->downloadedCur, n);
tor->downloadedCur -= std::min(tor->downloadedCur, uint64_t{ n });
tr_peerMgrGotBadPiece(tor, p);
}
}
@ -3449,7 +3449,7 @@ void tr_torrentGotBlock(tr_torrent* tor, tr_block_index_t block)
else
{
uint32_t const n = tr_torBlockCountBytes(tor, block);
tor->downloadedCur -= MIN(tor->downloadedCur, n);
tor->downloadedCur -= std::min(tor->downloadedCur, uint64_t{ n });
tr_logAddTorDbg(tor, "we have this block already...");
}
}
@ -3675,7 +3675,7 @@ void tr_torrentSetQueuePosition(tr_torrent* tor, int pos)
}
}
tor->queuePosition = MIN(pos, back + 1);
tor->queuePosition = std::min(pos, back + 1);
tor->anyDate = now;
TR_ASSERT(queueIsSequenced(tor->session));

View File

@ -22,14 +22,12 @@
*
*/
/* ansi */
#include <errno.h>
#include <stdio.h>
#include <string.h> /* memcpy(), memset(), memchr(), strlen() */
#include <stdlib.h> /* atoi() */
/* posix */
#include <signal.h> /* sig_atomic_t */
#include <algorithm>
#include <cerrno>
#include <csignal> /* sig_atomic_t */
#include <cstdio>
#include <cstdlib> /* atoi() */
#include <cstring> /* memcpy(), memset(), memchr(), strlen() */
#ifdef _WIN32
#include <inttypes.h>
@ -177,7 +175,7 @@ static void dht_bootstrap(void* closure)
tr_logAddNamedInfo("DHT", "Bootstrapping from %d IPv6 nodes", num6);
}
for (int i = 0; i < MAX(num, num6); ++i)
for (int i = 0; i < std::max(num, num6); ++i)
{
if (i < num && !bootstrap_done(cl->session, AF_INET))
{
@ -859,7 +857,7 @@ void dht_hash(void* hash_return, int hash_size, void const* v1, int len1, void c
unsigned char sha1[SHA_DIGEST_LENGTH];
tr_sha1(sha1, v1, len1, v2, len2, v3, len3, nullptr);
memset(hash_return, 0, hash_size);
memcpy(hash_return, sha1, MIN(hash_size, SHA_DIGEST_LENGTH));
memcpy(hash_return, sha1, std::min(hash_size, SHA_DIGEST_LENGTH));
}
int dht_random_bytes(void* buf, size_t size)

View File

@ -6,10 +6,11 @@
*
*/
#include <ctype.h> /* isspace() */
#include <stdio.h>
#include <stdlib.h> /* exit() */
#include <string.h>
#include <algorithm>
#include <cctype> /* isspace() */
#include <cstdio>
#include <cstdlib> /* exit() */
#include <cstring>
#include "transmission.h"
#include "tr-getopt.h"
@ -100,21 +101,23 @@ static void getopts_usage_line(tr_option const* opt, int longWidth, int shortWid
static void maxWidth(struct tr_option const* o, int* longWidth, int* shortWidth, int* argWidth)
{
// FIXME: in this function sign bits from int* are lost, then 64-bit result is truncated to 32-bit int
// Convert arguments to size_t*
char const* arg;
if (o->longName != nullptr)
{
*longWidth = MAX(*longWidth, (int)strlen(o->longName));
*longWidth = std::max((size_t)*longWidth, strlen(o->longName));
}
if (o->shortName != nullptr)
{
*shortWidth = MAX(*shortWidth, (int)strlen(o->shortName));
*shortWidth = std::max((size_t)*shortWidth, strlen(o->shortName));
}
if ((arg = getArgName(o)) != nullptr)
{
*argWidth = MAX(*argWidth, (int)strlen(arg));
*argWidth = std::max((size_t)*argWidth, strlen(arg));
}
}

View File

@ -20,21 +20,19 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* ansi */
#include <errno.h>
#include <stdio.h>
#include <string.h> /* strlen(), strncpy(), strstr(), memset() */
/* posix */
#include <signal.h> /* sig_atomic_t */
#include <ctype.h> /* toupper() */
#include <algorithm>
#include <cctype> /* toupper() */
#include <cerrno>
#include <csignal> /* sig_atomic_t */
#include <cstdio>
#include <cstring> /* strlen(), strncpy(), strstr(), memset() */
#ifdef _WIN32
#include <inttypes.h>
#include <ws2tcpip.h>
typedef uint16_t in_port_t; /* all missing */
#else
#include <sys/time.h>
#include <ctime>
#include <unistd.h> /* close() */
#include <sys/types.h>
#include <sys/socket.h> /* socket(), bind() */
@ -269,7 +267,7 @@ static bool lpd_extractParam(char const* const str, char const* const name, int
/* if value string hits the length limit n,
* leave space for a trailing '\0' character */
n = MIN(len, n - 1);
n = std::min(len, n - 1);
strncpy(val, beg, n);
val[n] = 0;
}

View File

@ -147,17 +147,6 @@
} while (0)
#endif
/* Sometimes the system defines MAX/MIN, sometimes not.
In the latter case, define those here since we will use them */
#ifndef MAX
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif
#ifndef MIN
#define MIN(a, b) ((a) > (b) ? (b) : (a))
#endif
/***
****
***/

View File

@ -13,16 +13,16 @@
#endif
#include <array> // std::array
#include <ctype.h> /* isdigit(), tolower() */
#include <errno.h>
#include <float.h> /* DBL_DIG */
#include <locale.h> /* localeconv() */
#include <math.h> /* fabs(), floor() */
#include <stdint.h> /* SIZE_MAX */
#include <stdio.h>
#include <stdlib.h> /* getenv() */
#include <string.h> /* strerror(), memset(), memmem() */
#include <time.h> /* nanosleep() */
#include <cctype> /* isdigit(), tolower() */
#include <cerrno>
#include <cfloat> /* DBL_DIG */
#include <clocale> /* localeconv() */
#include <cmath> /* fabs(), floor() */
#include <cstdint> /* SIZE_MAX */
#include <cstdio>
#include <cstdlib> /* getenv() */
#include <cstring> /* strerror(), memset(), memmem() */
#include <ctime> /* nanosleep() */
#ifdef _WIN32
#include <ws2tcpip.h> /* WSAStartup() */
@ -30,7 +30,7 @@
#include <shellapi.h> /* CommandLineToArgv() */
#include <shlwapi.h> /* StrStrIA() */
#else
#include <sys/time.h>
#include <ctime>
#include <unistd.h> /* getpagesize() */
#endif
@ -1423,8 +1423,8 @@ static bool parseNumberSection(char const* str, size_t len, struct number_range*
tr_free(tmp);
setme->low = MIN(a, b);
setme->high = MAX(a, b);
setme->low = (int)std::min(a, b); // FIXME: narrowing long to int
setme->high = (int)std::max(a, b);
errno = error;
return success;

View File

@ -6,8 +6,9 @@
*
*/
#include <string.h> /* memcmp() */
#include <stdlib.h> /* free() */
#include <algorithm>
#include <cstdlib> /* free() */
#include <cstring> /* memcmp() */
#include "transmission.h"
#include "completion.h"
@ -76,8 +77,8 @@ static bool verifyTorrent(tr_torrent* tor, bool* stopFlag)
/* figure out how much we can read this pass */
leftInPiece = tr_torPieceCountBytes(tor, pieceIndex) - piecePos;
leftInFile = file->length - filePos;
bytesThisPass = MIN(leftInFile, leftInPiece);
bytesThisPass = MIN(bytesThisPass, buflen);
bytesThisPass = std::min(leftInFile, leftInPiece);
bytesThisPass = std::min(bytesThisPass, uint64_t{ buflen });
/* read a bit */
if (fd != TR_BAD_SYS_FILE)

View File

@ -6,7 +6,8 @@
*
*/
#include <string.h> /* strlen(), strstr() */
#include <algorithm>
#include <cstring> /* strlen(), strstr() */
#ifdef _WIN32
#include <windows.h>
@ -541,7 +542,7 @@ static void tr_webThreadFunc(void* vsession)
/* curl_multi_wait() returns immediately if there are
* no fds to wait for, so we need an explicit wait here
* to emulate select() behavior */
tr_wait_msec(MIN(msec, THREADFUNC_MAX_SLEEP_MSEC / 2));
tr_wait_msec(std::min(msec, THREADFUNC_MAX_SLEEP_MSEC / 2L));
}
}
else

View File

@ -6,7 +6,8 @@
*
*/
#include <string.h> /* strlen() */
#include <algorithm>
#include <cstring> /* strlen() */
#include <event2/buffer.h>
#include <event2/event.h>
@ -163,7 +164,7 @@ static void write_block_func(void* vdata)
{
while (len > 0)
{
uint32_t const bytes_this_pass = MIN(len, block_size);
uint32_t const bytes_this_pass = std::min(len, block_size);
tr_cacheWriteBlock(cache, tor, piece, offset_end - len, bytes_this_pass, buf);
len -= bytes_this_pass;
}
@ -323,7 +324,7 @@ static void on_idle(tr_webseed* w)
blocks = tr_new(tr_block_index_t, want * 2);
tr_peerMgrGetNextRequests(tor, &w->parent, want, blocks, &got, true);
w->idle_connections -= MIN(w->idle_connections, got);
w->idle_connections -= std::min(w->idle_connections, got);
if (w->retry_tickcount >= FAILURE_RETRY_INTERVAL && got == want)
{
@ -488,7 +489,7 @@ static void task_request_next_chunk(struct tr_webseed_task* t)
tr_ioFindFileLocation(tor, step_piece, step_piece_offset, &file_index, &file_offset);
file = &inf->files[file_index];
this_pass = MIN(remain, file->length - file_offset);
this_pass = std::min(remain, file->length - file_offset);
if (urls[file_index] == nullptr)
{

View File

@ -6,6 +6,8 @@
*
*/
#include <algorithm>
#include "transmission.h"
#include "error.h"
#include "file.h"
@ -57,7 +59,7 @@ private:
size_t buf_pos = 0;
while (buf_pos < buf_len && bytes_remaining > 0)
{
uint64_t const chunk_size = MIN(buf_len - buf_pos, bytes_remaining);
uint64_t const chunk_size = std::min(uint64_t{ buf_len - buf_pos }, bytes_remaining);
uint64_t bytes_read = 0;
tr_sys_file_read(fd, buf + buf_pos, chunk_size, &bytes_read, nullptr);