From: Christopher Dykes Date: Fri, 27 Jan 2017 02:01:31 +0000 (-0800) Subject: Make most implicit integer truncations and sign conversions explicit X-Git-Tag: v2017.03.06.00~77 X-Git-Url: http://plrg.eecs.uci.edu/git/?p=folly.git;a=commitdiff_plain;h=fa172175980b13569ba42008202a857af6e959dd Make most implicit integer truncations and sign conversions explicit Summary: This makes a large number of implicit truncations and sign conversions into explicit casts, in preparation for eventually enabling `-Wconversion` on Folly. This set of changes should have zero semantic change. This focuses on the core of Folly and leaves the tests alone for the most part. A future diff will cleanup the warnings in the tests as well. Reviewed By: yfeldblum Differential Revision: D4454096 fbshipit-source-id: af1e1831675a804ec5679266c30c1fae62e8c35c --- diff --git a/folly/AtomicHashMap-inl.h b/folly/AtomicHashMap-inl.h index 184e2b96..e0031266 100644 --- a/folly/AtomicHashMap-inl.h +++ b/folly/AtomicHashMap-inl.h @@ -24,19 +24,26 @@ namespace folly { // AtomicHashMap constructor -- Atomic wrapper that allows growth // This class has a lot of overhead (184 Bytes) so only use for big maps -template -AtomicHashMap:: -AtomicHashMap(size_t finalSizeEst, const Config& config) - : kGrowthFrac_(config.growthFactor < 0 ? - 1.0 - config.maxLoadFactor : config.growthFactor) { - CHECK(config.maxLoadFactor > 0.0 && config.maxLoadFactor < 1.0); +template < + typename KeyT, + typename ValueT, + typename HashFcn, + typename EqualFcn, + typename Allocator, + typename ProbeFcn, + typename KeyConvertFcn> +AtomicHashMap< + KeyT, + ValueT, + HashFcn, + EqualFcn, + Allocator, + ProbeFcn, + KeyConvertFcn>::AtomicHashMap(size_t finalSizeEst, const Config& config) + : kGrowthFrac_( + config.growthFactor < 0 ? 1.0f - config.maxLoadFactor + : config.growthFactor) { + CHECK(config.maxLoadFactor > 0.0f && config.maxLoadFactor < 1.0f); subMaps_[0].store(SubMap::create(finalSizeEst, config).release(), std::memory_order_relaxed); auto subMapCount = kNumSubMaps_; @@ -128,7 +135,7 @@ insertInternal(LookupKeyT key, ArgTs&&... vCtorArgs) { size_t numCellsAllocated = (size_t) (primarySubMap->capacity_ * std::pow(1.0 + kGrowthFrac_, nextMapIdx - 1)); - size_t newSize = (int) (numCellsAllocated * kGrowthFrac_); + size_t newSize = size_t(numCellsAllocated * kGrowthFrac_); DCHECK(subMaps_[nextMapIdx].load(std::memory_order_relaxed) == (SubMap*)kLockedPtr_); // create a new map using the settings stored in the first map @@ -232,7 +239,8 @@ AtomicHashMapcapacity_)) { return SimpleRetT(0, ret.idx, ret.success); } - int const numMaps = numMapsAllocated_.load(std::memory_order_acquire); + const unsigned int numMaps = + numMapsAllocated_.load(std::memory_order_acquire); FOR_EACH_RANGE(i, 1, numMaps) { // Check each map successively. If one succeeds, we're done! SubMap* thisMap = subMaps_[i].load(std::memory_order_relaxed); diff --git a/folly/AtomicHashMap.h b/folly/AtomicHashMap.h index 0ed09224..ef27f860 100644 --- a/folly/AtomicHashMap.h +++ b/folly/AtomicHashMap.h @@ -197,7 +197,8 @@ typedef AtomicHashArray avail && maxSize < avail) { // we'll do our best @@ -454,13 +454,13 @@ struct AtomicUnorderedInsertMap { /// can specialize it differently during deterministic testing IndexType allocationAttempt(IndexType start, IndexType tries) const { if (LIKELY(tries < 8 && start + tries < numSlots_)) { - return start + tries; + return IndexType(start + tries); } else { IndexType rv; if (sizeof(IndexType) <= 4) { - rv = folly::Random::rand32(numSlots_); + rv = IndexType(folly::Random::rand32(numSlots_)); } else { - rv = folly::Random::rand64(numSlots_); + rv = IndexType(folly::Random::rand64(numSlots_)); } assert(rv < numSlots_); return rv; diff --git a/folly/Benchmark.cpp b/folly/Benchmark.cpp index aada48b5..4ec24c72 100644 --- a/folly/Benchmark.cpp +++ b/folly/Benchmark.cpp @@ -128,14 +128,14 @@ static double runBenchmarkGetNSPerIteration(const BenchmarkFun& fun, CHECK_EQ(0, ts.tv_sec) << "Clock sucks."; CHECK_LT(0, ts.tv_nsec) << "Clock too fast for its own good."; CHECK_EQ(1, ts.tv_nsec) << "Clock too coarse, upgrade your kernel."; - resolutionInNs = ts.tv_nsec; + resolutionInNs = uint64_t(ts.tv_nsec); } // We choose a minimum minimum (sic) of 100,000 nanoseconds, but if // the clock resolution is worse than that, it will be larger. In // essence we're aiming at making the quantization noise 0.01%. - static const auto minNanoseconds = - max(FLAGS_bm_min_usec * 1000UL, - min(resolutionInNs * 100000, 1000000000ULL)); + static const auto minNanoseconds = max( + uint64_t(FLAGS_bm_min_usec) * 1000ULL, + min(resolutionInNs * 100000ULL, 1000000000ULL)); // We do measurements in several epochs and take the minimum, to // account for jitter. @@ -150,9 +150,9 @@ static double runBenchmarkGetNSPerIteration(const BenchmarkFun& fun, size_t actualEpochs = 0; for (; actualEpochs < epochs; ++actualEpochs) { - const auto maxIters = FLAGS_bm_max_iters; - for (unsigned int n = FLAGS_bm_min_iters; n < maxIters; n *= 2) { - auto const nsecsAndIter = fun(n); + const auto maxIters = uint32_t(FLAGS_bm_max_iters); + for (auto n = uint32_t(FLAGS_bm_min_iters); n < maxIters; n *= 2) { + auto const nsecsAndIter = fun(static_cast(n)); if (nsecsAndIter.first < minNanoseconds) { continue; } diff --git a/folly/Benchmark.h b/folly/Benchmark.h index d1ed1211..e9547987 100644 --- a/folly/Benchmark.h +++ b/folly/Benchmark.h @@ -70,14 +70,12 @@ void addBenchmarkImpl(const char* file, inline uint64_t timespecDiff(timespec end, timespec start) { if (end.tv_sec == start.tv_sec) { assert(end.tv_nsec >= start.tv_nsec); - return end.tv_nsec - start.tv_nsec; + return uint64_t(end.tv_nsec - start.tv_nsec); } assert(end.tv_sec > start.tv_sec); auto diff = uint64_t(end.tv_sec - start.tv_sec); - assert(diff < - std::numeric_limits::max() / 1000000000UL); - return diff * 1000000000UL - + end.tv_nsec - start.tv_nsec; + assert(diff < std::numeric_limits::max() / 1000000000ULL); + return diff * 1000000000ULL + end.tv_nsec - start.tv_nsec; } /** diff --git a/folly/Bits.h b/folly/Bits.h index e4b1b5ea..7e59ce30 100644 --- a/folly/Bits.h +++ b/folly/Bits.h @@ -94,7 +94,7 @@ typename std::enable_if< sizeof(T) <= sizeof(unsigned int)), unsigned int>::type findFirstSet(T x) { - return __builtin_ffs(x); + return static_cast(__builtin_ffs(static_cast(x))); } template @@ -106,7 +106,7 @@ typename std::enable_if< sizeof(T) <= sizeof(unsigned long)), unsigned int>::type findFirstSet(T x) { - return __builtin_ffsl(x); + return static_cast(__builtin_ffsl(static_cast(x))); } template @@ -118,7 +118,7 @@ typename std::enable_if< sizeof(T) <= sizeof(unsigned long long)), unsigned int>::type findFirstSet(T x) { - return __builtin_ffsll(x); + return static_cast(__builtin_ffsll(static_cast(x))); } template @@ -217,7 +217,7 @@ inline typename std::enable_if< sizeof(T) <= sizeof(unsigned int)), size_t>::type popcount(T x) { - return detail::popcount(x); + return size_t(detail::popcount(x)); } template @@ -228,7 +228,7 @@ inline typename std::enable_if< sizeof(T) <= sizeof(unsigned long long)), size_t>::type popcount(T x) { - return detail::popcountll(x); + return size_t(detail::popcountll(x)); } /** @@ -429,7 +429,7 @@ class BitIterator void advance(ssize_t n) { size_t bpb = bitsPerBlock(); - ssize_t blocks = n / bpb; + ssize_t blocks = n / ssize_t(bpb); bitOffset_ += n % bpb; if (bitOffset_ >= bpb) { bitOffset_ -= bpb; @@ -457,9 +457,9 @@ class BitIterator } ssize_t distance_to(const BitIterator& other) const { - return - (other.base_reference() - this->base_reference()) * bitsPerBlock() + - other.bitOffset_ - bitOffset_; + return ssize_t( + (other.base_reference() - this->base_reference()) * bitsPerBlock() + + other.bitOffset_ - bitOffset_); } size_t bitOffset_; diff --git a/folly/ConcurrentSkipList-inl.h b/folly/ConcurrentSkipList-inl.h index 8b6f77f6..cf04ee72 100644 --- a/folly/ConcurrentSkipList-inl.h +++ b/folly/ConcurrentSkipList-inl.h @@ -59,7 +59,7 @@ class SkipListNode : private boost::noncopyable { height * sizeof(std::atomic); auto* node = static_cast(alloc.allocate(size)); // do placement new - new (node) SkipListNode(height, std::forward(data), isHead); + new (node) SkipListNode(uint8_t(height), std::forward(data), isHead); return node; } @@ -117,13 +117,13 @@ class SkipListNode : private boost::noncopyable { bool isHeadNode() const { return getFlags() & IS_HEAD_NODE; } void setIsHeadNode() { - setFlags(getFlags() | IS_HEAD_NODE); + setFlags(uint16_t(getFlags() | IS_HEAD_NODE)); } void setFullyLinked() { - setFlags(getFlags() | FULLY_LINKED); + setFlags(uint16_t(getFlags() | FULLY_LINKED)); } void setMarkedForRemoval() { - setFlags(getFlags() | MARKED_FOR_REMOVAL); + setFlags(uint16_t(getFlags() | MARKED_FOR_REMOVAL)); } private: diff --git a/folly/ConcurrentSkipList.h b/folly/ConcurrentSkipList.h index a1193837..7d5cb958 100644 --- a/folly/ConcurrentSkipList.h +++ b/folly/ConcurrentSkipList.h @@ -718,7 +718,7 @@ class ConcurrentSkipList::Skipper { } int max_layer = maxLayer(); for (int i = 0; i < max_layer; ++i) { - hints_[i] = i + 1; + hints_[i] = uint8_t(i + 1); } hints_[max_layer] = max_layer; } diff --git a/folly/Conv.cpp b/folly/Conv.cpp index 04f2252a..6af0f90f 100644 --- a/folly/Conv.cpp +++ b/folly/Conv.cpp @@ -269,7 +269,7 @@ Expected str_to_bool(StringPiece* src) noexcept { } bool result; - size_t len = e - b; + size_t len = size_t(e - b); switch (*b) { case '0': case '1': { @@ -361,10 +361,11 @@ Expected str_to_floating(StringPiece* src) noexcept { // want to raise an error; length will point past the last character // that was processed, so we need to check if that character was // whitespace or not. - if (length == 0 || (result == 0.0 && std::isspace((*src)[length - 1]))) { + if (length == 0 || + (result == 0.0 && std::isspace((*src)[size_t(length) - 1]))) { return makeUnexpected(ConversionCode::EMPTY_INPUT_STRING); } - src->advance(length); + src->advance(size_t(length)); return Tgt(result); } @@ -374,7 +375,7 @@ Expected str_to_floating(StringPiece* src) noexcept { // There must be non-whitespace, otherwise we would have caught this above assert(b < e); - size_t size = e - b; + size_t size = size_t(e - b); bool negative = false; if (*b == '-') { @@ -463,12 +464,12 @@ class SignedValueHandler { Expected finalize(U value) { T rv; if (negative_) { - rv = -value; + rv = T(-value); if (UNLIKELY(rv > 0)) { return makeUnexpected(ConversionCode::NEGATIVE_OVERFLOW); } } else { - rv = value; + rv = T(value); if (UNLIKELY(rv < 0)) { return makeUnexpected(ConversionCode::POSITIVE_OVERFLOW); } @@ -518,7 +519,7 @@ inline Expected digits_to( return makeUnexpected(err); } - size_t size = e - b; + size_t size = size_t(e - b); /* Although the string is entirely made of digits, we still need to * check for overflow. @@ -531,7 +532,7 @@ inline Expected digits_to( return Tgt(0); // just zeros, e.g. "0000" } if (*b != '0') { - size = e - b; + size = size_t(e - b); break; } } @@ -695,7 +696,7 @@ Expected str_to_integral(StringPiece* src) noexcept { auto res = sgn.finalize(tmp.value()); if (res.hasValue()) { - src->advance(m - src->data()); + src->advance(size_t(m - src->data())); } return res; diff --git a/folly/Exception.h b/folly/Exception.h index 220628e2..28e07938 100644 --- a/folly/Exception.h +++ b/folly/Exception.h @@ -66,7 +66,7 @@ void checkPosixError(int err, Args&&... args) { template void checkKernelError(ssize_t ret, Args&&... args) { if (UNLIKELY(ret < 0)) { - throwSystemErrorExplicit(-ret, std::forward(args)...); + throwSystemErrorExplicit(int(-ret), std::forward(args)...); } } diff --git a/folly/FBVector.h b/folly/FBVector.h index 17f9f5ee..3bdb0cf2 100644 --- a/folly/FBVector.h +++ b/folly/FBVector.h @@ -800,7 +800,7 @@ private: template fbvector(ForwardIterator first, ForwardIterator last, const Allocator& a, std::forward_iterator_tag) - : impl_(std::distance(first, last), a) + : impl_(size_type(std::distance(first, last)), a) { M_uninitialized_copy_e(first, last); } template @@ -827,7 +827,7 @@ private: template void assign(ForwardIterator first, ForwardIterator last, std::forward_iterator_tag) { - const size_t newSize = std::distance(first, last); + const auto newSize = size_type(std::distance(first, last)); if (newSize > capacity()) { impl_.reset(newSize); M_uninitialized_copy_e(first, last); @@ -1004,7 +1004,7 @@ public: return; } if (impl_.b_) - M_deallocate(impl_.b_, impl_.z_ - impl_.b_); + M_deallocate(impl_.b_, size_type(impl_.z_ - impl_.b_)); impl_.z_ = newB + newCap; impl_.e_ = newB + (impl_.e_ - impl_.b_); impl_.b_ = newB; @@ -1276,7 +1276,7 @@ private: // we have the private section first because it defines some macros void make_window(iterator position, size_type n) { // The result is guaranteed to be non-negative, so use an unsigned type: - size_type tail = std::distance(position, impl_.e_); + size_type tail = size_type(std::distance(position, impl_.e_)); if (tail <= n) { relocate_move(position + n, position, impl_.e_); @@ -1357,7 +1357,7 @@ private: // we have the private section first because it defines some macros assert(isValid(cpos)); \ } \ T* position = const_cast(cpos); \ - size_type idx = std::distance(impl_.b_, position); \ + size_type idx = size_type(std::distance(impl_.b_, position)); \ T* b; \ size_type newCap; /* intentionally uninitialized */ \ \ @@ -1473,7 +1473,7 @@ private: template iterator insert(const_iterator cpos, FIt first, FIt last, std::forward_iterator_tag) { - size_type n = std::distance(first, last); + size_type n = size_type(std::distance(first, last)); FOLLY_FBVECTOR_INSERT_PRE(cpos, n) FOLLY_FBVECTOR_INSERT_START(cpos, n) D_uninitialized_copy_a(start, first, last); diff --git a/folly/Format-inl.h b/folly/Format-inl.h index 945aa59e..deb8bdaa 100644 --- a/folly/Format-inl.h +++ b/folly/Format-inl.h @@ -388,7 +388,7 @@ void formatFormatter( int sz = static_cast(sp.size()); if (arg.precision != FormatArg::kDefaultPrecision) { sz = std::min(arg.precision, sz); - sp.reset(sp.data(), sz); + sp.reset(sp.data(), size_t(sz)); arg.precision -= sz; } if (!sp.empty()) { @@ -1035,7 +1035,7 @@ class FormatValue> { void format(FormatArg& arg, FormatCallback& cb) const { int key = arg.splitIntKey(); arg.enforce(key >= 0, "tuple index must be non-negative"); - doFormat(key, arg, cb); + doFormat(size_t(key), arg, cb); } private: diff --git a/folly/Format.cpp b/folly/Format.cpp index 177f9783..11f87e9d 100644 --- a/folly/Format.cpp +++ b/folly/Format.cpp @@ -168,7 +168,7 @@ void FormatArg::initSlow() { auto end = fullArgString.end(); // Parse key - auto p = static_cast(memchr(b, ':', end - b)); + auto p = static_cast(memchr(b, ':', size_t(end - b))); if (!p) { key_ = StringPiece(b, end); return; diff --git a/folly/GroupVarint.h b/folly/GroupVarint.h index 8160c380..9652a4d1 100644 --- a/folly/GroupVarint.h +++ b/folly/GroupVarint.h @@ -549,7 +549,7 @@ class GroupVarintDecoder { bool next(type* val) { if (pos_ == count_) { // refill - size_t rem = end_ - p_; + size_t rem = size_t(end_ - p_); if (rem == 0 || remaining_ == 0) { return false; } @@ -581,7 +581,7 @@ class GroupVarintDecoder { } } else { // Can't decode a full group - count_ = Base::partialCount(p_, end_ - p_); + count_ = Base::partialCount(p_, size_t(end_ - p_)); if (remaining_ >= count_) { remaining_ -= count_; p_ = end_; @@ -604,7 +604,7 @@ class GroupVarintDecoder { CHECK(pos_ == count_ && (p_ == end_ || remaining_ == 0)); // p_ may point to the internal buffer (tmp_), but we want // to return subpiece of the original data - size_t size = end_ - p_; + size_t size = size_t(end_ - p_); return StringPiece(rrest_ - size, rrest_); } diff --git a/folly/IPAddress.cpp b/folly/IPAddress.cpp index 0bd39102..792b75a4 100644 --- a/folly/IPAddress.cpp +++ b/folly/IPAddress.cpp @@ -89,8 +89,8 @@ CIDRNetwork IPAddress::createNetwork(StringPiece ipSlashCidr, "'")); } IPAddress subnet(vec.at(0)); - uint8_t cidr = - (defaultCidr > -1) ? uint8_t(defaultCidr) : (subnet.isV4() ? 32 : 128); + auto cidr = + uint8_t((defaultCidr > -1) ? defaultCidr : (subnet.isV4() ? 32 : 128)); if (elemCount == 2) { try { diff --git a/folly/IPAddressV6.cpp b/folly/IPAddressV6.cpp index 328d0674..9a7758c0 100644 --- a/folly/IPAddressV6.cpp +++ b/folly/IPAddressV6.cpp @@ -126,7 +126,7 @@ IPAddressV6::AddressStorage::AddressStorage(MacAddress mac) { // See RFC 4291 sections 2.5.1, 2.5.6, and Appendix A const auto* macBytes = mac.bytes(); memcpy(&bytes_.front(), "\xfe\x80\x00\x00\x00\x00\x00\x00", 8); - bytes_[8] = macBytes[0] ^ 0x02; + bytes_[8] = uint8_t(macBytes[0] ^ 0x02); bytes_[9] = macBytes[1]; bytes_[10] = macBytes[2]; bytes_[11] = 0xff; @@ -158,7 +158,7 @@ IPAddressV4 IPAddressV6::createIPv4() const { // convert two uint8_t bytes into a uint16_t as hibyte.lobyte static inline uint16_t unpack(uint8_t lobyte, uint8_t hibyte) { - return ((uint16_t)hibyte << 8) | (uint16_t)lobyte; + return uint16_t((uint16_t(hibyte) << 8) | lobyte); } // given a src string, unpack count*2 bytes into dest @@ -315,12 +315,12 @@ bool IPAddressV6::isMulticast() const { uint8_t IPAddressV6::getMulticastFlags() const { DCHECK(isMulticast()); - return ((addr_.bytes_[1] >> 4) & 0xf); + return uint8_t((addr_.bytes_[1] >> 4) & 0xf); } uint8_t IPAddressV6::getMulticastScope() const { DCHECK(isMulticast()); - return (addr_.bytes_[1] & 0xf); + return uint8_t(addr_.bytes_[1] & 0xf); } IPAddressV6 IPAddressV6::getSolicitedNodeAddress() const { diff --git a/folly/IndexedMemPool.h b/folly/IndexedMemPool.h index 3a7524e1..9b373da5 100644 --- a/folly/IndexedMemPool.h +++ b/folly/IndexedMemPool.h @@ -112,10 +112,11 @@ struct IndexedMemPool : boost::noncopyable { // of bits required to hold indices from a pool, given its capacity static constexpr uint32_t maxIndexForCapacity(uint32_t capacity) { - // index of uint32_t(-1) == UINT32_MAX is reserved for isAllocated tracking + // index of std::numeric_limits::max() is reserved for isAllocated + // tracking return uint32_t(std::min( uint64_t(capacity) + (NumLocalLists - 1) * LocalListLimit, - uint64_t(uint32_t(-1) - 1))); + uint64_t(std::numeric_limits::max() - 1))); } static constexpr uint32_t capacityForMaxIndex(uint32_t maxIndex) { @@ -131,7 +132,7 @@ struct IndexedMemPool : boost::noncopyable { , globalHead_(TaggedPtr{}) { const size_t needed = sizeof(Slot) * (actualCapacity_ + 1); - size_t pagesize = sysconf(_SC_PAGESIZE); + size_t pagesize = size_t(sysconf(_SC_PAGESIZE)); mmapLength_ = ((needed - 1) & ~(pagesize - 1)) + pagesize; assert(needed <= mmapLength_ && mmapLength_ < needed + pagesize); assert((mmapLength_ % pagesize) == 0); diff --git a/folly/MPMCPipeline.h b/folly/MPMCPipeline.h index 4fef5ead..eca0b29b 100644 --- a/folly/MPMCPipeline.h +++ b/folly/MPMCPipeline.h @@ -275,8 +275,9 @@ template class MPMCPipeline { * in any queue) are also counted. */ ssize_t sizeGuess() const noexcept { - return (std::get<0>(stages_).writeCount() * kAmplification - - std::get(stages_).readCount()); + return ssize_t( + std::get<0>(stages_).writeCount() * kAmplification - + std::get(stages_).readCount()); } private: diff --git a/folly/MPMCQueue.h b/folly/MPMCQueue.h index 22798880..b0cfc46f 100644 --- a/folly/MPMCQueue.h +++ b/folly/MPMCQueue.h @@ -1155,7 +1155,7 @@ class MPMCQueueBase> : boost::noncopyable { ticket = numPushes; const auto numPops = popTicket_.load(std::memory_order_acquire); // B // n will be negative if pops are pending - const int64_t n = numPushes - numPops; + const int64_t n = int64_t(numPushes - numPops); if (n >= static_cast(capacity_)) { // Full, linearize at B. We don't need to recheck the read we // performed at A, because if numPushes was stale at B then the diff --git a/folly/Math.h b/folly/Math.h index 6b61a2cc..e31335a1 100644 --- a/folly/Math.h +++ b/folly/Math.h @@ -132,9 +132,10 @@ constexpr auto kIntegerDivisionGivesRemainder = true; template inline constexpr detail::IdivResultType divFloor(N num, D denom) { using R = decltype(num / denom); - return kIntegerDivisionGivesRemainder && std::is_signed::value - ? detail::divFloorBranchless(num, denom) - : detail::divFloorBranchful(num, denom); + return detail::IdivResultType( + kIntegerDivisionGivesRemainder && std::is_signed::value + ? detail::divFloorBranchless(num, denom) + : detail::divFloorBranchful(num, denom)); } /** @@ -151,9 +152,10 @@ inline constexpr detail::IdivResultType divFloor(N num, D denom) { template inline constexpr detail::IdivResultType divCeil(N num, D denom) { using R = decltype(num / denom); - return kIntegerDivisionGivesRemainder && std::is_signed::value - ? detail::divCeilBranchless(num, denom) - : detail::divCeilBranchful(num, denom); + return detail::IdivResultType( + kIntegerDivisionGivesRemainder && std::is_signed::value + ? detail::divCeilBranchless(num, denom) + : detail::divCeilBranchful(num, denom)); } /** @@ -175,7 +177,7 @@ inline constexpr detail::IdivResultType divCeil(N num, D denom) { */ template inline constexpr detail::IdivResultType divTrunc(N num, D denom) { - return num / denom; + return detail::IdivResultType(num / denom); } /** @@ -193,9 +195,10 @@ inline constexpr detail::IdivResultType divTrunc(N num, D denom) { template inline constexpr detail::IdivResultType divRoundAway(N num, D denom) { using R = decltype(num / denom); - return kIntegerDivisionGivesRemainder && std::is_signed::value - ? detail::divRoundAwayBranchless(num, denom) - : detail::divRoundAwayBranchful(num, denom); + return detail::IdivResultType( + kIntegerDivisionGivesRemainder && std::is_signed::value + ? detail::divRoundAwayBranchless(num, denom) + : detail::divRoundAwayBranchful(num, denom)); } } // namespace folly diff --git a/folly/MemoryMapping.cpp b/folly/MemoryMapping.cpp index 89799fd1..a92e73f8 100644 --- a/folly/MemoryMapping.cpp +++ b/folly/MemoryMapping.cpp @@ -188,13 +188,13 @@ void MemoryMapping::init(off_t offset, off_t length) { (options_.writable ? PROT_WRITE : 0)); } - unsigned char* start = static_cast( - mmap(options_.address, mapLength_, prot, flags, file_.fd(), offset)); + unsigned char* start = static_cast(mmap( + options_.address, size_t(mapLength_), prot, flags, file_.fd(), offset)); PCHECK(start != MAP_FAILED) << " offset=" << offset << " length=" << mapLength_; mapStart_ = start; - data_.reset(start + skipStart, length); + data_.reset(start + skipStart, size_t(length)); } } @@ -231,7 +231,7 @@ bool memOpInChunks(std::function op, // chunks breaks the locking into intervals and lets other threads do memory // operations of their own. - size_t chunkSize = memOpChunkSize(off_t(bufSize), pageSize); + size_t chunkSize = size_t(memOpChunkSize(off_t(bufSize), pageSize)); char* addr = static_cast(mem); amountSucceeded = 0; @@ -251,8 +251,12 @@ bool memOpInChunks(std::function op, bool MemoryMapping::mlock(LockMode lock) { size_t amountSucceeded = 0; - locked_ = memOpInChunks(::mlock, mapStart_, mapLength_, options_.pageSize, - amountSucceeded); + locked_ = memOpInChunks( + ::mlock, + mapStart_, + size_t(mapLength_), + options_.pageSize, + amountSucceeded); if (locked_) { return true; } @@ -280,12 +284,16 @@ void MemoryMapping::munlock(bool dontneed) { if (!locked_) return; size_t amountSucceeded = 0; - if (!memOpInChunks(::munlock, mapStart_, mapLength_, options_.pageSize, - amountSucceeded)) { + if (!memOpInChunks( + ::munlock, + mapStart_, + size_t(mapLength_), + options_.pageSize, + amountSucceeded)) { PLOG(WARNING) << "munlock()"; } if (mapLength_ && dontneed && - ::madvise(mapStart_, mapLength_, MADV_DONTNEED)) { + ::madvise(mapStart_, size_t(mapLength_), MADV_DONTNEED)) { PLOG(WARNING) << "madvise()"; } locked_ = false; @@ -298,15 +306,21 @@ void MemoryMapping::hintLinearScan() { MemoryMapping::~MemoryMapping() { if (mapLength_) { size_t amountSucceeded = 0; - if (!memOpInChunks(::munmap, mapStart_, mapLength_, options_.pageSize, - amountSucceeded)) { + if (!memOpInChunks( + ::munmap, + mapStart_, + size_t(mapLength_), + options_.pageSize, + amountSucceeded)) { PLOG(FATAL) << folly::format("munmap({}) failed at {}", mapLength_, amountSucceeded); } } } -void MemoryMapping::advise(int advice) const { advise(advice, 0, mapLength_); } +void MemoryMapping::advise(int advice) const { + advise(advice, 0, size_t(mapLength_)); +} void MemoryMapping::advise(int advice, size_t offset, size_t length) const { CHECK_LE(offset + length, size_t(mapLength_)) diff --git a/folly/Padded.h b/folly/Padded.h index 0a772a2d..93b37ab4 100644 --- a/folly/Padded.h +++ b/folly/Padded.h @@ -385,7 +385,7 @@ class Adaptor { iterator end() { auto it = iterator(c_.end()); if (lastCount_ != Node::kElementCount) { - it -= (Node::kElementCount - lastCount_); + it -= difference_type(Node::kElementCount - lastCount_); } return it; } diff --git a/folly/PicoSpinLock.h b/folly/PicoSpinLock.h index b73f9f75..02d7bc92 100644 --- a/folly/PicoSpinLock.h +++ b/folly/PicoSpinLock.h @@ -94,7 +94,7 @@ struct PicoSpinLock { */ void init(IntType initialValue = 0) { CHECK(!(initialValue & kLockBitMask_)); - lock_ = initialValue; + lock_ = UIntType(initialValue); } /* @@ -118,7 +118,7 @@ struct PicoSpinLock { */ void setData(IntType w) { CHECK(!(w & kLockBitMask_)); - lock_ = (lock_ & kLockBitMask_) | w; + lock_ = UIntType((lock_ & kLockBitMask_) | w); } /* diff --git a/folly/Range.h b/folly/Range.h index 7872383c..d205a7b3 100644 --- a/folly/Range.h +++ b/folly/Range.h @@ -168,6 +168,7 @@ public: typedef typename std::remove_reference< typename std::iterator_traits::reference>::type value_type; + using difference_type = typename std::iterator_traits::difference_type; typedef typename std::iterator_traits::reference reference; /** @@ -364,7 +365,7 @@ public: return size_type(e_ - b_); } constexpr size_type walk_size() const { - return std::distance(b_, e_); + return size_type(std::distance(b_, e_)); } constexpr bool empty() const { return b_ == e_; @@ -785,7 +786,12 @@ public: auto i = find(delimiter); Range result(b_, i == std::string::npos ? size() : i); - b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size()); + b_ = result.end() == e_ + ? e_ + : std::next( + result.end(), + typename std::iterator_traits::difference_type( + delimiter.size())); return result; } diff --git a/folly/SocketAddress.cpp b/folly/SocketAddress.cpp index 785ff468..88781dad 100644 --- a/folly/SocketAddress.cpp +++ b/folly/SocketAddress.cpp @@ -329,7 +329,7 @@ void SocketAddress::setFromSockaddr(const struct sockaddr_un* address, storage_.un.init(); } external_ = true; - memcpy(storage_.un.addr, address, addrlen); + memcpy(storage_.un.addr, address, size_t(addrlen)); updateUnixAddressLength(addrlen); // Fill the rest with 0s, just for safety @@ -458,12 +458,13 @@ std::string SocketAddress::getPath() const { } if (storage_.un.addr->sun_path[0] == '\0') { // abstract namespace - return std::string(storage_.un.addr->sun_path, storage_.un.pathLength()); + return std::string( + storage_.un.addr->sun_path, size_t(storage_.un.pathLength())); } - return std::string(storage_.un.addr->sun_path, - strnlen(storage_.un.addr->sun_path, - storage_.un.pathLength())); + return std::string( + storage_.un.addr->sun_path, + strnlen(storage_.un.addr->sun_path, size_t(storage_.un.pathLength()))); } std::string SocketAddress::describe() const { @@ -477,9 +478,9 @@ std::string SocketAddress::describe() const { return ""; } - return std::string(storage_.un.addr->sun_path, - strnlen(storage_.un.addr->sun_path, - storage_.un.pathLength())); + return std::string( + storage_.un.addr->sun_path, + strnlen(storage_.un.addr->sun_path, size_t(storage_.un.pathLength()))); } switch (getFamily()) { case AF_UNSPEC: @@ -525,9 +526,10 @@ bool SocketAddress::operator==(const SocketAddress& other) const { if (storage_.un.len != other.storage_.un.len) { return false; } - int cmp = memcmp(storage_.un.addr->sun_path, - other.storage_.un.addr->sun_path, - storage_.un.pathLength()); + int cmp = memcmp( + storage_.un.addr->sun_path, + other.storage_.un.addr->sun_path, + size_t(storage_.un.pathLength())); return cmp == 0; } @@ -736,9 +738,10 @@ bool SocketAddress::operator<(const SocketAddress& other) const { if (thisPathLength != otherPathLength) { return thisPathLength < otherPathLength; } - int cmp = memcmp(storage_.un.addr->sun_path, - other.storage_.un.addr->sun_path, - thisPathLength); + int cmp = memcmp( + storage_.un.addr->sun_path, + other.storage_.un.addr->sun_path, + size_t(thisPathLength)); return cmp < 0; } switch (getFamily()) { diff --git a/folly/SocketAddress.h b/folly/SocketAddress.h index e6a63626..480a37d9 100644 --- a/folly/SocketAddress.h +++ b/folly/SocketAddress.h @@ -392,7 +392,7 @@ class SocketAddress { sa_family_t getFamily() const { DCHECK(external_ || AF_UNIX != storage_.addr.family()); - return external_ ? AF_UNIX : storage_.addr.family(); + return external_ ? sa_family_t(AF_UNIX) : storage_.addr.family(); } bool empty() const { @@ -548,7 +548,7 @@ class SocketAddress { static constexpr uint64_t kMagic = 0x1234faceb00c; socklen_t pathLength() const { - return len - offsetof(struct sockaddr_un, sun_path); + return socklen_t(len - offsetof(struct sockaddr_un, sun_path)); } void init() { @@ -561,7 +561,7 @@ class SocketAddress { addr = new sockaddr_un; magic = kMagic; len = other.len; - memcpy(addr, other.addr, len); + memcpy(addr, other.addr, size_t(len)); // Fill the rest with 0s, just for safety memset(reinterpret_cast(addr) + len, 0, sizeof(struct sockaddr_un) - len); @@ -569,7 +569,7 @@ class SocketAddress { void copy(const ExternalUnixAddr &other) { CHECK(magic == kMagic); len = other.len; - memcpy(addr, other.addr, len); + memcpy(addr, other.addr, size_t(len)); } void free() { CHECK(magic == kMagic); diff --git a/folly/String-inl.h b/folly/String-inl.h index 392bd672..dbfefa01 100644 --- a/folly/String-inl.h +++ b/folly/String-inl.h @@ -50,7 +50,7 @@ void cEscape(StringPiece str, String& out) { if (e == 'P') { // printable ++p; } else if (e == 'O') { // octal - out.append(&*last, p - last); + out.append(&*last, size_t(p - last)); esc[1] = '0' + ((v >> 6) & 7); esc[2] = '0' + ((v >> 3) & 7); esc[3] = '0' + (v & 7); @@ -58,14 +58,14 @@ void cEscape(StringPiece str, String& out) { ++p; last = p; } else { // special 1-character escape - out.append(&*last, p - last); + out.append(&*last, size_t(p - last)); esc[1] = e; out.append(esc, 2); ++p; last = p; } } - out.append(&*last, p - last); + out.append(&*last, size_t(p - last)); } namespace detail { @@ -177,12 +177,12 @@ void uriEscape(StringPiece str, String& out, UriEscapeMode mode) { if (LIKELY(discriminator <= minEncode)) { ++p; } else if (mode == UriEscapeMode::QUERY && discriminator == 3) { - out.append(&*last, p - last); + out.append(&*last, size_t(p - last)); out.push_back('+'); ++p; last = p; } else { - out.append(&*last, p - last); + out.append(&*last, size_t(p - last)); esc[1] = hexValues[v >> 4]; esc[2] = hexValues[v & 0x0f]; out.append(esc, 3); @@ -190,7 +190,7 @@ void uriEscape(StringPiece str, String& out, UriEscapeMode mode) { last = p; } } - out.append(&*last, p - last); + out.append(&*last, size_t(p - last)); } template @@ -213,7 +213,7 @@ void uriUnescape(StringPiece str, String& out, UriEscapeMode mode) { if (UNLIKELY(h1 == 16 || h2 == 16)) { throw std::invalid_argument("invalid percent encode sequence"); } - out.append(&*last, p - last); + out.append(&*last, size_t(p - last)); out.push_back((h1 << 4) | h2); p += 3; last = p; @@ -221,7 +221,7 @@ void uriUnescape(StringPiece str, String& out, UriEscapeMode mode) { } case '+': if (mode == UriEscapeMode::QUERY) { - out.append(&*last, p - last); + out.append(&*last, size_t(p - last)); out.push_back(' '); ++p; last = p; @@ -233,7 +233,7 @@ void uriUnescape(StringPiece str, String& out, UriEscapeMode mode) { break; } } - out.append(&*last, p - last); + out.append(&*last, size_t(p - last)); } namespace detail { diff --git a/folly/String.cpp b/folly/String.cpp index 2cb3fb6f..e8de48da 100644 --- a/folly/String.cpp +++ b/folly/String.cpp @@ -66,21 +66,21 @@ void stringAppendfImpl(std::string& output, const char* format, va_list args) { } if (static_cast(bytes_used) < inline_buffer.size()) { - output.append(inline_buffer.data(), bytes_used); + output.append(inline_buffer.data(), size_t(bytes_used)); return; } // Couldn't fit. Heap allocate a buffer, oh well. - std::unique_ptr heap_buffer(new char[bytes_used + 1]); - int final_bytes_used = - stringAppendfImplHelper(heap_buffer.get(), bytes_used + 1, format, args); + std::unique_ptr heap_buffer(new char[size_t(bytes_used + 1)]); + int final_bytes_used = stringAppendfImplHelper( + heap_buffer.get(), size_t(bytes_used + 1), format, args); // The second call can take fewer bytes if, for example, we were printing a // string buffer with null-terminating char using a width specifier - // vsnprintf("%.*s", buf.size(), buf) CHECK(bytes_used >= final_bytes_used); // We don't keep the trailing '\0' in our output string - output.append(heap_buffer.get(), final_bytes_used); + output.append(heap_buffer.get(), size_t(final_bytes_used)); } } // anon namespace @@ -299,7 +299,7 @@ double prettyToDouble(folly::StringPiece *const prettyString, "Unable to parse suffix \"", prettyString->toString(), "\"")); } - prettyString->advance(longestPrefixLen); + prettyString->advance(size_t(longestPrefixLen)); return suffixes[bestPrefixId].val ? value * suffixes[bestPrefixId].val : value; } @@ -373,7 +373,7 @@ void toLowerAscii8(char& c) { // by adding 0x20. // Step 1: Clear the high order bit. We'll deal with it in Step 5. - unsigned char rotated = c & 0x7f; + uint8_t rotated = uint8_t(c & 0x7f); // Currently, the value of rotated, as a function of the original c is: // below 'A': 0- 64 // 'A'-'Z': 65- 90 @@ -419,7 +419,7 @@ void toLowerAscii8(char& c) { // At this point, rotated is 0x20 if c is 'A'-'Z' and 0x00 otherwise // Step 7: Add rotated to c - c += rotated; + c += char(rotated); } void toLowerAscii32(uint32_t& c) { diff --git a/folly/ThreadCachedInt.h b/folly/ThreadCachedInt.h index 3ed53b20..58816e37 100644 --- a/folly/ThreadCachedInt.h +++ b/folly/ThreadCachedInt.h @@ -110,7 +110,10 @@ class ThreadCachedInt : boost::noncopyable { ThreadCachedInt& operator-=(IntT inc) { increment(-inc); return *this; } // pre-increment (we don't support post-increment) ThreadCachedInt& operator++() { increment(1); return *this; } - ThreadCachedInt& operator--() { increment(-1); return *this; } + ThreadCachedInt& operator--() { + increment(IntT(-1)); + return *this; + } // Thread-safe set function. // This is a best effort implementation. In some edge cases, there could be diff --git a/folly/Varint.h b/folly/Varint.h index 6cb42d1f..4664cb95 100644 --- a/folly/Varint.h +++ b/folly/Varint.h @@ -88,7 +88,7 @@ inline size_t encodeVarint(uint64_t val, uint8_t* buf) { val >>= 7; } *p++ = uint8_t(val); - return p - buf; + return size_t(p - buf); } template diff --git a/folly/build/GenerateFingerprintTables.cpp b/folly/build/GenerateFingerprintTables.cpp index 28018fd6..4911fb58 100644 --- a/folly/build/GenerateFingerprintTables.cpp +++ b/folly/build/GenerateFingerprintTables.cpp @@ -73,7 +73,7 @@ void computeTables(FILE* file, const FingerprintPolynomial& poly) { // whose coefficients are the bits of q. for (int x = 0; x < 256; x++) { FingerprintPolynomial t; - t.setHigh8Bits(x); + t.setHigh8Bits(uint8_t(x)); for (int i = 0; i < 8; i++) { t.mulXkmod(8, poly); t.write(&(table[i][x][0])); diff --git a/folly/detail/CacheLocality.cpp b/folly/detail/CacheLocality.cpp index b5737cda..7b9f7e9d 100644 --- a/folly/detail/CacheLocality.cpp +++ b/folly/detail/CacheLocality.cpp @@ -55,7 +55,7 @@ static CacheLocality getSystemLocalityInfo() { // wiggle room numCpus = 32; } - return CacheLocality::uniform(numCpus); + return CacheLocality::uniform(size_t(numCpus)); } template <> diff --git a/folly/detail/FingerprintPolynomial.h b/folly/detail/FingerprintPolynomial.h index a4d3dbd0..db9a1783 100644 --- a/folly/detail/FingerprintPolynomial.h +++ b/folly/detail/FingerprintPolynomial.h @@ -57,7 +57,7 @@ class FingerprintPolynomial { // Multiply by X. The actual degree must be < DEG. void mulX() { - CHECK_EQ(0, val_[0] & (1ULL<<63)); + CHECK_EQ(0u, val_[0] & (1ULL << 63)); uint64_t b = 0; for (int i = size()-1; i >= 0; i--) { uint64_t nb = val_[i] >> 63; diff --git a/folly/detail/IPAddressSource.h b/folly/detail/IPAddressSource.h index 9447812d..a785c985 100644 --- a/folly/detail/IPAddressSource.h +++ b/folly/detail/IPAddressSource.h @@ -51,7 +51,7 @@ struct Bytes { std::size_t asize = a.size(); std::array ba{{0}}; for (std::size_t i = 0; i < asize; i++) { - ba[i] = a[i] & b[i]; + ba[i] = uint8_t(a[i] & b[i]); } return ba; } @@ -174,7 +174,7 @@ struct Bytes { template < class IntegralType, IntegralType DigitCount, - IntegralType Base = 10, + IntegralType Base = IntegralType(10), bool PrintAllDigits = false, class = typename std::enable_if< std::is_integral::value && @@ -197,7 +197,7 @@ inline void writeIntegerString(IntegralType val, char** buffer) { bool found = PrintAllDigits; while (powerToPrint) { if (found || powerToPrint <= val) { - IntegralType value = val / powerToPrint; + IntegralType value = IntegralType(val / powerToPrint); if (Base == 10 || value < 10) { value += '0'; } else { diff --git a/folly/detail/RangeSse42.cpp b/folly/detail/RangeSse42.cpp index 053aba7d..d54a4a36 100644 --- a/folly/detail/RangeSse42.cpp +++ b/folly/detail/RangeSse42.cpp @@ -108,7 +108,7 @@ size_t qfind_first_byte_of_needles16(const StringPieceLite haystack, auto index = _mm_cmpestri(arr2, int(needles.size()), arr1, int(haystack.size()), 0); if (index < 16) { - return index; + return size_t(index); } // Now, we can do aligned loads hereafter... diff --git a/folly/dynamic.cpp b/folly/dynamic.cpp index 47fba09b..c2fac276 100644 --- a/folly/dynamic.cpp +++ b/folly/dynamic.cpp @@ -208,7 +208,7 @@ const dynamic* dynamic::get_ptr(dynamic const& idx) const& { if (idx < 0 || idx >= parray->size()) { return nullptr; } - return &(*parray)[idx.asInt()]; + return &(*parray)[size_t(idx.asInt())]; } else if (auto* pobject = get_nothrow()) { auto it = pobject->find(idx); if (it == pobject->end()) { @@ -228,7 +228,7 @@ dynamic const& dynamic::at(dynamic const& idx) const& { if (idx < 0 || idx >= parray->size()) { std::__throw_out_of_range("out of range in dynamic array"); } - return (*parray)[idx.asInt()]; + return (*parray)[size_t(idx.asInt())]; } else if (auto* pobject = get_nothrow()) { auto it = pobject->find(idx); if (it == pobject->end()) { diff --git a/folly/experimental/AsymmetricMemoryBarrier.cpp b/folly/experimental/AsymmetricMemoryBarrier.cpp index 03dc8249..55bec5f1 100644 --- a/folly/experimental/AsymmetricMemoryBarrier.cpp +++ b/folly/experimental/AsymmetricMemoryBarrier.cpp @@ -40,7 +40,7 @@ struct DummyPageCreator { private: static void* create() { auto ptr = mmap(nullptr, 1, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - checkUnixError(reinterpret_cast(ptr), "mmap"); + checkUnixError(reinterpret_cast(ptr), "mmap"); // Optimistically try to lock the page so it stays resident. Could make // the heavy barrier faster. diff --git a/folly/experimental/BitVectorCoding.h b/folly/experimental/BitVectorCoding.h index 7c963388..e2290fcd 100644 --- a/folly/experimental/BitVectorCoding.h +++ b/folly/experimental/BitVectorCoding.h @@ -94,7 +94,7 @@ struct BitVectorEncoder { if (begin == end) { return MutableCompressedList(); } - BitVectorEncoder encoder(end - begin, *(end - 1)); + BitVectorEncoder encoder(size_t(end - begin), *(end - 1)); for (; begin != end; ++begin) { encoder.add(*begin); } diff --git a/folly/experimental/Bits.h b/folly/experimental/Bits.h index a1208050..191cb2d2 100644 --- a/folly/experimental/Bits.h +++ b/folly/experimental/Bits.h @@ -242,8 +242,9 @@ inline void Bits::set(T* p, size_t bitStart, size_t count, size_t countInThisBlock = bitsPerBlock - offset; size_t countInNextBlock = count - countInThisBlock; - UnderlyingType thisBlock = value & ((one << countInThisBlock) - 1); - UnderlyingType nextBlock = value >> countInThisBlock; + UnderlyingType thisBlock = + UnderlyingType(value & ((one << countInThisBlock) - 1)); + UnderlyingType nextBlock = UnderlyingType(value >> countInThisBlock); if (std::is_signed::value) { nextBlock &= ones(countInNextBlock); } diff --git a/folly/experimental/EliasFanoCoding.h b/folly/experimental/EliasFanoCoding.h index cc2602d2..acc949a5 100644 --- a/folly/experimental/EliasFanoCoding.h +++ b/folly/experimental/EliasFanoCoding.h @@ -64,7 +64,9 @@ struct EliasFanoCompressedListBase { return ::free(data.data()); } - size_t upperSize() const { return data.end() - upper; } + size_t upperSize() const { + return size_t(data.end() - upper); + } size_t size = 0; uint8_t numLowerBits = 0; @@ -106,7 +108,7 @@ struct EliasFanoEncoderV2 { return 0; } // floor(log(upperBound / size)); - return folly::findLastSet(upperBound / size) - 1; + return uint8_t(folly::findLastSet(upperBound / size) - 1); } // Requires: input range (begin, end) is sorted (encoding @@ -120,7 +122,7 @@ struct EliasFanoEncoderV2 { if (begin == end) { return MutableCompressedList(); } - EliasFanoEncoderV2 encoder(end - begin, *(end - 1)); + EliasFanoEncoderV2 encoder(size_t(end - begin), *(end - 1)); for (; begin != end; ++begin) { encoder.add(*begin); } @@ -161,7 +163,7 @@ struct EliasFanoEncoderV2 { /* static */ if (skipQuantum != 0) { while ((skipPointersSize_ + 1) * skipQuantum <= upperBits) { // Store the number of preceding 1-bits. - skipPointers_[skipPointersSize_++] = size_; + skipPointers_[skipPointersSize_++] = SkipValue(size_); } } @@ -338,8 +340,8 @@ class UpperBitsReader { void reset() { block_ = start_ != nullptr ? folly::loadUnaligned(start_) : 0; outer_ = 0; - inner_ = -1; - position_ = -1; + inner_ = std::numeric_limits::max(); + position_ = std::numeric_limits::max(); value_ = 0; } @@ -354,7 +356,7 @@ class UpperBitsReader { } ++position_; - inner_ = Instructions::ctz(block_); + inner_ = size_t(Instructions::ctz(block_)); block_ = Instructions::blsr(block_); return setValue(); @@ -442,7 +444,7 @@ class UpperBitsReader { if (Encoder::forwardQuantum == 0 || n <= Encoder::forwardQuantum) { reset(); } else { - position_ = -1; // Avoid reading the head, skip() will reposition. + position_ = size_t(-1); // Avoid reading the head, skip() will reposition. } return skip(n); } @@ -529,7 +531,7 @@ class EliasFanoReader { lastValue_ = 0; return; } - ValueType lastUpperValue = 8 * list.upperSize() - size_; + ValueType lastUpperValue = ValueType(8 * list.upperSize() - size_); auto it = list.upper + list.upperSize() - 1; DCHECK_NE(*it, 0); lastUpperValue -= 8 - folly::findLastSet(*it); diff --git a/folly/experimental/Instructions.h b/folly/experimental/Instructions.h index ab2db160..a2754b89 100644 --- a/folly/experimental/Instructions.h +++ b/folly/experimental/Instructions.h @@ -43,7 +43,7 @@ struct Default { return true; } static FOLLY_ALWAYS_INLINE uint64_t popcount(uint64_t value) { - return __builtin_popcountll(value); + return uint64_t(__builtin_popcountll(value)); } static FOLLY_ALWAYS_INLINE int ctz(uint64_t value) { DCHECK_GT(value, 0u); diff --git a/folly/experimental/JSONSchema.cpp b/folly/experimental/JSONSchema.cpp index f2b9ec50..f559a545 100644 --- a/folly/experimental/JSONSchema.cpp +++ b/folly/experimental/JSONSchema.cpp @@ -219,7 +219,7 @@ struct SizeValidator final : IValidator { if (value.type() != type_) { return none; } - if (!Comparison()(size_t(length_), value.size())) { + if (!Comparison()(length_, int64_t(value.size()))) { return makeError("different length string/array/object", value); } return none; diff --git a/folly/experimental/TestUtil.cpp b/folly/experimental/TestUtil.cpp index dc680d6d..aeef414b 100644 --- a/folly/experimental/TestUtil.cpp +++ b/folly/experimental/TestUtil.cpp @@ -208,11 +208,11 @@ std::string CaptureFD::readIncremental() { std::string filename = file_.path().string(); // Yes, I know that I could just keep the file open instead. So sue me. folly::File f(openNoInt(filename.c_str(), O_RDONLY), true); - auto size = lseek(f.fd(), 0, SEEK_END) - readOffset_; + auto size = size_t(lseek(f.fd(), 0, SEEK_END) - readOffset_); std::unique_ptr buf(new char[size]); auto bytes_read = folly::preadFull(f.fd(), buf.get(), size, readOffset_); - PCHECK(size == bytes_read); - readOffset_ += size; + PCHECK(ssize_t(size) == bytes_read); + readOffset_ += off_t(size); chunkCob_(StringPiece(buf.get(), buf.get() + size)); return std::string(buf.get(), size); } diff --git a/folly/experimental/bser/Dump.cpp b/folly/experimental/bser/Dump.cpp index dbf7c746..4a8d5b51 100644 --- a/folly/experimental/bser/Dump.cpp +++ b/folly/experimental/bser/Dump.cpp @@ -76,7 +76,7 @@ static void bserEncodeInt(int64_t ival, QueueAppender& appender) { static void bserEncodeString(folly::StringPiece str, QueueAppender& appender) { appender.write((int8_t)BserType::String); - bserEncodeInt(str.size(), appender); + bserEncodeInt(int64_t(str.size()), appender); appender.push((uint8_t*)str.data(), str.size()); } @@ -84,7 +84,7 @@ static void bserEncodeArraySimple(dynamic const& dyn, QueueAppender& appender, const serialization_opts& opts) { appender.write((int8_t)BserType::Array); - bserEncodeInt(dyn.size(), appender); + bserEncodeInt(int64_t(dyn.size()), appender); for (const auto& ele : dyn) { bserEncode(ele, appender, opts); } @@ -102,7 +102,7 @@ static void bserEncodeArray(dynamic const& dyn, bserEncodeArraySimple(*templ, appender, opts); // The number of objects in the array - bserEncodeInt(dyn.size(), appender); + bserEncodeInt(int64_t(dyn.size()), appender); // For each object in the array for (const auto& ele : dyn) { @@ -131,7 +131,7 @@ static void bserEncodeObject(dynamic const& dyn, QueueAppender& appender, const serialization_opts& opts) { appender.write((int8_t)BserType::Object); - bserEncodeInt(dyn.size(), appender); + bserEncodeInt(int64_t(dyn.size()), appender); if (opts.sort_keys) { std::vector> sorted(dyn.items().begin(), diff --git a/folly/experimental/bser/Load.cpp b/folly/experimental/bser/Load.cpp index 161f72a3..e462ee49 100644 --- a/folly/experimental/bser/Load.cpp +++ b/folly/experimental/bser/Load.cpp @@ -56,7 +56,7 @@ static std::string decodeString(Cursor& curs) { if (len < 0) { throw std::range_error("string length must not be negative"); } - str.reserve(len); + str.reserve(size_t(len)); size_t available = curs.length(); while (available < (size_t)len) { @@ -73,8 +73,8 @@ static std::string decodeString(Cursor& curs) { available = curs.length(); } - str.append(reinterpret_cast(curs.data()), len); - curs.skipAtMost(len); + str.append(reinterpret_cast(curs.data()), size_t(len)); + curs.skipAtMost(size_t(len)); return str; } diff --git a/folly/experimental/io/HugePages.cpp b/folly/experimental/io/HugePages.cpp index 0733d3a9..f94b818b 100644 --- a/folly/experimental/io/HugePages.cpp +++ b/folly/experimental/io/HugePages.cpp @@ -52,7 +52,8 @@ size_t getDefaultHugePageSize() { bool error = gen::byLine("/proc/meminfo") | [&] (StringPiece line) -> bool { if (boost::regex_match(line.begin(), line.end(), match, regex)) { - StringPiece numStr(line.begin() + match.position(1), match.length(1)); + StringPiece numStr( + line.begin() + match.position(1), size_t(match.length(1))); pageSize = to(numStr) * 1024; // in KiB return false; // stop } @@ -75,7 +76,8 @@ HugePageSizeVec readRawHugePageSizes() { for (fs::directory_iterator it(path); it != fs::directory_iterator(); ++it) { std::string filename(it->path().filename().string()); if (boost::regex_match(filename, match, regex)) { - StringPiece numStr(filename.data() + match.position(1), match.length(1)); + StringPiece numStr( + filename.data() + match.position(1), size_t(match.length(1))); vec.emplace_back(to(numStr) * 1024); } } @@ -92,9 +94,9 @@ size_t parsePageSizeValue(StringPiece value) { } char c = '\0'; if (match.length(2) != 0) { - c = char(tolower(value[match.position(2)])); + c = char(tolower(value[size_t(match.position(2))])); } - StringPiece numStr(value.data() + match.position(1), match.length(1)); + StringPiece numStr(value.data() + match.position(1), size_t(match.length(1))); size_t size = to(numStr); switch (c) { case 't': size *= 1024; diff --git a/folly/fibers/GuardPageAllocator.cpp b/folly/fibers/GuardPageAllocator.cpp index 2a3aff70..fe521a47 100644 --- a/folly/fibers/GuardPageAllocator.cpp +++ b/folly/fibers/GuardPageAllocator.cpp @@ -144,7 +144,7 @@ class StackCache { // Use a read lock for reading. SYNCHRONIZED_CONST(pages, protectedPages()) { for (const auto& page : pages) { - intptr_t pageEnd = page + pagesize(); + intptr_t pageEnd = intptr_t(page + pagesize()); if (page <= addr && addr < pageEnd) { return true; } @@ -164,7 +164,7 @@ class StackCache { std::vector> freeList_; static size_t pagesize() { - static const size_t pagesize = sysconf(_SC_PAGESIZE); + static const size_t pagesize = size_t(sysconf(_SC_PAGESIZE)); return pagesize; } diff --git a/folly/fibers/WhenN-inl.h b/folly/fibers/WhenN-inl.h index 8b7fa621..160301c1 100644 --- a/folly/fibers/WhenN-inl.h +++ b/folly/fibers/WhenN-inl.h @@ -160,7 +160,7 @@ typename std::vector< type> inline collectAll(InputIterator first, InputIterator last) { typedef typename std::result_of< typename std::iterator_traits::value_type()>::type Result; - size_t n = std::distance(first, last); + size_t n = size_t(std::distance(first, last)); std::vector results; std::vector order(n); results.reserve(n); diff --git a/folly/futures/Future-inl.h b/folly/futures/Future-inl.h index 6ac7acdb..28935a21 100644 --- a/folly/futures/Future-inl.h +++ b/folly/futures/Future-inl.h @@ -594,7 +594,8 @@ collectAll(InputIterator first, InputIterator last) { std::vector> results; }; - auto ctx = std::make_shared(std::distance(first, last)); + auto ctx = + std::make_shared(size_t(std::distance(first, last))); mapSetCallback(first, last, [ctx](size_t i, Try&& t) { ctx->results[i] = std::move(t); }); @@ -723,7 +724,7 @@ collectAnyWithoutException(InputIterator first, InputIterator last) { }; auto ctx = std::make_shared(); - ctx->nTotal = std::distance(first, last); + ctx->nTotal = size_t(std::distance(first, last)); mapSetCallback(first, last, [ctx](size_t i, Try&& t) { if (!t.hasException() && !ctx->done.exchange(true)) { diff --git a/folly/gen/Parallel-inl.h b/folly/gen/Parallel-inl.h index 0992cacd..18c7c434 100644 --- a/folly/gen/Parallel-inl.h +++ b/folly/gen/Parallel-inl.h @@ -293,8 +293,9 @@ class Parallel : public Operator> { : source_(std::move(source)), ops_(std::move(ops)), threads_( - threads ? threads - : std::max(1, sysconf(_SC_NPROCESSORS_CONF))) {} + threads + ? threads + : size_t(std::max(1, sysconf(_SC_NPROCESSORS_CONF)))) {} template bool apply(Handler&& handler) const { diff --git a/folly/io/IOBuf.cpp b/folly/io/IOBuf.cpp index caccec13..2a295aa8 100644 --- a/folly/io/IOBuf.cpp +++ b/folly/io/IOBuf.cpp @@ -163,7 +163,7 @@ void IOBuf::releaseStorage(HeapStorage* storage, uint16_t freeFlags) { DCHECK_EQ((flags & freeFlags), freeFlags); while (true) { - uint16_t newFlags = (flags & ~freeFlags); + uint16_t newFlags = uint16_t(flags & ~freeFlags); if (newFlags == 0) { // The storage space is now unused. Free it. storage->prefix.HeapPrefix::~HeapPrefix(); @@ -250,7 +250,7 @@ unique_ptr IOBuf::createCombined(uint64_t capacity) { uint8_t* bufAddr = reinterpret_cast(&storage->align); uint8_t* storageEnd = reinterpret_cast(storage) + mallocSize; - size_t actualCapacity = storageEnd - bufAddr; + size_t actualCapacity = size_t(storageEnd - bufAddr); unique_ptr ret(new (&storage->hs.buf) IOBuf( InternalConstructor(), packFlagsAndSharedInfo(0, &storage->shared), bufAddr, actualCapacity, bufAddr, 0)); @@ -898,7 +898,7 @@ void IOBuf::initExtBuffer(uint8_t* buf, size_t mallocSize, uint8_t* infoStart = (buf + mallocSize) - sizeof(SharedInfo); SharedInfo* sharedInfo = new(infoStart) SharedInfo; - *capacityReturn = infoStart - buf; + *capacityReturn = uint64_t(infoStart - buf); *infoReturn = sharedInfo; } diff --git a/folly/io/RecordIO.cpp b/folly/io/RecordIO.cpp index ba351213..50c854ec 100644 --- a/folly/io/RecordIO.cpp +++ b/folly/io/RecordIO.cpp @@ -66,7 +66,7 @@ void RecordIOWriter::write(std::unique_ptr buf) { #endif checkUnixError(bytes, "pwrite() failed"); - DCHECK_EQ(bytes, totalLength); + DCHECK_EQ(size_t(bytes), totalLength); } RecordIOReader::RecordIOReader(File file, uint32_t fileId) @@ -84,7 +84,7 @@ RecordIOReader::Iterator::Iterator(ByteRange range, uint32_t fileId, off_t pos) range_.clear(); } else { recordAndPos_.second = pos; - range_.advance(pos); + range_.advance(size_t(pos)); advanceToValid(); } } diff --git a/folly/io/ShutdownSocketSet.cpp b/folly/io/ShutdownSocketSet.cpp index 138091c3..839fd386 100644 --- a/folly/io/ShutdownSocketSet.cpp +++ b/folly/io/ShutdownSocketSet.cpp @@ -27,11 +27,10 @@ namespace folly { ShutdownSocketSet::ShutdownSocketSet(int maxFd) - : maxFd_(maxFd), - data_(static_cast*>( - folly::checkedCalloc(maxFd, sizeof(std::atomic)))), - nullFile_("/dev/null", O_RDWR) { -} + : maxFd_(maxFd), + data_(static_cast*>( + folly::checkedCalloc(size_t(maxFd), sizeof(std::atomic)))), + nullFile_("/dev/null", O_RDWR) {} void ShutdownSocketSet::add(int fd) { // Silently ignore any fds >= maxFd_, very unlikely @@ -40,7 +39,7 @@ void ShutdownSocketSet::add(int fd) { return; } - auto& sref = data_[fd]; + auto& sref = data_[size_t(fd)]; uint8_t prevState = FREE; CHECK(sref.compare_exchange_strong(prevState, IN_USE, @@ -54,7 +53,7 @@ void ShutdownSocketSet::remove(int fd) { return; } - auto& sref = data_[fd]; + auto& sref = data_[size_t(fd)]; uint8_t prevState = 0; retry_load: @@ -82,7 +81,7 @@ int ShutdownSocketSet::close(int fd) { return folly::closeNoInt(fd); } - auto& sref = data_[fd]; + auto& sref = data_[size_t(fd)]; uint8_t prevState = sref.load(std::memory_order_relaxed); uint8_t newState = 0; @@ -115,7 +114,7 @@ void ShutdownSocketSet::shutdown(int fd, bool abortive) { return; } - auto& sref = data_[fd]; + auto& sref = data_[size_t(fd)]; uint8_t prevState = IN_USE; if (!sref.compare_exchange_strong(prevState, IN_SHUTDOWN, @@ -145,7 +144,7 @@ void ShutdownSocketSet::shutdown(int fd, bool abortive) { void ShutdownSocketSet::shutdownAll(bool abortive) { for (int i = 0; i < maxFd_; ++i) { - auto& sref = data_[i]; + auto& sref = data_[size_t(i)]; if (sref.load(std::memory_order_acquire) == IN_USE) { shutdown(i, abortive); } diff --git a/folly/io/async/AsyncPipe.cpp b/folly/io/async/AsyncPipe.cpp index 94f73b7d..d64a164d 100644 --- a/folly/io/async/AsyncPipe.cpp +++ b/folly/io/async/AsyncPipe.cpp @@ -108,10 +108,10 @@ void AsyncPipeReader::handlerReady(uint16_t events) noexcept { if (bytesRead > 0) { if (movable) { - ioBuf->append(bytesRead); + ioBuf->append(uint64_t(bytesRead)); readCallback_->readBufferAvailable(std::move(ioBuf)); } else { - readCallback_->readDataAvailable(bytesRead); + readCallback_->readDataAvailable(size_t(bytesRead)); } // Fall through and continue around the loop if the read // completely filled the available buffer. @@ -247,7 +247,7 @@ void AsyncPipeWriter::handleWrite() { registerHandler(EventHandler::WRITE); return; } - curQueue.trimStart(rc); + curQueue.trimStart(size_t(rc)); if (curQueue.empty()) { auto cb = front.second; queue_.pop_front(); diff --git a/folly/io/async/AsyncSSLSocket.cpp b/folly/io/async/AsyncSSLSocket.cpp index d6fe2495..1f66ddd6 100644 --- a/folly/io/async/AsyncSSLSocket.cpp +++ b/folly/io/async/AsyncSSLSocket.cpp @@ -1580,7 +1580,7 @@ int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) { AsyncSSLSocket* tsslSock; iov.iov_base = const_cast(in); - iov.iov_len = inl; + iov.iov_len = size_t(inl); memset(&msg, 0, sizeof(msg)); msg.msg_iov = &iov; msg.msg_iovlen = 1; diff --git a/folly/io/async/AsyncSocket.cpp b/folly/io/async/AsyncSocket.cpp index db623129..bbdbc46c 100644 --- a/folly/io/async/AsyncSocket.cpp +++ b/folly/io/async/AsyncSocket.cpp @@ -1306,7 +1306,7 @@ void AsyncSocket::ioReady(uint16_t events) noexcept { assert(events & EventHandler::READ_WRITE); assert(eventBase_->isInEventBaseThread()); - uint16_t relevantEvents = events & EventHandler::READ_WRITE; + uint16_t relevantEvents = uint16_t(events & EventHandler::READ_WRITE); if (relevantEvents == EventHandler::READ) { handleRead(); } else if (relevantEvents == EventHandler::WRITE) { @@ -1427,7 +1427,7 @@ void AsyncSocket::handleRead() noexcept { << bytesRead << " bytes"; if (bytesRead > 0) { if (!isBufferMovable_) { - readCallback_->readDataAvailable(bytesRead); + readCallback_->readDataAvailable(size_t(bytesRead)); } else { CHECK(kOpenSslModeMoveBufferOwnership); VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got " @@ -1958,7 +1958,8 @@ bool AsyncSocket::updateEventRegistration() { // Always register for persistent events, so we don't have to re-register // after being called back. - if (!ioHandler_.registerHandler(eventFlags_ | EventHandler::PERSIST)) { + if (!ioHandler_.registerHandler( + uint16_t(eventFlags_ | EventHandler::PERSIST))) { eventFlags_ = EventHandler::NONE; // we're not registered after error AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR, withAddr("failed to update AsyncSocket event registration")); diff --git a/folly/io/async/AsyncUDPSocket.cpp b/folly/io/async/AsyncUDPSocket.cpp index a516f9ae..5d99e444 100644 --- a/folly/io/async/AsyncUDPSocket.cpp +++ b/folly/io/async/AsyncUDPSocket.cpp @@ -248,7 +248,7 @@ void AsyncUDPSocket::handleRead() noexcept { struct sockaddr_storage addrStorage; socklen_t addrLen = sizeof(addrStorage); - memset(&addrStorage, 0, addrLen); + memset(&addrStorage, 0, size_t(addrLen)); struct sockaddr* rawAddr = reinterpret_cast(&addrStorage); rawAddr->sa_family = localAddress_.getFamily(); @@ -260,10 +260,11 @@ void AsyncUDPSocket::handleRead() noexcept { bool truncated = false; if ((size_t)bytesRead > len) { truncated = true; - bytesRead = len; + bytesRead = ssize_t(len); } - readCallback_->onDataAvailable(clientAddress_, bytesRead, truncated); + readCallback_->onDataAvailable( + clientAddress_, size_t(bytesRead), truncated); } } else { if (errno == EAGAIN || errno == EWOULDBLOCK) { @@ -293,7 +294,7 @@ bool AsyncUDPSocket::updateRegistration() noexcept { flags |= READ; } - return registerHandler(flags | PERSIST); + return registerHandler(uint16_t(flags | PERSIST)); } } // Namespace diff --git a/folly/io/async/EventBase.cpp b/folly/io/async/EventBase.cpp index 31cec0bf..a493d928 100644 --- a/folly/io/async/EventBase.cpp +++ b/folly/io/async/EventBase.cpp @@ -170,7 +170,7 @@ EventBase::~EventBase() { clearCobTimeouts(); - DCHECK_EQ(0, runBeforeLoopCallbacks_.size()); + DCHECK_EQ(0u, runBeforeLoopCallbacks_.size()); (void)runLoopCallbacks(); diff --git a/folly/io/async/EventHandler.cpp b/folly/io/async/EventHandler.cpp index 5f63418f..a90458d7 100644 --- a/folly/io/async/EventHandler.cpp +++ b/folly/io/async/EventHandler.cpp @@ -62,8 +62,12 @@ bool EventHandler::registerImpl(uint16_t events, bool internal) { // Unfortunately, event_set() resets the event_base, so we have to remember // it before hand, then pass it back into event_base_set() afterwards struct event_base* evb = event_.ev_base; - event_set(&event_, event_.ev_fd, events, - &EventHandler::libeventCallback, this); + event_set( + &event_, + event_.ev_fd, + short(events), + &EventHandler::libeventCallback, + this); event_base_set(evb, &event_); // Set EVLIST_INTERNAL if this is an internal event @@ -157,7 +161,7 @@ void EventHandler::libeventCallback(libevent_fd_t fd, short events, void* arg) { // this can't possibly fire if handler->eventBase_ is nullptr handler->eventBase_->bumpHandlingTime(); - handler->handlerReady(events); + handler->handlerReady(uint16_t(events)); if (observer) { observer->stopped(reinterpret_cast(handler)); diff --git a/folly/io/async/SSLContext.cpp b/folly/io/async/SSLContext.cpp index dd28da58..a6bed842 100644 --- a/folly/io/async/SSLContext.cpp +++ b/folly/io/async/SSLContext.cpp @@ -451,7 +451,7 @@ void SSLContext::switchCiphersIfTLS11( << ", but tls11AltCipherlist is of length " << tls11AltCipherlist.size(); } else { - ciphers = &tls11AltCipherlist[index].first; + ciphers = &tls11AltCipherlist[size_t(index)].first; } } @@ -586,7 +586,7 @@ void SSLContext::unsetNextProtocols() { size_t SSLContext::pickNextProtocols() { CHECK(!advertisedNextProtocols_.empty()) << "Failed to pickNextProtocols"; auto rng = ThreadLocalPRNG(); - return nextProtocolDistribution_(rng); + return size_t(nextProtocolDistribution_(rng)); } int SSLContext::advertisedNextProtocolCallback(SSL* ssl, @@ -669,8 +669,9 @@ void SSLContext::setSessionCacheContext(const std::string& context) { SSL_CTX_set_session_id_context( ctx_, reinterpret_cast(context.data()), - std::min( - static_cast(context.length()), SSL_MAX_SSL_SESSION_ID_LENGTH)); + std::min( + static_cast(context.length()), + SSL_MAX_SSL_SESSION_ID_LENGTH)); } /** @@ -721,7 +722,7 @@ int SSLContext::passwordCallback(char* password, if (length > size) { length = size; } - strncpy(password, userPassword.c_str(), length); + strncpy(password, userPassword.c_str(), size_t(length)); return length; } @@ -772,9 +773,9 @@ static std::map& lockTypes() { static void callbackLocking(int mode, int n, const char*, int) { if (mode & CRYPTO_LOCK) { - locks()[n].lock(); + locks()[size_t(n)].lock(); } else { - locks()[n].unlock(); + locks()[size_t(n)].unlock(); } } @@ -838,9 +839,9 @@ void SSLContext::initializeOpenSSLLocked() { SSL_load_error_strings(); ERR_load_crypto_strings(); // static locking - locks().reset(new SSLLock[::CRYPTO_num_locks()]); + locks().reset(new SSLLock[size_t(::CRYPTO_num_locks())]); for (auto it: lockTypes()) { - locks()[it.first].lockType = it.second; + locks()[size_t(it.first)].lockType = it.second; } CRYPTO_set_id_callback(callbackThreadID); CRYPTO_set_locking_callback(callbackLocking); diff --git a/folly/io/async/test/AsyncSSLSocketWriteTest.cpp b/folly/io/async/test/AsyncSSLSocketWriteTest.cpp index d47af702..326a077c 100644 --- a/folly/io/async/test/AsyncSSLSocketWriteTest.cpp +++ b/folly/io/async/test/AsyncSSLSocketWriteTest.cpp @@ -272,12 +272,12 @@ TEST_F(AsyncSSLSocketWriteTest, write_with_eor1) { EXPECT_TRUE(sock_->isEorTrackingEnabled()); EXPECT_CALL(*(sock_.get()), getRawBytesWritten()) - // rawBytesWritten after writting initAppBytesWritten + 1500 - // + some random SSL overhead - .WillOnce(Return(3600)) - // rawBytesWritten after writting last 6 bytes - // + some random SSL overhead - .WillOnce(Return(3728)); + // rawBytesWritten after writting initAppBytesWritten + 1500 + // + some random SSL overhead + .WillOnce(Return(3600u)) + // rawBytesWritten after writting last 6 bytes + // + some random SSL overhead + .WillOnce(Return(3728u)); EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 1500)) .WillOnce(Invoke([=, &pos] (SSL *, const void *buf, int m) { // the first 1500 does not have the EOR byte diff --git a/folly/io/test/IOBufCursorTest.cpp b/folly/io/test/IOBufCursorTest.cpp index d70c0e4e..cae9c496 100644 --- a/folly/io/test/IOBufCursorTest.cpp +++ b/folly/io/test/IOBufCursorTest.cpp @@ -46,15 +46,15 @@ TEST(IOBuf, RWCursor) { wcursor.writeLE((uint64_t)1); wcursor.write((uint8_t)1); - EXPECT_EQ(1, rcursor.readLE()); + EXPECT_EQ(1u, rcursor.readLE()); rcursor.skip(8); - EXPECT_EQ(1, rcursor.readLE()); + EXPECT_EQ(1u, rcursor.readLE()); rcursor.skip(0); - EXPECT_EQ(0, rcursor.read()); - EXPECT_EQ(0, rcursor.read()); - EXPECT_EQ(0, rcursor.read()); - EXPECT_EQ(0, rcursor.read()); - EXPECT_EQ(1, rcursor.read()); + EXPECT_EQ(0u, rcursor.read()); + EXPECT_EQ(0u, rcursor.read()); + EXPECT_EQ(0u, rcursor.read()); + EXPECT_EQ(0u, rcursor.read()); + EXPECT_EQ(1u, rcursor.read()); } TEST(IOBuf, skip) { @@ -475,7 +475,7 @@ TEST(IOBuf, Printf) { "longer than our original allocation size,", "and will therefore require a new allocation", 0x12345678); // The tailroom should start with a nul byte now. - EXPECT_GE(head.prev()->tailroom(), 1); + EXPECT_GE(head.prev()->tailroom(), 1u); EXPECT_EQ(0, *head.prev()->tail()); EXPECT_EQ("test32this string is longer than our original " @@ -515,10 +515,10 @@ TEST(IOBuf, QueueAppender) { } // There must be a goodMallocSize between 100 and 1024... - EXPECT_LT(1, queue.front()->countChainElements()); + EXPECT_LT(1u, queue.front()->countChainElements()); const IOBuf* buf = queue.front(); do { - EXPECT_LE(100, buf->capacity()); + EXPECT_LE(100u, buf->capacity()); buf = buf->next(); } while (buf != queue.front()); diff --git a/folly/json.cpp b/folly/json.cpp index f101a7b5..4ecb264f 100644 --- a/folly/json.cpp +++ b/folly/json.cpp @@ -487,7 +487,7 @@ std::string decodeUnicodeEscape(Input& in) { in.error("expected 4 hex digits"); } - uint16_t ret = hexVal(*in) * 4096; + uint16_t ret = uint16_t(hexVal(*in) * 4096); ++in; ret += hexVal(*in) * 256; ++in; @@ -669,12 +669,12 @@ void escapeString( // note that this if condition captures non readable chars // with value < 32, so size = 1 byte (e.g control chars). out.append("\\u00"); - out.push_back(hexDigit((*p & 0xf0) >> 4)); - out.push_back(hexDigit(*p & 0xf)); + out.push_back(hexDigit(uint8_t((*p & 0xf0) >> 4))); + out.push_back(hexDigit(uint8_t(*p & 0xf))); p++; } } else { - out.push_back(*p++); + out.push_back(char(*p++)); } } diff --git a/folly/portability/Constexpr.h b/folly/portability/Constexpr.h index 08f9095f..2813194b 100755 --- a/folly/portability/Constexpr.h +++ b/folly/portability/Constexpr.h @@ -70,7 +70,7 @@ struct constexpr_abs_helper< std::is_integral::value && !std::is_same::value && std::is_signed::value>::type> { static constexpr typename std::make_unsigned::type go(T t) { - return t < static_cast(0) ? -t : t; + return typename std::make_unsigned::type(t < static_cast(0) ? -t : t); } }; } // namespace detail diff --git a/folly/portability/Fcntl.cpp b/folly/portability/Fcntl.cpp index 757a63f3..60e59fc5 100755 --- a/folly/portability/Fcntl.cpp +++ b/folly/portability/Fcntl.cpp @@ -36,7 +36,7 @@ int fcntl(int fd, int cmd, ...) { if (h != INVALID_HANDLE_VALUE) { DWORD flags; if (GetHandleInformation(h, &flags)) { - res = flags & HANDLE_FLAG_INHERIT; + res = int(flags & HANDLE_FLAG_INHERIT); } } break; diff --git a/folly/portability/Sockets.cpp b/folly/portability/Sockets.cpp index 11c319a3..68f70c86 100755 --- a/folly/portability/Sockets.cpp +++ b/folly/portability/Sockets.cpp @@ -134,7 +134,7 @@ int inet_aton(const char* cp, struct in_addr* inp) { } const char* inet_ntop(int af, const void* src, char* dst, socklen_t size) { - return ::inet_ntop(af, (char*)src, dst, size); + return ::inet_ntop(af, (char*)src, dst, size_t(size)); } int listen(int s, int backlog) { diff --git a/folly/portability/SysFile.cpp b/folly/portability/SysFile.cpp index b4848816..9e42fa71 100755 --- a/folly/portability/SysFile.cpp +++ b/folly/portability/SysFile.cpp @@ -33,10 +33,9 @@ extern "C" int flock(int fd, int operation) { return -1; } } else { - DWORD flags = 0 - | (operation & LOCK_NB ? LOCKFILE_FAIL_IMMEDIATELY : 0) - | (operation & LOCK_EX ? LOCKFILE_EXCLUSIVE_LOCK : 0) - ; + DWORD flags = DWORD( + (operation & LOCK_NB ? LOCKFILE_FAIL_IMMEDIATELY : 0) | + (operation & LOCK_EX ? LOCKFILE_EXCLUSIVE_LOCK : 0)); OVERLAPPED ov = {}; if (!LockFileEx(h, flags, 0, kMaxDWORD, kMaxDWORD, &ov)) { return -1; diff --git a/folly/portability/Time.cpp b/folly/portability/Time.cpp index 51a8b877..237bc9e3 100755 --- a/folly/portability/Time.cpp +++ b/folly/portability/Time.cpp @@ -198,7 +198,7 @@ extern "C" int clock_getres(clockid_t clock_id, struct timespec* res) { } res->tv_sec = 0; - res->tv_nsec = timeIncrement * 100; + res->tv_nsec = long(timeIncrement * 100); return 0; } diff --git a/folly/portability/Unistd.cpp b/folly/portability/Unistd.cpp index d0435ba6..741be705 100755 --- a/folly/portability/Unistd.cpp +++ b/folly/portability/Unistd.cpp @@ -283,7 +283,7 @@ ssize_t write(int fh, void const* buf, size_t count) { } } auto r = _write(fh, buf, unsigned int(count)); - if ((r > 0 && r != count) || (r == -1 && errno == ENOSPC)) { + if ((r > 0 && size_t(r) != count) || (r == -1 && errno == ENOSPC)) { // Writing to a pipe with a full buffer doesn't generate // any error type, unless it caused us to write exactly 0 // bytes, so we have to see if we have a pipe first. We diff --git a/folly/ssl/OpenSSLHash.h b/folly/ssl/OpenSSLHash.h index b78ce4fe..da05bb0b 100644 --- a/folly/ssl/OpenSSLHash.h +++ b/folly/ssl/OpenSSLHash.h @@ -53,10 +53,10 @@ class OpenSSLHash { } void hash_final(MutableByteRange out) { const auto size = EVP_MD_size(md_); - check_out_size(size, out); + check_out_size(size_t(size), out); unsigned int len = 0; check_libssl_result(1, EVP_DigestFinal_ex(&ctx_, out.data(), &len)); - check_libssl_result(size, len); + check_libssl_result(size, int(len)); md_ = nullptr; } private: @@ -118,7 +118,7 @@ class OpenSSLHash { } void hash_final(MutableByteRange out) { const auto size = EVP_MD_size(md_); - check_out_size(size, out); + check_out_size(size_t(size), out); unsigned int len = 0; check_libssl_result(1, HMAC_Final(&ctx_, out.data(), &len)); check_libssl_result(size, int(len)); diff --git a/folly/ssl/detail/SSLSessionImpl.cpp b/folly/ssl/detail/SSLSessionImpl.cpp index 67dd79e2..7dc39d1a 100644 --- a/folly/ssl/detail/SSLSessionImpl.cpp +++ b/folly/ssl/detail/SSLSessionImpl.cpp @@ -58,7 +58,7 @@ std::string SSLSessionImpl::serialize(void) const { auto len = i2d_SSL_SESSION(session_, nullptr); if (len > 0) { - std::unique_ptr uptr(new unsigned char[len]); + std::unique_ptr uptr(new unsigned char[size_t(len)]); auto p = uptr.get(); auto written = i2d_SSL_SESSION(session_, &p); if (written <= 0) { diff --git a/folly/ssl/test/OpenSSLHashTest.cpp b/folly/ssl/test/OpenSSLHashTest.cpp index a4d4aed4..c63bfd86 100644 --- a/folly/ssl/test/OpenSSLHashTest.cpp +++ b/folly/ssl/test/OpenSSLHashTest.cpp @@ -58,9 +58,12 @@ TEST_F(OpenSSLHashTest, hmac_sha256) { auto combined = ByteRange(StringPiece("foobar")); HMAC( EVP_sha256(), - key.data(), key.size(), - combined.data(), combined.size(), - expected.data(), nullptr); + key.data(), + int(key.size()), + combined.data(), + combined.size(), + expected.data(), + nullptr); auto out = vector(32); OpenSSLHash::hmac_sha256(range(out), key, buf); diff --git a/folly/stats/BucketedTimeSeries-defs.h b/folly/stats/BucketedTimeSeries-defs.h index 08d9c292..ddb77569 100644 --- a/folly/stats/BucketedTimeSeries-defs.h +++ b/folly/stats/BucketedTimeSeries-defs.h @@ -36,7 +36,7 @@ BucketedTimeSeries::BucketedTimeSeries( // There is no point in having more buckets than our timestamp // granularity: otherwise we would have buckets that could never be used. if (nBuckets > size_t(duration_.count())) { - nBuckets = duration_.count(); + nBuckets = size_t(duration_.count()); } buckets_.resize(nBuckets, Bucket()); @@ -269,7 +269,7 @@ uint64_t BucketedTimeSeries::count(TimePoint start, TimePoint end) TimePoint bucketStart, TimePoint nextBucketStart) -> bool { sample_count += this->rangeAdjust( - bucketStart, nextBucketStart, start, end, bucket.count); + bucketStart, nextBucketStart, start, end, ValueType(bucket.count)); return true; }); @@ -291,7 +291,7 @@ ReturnType BucketedTimeSeries::avg(TimePoint start, TimePoint end) total += this->rangeAdjust( bucketStart, nextBucketStart, start, end, bucket.sum); sample_count += this->rangeAdjust( - bucketStart, nextBucketStart, start, end, bucket.count); + bucketStart, nextBucketStart, start, end, ValueType(bucket.count)); return true; }); @@ -346,11 +346,11 @@ void BucketedTimeSeries::getBucketInfo( Duration timeMod = time.time_since_epoch() % duration_; TimeInt numFullDurations = time.time_since_epoch() / duration_; - TimeInt scaledTime = timeMod.count() * buckets_.size(); + TimeInt scaledTime = timeMod.count() * TimeInt(buckets_.size()); // Keep these two lines together. The compiler should be able to compute // both the division and modulus with a single operation. - *bucketIdx = scaledTime / duration_.count(); + *bucketIdx = size_t(scaledTime / duration_.count()); TimeInt scaledOffsetInBucket = scaledTime % duration_.count(); TimeInt scaledBucketStart = scaledTime - scaledOffsetInBucket; @@ -381,8 +381,8 @@ void BucketedTimeSeries::forEachBucket(Function fn) const { Duration timeMod = latestTime_.time_since_epoch() % duration_; TimeInt numFullDurations = latestTime_.time_since_epoch() / duration_; TimePoint durationStart(numFullDurations * duration_); - TimeInt scaledTime = timeMod.count() * buckets_.size(); - size_t latestBucketIdx = scaledTime / duration_.count(); + TimeInt scaledTime = timeMod.count() * TimeInt(buckets_.size()); + size_t latestBucketIdx = size_t(scaledTime / duration_.count()); TimeInt scaledOffsetInBucket = scaledTime % duration_.count(); TimeInt scaledBucketStart = scaledTime - scaledOffsetInBucket; TimeInt scaledNextBucketStart = scaledBucketStart + duration_.count(); diff --git a/folly/stats/BucketedTimeSeries.h b/folly/stats/BucketedTimeSeries.h index 57307e5d..0b531d8f 100644 --- a/folly/stats/BucketedTimeSeries.h +++ b/folly/stats/BucketedTimeSeries.h @@ -271,7 +271,7 @@ class BucketedTimeSeries { */ template ReturnType rate() const { - return rateHelper(total_.sum, elapsed()); + return rateHelper(ReturnType(total_.sum), elapsed()); } /* @@ -288,7 +288,8 @@ class BucketedTimeSeries { */ template ReturnType countRate() const { - return rateHelper(total_.count, elapsed()); + return rateHelper( + ReturnType(total_.count), elapsed()); } /* @@ -349,7 +350,8 @@ class BucketedTimeSeries { ReturnType countRate(TimePoint start, TimePoint end) const { uint64_t intervalCount = count(start, end); Duration interval = elapsed(start, end); - return rateHelper(intervalCount, interval); + return rateHelper( + ReturnType(intervalCount), interval); } /* @@ -412,7 +414,7 @@ class BucketedTimeSeries { return addValueAggregated(TimePoint(now), val, 1); } bool addValue(Duration now, const ValueType& val, int64_t times) { - return addValueAggregated(TimePoint(now), val * times, times); + return addValueAggregated(TimePoint(now), val * ValueType(times), times); } bool addValueAggregated(Duration now, const ValueType& total, int64_t nsamples) { diff --git a/folly/stats/Histogram.h b/folly/stats/Histogram.h index fbb25983..a6daa374 100644 --- a/folly/stats/Histogram.h +++ b/folly/stats/Histogram.h @@ -125,7 +125,7 @@ class HistogramBuckets { return max_; } - return min_ + ((idx - 1) * bucketSize_); + return ValueType(min_ + ((idx - 1) * bucketSize_)); } /* @@ -140,7 +140,7 @@ class HistogramBuckets { return std::numeric_limits::max(); } - return min_ + (idx * bucketSize_); + return ValueType(min_ + (idx * bucketSize_)); } /** diff --git a/folly/stats/MultiLevelTimeSeries-defs.h b/folly/stats/MultiLevelTimeSeries-defs.h index 8451af5c..11b2afd5 100644 --- a/folly/stats/MultiLevelTimeSeries-defs.h +++ b/folly/stats/MultiLevelTimeSeries-defs.h @@ -75,7 +75,7 @@ void MultiLevelTimeSeries::addValue( TimePoint now, const ValueType& val, uint64_t times) { - addValueAggregated(now, val * times, times); + addValueAggregated(now, val * ValueType(times), times); } template diff --git a/folly/test/IndexedMemPoolTest.cpp b/folly/test/IndexedMemPoolTest.cpp index ff0a634c..109c63f5 100644 --- a/folly/test/IndexedMemPoolTest.cpp +++ b/folly/test/IndexedMemPoolTest.cpp @@ -44,7 +44,7 @@ TEST(IndexedMemPool, unique_ptr) { break; } leak.emplace_back(std::move(ptr)); - EXPECT_LT(leak.size(), 10000); + EXPECT_LT(leak.size(), 10000u); } } @@ -75,7 +75,7 @@ TEST(IndexedMemPool, no_starvation) { for (auto i = 0; i < count; ++i) { Sched::wait(&allocSem); uint32_t idx = pool.allocIndex(); - EXPECT_NE(idx, 0); + EXPECT_NE(idx, 0u); EXPECT_LE(idx, poolSize + (pool.NumLocalLists - 1) * pool.LocalListLimit); pool[idx] = i; @@ -90,7 +90,7 @@ TEST(IndexedMemPool, no_starvation) { Sched::wait(&readSem); EXPECT_EQ(read(fd[0], &idx, sizeof(idx)), sizeof(idx)); EXPECT_NE(idx, 0); - EXPECT_GE(idx, 1); + EXPECT_GE(idx, 1u); EXPECT_LE(idx, poolSize + (Pool::NumLocalLists - 1) * Pool::LocalListLimit); EXPECT_EQ(pool[idx], i); @@ -111,12 +111,12 @@ TEST(IndexedMemPool, st_capacity) { typedef IndexedMemPool Pool; Pool pool(10); - EXPECT_EQ(pool.capacity(), 10); - EXPECT_EQ(Pool::maxIndexForCapacity(10), 10); + EXPECT_EQ(pool.capacity(), 10u); + EXPECT_EQ(Pool::maxIndexForCapacity(10), 10u); for (auto i = 0; i < 10; ++i) { - EXPECT_NE(pool.allocIndex(), 0); + EXPECT_NE(pool.allocIndex(), 0u); } - EXPECT_EQ(pool.allocIndex(), 0); + EXPECT_EQ(pool.allocIndex(), 0u); } TEST(IndexedMemPool, mt_capacity) { @@ -128,7 +128,7 @@ TEST(IndexedMemPool, mt_capacity) { threads[i] = std::thread([&]() { for (auto j = 0; j < 100; ++j) { uint32_t idx = pool.allocIndex(); - EXPECT_NE(idx, 0); + EXPECT_NE(idx, 0u); } }); } @@ -140,7 +140,7 @@ TEST(IndexedMemPool, mt_capacity) { for (auto i = 0; i < 16 * 32; ++i) { pool.allocIndex(); } - EXPECT_EQ(pool.allocIndex(), 0); + EXPECT_EQ(pool.allocIndex(), 0u); } TEST(IndexedMemPool, locate_elem) { diff --git a/folly/test/MathTest.cpp b/folly/test/MathTest.cpp index acd40305..dba0d35c 100644 --- a/folly/test/MathTest.cpp +++ b/folly/test/MathTest.cpp @@ -106,14 +106,14 @@ std::vector cornerValues() { std::vector rv; for (T i = 1; i < 24; ++i) { rv.push_back(i); - rv.push_back(std::numeric_limits::max() / i); - rv.push_back(std::numeric_limits::max() - i); - rv.push_back(std::numeric_limits::max() / 2 - i); + rv.push_back(T(std::numeric_limits::max() / i)); + rv.push_back(T(std::numeric_limits::max() - i)); + rv.push_back(T(std::numeric_limits::max() / T(2) - i)); if (std::is_signed::value) { rv.push_back(-i); - rv.push_back(std::numeric_limits::min() / i); - rv.push_back(std::numeric_limits::min() + i); - rv.push_back(std::numeric_limits::min() / 2 + i); + rv.push_back(T(std::numeric_limits::min() / i)); + rv.push_back(T(std::numeric_limits::min() + i)); + rv.push_back(T(std::numeric_limits::min() / T(2) + i)); } } return rv;