From 326315ff3118965dec129366769e8f3d53706589 Mon Sep 17 00:00:00 2001 From: Stephane JANEL Date: Wed, 17 Sep 2025 00:06:44 +0200 Subject: [PATCH] Implicit conversions clean-up --- trantor/net/inner/Socket.cc | 8 ++-- trantor/utils/Date.cc | 46 ++++++++++----------- trantor/utils/LogStream.cc | 41 ++++++++++--------- trantor/utils/LogStream.h | 28 ++++++++----- trantor/utils/Logger.cc | 4 +- trantor/utils/Logger.h | 4 +- trantor/utils/MsgBuffer.cc | 6 +-- trantor/utils/MsgBuffer.h | 2 +- trantor/utils/Utilities.cc | 79 ++++++++++++++++++++++--------------- 9 files changed, 120 insertions(+), 98 deletions(-) diff --git a/trantor/net/inner/Socket.cc b/trantor/net/inner/Socket.cc index 2aff5a03..72ead949 100755 --- a/trantor/net/inner/Socket.cc +++ b/trantor/net/inner/Socket.cc @@ -113,7 +113,7 @@ void Socket::closeWrite() int Socket::read(char *buffer, uint64_t len) { #ifndef _WIN32 - return ::read(sockFd_, buffer, len); + return static_cast(::read(sockFd_, buffer, len)); #else return recv(sockFd_, buffer, static_cast(len), 0); #endif @@ -121,8 +121,7 @@ int Socket::read(char *buffer, uint64_t len) struct sockaddr_in6 Socket::getLocalAddr(int sockfd) { - struct sockaddr_in6 localaddr; - memset(&localaddr, 0, sizeof(localaddr)); + struct sockaddr_in6 localaddr{}; socklen_t addrlen = static_cast(sizeof localaddr); if (::getsockname(sockfd, static_cast((void *)(&localaddr)), @@ -135,8 +134,7 @@ struct sockaddr_in6 Socket::getLocalAddr(int sockfd) struct sockaddr_in6 Socket::getPeerAddr(int sockfd) { - struct sockaddr_in6 peeraddr; - memset(&peeraddr, 0, sizeof(peeraddr)); + struct sockaddr_in6 peeraddr{}; socklen_t addrlen = static_cast(sizeof peeraddr); if (::getpeername(sockfd, static_cast((void *)(&peeraddr)), diff --git a/trantor/utils/Date.cc b/trantor/utils/Date.cc index 26acf794..e15ba131 100644 --- a/trantor/utils/Date.cc +++ b/trantor/utils/Date.cc @@ -53,20 +53,21 @@ const Date Date::date() { #ifndef _WIN32 struct timeval tv; - gettimeofday(&tv, NULL); + gettimeofday(&tv, nullptr); int64_t seconds = tv.tv_sec; return Date(seconds * MICRO_SECONDS_PER_SEC + tv.tv_usec); #else timeval tv; - gettimeofday(&tv, NULL); + gettimeofday(&tv, nullptr); int64_t seconds = tv.tv_sec; return Date(seconds * MICRO_SECONDS_PER_SEC + tv.tv_usec); #endif } const Date Date::after(double second) const { - return Date(static_cast(microSecondsSinceEpoch_ + - second * MICRO_SECONDS_PER_SEC)); + return Date(microSecondsSinceEpoch_ + + static_cast( + second * static_cast(MICRO_SECONDS_PER_SEC))); } const Date Date::roundSecond() const { @@ -86,7 +87,7 @@ const Date Date::roundDay() const t.tm_hour = 0; t.tm_min = 0; t.tm_sec = 0; - return Date(mktime(&t) * MICRO_SECONDS_PER_SEC); + return Date(static_cast(mktime(&t)) * MICRO_SECONDS_PER_SEC); } struct tm Date::tmStruct() const { @@ -281,8 +282,8 @@ std::string Date::toDbString() const Date Date::fromDbStringLocal(const std::string &datetime) { - unsigned int year = {0}, month = {0}, day = {0}, hour = {0}, minute = {0}, - second = {0}, microSecond = {0}; + unsigned int year = 0U, month = 0U, day = 0U, hour = 0U, minute = 0U, + second = 0U, microSecond = 0U; std::vector &&v = splitString(datetime, " "); if (v.size() == 0) @@ -315,16 +316,16 @@ Date Date::fromDbStringLocal(const std::string &datetime) // Format YYYY-MM-DD HH:MM:SS[.UUUUUU] is given try { - year = std::stol(date[0]); - month = std::stol(date[1]); - day = std::stol(date[2]); + year = static_cast(std::stoul(date[0])); + month = static_cast(std::stoul(date[1])); + day = static_cast(std::stoul(date[2])); std::vector time = splitString(v[1], ":"); if (2 < time.size()) { - hour = std::stol(time[0]); - minute = std::stol(time[1]); + hour = static_cast(std::stoul(time[0])); + minute = static_cast(std::stoul(time[1])); auto seconds = splitString(time[2], "."); - second = std::stol(seconds[0]); + second = static_cast(std::stoul(seconds[0])); if (1 < seconds.size()) { if (seconds[1].length() > 6) @@ -335,7 +336,8 @@ Date Date::fromDbStringLocal(const std::string &datetime) { seconds[1].append(6 - seconds[1].length(), '0'); } - microSecond = std::stol(seconds[1]); + microSecond = + static_cast(std::stoul(seconds[1])); } } } @@ -358,7 +360,7 @@ Date Date::fromDbString(const std::string &datetime) std::string Date::toCustomFormattedStringLocal(const std::string &fmtStr, bool showMicroseconds) const { - char buf[256] = {0}; + char buf[256]{}; time_t seconds = static_cast(microSecondsSinceEpoch_ / MICRO_SECONDS_PER_SEC); struct tm tm_time; @@ -370,7 +372,7 @@ std::string Date::toCustomFormattedStringLocal(const std::string &fmtStr, strftime(buf, sizeof(buf), fmtStr.c_str(), &tm_time); if (!showMicroseconds) return std::string(buf); - char decimals[12] = {0}; + char decimals[12]{}; int microseconds = static_cast(microSecondsSinceEpoch_ % MICRO_SECONDS_PER_SEC); snprintf(decimals, sizeof(decimals), ".%06d", microseconds); @@ -388,12 +390,12 @@ Date::Date(unsigned int year, memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; time_t epoch; - tm.tm_year = year - 1900; - tm.tm_mon = month - 1; - tm.tm_mday = day; - tm.tm_hour = hour; - tm.tm_min = minute; - tm.tm_sec = second; + tm.tm_year = static_cast(year - 1900); + tm.tm_mon = static_cast(month - 1); + tm.tm_mday = static_cast(day); + tm.tm_hour = static_cast(hour); + tm.tm_min = static_cast(minute); + tm.tm_sec = static_cast(second); epoch = mktime(&tm); microSecondsSinceEpoch_ = static_cast(epoch) * MICRO_SECONDS_PER_SEC + microSecond; diff --git a/trantor/utils/LogStream.cc b/trantor/utils/LogStream.cc index bbb6bd56..a62a3298 100644 --- a/trantor/utils/LogStream.cc +++ b/trantor/utils/LogStream.cc @@ -21,7 +21,6 @@ #include #include #include -#include using namespace trantor; using namespace trantor::detail; @@ -30,33 +29,32 @@ namespace trantor { namespace detail { -const char digits[] = "9876543210123456789"; -const char *zero = digits + 9; +constexpr char digits[] = "9876543210123456789"; +constexpr const char *const zero = digits + 9; -const char digitsHex[] = "0123456789ABCDEF"; +constexpr const char digitsHex[] = "0123456789ABCDEF"; // Efficient Integer to String Conversions, by Matthew Wilson. template -size_t convert(char buf[], T value) +size_t convert(char *buf, T value) { - T i = value; + if (value < 0) + { + *buf++ = '-'; + } char *p = buf; do { - int lsd = static_cast(i % 10); - i /= 10; + int lsd = static_cast(value % 10); + value /= 10; *p++ = zero[lsd]; - } while (i != 0); + } while (value != 0); - if (value < 0) - { - *p++ = '-'; - } *p = '\0'; std::reverse(buf, p); - return p - buf; + return static_cast(p - buf); } size_t convertHex(char buf[], uintptr_t value) @@ -74,7 +72,7 @@ size_t convertHex(char buf[], uintptr_t value) *p = '\0'; std::reverse(buf, p); - return p - buf; + return static_cast(p - buf); } template class FixedBuffer; @@ -211,7 +209,7 @@ LogStream &LogStream::operator<<(const double &v) if (buffer_.avail() >= kMaxNumericSize) { int len = snprintf(buffer_.current(), kMaxNumericSize, "%.12g", v); - buffer_.add(len); + buffer_.add(static_cast(len)); return *this; } else @@ -222,7 +220,7 @@ LogStream &LogStream::operator<<(const double &v) auto oldLen = exBuffer_.length(); exBuffer_.resize(oldLen + kMaxNumericSize); int len = snprintf(&(exBuffer_[oldLen]), kMaxNumericSize, "%.12g", v); - exBuffer_.resize(oldLen + len); + exBuffer_.resize(oldLen + static_cast(len)); return *this; } @@ -234,7 +232,7 @@ LogStream &LogStream::operator<<(const long double &v) if (buffer_.avail() >= kMaxNumericSize) { int len = snprintf(buffer_.current(), kMaxNumericSize, "%.12Lg", v); - buffer_.add(len); + buffer_.add(static_cast(len)); return *this; } else @@ -245,15 +243,16 @@ LogStream &LogStream::operator<<(const long double &v) auto oldLen = exBuffer_.length(); exBuffer_.resize(oldLen + kMaxNumericSize); int len = snprintf(&(exBuffer_[oldLen]), kMaxNumericSize, "%.12Lg", v); - exBuffer_.resize(oldLen + len); + exBuffer_.resize(oldLen + static_cast(len)); return *this; } template Fmt::Fmt(const char *fmt, T val) { - length_ = snprintf(buf_, sizeof buf_, fmt, val); - assert(static_cast(length_) < sizeof buf_); + length_ = + static_cast(snprintf(buf_, sizeof(buf_), fmt, val)); + assert(static_cast(length_) < sizeof(buf_)); } // Explicit instantiations diff --git a/trantor/utils/LogStream.h b/trantor/utils/LogStream.h index d6684345..1ad3297c 100644 --- a/trantor/utils/LogStream.h +++ b/trantor/utils/LogStream.h @@ -21,13 +21,20 @@ #include #include // memcpy #include +#include namespace trantor { namespace detail { +#if (__cplusplus >= 201703L) +// Note: in C++17, static should be replaced by inline +inline constexpr size_t kSmallBuffer{4000}; +inline constexpr size_t kLargeBuffer{4000 * 1000}; +#else static constexpr size_t kSmallBuffer{4000}; static constexpr size_t kLargeBuffer{4000 * 1000}; +#endif template class TRANTOR_EXPORT FixedBuffer : NonCopyable @@ -38,6 +45,11 @@ class TRANTOR_EXPORT FixedBuffer : NonCopyable setCookie(cookieStart); } + FixedBuffer(const FixedBuffer &) = delete; + FixedBuffer &operator=(const FixedBuffer &) = delete; + FixedBuffer(FixedBuffer &&) = delete; + FixedBuffer &operator=(FixedBuffer &&) = delete; + ~FixedBuffer() { setCookie(cookieEnd); @@ -45,7 +57,7 @@ class TRANTOR_EXPORT FixedBuffer : NonCopyable bool append(const char * /*restrict*/ buf, size_t len) { - if ((size_t)(avail()) > len) + if (static_cast(avail()) > len) { memcpy(cur_, buf, len); cur_ += len; @@ -58,9 +70,9 @@ class TRANTOR_EXPORT FixedBuffer : NonCopyable { return data_; } - int length() const + size_t length() const { - return static_cast(cur_ - data_); + return static_cast(cur_ - data_); } // write to data_ directly @@ -97,8 +109,6 @@ class TRANTOR_EXPORT FixedBuffer : NonCopyable { return std::string(data_, length()); } - // StringPiece toStringPiece() const { return StringPiece(data_, length()); - // } private: const char *end() const @@ -154,8 +164,6 @@ class TRANTOR_EXPORT LogStream : NonCopyable return *this; } - // self& operator<<(signed char); - // self& operator<<(unsigned char); template self &operator<<(const char (&buf)[N]) { @@ -248,7 +256,7 @@ class TRANTOR_EXPORT LogStream : NonCopyable std::string exBuffer_; }; -class TRANTOR_EXPORT Fmt // : boost::noncopyable +class TRANTOR_EXPORT Fmt { public: template @@ -258,14 +266,14 @@ class TRANTOR_EXPORT Fmt // : boost::noncopyable { return buf_; } - int length() const + uint8_t length() const { return length_; } private: char buf_[48]; - int length_; + uint8_t length_; }; inline LogStream &operator<<(LogStream &s, const Fmt &fmt) diff --git a/trantor/utils/Logger.cc b/trantor/utils/Logger.cc index 56f0349a..5df6261a 100644 --- a/trantor/utils/Logger.cc +++ b/trantor/utils/Logger.cc @@ -85,7 +85,7 @@ inline LogStream &operator<<(LogStream &s, T v) inline LogStream &operator<<(LogStream &s, const Logger::SourceFile &v) { - s.append(v.data_, v.size_); + s.append(v.data_, static_cast(v.size_)); return s; } @@ -444,7 +444,7 @@ RawLogger::~RawLogger() } else { - auto &oFunc = Logger::outputFunc_(index_); + auto &oFunc = Logger::outputFunc_(static_cast(index_)); if (!oFunc) return; oFunc(logStream_.bufferData(), logStream_.bufferLength()); diff --git a/trantor/utils/Logger.h b/trantor/utils/Logger.h index 16d040aa..d58822ad 100644 --- a/trantor/utils/Logger.h +++ b/trantor/utils/Logger.h @@ -133,8 +133,8 @@ class TRANTOR_EXPORT Logger : public NonCopyable } else { - outputFunc_(index) = outputFunc; - flushFunc_(index) = flushFunc; + outputFunc_(static_cast(index)) = outputFunc; + flushFunc_(static_cast(index)) = flushFunc; } } diff --git a/trantor/utils/MsgBuffer.cc b/trantor/utils/MsgBuffer.cc index 038f7ea7..627c8a17 100644 --- a/trantor/utils/MsgBuffer.cc +++ b/trantor/utils/MsgBuffer.cc @@ -151,7 +151,7 @@ ssize_t MsgBuffer::readFd(int fd, int *retErrno) struct iovec vec[2]; size_t writable = writableBytes(); vec[0].iov_base = begin() + tail_; - vec[0].iov_len = static_cast(writable); + vec[0].iov_len = writable; vec[1].iov_base = extBuffer; vec[1].iov_len = sizeof(extBuffer); const int iovcnt = (writable < sizeof extBuffer) ? 2 : 1; @@ -162,12 +162,12 @@ ssize_t MsgBuffer::readFd(int fd, int *retErrno) } else if (static_cast(n) <= writable) { - tail_ += n; + tail_ += static_cast(n); } else { tail_ = buffer_.size(); - append(extBuffer, n - writable); + append(extBuffer, static_cast(n) - writable); } return n; } diff --git a/trantor/utils/MsgBuffer.h b/trantor/utils/MsgBuffer.h index 4e8600cf..32fd995c 100644 --- a/trantor/utils/MsgBuffer.h +++ b/trantor/utils/MsgBuffer.h @@ -284,7 +284,7 @@ class TRANTOR_EXPORT MsgBuffer { assert(peek() <= end); assert(end <= beginWrite()); - retrieve(end - peek()); + retrieve(static_cast(end - peek())); } /** diff --git a/trantor/utils/Utilities.cc b/trantor/utils/Utilities.cc index 665253d2..d2a427db 100644 --- a/trantor/utils/Utilities.cc +++ b/trantor/utils/Utilities.cc @@ -161,17 +161,23 @@ std::string toUtf8(const std::wstring &wstr) std::string strTo; #ifdef _WIN32 - int nSizeNeeded = ::WideCharToMultiByte( - CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); + int nSizeNeeded = ::WideCharToMultiByte(CP_UTF8, + 0, + &wstr[0], + static_cast(wstr.size()), + nullptr, + 0, + nullptr, + nullptr); strTo.resize(nSizeNeeded, 0); ::WideCharToMultiByte(CP_UTF8, 0, &wstr[0], - (int)wstr.size(), + static_cast(wstr.size()), &strTo[0], nSizeNeeded, - NULL, - NULL); + nullptr, + nullptr); #elif __cplusplus < 201103L || __cplusplus >= 201703L strTo = utf16Toutf8(wstr); #else // c++11 to c++14 @@ -186,11 +192,15 @@ std::wstring fromUtf8(const std::string &str) return {}; std::wstring wstrTo; #ifdef _WIN32 - int nSizeNeeded = - ::MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0); + int nSizeNeeded = ::MultiByteToWideChar( + CP_UTF8, 0, &str[0], static_cast(str.size()), nullptr, 0); wstrTo.resize(nSizeNeeded, 0); - ::MultiByteToWideChar( - CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], nSizeNeeded); + ::MultiByteToWideChar(CP_UTF8, + 0, + &str[0], + static_cast(str.size()), + &wstrTo[0], + nSizeNeeded); #elif __cplusplus < 201103L || __cplusplus >= 201703L wstrTo = utf8Toutf16(str); #else // c++11 to c++14 @@ -271,16 +281,16 @@ bool verifySslName(const std::string &certName, const std::string &hostname) { // compare if `hostname` ends with `certName` but without the leftmost // should be fine as domain names can't be that long - intmax_t hostnameIdx = hostname.size() - 1; - intmax_t certNameIdx = certName.size() - 1; + intmax_t hostnameIdx = static_cast(hostname.size()) - 1; + intmax_t certNameIdx = static_cast(certName.size()) - 1; while (hostnameIdx >= 0 && certNameIdx != 0) { if (hostname[hostnameIdx] != certName[certNameIdx]) { return false; } - hostnameIdx--; - certNameIdx--; + --hostnameIdx; + --certNameIdx; } if (certNameIdx != 0) { @@ -322,8 +332,8 @@ bool verifySslName(const std::string &certName, const std::string &hostname) return false; } } - intmax_t hostnameIdx = hostFirstDot - 1; - intmax_t certNameIdx = firstDot - 1; + intmax_t hostnameIdx = static_cast(hostFirstDot) - 1; + intmax_t certNameIdx = static_cast(firstDot) - 1; while (hostnameIdx >= 0 && certNameIdx >= 0 && certName[certNameIdx] != '*') { @@ -331,8 +341,8 @@ bool verifySslName(const std::string &certName, const std::string &hostname) { return false; } - hostnameIdx--; - certNameIdx--; + --hostnameIdx; + --certNameIdx; } return true; } @@ -357,9 +367,9 @@ Hash128 md5(const void *data, size_t len) { MD5_CTX ctx; trantor_md5_init(&ctx); - trantor_md5_update(&ctx, (const unsigned char *)data, len); + trantor_md5_update(&ctx, static_cast(data), len); Hash128 hash; - trantor_md5_final(&ctx, (unsigned char *)&hash); + trantor_md5_final(&ctx, reinterpret_cast(&hash)); return hash; } @@ -367,9 +377,9 @@ Hash160 sha1(const void *data, size_t len) { SHA1_CTX ctx; trantor_sha1_init(&ctx); - trantor_sha1_update(&ctx, (const unsigned char *)data, len); + trantor_sha1_update(&ctx, static_cast(data), len); Hash160 hash; - trantor_sha1_final((unsigned char *)&hash, &ctx); + trantor_sha1_final(reinterpret_cast(&hash), &ctx); return hash; } @@ -377,23 +387,26 @@ Hash256 sha256(const void *data, size_t len) { SHA256_CTX ctx; trantor_sha256_init(&ctx); - trantor_sha256_update(&ctx, (const unsigned char *)data, len); + trantor_sha256_update(&ctx, static_cast(data), len); Hash256 hash; - trantor_sha256_final(&ctx, (unsigned char *)&hash); + trantor_sha256_final(&ctx, reinterpret_cast(&hash)); return hash; } Hash256 sha3(const void *data, size_t len) { Hash256 hash; - trantor_sha3((const unsigned char *)data, len, &hash, sizeof(hash)); + trantor_sha3(static_cast(data), + len, + &hash, + sizeof(hash)); return hash; } Hash256 blake2b(const void *data, size_t len) { Hash256 hash; - trantor_blake2b(&hash, sizeof(hash), data, len, NULL, 0); + trantor_blake2b(&hash, sizeof(hash), data, len, nullptr, 0); return hash; } #endif @@ -404,7 +417,7 @@ std::string toHexString(const void *data, size_t len) str.resize(len * 2); for (size_t i = 0; i < len; i++) { - unsigned char c = ((const unsigned char *)data)[i]; + auto c = static_cast(const_cast(data))[i]; str[i * 2] = "0123456789ABCDEF"[c >> 4]; str[i * 2 + 1] = "0123456789ABCDEF"[c & 0xf]; } @@ -526,7 +539,7 @@ bool secureRandomBytes(void *data, size_t len) uint32_t timeLo, timeHi; asm volatile("rdtimeh %0" : "=r"(timeHi)); asm volatile("rdtime %0" : "=r"(timeLo)); - state.time = (uint64_t)timeHi << 32 | timeLo; + state.time = (static_cast(timeHi) << 32) | timeLo; #elif defined(__s390__) // both s390 and s390x asm volatile("stck %0" : "=Q"(state.time)); #else @@ -542,7 +555,7 @@ bool secureRandomBytes(void *data, size_t len) // This code works on both 32-bit and 64-bit systems. As well as big-endian // and little-endian systems. void *stack_ptr = &now; - uint32_t *stack_ptr32 = (uint32_t *)&stack_ptr; + auto *stack_ptr32 = reinterpret_cast(&stack_ptr); uint32_t garbage = *stack_ptr32; static_assert(sizeof(void *) >= sizeof(uint32_t), "pointer size too small"); for (size_t i = 1; i < sizeof(void *) / sizeof(uint32_t); i++) @@ -556,16 +569,18 @@ bool secureRandomBytes(void *data, size_t len) for (size_t i = 0; i < len / sizeof(Hash256); i++) { auto hash = blake2b(&state, sizeof(state)); - memcpy((char *)data + i * sizeof(hash), &hash, sizeof(hash)); + std::memcpy(static_cast(data) + i * sizeof(hash), + &hash, + sizeof(hash)); state.counter++; state.prev = hash; } if (len % sizeof(Hash256) != 0) { auto hash = blake2b(&state, sizeof(state)); - memcpy((char *)data + len - len % sizeof(hash), - &hash, - len % sizeof(hash)); + std::memcpy(static_cast(data) + len - len % sizeof(hash), + &hash, + len % sizeof(hash)); state.counter++; state.prev = hash; }