Skip to content

Commit

Permalink
Fix Clang warning -Wtautological-type-limit-compare
Browse files Browse the repository at this point in the history
Potentially we could use `concept` to restrict the input types to unsigned integers. Though this is a private implementation function called from only one place, so maybe not necessary to be fully generic here.
  • Loading branch information
DanRStevens committed Mar 1, 2025
1 parent ded192e commit 21a6e49
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions NAS2D/Filesystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,20 @@ namespace
{
return std::error_code{errno, std::generic_category()}.message();
}


template <typename ToType, typename FromType>
auto safeConvert(FromType value)
{
if constexpr (std::numeric_limits<FromType>::max() > std::numeric_limits<ToType>::max())
{
if (value > std::numeric_limits<ToType>::max())
{
throw std::runtime_error("Value is too large to convert to destination type: " + std::to_string(value));
}
}
return static_cast<ToType>(value);
}
}


Expand Down Expand Up @@ -315,14 +329,7 @@ std::string Filesystem::readFile(const std::filesystem::path& filename) const
}

const auto fileSize = std::filesystem::file_size(filePath);
if constexpr (std::numeric_limits<decltype(fileSize)>::max() > std::numeric_limits<std::string::size_type>::max())
{
if (fileSize > std::numeric_limits<std::string::size_type>::max())
{
throw std::runtime_error("Error opening file: " + filename.string() + " : File too large");
}
}
const auto bufferSize = static_cast<std::string::size_type>(fileSize);
const auto bufferSize = safeConvert<std::string::size_type>(fileSize);

std::string fileBuffer;
fileBuffer.resize(bufferSize);
Expand Down

0 comments on commit 21a6e49

Please sign in to comment.