refactor: cppcoreguidelines-init-variables pt. 5 (#1970)

* fix: uninitialized variables in torrent.cc
This commit is contained in:
Charles Kerr 2021-10-17 12:06:00 -05:00 committed by GitHub
parent 4aba9b623f
commit 2bc9959dc9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 175 additions and 270 deletions

View File

@ -18,6 +18,7 @@
#include <sstream>
#include <string>
#include <typeinfo>
#include <unordered_map>
#ifndef _WIN32
#include <sys/wait.h> /* wait() */
@ -101,10 +102,10 @@ tr_torrent* tr_torrentFindFromHash(tr_session* session, uint8_t const* hash)
tr_torrent* tr_torrentFindFromMagnetLink(tr_session* session, char const* magnet)
{
tr_magnet_info* info;
tr_torrent* tor = nullptr;
if ((info = tr_magnetParse(magnet)) != nullptr)
tr_magnet_info* const info = tr_magnetParse(magnet);
if (info != nullptr)
{
tor = tr_torrentFindFromHash(session, info->hash);
tr_magnetFree(info);
@ -162,18 +163,8 @@ static constexpr void tr_torrentUnsetPeerId(tr_torrent* tor)
static int peerIdTTL(tr_torrent const* tor)
{
int ttl;
if (tor->peer_id_creation_time == 0)
{
ttl = 0;
}
else
{
ttl = (int)difftime(tor->peer_id_creation_time + tor->session->peer_id_ttl_hours * 3600, tr_time());
}
return ttl;
auto const ctime = tor->peer_id_creation_time;
return ctime == 0 ? 0 : (int)difftime(ctime + tor->session->peer_id_ttl_hours * 3600, tr_time());
}
unsigned char const* tr_torrentGetPeerId(tr_torrent* tor)
@ -306,9 +297,9 @@ double tr_torrentGetRatioLimit(tr_torrent const* tor)
bool tr_torrentGetSeedRatio(tr_torrent const* tor, double* ratio)
{
TR_ASSERT(tr_isTorrent(tor));
auto isLimited = bool{};
bool isLimited;
TR_ASSERT(tr_isTorrent(tor));
switch (tr_torrentGetRatioMode(tor))
{
@ -344,11 +335,11 @@ bool tr_torrentGetSeedRatio(tr_torrent const* tor, double* ratio)
* it applies if the torrent's a seed AND it has a seed ratio set */
static bool tr_torrentGetSeedRatioBytes(tr_torrent const* tor, uint64_t* setmeLeft, uint64_t* setmeGoal)
{
TR_ASSERT(tr_isTorrent(tor));
double seedRatio;
bool seedRatioApplies = false;
TR_ASSERT(tr_isTorrent(tor));
auto seedRatio = double{};
if (tr_torrentGetSeedRatio(tor, &seedRatio))
{
uint64_t const u = tor->uploadedCur + tor->uploadedPrev;
@ -374,7 +365,7 @@ static bool tr_torrentGetSeedRatioBytes(tr_torrent const* tor, uint64_t* setmeLe
static bool tr_torrentIsSeedRatioDone(tr_torrent const* tor)
{
uint64_t bytesLeft;
auto bytesLeft = uint64_t{};
return tr_torrentGetSeedRatioBytes(tor, &bytesLeft, nullptr) && bytesLeft == 0;
}
@ -423,7 +414,7 @@ uint16_t tr_torrentGetIdleLimit(tr_torrent const* tor)
bool tr_torrentGetSeedIdle(tr_torrent const* tor, uint16_t* idleMinutes)
{
bool isLimited;
auto isLimited = bool{};
switch (tr_torrentGetIdleMode(tor))
{
@ -457,7 +448,7 @@ bool tr_torrentGetSeedIdle(tr_torrent const* tor, uint16_t* idleMinutes)
static bool tr_torrentIsSeedIdleLimitDone(tr_torrent* tor)
{
uint16_t idleMinutes;
auto idleMinutes = uint16_t{};
return tr_torrentGetSeedIdle(tor, &idleMinutes) &&
difftime(tr_time(), std::max(tor->startDate, tor->activityDate)) >= idleMinutes * 60U;
}
@ -866,10 +857,6 @@ static void torrentInit(tr_torrent* tor, tr_ctor const* ctor)
tr_sessionLock(session);
bool doStart;
uint64_t loaded;
char const* dir;
bool isNewTorrent;
static int nextUniqueId = 1;
tor->session = session;
@ -879,6 +866,7 @@ static void torrentInit(tr_torrent* tor, tr_ctor const* ctor)
tr_sha1(tor->obfuscatedHash, "req2", 4, tor->info.hash, SHA_DIGEST_LENGTH, nullptr);
char const* dir = nullptr;
if (tr_ctorGetDownloadDir(ctor, TR_FORCE, &dir) || tr_ctorGetDownloadDir(ctor, TR_FALLBACK, &dir))
{
tor->downloadDir = tr_strdup(dir);
@ -910,7 +898,7 @@ static void torrentInit(tr_torrent* tor, tr_ctor const* ctor)
torrentInitFromInfo(tor);
bool didRenameResumeFileToHashOnlyName = false;
loaded = tr_torrentLoadResume(tor, ~(uint64_t)0, ctor, &didRenameResumeFileToHashOnlyName);
auto const loaded = tr_torrentLoadResume(tor, ~(uint64_t)0, ctor, &didRenameResumeFileToHashOnlyName);
if (didRenameResumeFileToHashOnlyName)
{
@ -926,7 +914,7 @@ static void torrentInit(tr_torrent* tor, tr_ctor const* ctor)
refreshCurrentDir(tor);
doStart = tor->isRunning;
bool const doStart = tor->isRunning;
tor->isRunning = false;
if ((loaded & TR_FR_SPEEDLIMIT) == 0)
@ -953,13 +941,12 @@ static void torrentInit(tr_torrent* tor, tr_ctor const* ctor)
tr_sessionAddTorrent(session, tor);
/* if we don't have a local .torrent file already, assume the torrent is new */
isNewTorrent = !tr_sys_path_exists(tor->info.torrent, nullptr);
bool const isNewTorrent = !tr_sys_path_exists(tor->info.torrent, nullptr);
/* maybe save our own copy of the metainfo */
if (tr_ctorGetSave(ctor))
{
tr_variant const* val;
tr_variant const* val = nullptr;
if (tr_ctorGetMetainfo(ctor, &val))
{
char const* path = tor->info.torrent;
@ -1009,28 +996,26 @@ static tr_parse_result torrentParseImpl(
size_t* dictLength,
int* setme_duplicate_id)
{
bool doFree;
bool didParse;
bool hasInfo = false;
tr_info tmp;
tr_variant const* metainfo;
tr_session* session = tr_ctorGetSession(ctor);
tr_parse_result result = TR_PARSE_OK;
tr_info tmp;
if (setmeInfo == nullptr)
{
setmeInfo = &tmp;
}
memset(setmeInfo, 0, sizeof(tr_info));
*setmeInfo = {};
tr_variant const* metainfo = nullptr;
if (!tr_ctorGetMetainfo(ctor, &metainfo))
{
return TR_PARSE_ERR;
}
didParse = tr_metainfoParse(session, metainfo, setmeInfo, &hasInfo, dictLength);
doFree = didParse && (setmeInfo == &tmp);
auto hasInfo = bool{};
bool const didParse = tr_metainfoParse(session, metainfo, setmeInfo, &hasInfo, dictLength);
bool const doFree = didParse && (setmeInfo == &tmp);
if (!didParse)
{
@ -1077,16 +1062,15 @@ tr_parse_result tr_torrentParse(tr_ctor const* ctor, tr_info* setmeInfo)
tr_torrent* tr_torrentNew(tr_ctor const* ctor, int* setme_error, int* setme_duplicate_id)
{
tr_torrent* tor = nullptr;
TR_ASSERT(ctor != nullptr);
TR_ASSERT(tr_isSession(tr_ctorGetSession(ctor)));
size_t len;
bool hasInfo;
tr_info tmpInfo;
tr_parse_result r;
tr_torrent* tor = nullptr;
r = torrentParseImpl(ctor, &tmpInfo, &hasInfo, &len, setme_duplicate_id);
auto tmpInfo = tr_info{};
auto hasInfo = bool{};
auto len = size_t{};
tr_parse_result const r = torrentParseImpl(ctor, &tmpInfo, &hasInfo, &len, setme_duplicate_id);
if (r == TR_PARSE_OK)
{
@ -1278,13 +1262,6 @@ tr_stat const* tr_torrentStat(tr_torrent* tor)
uint64_t const now = tr_time_msec();
tr_stat* s;
uint64_t seedRatioBytesLeft;
uint64_t seedRatioBytesGoal;
bool seedRatioApplies;
uint16_t seedIdleMinutes;
unsigned int pieceUploadSpeed_Bps;
unsigned int pieceDownloadSpeed_Bps;
auto swarm_stats = tr_swarm_stats{};
tor->lastStatTime = tr_time();
@ -1294,7 +1271,7 @@ tr_stat const* tr_torrentStat(tr_torrent* tor)
tr_swarmGetStats(tor->swarm, &swarm_stats);
}
s = &tor->stats;
tr_stat* const s = &tor->stats;
s->id = tor->uniqueId;
s->activity = tr_torrentGetActivity(tor);
s->error = tor->error;
@ -1316,9 +1293,9 @@ tr_stat const* tr_torrentStat(tr_torrent* tor)
s->rawUploadSpeed_KBps = toSpeedKBps(tor->bandwidth->getRawSpeedBytesPerSecond(now, TR_UP));
s->rawDownloadSpeed_KBps = toSpeedKBps(tor->bandwidth->getRawSpeedBytesPerSecond(now, TR_DOWN));
pieceUploadSpeed_Bps = tor->bandwidth->getPieceSpeedBytesPerSecond(now, TR_UP);
pieceDownloadSpeed_Bps = tor->bandwidth->getPieceSpeedBytesPerSecond(now, TR_DOWN);
auto const pieceUploadSpeed_Bps = tor->bandwidth->getPieceSpeedBytesPerSecond(now, TR_UP);
s->pieceUploadSpeed_KBps = toSpeedKBps(pieceUploadSpeed_Bps);
auto const pieceDownloadSpeed_Bps = tor->bandwidth->getPieceSpeedBytesPerSecond(now, TR_DOWN);
s->pieceDownloadSpeed_KBps = toSpeedKBps(pieceDownloadSpeed_Bps);
s->percentComplete = tr_cpPercentComplete(&tor->completion);
@ -1345,7 +1322,9 @@ tr_stat const* tr_torrentStat(tr_torrent* tor)
s->ratio = tr_getRatio(s->uploadedEver, s->downloadedEver != 0 ? s->downloadedEver : s->haveValid);
seedRatioApplies = tr_torrentGetSeedRatioBytes(tor, &seedRatioBytesLeft, &seedRatioBytesGoal);
auto seedRatioBytesLeft = uint64_t{};
auto seedRatioBytesGoal = uint64_t{};
bool const seedRatioApplies = tr_torrentGetSeedRatioBytes(tor, &seedRatioBytesLeft, &seedRatioBytesGoal);
switch (s->activity)
{
@ -1403,13 +1382,11 @@ tr_stat const* tr_torrentStat(tr_torrent* tor)
}
}
if (tor->etaULSpeed_Bps < 1 && tr_torrentGetSeedIdle(tor, &seedIdleMinutes))
{
s->etaIdle = seedIdleMinutes * 60 - s->idleSecs;
}
else
{
s->etaIdle = TR_ETA_NOT_AVAIL;
auto seedIdleMinutes = uint16_t{};
s->etaIdle = tor->etaULSpeed_Bps < 1 && tr_torrentGetSeedIdle(tor, &seedIdleMinutes) ?
seedIdleMinutes * 60 - s->idleSecs :
TR_ETA_NOT_AVAIL;
}
break;
@ -1451,44 +1428,41 @@ tr_stat const* tr_torrentStat(tr_torrent* tor)
static uint64_t countFileBytesCompleted(tr_torrent const* tor, tr_file_index_t index)
{
uint64_t total = 0;
tr_file const* f = &tor->info.files[index];
if (f->length != 0)
tr_file const& f = tor->info.files[index];
if (f.length == 0)
{
tr_block_index_t first;
tr_block_index_t last;
tr_torGetFileBlockRange(tor, index, &first, &last);
return 0;
}
if (first == last)
{
if (tr_torrentBlockIsComplete(tor, first))
{
total = f->length;
}
}
else
{
/* the first block */
if (tr_torrentBlockIsComplete(tor, first))
{
total += tor->blockSize - f->offset % tor->blockSize;
}
auto first = tr_block_index_t{};
auto last = tr_block_index_t{};
tr_torGetFileBlockRange(tor, index, &first, &last);
/* the middle blocks */
if (first + 1 < last)
{
uint64_t u = tor->completion.blockBitfield->countRange(first + 1, last);
u *= tor->blockSize;
total += u;
}
if (first == last)
{
return tr_torrentBlockIsComplete(tor, first) ? f.length : 0;
}
/* the last block */
if (tr_torrentBlockIsComplete(tor, last))
{
total += f->offset + f->length - (uint64_t)tor->blockSize * last;
}
}
auto total = uint64_t{};
// the first block
if (tr_torrentBlockIsComplete(tor, first))
{
total += tor->blockSize - f.offset % tor->blockSize;
}
// the middle blocks
if (first + 1 < last)
{
uint64_t u = tor->completion.blockBitfield->countRange(first + 1, last);
u *= tor->blockSize;
total += u;
}
// the last block
if (tr_torrentBlockIsComplete(tor, last))
{
total += f.offset + f.length - (uint64_t)tor->blockSize * last;
}
return total;
@ -1852,38 +1826,37 @@ static void onVerifyDone(tr_torrent* tor, bool aborted, void* vdata)
static void verifyTorrent(void* vdata)
{
auto* data = static_cast<struct verify_data*>(vdata);
bool startAfter;
tr_torrent* tor = data->tor;
tr_sessionLock(tor->session);
if (tor->isDeleting)
{
tr_free(data);
goto unlock;
}
/* if the torrent's already being verified, stop it */
tr_verifyRemove(tor);
startAfter = (tor->isRunning || tor->startAfterVerify) && !tor->isStopping;
if (tor->isRunning)
{
tr_torrentStop(tor);
}
tor->startAfterVerify = startAfter;
if (setLocalErrorIfFilesDisappeared(tor))
{
tor->startAfterVerify = false;
}
else
{
tr_verifyAdd(tor, onVerifyDone, data);
/* if the torrent's already being verified, stop it */
tr_verifyRemove(tor);
bool const startAfter = (tor->isRunning || tor->startAfterVerify) && !tor->isStopping;
if (tor->isRunning)
{
tr_torrentStop(tor);
}
tor->startAfterVerify = startAfter;
if (setLocalErrorIfFilesDisappeared(tor))
{
tor->startAfterVerify = false;
}
else
{
tr_verifyAdd(tor, onVerifyDone, data);
}
}
unlock:
tr_sessionUnlock(tor->session);
}
@ -2183,11 +2156,9 @@ static void torrentCallScript(tr_torrent const* tor, char const* script)
void tr_torrentRecheckCompleteness(tr_torrent* tor)
{
tr_completeness completeness;
tr_torrentLock(tor);
completeness = tr_cpGetStatus(&tor->completion);
auto const completeness = tr_cpGetStatus(&tor->completion);
if (completeness != tor->completeness)
{
@ -2335,19 +2306,15 @@ tr_priority_t* tr_torrentGetFilePriorities(tr_torrent const* tor)
static void setFileDND(tr_torrent* tor, tr_file_index_t fileIndex, bool doDownload)
{
bool const dnd = !doDownload;
tr_piece_index_t firstPiece;
bool firstPieceDND;
tr_piece_index_t lastPiece;
bool lastPieceDND;
tr_file* file = &tor->info.files[fileIndex];
file->dnd = dnd;
firstPiece = file->firstPiece;
lastPiece = file->lastPiece;
auto const firstPiece = file->firstPiece;
auto const lastPiece = file->lastPiece;
/* can't set the first piece to DND unless
every file using that piece is DND */
firstPieceDND = dnd;
auto firstPieceDND = dnd;
if (fileIndex > 0)
{
@ -2369,7 +2336,7 @@ static void setFileDND(tr_torrent* tor, tr_file_index_t fileIndex, bool doDownlo
/* can't set the last piece to DND unless
every file using that piece is DND */
lastPieceDND = dnd;
auto lastPieceDND = dnd;
for (tr_file_index_t i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i)
{
@ -2579,8 +2546,7 @@ uint64_t tr_pieceOffset(tr_torrent const* tor, tr_piece_index_t index, uint32_t
{
TR_ASSERT(tr_isTorrent(tor));
uint64_t ret;
auto ret = uint64_t{};
ret = tor->info.pieceSize;
ret *= index;
ret += offset;
@ -2656,7 +2622,7 @@ bool tr_torrentCheckPiece(tr_torrent* tor, tr_piece_index_t pieceIndex)
time_t tr_torrentGetFileMTime(tr_torrent const* tor, tr_file_index_t i)
{
time_t mtime = 0;
auto mtime = time_t{};
if (!tr_fdFileGetCachedMTime(tor->session, tor->uniqueId, i, &mtime))
{
@ -2683,8 +2649,8 @@ bool tr_torrentPieceNeedsCheck(tr_torrent const* tor, tr_piece_index_t p)
/* If we think we've completed one of the files in this piece,
* but it's been modified since we last checked it,
* then it needs to be rechecked */
tr_file_index_t f;
uint64_t unused;
auto f = tr_file_index_t{};
auto unused = uint64_t{};
tr_ioFindFileLocation(tor, p, 0, &f, &unused);
for (tr_file_index_t i = f; i < inf->fileCount && pieceHasFile(p, &inf->files[i]); ++i)
@ -2723,8 +2689,8 @@ bool tr_torrentSetAnnounceList(tr_torrent* tor, tr_tracker_info const* trackers_
tr_torrentLock(tor);
tr_variant metainfo;
bool ok = true;
auto metainfo = tr_variant{};
auto ok = bool{ true };
/* ensure the trackers' tiers are in ascending order */
auto* trackers = static_cast<tr_tracker_info*>(tr_memdup(trackers_in, sizeof(tr_tracker_info) * trackerCount));
@ -2742,9 +2708,6 @@ bool tr_torrentSetAnnounceList(tr_torrent* tor, tr_tracker_info const* trackers_
/* save to the .torrent file */
if (ok && tr_variantFromFile(&metainfo, TR_VARIANT_FMT_BENC, tor->info.torrent, nullptr))
{
bool hasInfo;
tr_info tmpInfo;
/* remove the old fields */
tr_variantDictRemove(&metainfo, TR_KEY_announce);
tr_variantDictRemove(&metainfo, TR_KEY_announce_list);
@ -2774,12 +2737,11 @@ bool tr_torrentSetAnnounceList(tr_torrent* tor, tr_tracker_info const* trackers_
}
/* try to parse it back again, to make sure it's good */
memset(&tmpInfo, 0, sizeof(tr_info));
auto tmpInfo = tr_info{};
auto hasInfo = bool{};
if (tr_metainfoParse(tor->session, &metainfo, &tmpInfo, &hasInfo, &tor->infoDictLength))
{
/* it's good, so keep these new trackers and free the old ones */
tr_info swap;
swap.trackers = tor->info.trackers;
swap.trackerCount = tor->info.trackerCount;
@ -2932,35 +2894,35 @@ static constexpr bool isJunkFile(std::string_view base)
static void removeEmptyFoldersAndJunkFiles(char const* folder)
{
tr_sys_dir_t odir;
if ((odir = tr_sys_dir_open(folder, nullptr)) != TR_BAD_SYS_DIR)
auto const odir = tr_sys_dir_open(folder, nullptr);
if (odir == TR_BAD_SYS_DIR)
{
char const* name;
while ((name = tr_sys_dir_read_name(odir, nullptr)) != nullptr)
{
if (strcmp(name, ".") != 0 && strcmp(name, "..") != 0)
{
tr_sys_path_info info;
char* filename = tr_buildPath(folder, name, nullptr);
if (tr_sys_path_get_info(filename, 0, &info, nullptr) && info.type == TR_SYS_PATH_IS_DIRECTORY)
{
removeEmptyFoldersAndJunkFiles(filename);
}
else if (isJunkFile(name))
{
tr_sys_path_remove(filename, nullptr);
}
tr_free(filename);
}
}
tr_sys_path_remove(folder, nullptr);
tr_sys_dir_close(odir, nullptr);
return;
}
char const* name = nullptr;
while ((name = tr_sys_dir_read_name(odir, nullptr)) != nullptr)
{
if (strcmp(name, ".") != 0 && strcmp(name, "..") != 0)
{
char* const filename = tr_buildPath(folder, name, nullptr);
auto info = tr_sys_path_info{};
if (tr_sys_path_get_info(filename, 0, &info, nullptr) && info.type == TR_SYS_PATH_IS_DIRECTORY)
{
removeEmptyFoldersAndJunkFiles(filename);
}
else if (isJunkFile(name))
{
tr_sys_path_remove(filename, nullptr);
}
tr_free(filename);
}
}
tr_sys_path_remove(folder, nullptr);
tr_sys_dir_close(odir, nullptr);
}
/**
@ -3001,10 +2963,8 @@ static void deleteLocalData(tr_torrent* tor, tr_fileFunc func)
for (tr_file_index_t f = 0; f < tor->info.fileCount; ++f)
{
char* filename;
/* try to find the file, looking in the partial and download dirs */
filename = tr_buildPath(top, tor->info.files[f].name, nullptr);
char* filename = tr_buildPath(top, tor->info.files[f].name, nullptr);
if (!tr_sys_path_exists(filename, nullptr))
{
@ -3041,11 +3001,10 @@ static void deleteLocalData(tr_torrent* tor, tr_fileFunc func)
***/
/* try deleting the local data's top-level files & folders */
tr_sys_dir_t odir;
if ((odir = tr_sys_dir_open(tmpdir, nullptr)) != TR_BAD_SYS_DIR)
tr_sys_dir_t const odir = tr_sys_dir_open(tmpdir, nullptr);
if (odir != TR_BAD_SYS_DIR)
{
char const* name;
char const* name = nullptr;
while ((name = tr_sys_dir_read_name(odir, nullptr)) != nullptr)
{
if (strcmp(name, ".") != 0 && strcmp(name, "..") != 0)
@ -3084,12 +3043,9 @@ static void deleteLocalData(tr_torrent* tor, tr_fileFunc func)
/* build a list of 'top's child directories that belong to this torrent */
for (tr_file_index_t f = 0; f < tor->info.fileCount; ++f)
{
char* dir;
char* filename;
/* get the directory that this file goes in... */
filename = tr_buildPath(top, tor->info.files[f].name, nullptr);
dir = tr_sys_path_dirname(filename, nullptr);
char* const filename = tr_buildPath(top, tor->info.files[f].name, nullptr);
char* dir = tr_sys_path_dirname(filename, nullptr);
tr_free(filename);
if (dir == nullptr)
@ -3187,10 +3143,10 @@ static void setLocation(void* vdata)
* if the target directory runs out of space halfway through... */
for (tr_file_index_t i = 0; !err && i < tor->info.fileCount; ++i)
{
char* sub;
char const* oldbase;
tr_file const* f = &tor->info.files[i];
tr_file const* const f = &tor->info.files[i];
char const* oldbase = nullptr;
char* sub = nullptr;
if (tr_torrentFindFile2(tor, i, &oldbase, &sub, nullptr))
{
char* oldpath = tr_buildPath(oldbase, sub, nullptr);
@ -3286,54 +3242,33 @@ void tr_torrentSetLocation(
char const* tr_torrentPrimaryMimeType(tr_torrent const* tor)
{
struct count
{
uint64_t length;
char const* mime_type;
};
tr_info const* inf = &tor->info;
struct count* counts = tr_new0(struct count, inf->fileCount);
size_t num_counts = 0;
// count up how many bytes there are for each mime-type in the torrent
// NB: get_mime_type_for_filename() always returns the same ptr for a
// mime_type, so its raw pointer can be used as a key.
// TODO: tr_get_mime_type_for_filename should return a std::string_view
auto size_per_mime_type = std::unordered_map<char const*, size_t>{};
for (tr_file const *it = inf->files, *end = it + inf->fileCount; it != end; ++it)
{
char const* mime_type = tr_get_mime_type_for_filename(it->name);
size_t i;
for (i = 0; i < num_counts; ++i)
{
if (counts[i].mime_type == mime_type)
{
counts[i].length += it->length;
break;
}
}
if (i == num_counts)
{
counts[i].mime_type = mime_type;
counts[i].length = it->length;
++num_counts;
}
size_per_mime_type[mime_type] += it->length;
}
uint64_t max_len = 0;
char const* mime_type = nullptr;
for (struct count const *it = counts, *end = it + num_counts; it != end; ++it)
// now that we have the totals,
// sort by number so that we can get the biggest
auto mime_type_per_size = std::map<size_t, char const*>{};
for (auto it : size_per_mime_type)
{
if ((max_len < it->length) && (it->mime_type != nullptr))
{
max_len = it->length;
mime_type = it->mime_type;
}
mime_type_per_size.emplace(it.second, it.first);
}
tr_free(counts);
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
// application/octet-stream is the default value for all other cases.
// An unknown file type should use this type.
return mime_type != nullptr ? mime_type : "application/octet-stream";
char const* const fallback = "application/octet-stream";
return std::empty(mime_type_per_size) ? fallback : mime_type_per_size.rbegin()->second;
}
/***
@ -3342,8 +3277,6 @@ char const* tr_torrentPrimaryMimeType(tr_torrent const* tor)
static void tr_torrentFileCompleted(tr_torrent* tor, tr_file_index_t fileIndex)
{
char* sub;
char const* base;
tr_info const* inf = &tor->info;
tr_file const* f = &inf->files[fileIndex];
time_t const now = tr_time();
@ -3362,6 +3295,8 @@ static void tr_torrentFileCompleted(tr_torrent* tor, tr_file_index_t fileIndex)
/* if the torrent's current filename isn't the same as the one in the
* metadata -- for example, if it had the ".part" suffix appended to
* it until now -- then rename it to match the one in the metadata */
char const* base = nullptr;
char* sub = nullptr;
if (tr_torrentFindFile2(tor, fileIndex, &base, &sub, nullptr))
{
if (strcmp(sub, f->name) != 0)
@ -3409,12 +3344,10 @@ void tr_torrentGotBlock(tr_torrent* tor, tr_block_index_t block)
if (block_is_new)
{
tr_piece_index_t p;
tr_cpBlockAdd(&tor->completion, block);
tr_torrentSetDirty(tor);
p = tr_torBlockPiece(tor, block);
tr_piece_index_t const p = tr_torBlockPiece(tor, block);
if (tr_torrentPieceIsComplete(tor, p))
{
@ -3470,18 +3403,14 @@ bool tr_torrentFindFile2(tr_torrent const* tor, tr_file_index_t fileNum, char co
TR_ASSERT(fileNum < tor->info.fileCount);
char* part = nullptr;
tr_file const* file;
char const* b = nullptr;
char const* s = nullptr;
auto file_info = tr_sys_path_info{};
file = &tor->info.files[fileNum];
tr_file const* const file = &tor->info.files[fileNum];
/* look in the download dir... */
if (b == nullptr)
{
find_file_in_dir(file->name, tor->downloadDir, &b, &s, &file_info);
}
char const* b = nullptr;
find_file_in_dir(file->name, tor->downloadDir, &b, &s, &file_info);
/* look in the incomplete dir... */
if (b == nullptr && tor->incompleteDir != nullptr)
@ -3529,10 +3458,10 @@ bool tr_torrentFindFile2(tr_torrent const* tor, tr_file_index_t fileNum, char co
char* tr_torrentFindFile(tr_torrent const* tor, tr_file_index_t fileNum)
{
char* subpath;
char* ret = nullptr;
char const* base;
char const* base = nullptr;
char* subpath = nullptr;
if (tr_torrentFindFile2(tor, fileNum, &base, &subpath, nullptr))
{
ret = tr_buildPath(base, subpath, nullptr);
@ -3747,12 +3676,10 @@ static bool renameArgsAreValid(char const* oldpath, char const* newname)
static tr_file_index_t* renameFindAffectedFiles(tr_torrent* tor, char const* oldpath, size_t* setme_n)
{
size_t n;
size_t oldpath_len;
auto n = size_t{};
tr_file_index_t* indices = tr_new0(tr_file_index_t, tor->info.fileCount);
n = 0;
oldpath_len = strlen(oldpath);
auto const oldpath_len = strlen(oldpath);
for (tr_file_index_t i = 0; i < tor->info.fileCount; ++i)
{
@ -3771,20 +3698,11 @@ static tr_file_index_t* renameFindAffectedFiles(tr_torrent* tor, char const* old
static int renamePath(tr_torrent* tor, char const* oldpath, char const* newname)
{
char* src;
char const* base;
int err = 0;
if (!tr_torrentIsSeed(tor) && tor->incompleteDir != nullptr)
{
base = tor->incompleteDir;
}
else
{
base = tor->downloadDir;
}
char const* const base = !tr_torrentIsSeed(tor) && tor->incompleteDir != nullptr ? tor->incompleteDir : tor->downloadDir;
src = tr_buildPath(base, oldpath, nullptr);
char* src = tr_buildPath(base, oldpath, nullptr);
if (!tr_sys_path_exists(src, nullptr)) /* check for it as a partial */
{
@ -3795,22 +3713,13 @@ static int renamePath(tr_torrent* tor, char const* oldpath, char const* newname)
if (tr_sys_path_exists(src, nullptr))
{
int tmp;
bool tgt_exists;
char* parent = tr_sys_path_dirname(src, nullptr);
char* tgt;
char* const tgt = tr_str_has_suffix(src, ".part") ?
tr_strdup_printf("%s" TR_PATH_DELIMITER_STR "%s.part", parent, newname) :
tr_buildPath(parent, newname, nullptr);
if (tr_str_has_suffix(src, ".part"))
{
tgt = tr_strdup_printf("%s" TR_PATH_DELIMITER_STR "%s.part", parent, newname);
}
else
{
tgt = tr_buildPath(parent, newname, nullptr);
}
tmp = errno;
tgt_exists = tr_sys_path_exists(tgt, nullptr);
auto tmp = errno;
bool const tgt_exists = tr_sys_path_exists(tgt, nullptr);
errno = tmp;
if (!tgt_exists)
@ -3839,7 +3748,7 @@ static int renamePath(tr_torrent* tor, char const* oldpath, char const* newname)
static void renameTorrentFileString(tr_torrent* tor, char const* oldpath, char const* newname, tr_file_index_t fileIndex)
{
char* name;
char* name = nullptr;
tr_file* file = &tor->info.files[fileIndex];
size_t const oldpath_len = strlen(oldpath);
@ -3917,10 +3826,8 @@ static void torrentRenamePath(void* vdata)
}
else
{
size_t n;
tr_file_index_t* file_indices;
file_indices = renameFindAffectedFiles(tor, oldpath, &n);
auto n = size_t{};
tr_file_index_t* const file_indices = renameFindAffectedFiles(tor, oldpath, &n);
if (n == 0)
{
@ -3978,9 +3885,7 @@ void tr_torrentRenamePath(
tr_torrent_rename_done_func callback,
void* callback_user_data)
{
struct rename_data* data;
data = tr_new0(struct rename_data, 1);
auto* const data = tr_new0(struct rename_data, 1);
data->tor = tor;
data->oldpath = tr_strdup(oldpath);
data->newname = tr_strdup(newname);