Make most implicit integer truncations and sign conversions explicit
authorChristopher Dykes <cdykes@fb.com>
Fri, 27 Jan 2017 02:01:31 +0000 (18:01 -0800)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Fri, 27 Jan 2017 02:03:01 +0000 (18:03 -0800)
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

78 files changed:
folly/AtomicHashMap-inl.h
folly/AtomicHashMap.h
folly/AtomicUnorderedMap.h
folly/Benchmark.cpp
folly/Benchmark.h
folly/Bits.h
folly/ConcurrentSkipList-inl.h
folly/ConcurrentSkipList.h
folly/Conv.cpp
folly/Exception.h
folly/FBVector.h
folly/Format-inl.h
folly/Format.cpp
folly/GroupVarint.h
folly/IPAddress.cpp
folly/IPAddressV6.cpp
folly/IndexedMemPool.h
folly/MPMCPipeline.h
folly/MPMCQueue.h
folly/Math.h
folly/MemoryMapping.cpp
folly/Padded.h
folly/PicoSpinLock.h
folly/Range.h
folly/SocketAddress.cpp
folly/SocketAddress.h
folly/String-inl.h
folly/String.cpp
folly/ThreadCachedInt.h
folly/Varint.h
folly/build/GenerateFingerprintTables.cpp
folly/detail/CacheLocality.cpp
folly/detail/FingerprintPolynomial.h
folly/detail/IPAddressSource.h
folly/detail/RangeSse42.cpp
folly/dynamic.cpp
folly/experimental/AsymmetricMemoryBarrier.cpp
folly/experimental/BitVectorCoding.h
folly/experimental/Bits.h
folly/experimental/EliasFanoCoding.h
folly/experimental/Instructions.h
folly/experimental/JSONSchema.cpp
folly/experimental/TestUtil.cpp
folly/experimental/bser/Dump.cpp
folly/experimental/bser/Load.cpp
folly/experimental/io/HugePages.cpp
folly/fibers/GuardPageAllocator.cpp
folly/fibers/WhenN-inl.h
folly/futures/Future-inl.h
folly/gen/Parallel-inl.h
folly/io/IOBuf.cpp
folly/io/RecordIO.cpp
folly/io/ShutdownSocketSet.cpp
folly/io/async/AsyncPipe.cpp
folly/io/async/AsyncSSLSocket.cpp
folly/io/async/AsyncSocket.cpp
folly/io/async/AsyncUDPSocket.cpp
folly/io/async/EventBase.cpp
folly/io/async/EventHandler.cpp
folly/io/async/SSLContext.cpp
folly/io/async/test/AsyncSSLSocketWriteTest.cpp
folly/io/test/IOBufCursorTest.cpp
folly/json.cpp
folly/portability/Constexpr.h
folly/portability/Fcntl.cpp
folly/portability/Sockets.cpp
folly/portability/SysFile.cpp
folly/portability/Time.cpp
folly/portability/Unistd.cpp
folly/ssl/OpenSSLHash.h
folly/ssl/detail/SSLSessionImpl.cpp
folly/ssl/test/OpenSSLHashTest.cpp
folly/stats/BucketedTimeSeries-defs.h
folly/stats/BucketedTimeSeries.h
folly/stats/Histogram.h
folly/stats/MultiLevelTimeSeries-defs.h
folly/test/IndexedMemPoolTest.cpp
folly/test/MathTest.cpp

index 184e2b967f9b4fd0bec2488eebd0155e9b4918d9..e00312662e942b6d6c65eb6287d7191f2f6e4638 100644 (file)
@@ -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 <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.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 @@ AtomicHashMap<KeyT, ValueT, HashFcn, EqualFcn,
   if (LIKELY(ret.idx != primaryMap->capacity_)) {
     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);
index 0ed0922445f34b9118209076a84d110322490111..ef27f860df41229eb586e63ea7961783ceedcd93 100644 (file)
@@ -197,7 +197,8 @@ typedef AtomicHashArray<KeyT, ValueT, HashFcn, EqualFcn,
   explicit AtomicHashMap(size_t finalSizeEst, const Config& c = Config());
 
   ~AtomicHashMap() {
-    const int numMaps = numMapsAllocated_.load(std::memory_order_relaxed);
+    const unsigned int numMaps =
+        numMapsAllocated_.load(std::memory_order_relaxed);
     FOR_EACH_RANGE (i, 0, numMaps) {
       SubMap* thisMap = subMaps_[i].load(std::memory_order_relaxed);
       DCHECK(thisMap);
index 75ab6f5571845e8df6752df3c2532e98bf99ed7d..12c02579d6b2f81fd25bbdaaa6150620b5fbaca0 100644 (file)
@@ -212,7 +212,7 @@ struct AtomicUnorderedInsertMap {
       const Allocator& alloc = Allocator())
     : allocator_(alloc)
   {
-    size_t capacity = maxSize / std::min(1.0f, maxLoadFactor) + 128;
+    size_t capacity = size_t(maxSize / std::min(1.0f, maxLoadFactor) + 128);
     size_t avail = size_t{1} << (8 * sizeof(IndexType) - 2);
     if (capacity > 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;
index aada48b5e7f13262449e186294446711297100e8..4ec24c72970e2386831615baf47785b304cc83ea 100644 (file)
@@ -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<uint64_t>(FLAGS_bm_min_usec * 1000UL,
-        min<uint64_t>(resolutionInNs * 100000, 1000000000ULL));
+  static const auto minNanoseconds = max<uint64_t>(
+      uint64_t(FLAGS_bm_min_usec) * 1000ULL,
+      min<uint64_t>(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<unsigned int>(n));
       if (nsecsAndIter.first < minNanoseconds) {
         continue;
       }
index d1ed12114b204aeeca9bb8a7f52473d34ea0a88f..e954798790510b26f203f96229464fe5fd518a54 100644 (file)
@@ -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<uint64_t>::max() / 1000000000UL);
-  return diff * 1000000000UL
-    + end.tv_nsec - start.tv_nsec;
+  assert(diff < std::numeric_limits<uint64_t>::max() / 1000000000ULL);
+  return diff * 1000000000ULL + end.tv_nsec - start.tv_nsec;
 }
 
 /**
index e4b1b5ea0c38e4d660c2e1af443d07942174da9f..7e59ce3093267a7fad7e5bdbe1a8d8c08cb3c42d 100644 (file)
@@ -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<unsigned int>(__builtin_ffs(static_cast<int>(x)));
 }
 
 template <class T>
@@ -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<unsigned int>(__builtin_ffsl(static_cast<long>(x)));
 }
 
 template <class T>
@@ -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<unsigned int>(__builtin_ffsll(static_cast<long long>(x)));
 }
 
 template <class T>
@@ -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 <class T>
@@ -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_;
index 8b6f77f6922831f7313557048e7e42cdea028390..cf04ee725d25579a20047c213b3a8c73a5fab209 100644 (file)
@@ -59,7 +59,7 @@ class SkipListNode : private boost::noncopyable {
       height * sizeof(std::atomic<SkipListNode*>);
     auto* node = static_cast<SkipListNode*>(alloc.allocate(size));
     // do placement new
-    new (node) SkipListNode(height, std::forward<U>(data), isHead);
+    new (node) SkipListNode(uint8_t(height), std::forward<U>(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:
index a1193837b011095b3768170af2fcc1dcef43224e..7d5cb9589c478fa2bcdf916a623d9149bf0fab10 100644 (file)
@@ -718,7 +718,7 @@ class ConcurrentSkipList<T, Comp, NodeAlloc, MAX_HEIGHT>::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;
   }
index 04f2252a03d222b57c69764a1191921e0ac9cea0..6af0f90fbecd51754c6dcf9b05a82ca2d1d9aa4a 100644 (file)
@@ -269,7 +269,7 @@ Expected<bool, ConversionCode> 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<Tgt, ConversionCode> 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<Tgt, ConversionCode> 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<T, true> {
   Expected<T, ConversionCode> 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<Tgt, ConversionCode> 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<Tgt, ConversionCode> 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<Tgt, ConversionCode> 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;
index 220628e234f55fa88fc1716ee4e5adad03acf50c..28e0793816dbfcf448416fe5e441623792be1d1b 100644 (file)
@@ -66,7 +66,7 @@ void checkPosixError(int err, Args&&... args) {
 template <class... Args>
 void checkKernelError(ssize_t ret, Args&&... args) {
   if (UNLIKELY(ret < 0)) {
-    throwSystemErrorExplicit(-ret, std::forward<Args>(args)...);
+    throwSystemErrorExplicit(int(-ret), std::forward<Args>(args)...);
   }
 }
 
index 17f9f5ee01c74d019eb071974a09188e3853fe4e..3bdb0cf2737a65535dee0d6a0e7a1ca286f26307 100644 (file)
@@ -800,7 +800,7 @@ private:
   template <class ForwardIterator>
   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 <class InputIterator>
@@ -827,7 +827,7 @@ private:
   template <class ForwardIterator>
   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<T*>(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 <class FIt>
   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);
index 945aa59ee296281777e3a51efc4361bf2ff4a194..deb8bdaa30db9ffc293eab1cd7ffac1a48e4f28b 100644 (file)
@@ -388,7 +388,7 @@ void formatFormatter(
       int sz = static_cast<int>(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<std::tuple<Args...>> {
   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:
index 177f9783e4afa4de4cf55ddac3205f30f8d15dec..11f87e9da61e64617d04fdd440c5794fa24d063e 100644 (file)
@@ -168,7 +168,7 @@ void FormatArg::initSlow() {
   auto end = fullArgString.end();
 
   // Parse key
-  auto p = static_cast<const char*>(memchr(b, ':', end - b));
+  auto p = static_cast<const char*>(memchr(b, ':', size_t(end - b)));
   if (!p) {
     key_ = StringPiece(b, end);
     return;
index 8160c380b9e08ad24a3751e17c4bc192c1555782..9652a4d1ad185967dac209184305841e56b18005 100644 (file)
@@ -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_);
   }
 
index 0bd391024cd28ac9993b83b524b951b2b70717b3..792b75a4afac5a1da4b6c39580f4185e0bf517fb 100644 (file)
@@ -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 {
index 328d067477e334065e24bb262913faa5b270d140..9a7758c0e095bbbd66723fd7c0e72df83185ec79 100644 (file)
@@ -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 {
index 3a7524e1219ef46ed344d3eb889001fe1e48e543..9b373da57e03cc2f91005be8cb4f9787f485290b 100644 (file)
@@ -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<uint32_t>::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<uint32_t>::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);
index 4fef5ead5ad82a2601b04b0a6db8faf09333b493..eca0b29b7fda3bc27b0ef97dab48e00e9345962d 100644 (file)
@@ -275,8 +275,9 @@ template <class In, class... Stages> class MPMCPipeline {
    * in any queue) are also counted.
    */
   ssize_t sizeGuess() const noexcept {
-    return (std::get<0>(stages_).writeCount() * kAmplification -
-            std::get<sizeof...(Stages)>(stages_).readCount());
+    return ssize_t(
+        std::get<0>(stages_).writeCount() * kAmplification -
+        std::get<sizeof...(Stages)>(stages_).readCount());
   }
 
  private:
index 22798880d4e9c58e3ddbb34382f6711f1475f370..b0cfc46f6dfc833c839544f055bd12f4282835fd 100644 (file)
@@ -1155,7 +1155,7 @@ class MPMCQueueBase<Derived<T, Atom, Dynamic>> : 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<ssize_t>(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
index 6b61a2cc1b9fa0d9d954b5577981f27a9e7fcf42..e31335a118032be65c96d7425da6b0f534ea061e 100644 (file)
@@ -132,9 +132,10 @@ constexpr auto kIntegerDivisionGivesRemainder = true;
 template <typename N, typename D>
 inline constexpr detail::IdivResultType<N, D> divFloor(N num, D denom) {
   using R = decltype(num / denom);
-  return kIntegerDivisionGivesRemainder && std::is_signed<R>::value
-      ? detail::divFloorBranchless<R>(num, denom)
-      : detail::divFloorBranchful<R>(num, denom);
+  return detail::IdivResultType<N, D>(
+      kIntegerDivisionGivesRemainder && std::is_signed<R>::value
+          ? detail::divFloorBranchless<R>(num, denom)
+          : detail::divFloorBranchful<R>(num, denom));
 }
 
 /**
@@ -151,9 +152,10 @@ inline constexpr detail::IdivResultType<N, D> divFloor(N num, D denom) {
 template <typename N, typename D>
 inline constexpr detail::IdivResultType<N, D> divCeil(N num, D denom) {
   using R = decltype(num / denom);
-  return kIntegerDivisionGivesRemainder && std::is_signed<R>::value
-      ? detail::divCeilBranchless<R>(num, denom)
-      : detail::divCeilBranchful<R>(num, denom);
+  return detail::IdivResultType<N, D>(
+      kIntegerDivisionGivesRemainder && std::is_signed<R>::value
+          ? detail::divCeilBranchless<R>(num, denom)
+          : detail::divCeilBranchful<R>(num, denom));
 }
 
 /**
@@ -175,7 +177,7 @@ inline constexpr detail::IdivResultType<N, D> divCeil(N num, D denom) {
  */
 template <typename N, typename D>
 inline constexpr detail::IdivResultType<N, D> divTrunc(N num, D denom) {
-  return num / denom;
+  return detail::IdivResultType<N, D>(num / denom);
 }
 
 /**
@@ -193,9 +195,10 @@ inline constexpr detail::IdivResultType<N, D> divTrunc(N num, D denom) {
 template <typename N, typename D>
 inline constexpr detail::IdivResultType<N, D> divRoundAway(N num, D denom) {
   using R = decltype(num / denom);
-  return kIntegerDivisionGivesRemainder && std::is_signed<R>::value
-      ? detail::divRoundAwayBranchless<R>(num, denom)
-      : detail::divRoundAwayBranchful<R>(num, denom);
+  return detail::IdivResultType<N, D>(
+      kIntegerDivisionGivesRemainder && std::is_signed<R>::value
+          ? detail::divRoundAwayBranchless<R>(num, denom)
+          : detail::divRoundAwayBranchful<R>(num, denom));
 }
 
 } // namespace folly
index 89799fd143d5f38fc3deea189b39654c4bcdec66..a92e73f8725506f6cf8e90c97ae85b2d6caaeb92 100644 (file)
@@ -188,13 +188,13 @@ void MemoryMapping::init(off_t offset, off_t length) {
               (options_.writable ? PROT_WRITE : 0));
     }
 
-    unsigned char* start = static_cast<unsigned char*>(
-      mmap(options_.address, mapLength_, prot, flags, file_.fd(), offset));
+    unsigned char* start = static_cast<unsigned char*>(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<int(void*, size_t)> 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<char*>(mem);
   amountSucceeded = 0;
@@ -251,8 +251,12 @@ bool memOpInChunks(std::function<int(void*, size_t)> 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_))
index 0a772a2d56fceb458d4e9a95b4775960d799bfdc..93b37ab4e4abfee37e47d73259150a220053db58 100644 (file)
@@ -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;
   }
index b73f9f752f7939cfdcfc2758a3a6c35e5d80b2f8..02d7bc924183f8f5d59facaff3062731ba821504 100644 (file)
@@ -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);
   }
 
   /*
index 7872383ce8b46a1239b66338e034101f16a367e3..d205a7b3d654c8b839f6346ae740899ad997ac16 100644 (file)
@@ -168,6 +168,7 @@ public:
   typedef typename std::remove_reference<
     typename std::iterator_traits<Iter>::reference>::type
   value_type;
+  using difference_type = typename std::iterator_traits<Iter>::difference_type;
   typedef typename std::iterator_traits<Iter>::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<Iter>::difference_type(
+                  delimiter.size()));
 
     return result;
   }
index 785ff468fd2b53fb4e6ca668d0ca1eef45f2dc34..88781dad0d1594397bdc4f0b7b4da529d95a32d4 100644 (file)
@@ -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 "<abstract unix address>";
     }
 
-    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()) {
index e6a63626e0ad434108cf10d1ea99cc7d05f08b4f..480a37d94941f02a577942f62e9373f716fd02e7 100644 (file)
@@ -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<char*>(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);
index 392bd672549f934cf4b8af0c1f2778046c81671a..dbfefa010fb6f97ac530ce280b74f086996b7ec0 100644 (file)
@@ -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 <class String>
@@ -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 {
index 2cb3fb6f3ea6aa6eca6fccf1e37a45a06545a09b..e8de48dac9c10dfd72460f98b466a7e6e9ab6556 100644 (file)
@@ -66,21 +66,21 @@ void stringAppendfImpl(std::string& output, const char* format, va_list args) {
   }
 
   if (static_cast<size_t>(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<char[]> heap_buffer(new char[bytes_used + 1]);
-  int final_bytes_used =
-      stringAppendfImplHelper(heap_buffer.get(), bytes_used + 1, format, args);
+  std::unique_ptr<char[]> 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) {
index 3ed53b20bacf584e1951c70f8dd49a5f2fa893f2..58816e37f363e7ef88b3188ff69133d03eec1ff7 100644 (file)
@@ -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
index 6cb42d1fa9d2f84308a92547fc483a255f676ca0..4664cb95d4f5c4e2aa33efdb95f3398199ff1b53 100644 (file)
@@ -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 <class T>
index 28018fd686faae0065d891f12cb51630a4e99afc..4911fb589ec6c52efd83ab180f783dc428924d2a 100644 (file)
@@ -73,7 +73,7 @@ void computeTables(FILE* file, const FingerprintPolynomial<DEG>& poly) {
   // whose coefficients are the bits of q.
   for (int x = 0; x < 256; x++) {
     FingerprintPolynomial<DEG> 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]));
index b5737cdae50c7cfa4ec9c1dd1f444971a266f657..7b9f7e9d81a5d02d400cab808e70672f5036ecc4 100644 (file)
@@ -55,7 +55,7 @@ static CacheLocality getSystemLocalityInfo() {
     // wiggle room
     numCpus = 32;
   }
-  return CacheLocality::uniform(numCpus);
+  return CacheLocality::uniform(size_t(numCpus));
 }
 
 template <>
index a4d3dbd04f2a6647207845bd6a770fd29ed97870..db9a178393ad4c8717086dbfa5880811f9e23030 100644 (file)
@@ -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;
index 9447812d63018372830aebe15b8bcd3746de9233..a785c98582b7a48357160c0d71329ae34bd2d93c 100644 (file)
@@ -51,7 +51,7 @@ struct Bytes {
     std::size_t asize = a.size();
     std::array<uint8_t, N> 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<IntegralType>::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 {
index 053aba7dbbf6bd82530be6a8c9bf1bd64f880a31..d54a4a36a8c2dd064b2eb76ff59e02b95e7c6a32 100644 (file)
@@ -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...
index 47fba09b1ce1c61ffb12b3ef64336e4922f333b7..c2fac276628b2d2842708c773d3e11e6d446a179 100644 (file)
@@ -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<ObjectImpl>()) {
     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<ObjectImpl>()) {
     auto it = pobject->find(idx);
     if (it == pobject->end()) {
index 03dc8249526778ef12feaf21c5a44ba6ee1f8eac..55bec5f141bdc17d35d6347c1477b8d8dc9b4ac4 100644 (file)
@@ -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<uintptr_t>(ptr), "mmap");
+    checkUnixError(reinterpret_cast<ssize_t>(ptr), "mmap");
 
     // Optimistically try to lock the page so it stays resident. Could make
     // the heavy barrier faster.
index 7c96338889fcbef7e15e6d5e11ef68386a458e69..e2290fcd3d8f35dd25f79c998c09018c87febc4c 100644 (file)
@@ -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);
     }
index a12080501ed585f771500acbbb9143ea72c4667c..191cb2d2bbe9dfb43a348c5d495f5c5eafefaef0 100644 (file)
@@ -242,8 +242,9 @@ inline void Bits<T, Traits>::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<UnderlyingType>::value) {
       nextBlock &= ones(countInNextBlock);
     }
index cc2602d203f5932eed452747e5488fe15295839e..acc949a56359daf8616cf2db88d1079b50175234 100644 (file)
@@ -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<block_t>(start_) : 0;
     outer_ = 0;
-    inner_ = -1;
-    position_ = -1;
+    inner_ = std::numeric_limits<size_t>::max();
+    position_ = std::numeric_limits<size_t>::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);
index ab2db160d9ec180316bd293ef30e8e87983914a4..a2754b8907c6acf498a7ae64ac2633bc44ca9e75 100644 (file)
@@ -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);
index f2b9ec50bd189e6cc3d52f422a16debb4a7cb6bb..f559a545d5985e6d886a6827c3b2b0bf58787ffb 100644 (file)
@@ -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;
index dc680d6d89dcbe728600688f693cc2cfa88469d0..aeef414bcc31f04050be0e70fe3a421c16b18cd9 100644 (file)
@@ -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<char[]> 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);
 }
index dbf7c74662e0672a9c52c265006ec6590f016dc7..4a8d5b5110fa4978540676dc39e42af39d4cf669 100644 (file)
@@ -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<std::pair<dynamic, dynamic>> sorted(dyn.items().begin(),
index 161f72a31626caf7ed6144db889398a9fa851bb9..e462ee491092c9ce8cea7d00491f3950d3e7367e 100644 (file)
@@ -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<const char*>(curs.data()), len);
-  curs.skipAtMost(len);
+  str.append(reinterpret_cast<const char*>(curs.data()), size_t(len));
+  curs.skipAtMost(size_t(len));
   return str;
 }
 
index 0733d3a968afb53516642f716e2d4198c0253d5f..f94b818b2aa0a94500fe7a35786377fed29f5b1a 100644 (file)
@@ -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<size_t>(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<size_t>(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<size_t>(numStr);
   switch (c) {
   case 't': size *= 1024;
index 2a3aff7071ee508857d45643471968fb5572ae8a..fe521a472c74a1b83d2e7a56583a252e3cd5d71d 100644 (file)
@@ -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<std::pair<unsigned char*, bool>> 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;
   }
 
index 8b7fa6218067bc5078354eb089fab8693664d87d..160301c18f8b6b4f685409af2db8b8f150f4a3b4 100644 (file)
@@ -160,7 +160,7 @@ typename std::vector<
         type> inline collectAll(InputIterator first, InputIterator last) {
   typedef typename std::result_of<
       typename std::iterator_traits<InputIterator>::value_type()>::type Result;
-  size_t n = std::distance(first, last);
+  size_t n = size_t(std::distance(first, last));
   std::vector<Result> results;
   std::vector<size_t> order(n);
   results.reserve(n);
index 6ac7acdb561ca1e43d184f62c8b5fc7fab545b52..28935a218ff157fe1e0d1d605fc266ee31d99939 100644 (file)
@@ -594,7 +594,8 @@ collectAll(InputIterator first, InputIterator last) {
     std::vector<Try<T>> results;
   };
 
-  auto ctx = std::make_shared<CollectAllContext>(std::distance(first, last));
+  auto ctx =
+      std::make_shared<CollectAllContext>(size_t(std::distance(first, last)));
   mapSetCallback<T>(first, last, [ctx](size_t i, Try<T>&& t) {
     ctx->results[i] = std::move(t);
   });
@@ -723,7 +724,7 @@ collectAnyWithoutException(InputIterator first, InputIterator last) {
   };
 
   auto ctx = std::make_shared<CollectAnyWithoutExceptionContext>();
-  ctx->nTotal = std::distance(first, last);
+  ctx->nTotal = size_t(std::distance(first, last));
 
   mapSetCallback<T>(first, last, [ctx](size_t i, Try<T>&& t) {
     if (!t.hasException() && !ctx->done.exchange(true)) {
index 0992cacd889c17da41e1ee5f357cf748864bcaec..18c7c4342d0a32f35c7857ca34932e2207f2fbc4 100644 (file)
@@ -293,8 +293,9 @@ class Parallel : public Operator<Parallel<Ops>> {
         : source_(std::move(source)),
           ops_(std::move(ops)),
           threads_(
-              threads ? threads
-                      : std::max<size_t>(1, sysconf(_SC_NPROCESSORS_CONF))) {}
+              threads
+                  ? threads
+                  : size_t(std::max<long>(1, sysconf(_SC_NPROCESSORS_CONF)))) {}
 
     template <class Handler>
     bool apply(Handler&& handler) const {
index caccec139bcdb1564e0b6cabfc982cb3856d87d7..2a295aa8a0289a1f845609cf4ce8965b6b47051b 100644 (file)
@@ -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> IOBuf::createCombined(uint64_t capacity) {
 
   uint8_t* bufAddr = reinterpret_cast<uint8_t*>(&storage->align);
   uint8_t* storageEnd = reinterpret_cast<uint8_t*>(storage) + mallocSize;
-  size_t actualCapacity = storageEnd - bufAddr;
+  size_t actualCapacity = size_t(storageEnd - bufAddr);
   unique_ptr<IOBuf> 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;
 }
 
index ba3512136be4dc664cc3edc3976b47c8332ebdfa..50c854ec01062bb23b0c0c1b6d216f14393f7724 100644 (file)
@@ -66,7 +66,7 @@ void RecordIOWriter::write(std::unique_ptr<IOBuf> 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();
   }
 }
index 138091c3362a7ce0fb41865b814ca8f2b300d190..839fd3869882b22748c8255906442a8dad649f4a 100644 (file)
 namespace folly {
 
 ShutdownSocketSet::ShutdownSocketSet(int maxFd)
-  : maxFd_(maxFd),
-    data_(static_cast<std::atomic<uint8_t>*>(
-            folly::checkedCalloc(maxFd, sizeof(std::atomic<uint8_t>)))),
-    nullFile_("/dev/null", O_RDWR) {
-}
+    : maxFd_(maxFd),
+      data_(static_cast<std::atomic<uint8_t>*>(
+          folly::checkedCalloc(size_t(maxFd), sizeof(std::atomic<uint8_t>)))),
+      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);
     }
index 94f73b7d031aac541901bc2a3d937f428c4f83c7..d64a164d6c4706a96559a51ca7e8163e1de7a3d2 100644 (file)
@@ -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();
index d6fe249580eeda49f79c3884cb81fd5f9c22ef6e..1f66ddd640dc1d6821d8c8568cde4c45d7cca454 100644 (file)
@@ -1580,7 +1580,7 @@ int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
   AsyncSSLSocket* tsslSock;
 
   iov.iov_base = const_cast<char*>(in);
-  iov.iov_len = inl;
+  iov.iov_len = size_t(inl);
   memset(&msg, 0, sizeof(msg));
   msg.msg_iov = &iov;
   msg.msg_iovlen = 1;
index db6231291cbb55989836fb68c0d34691b09cfedf..bbdbc46cec4ff2de7b7918bc46ea0f0cae453f93 100644 (file)
@@ -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"));
index a516f9ae406074512f681dd8dc9b663c078e2e3d..5d99e44465aa0584e1223737a30005f94abaebed 100644 (file)
@@ -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<sockaddr*>(&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
index 31cec0bfd5e787aeee4fc121df2a1b66e3117b8d..a493d928e29d08f7ebce4cb878d52f5135b39e0c 100644 (file)
@@ -170,7 +170,7 @@ EventBase::~EventBase() {
 
   clearCobTimeouts();
 
-  DCHECK_EQ(0, runBeforeLoopCallbacks_.size());
+  DCHECK_EQ(0u, runBeforeLoopCallbacks_.size());
 
   (void)runLoopCallbacks();
 
index 5f63418fcfc8dd183c8c90001ffb3337b64acf8d..a90458d74124e5d3a5d6f3e925e9cf3348ecfbab 100644 (file)
@@ -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<uintptr_t>(handler));
index dd28da58fb7236629103f1bb0196a40af7ebe42a..a6bed842922169a1b3bc1d1b6b30702dd44678ff 100644 (file)
@@ -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<const unsigned char*>(context.data()),
-      std::min(
-          static_cast<int>(context.length()), SSL_MAX_SSL_SESSION_ID_LENGTH));
+      std::min<unsigned int>(
+          static_cast<unsigned int>(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<int, SSLContext::SSLLockType>& 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);
index d47af702d428a17bc9e265630f17c267c343945b..326a077c85f43166cd528abd6192155743e140e1 100644 (file)
@@ -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
index d70c0e4e81d4422056124d88ed0b4d59775890cd..cae9c496baaf831d5c7660dc648dcfded769e51c 100644 (file)
@@ -46,15 +46,15 @@ TEST(IOBuf, RWCursor) {
   wcursor.writeLE((uint64_t)1);
   wcursor.write((uint8_t)1);
 
-  EXPECT_EQ(1, rcursor.readLE<uint64_t>());
+  EXPECT_EQ(1u, rcursor.readLE<uint64_t>());
   rcursor.skip(8);
-  EXPECT_EQ(1, rcursor.readLE<uint32_t>());
+  EXPECT_EQ(1u, rcursor.readLE<uint32_t>());
   rcursor.skip(0);
-  EXPECT_EQ(0, rcursor.read<uint8_t>());
-  EXPECT_EQ(0, rcursor.read<uint8_t>());
-  EXPECT_EQ(0, rcursor.read<uint8_t>());
-  EXPECT_EQ(0, rcursor.read<uint8_t>());
-  EXPECT_EQ(1, rcursor.read<uint8_t>());
+  EXPECT_EQ(0u, rcursor.read<uint8_t>());
+  EXPECT_EQ(0u, rcursor.read<uint8_t>());
+  EXPECT_EQ(0u, rcursor.read<uint8_t>());
+  EXPECT_EQ(0u, rcursor.read<uint8_t>());
+  EXPECT_EQ(1u, rcursor.read<uint8_t>());
 }
 
 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());
 
index f101a7b59e20c1489a485e8641a4fd604f09f4ff..4ecb264fbd567b3283a121123d47905fb0f354d2 100644 (file)
@@ -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++));
     }
   }
 
index 08f9095fb5ea5addc17a0b8e1d7c3a79f9e22aef..2813194b2d98f81061d759ba5be767af879b0e95 100755 (executable)
@@ -70,7 +70,7 @@ struct constexpr_abs_helper<
         std::is_integral<T>::value && !std::is_same<T, bool>::value &&
         std::is_signed<T>::value>::type> {
   static constexpr typename std::make_unsigned<T>::type go(T t) {
-    return t < static_cast<T>(0) ? -t : t;
+    return typename std::make_unsigned<T>::type(t < static_cast<T>(0) ? -t : t);
   }
 };
 } // namespace detail
index 757a63f38488bc5925e78a0f57f43bb4be4b0328..60e59fc57f84e73b2b0de9c87b5fe6ea3d73d79d 100755 (executable)
@@ -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;
index 11c319a3adcbdbb268f73422a77a0a6b53fac591..68f70c860681a8821ea541a32801394a22dd24f6 100755 (executable)
@@ -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) {
index b484881665051669f9782fdba7b9fe6078862c8b..9e42fa71f2aa9d0d2ccd5e0ebfa7b58b840bd1bd 100755 (executable)
@@ -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;
index 51a8b87770d44d3b3e6f0e66212c9ed44fcae22b..237bc9e370e05df40ae78cd178cb1ee534179224 100755 (executable)
@@ -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;
     }
 
index d0435ba6156e05965a6b50c144ca16f81251544b..741be705a3e7f003062002f02f41164dfe5f0105 100755 (executable)
@@ -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
index b78ce4fe6ddae3b6008da76c53f6de44fe1c95f9..da05bb0b0205cdcb9441f9d4c5a0846ce5f75c61 100644 (file)
@@ -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));
index 67dd79e2092abb5e9bec8826ca095e341c04d7f4..7dc39d1ac6937fdebe05a2ae15c359073d184d80 100644 (file)
@@ -58,7 +58,7 @@ std::string SSLSessionImpl::serialize(void) const {
   auto len = i2d_SSL_SESSION(session_, nullptr);
 
   if (len > 0) {
-    std::unique_ptr<unsigned char[]> uptr(new unsigned char[len]);
+    std::unique_ptr<unsigned char[]> uptr(new unsigned char[size_t(len)]);
     auto p = uptr.get();
     auto written = i2d_SSL_SESSION(session_, &p);
     if (written <= 0) {
index a4d4aed4e9411a8400755750d0b01d4ba09473b5..c63bfd8652fc885c39b1c800a000128365c57502 100644 (file)
@@ -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<uint8_t>(32);
   OpenSSLHash::hmac_sha256(range(out), key, buf);
index 08d9c292c8524fb7f075e68288243c92015666d6..ddb77569075e5371458bf07faf9ea69464b3951f 100644 (file)
@@ -36,7 +36,7 @@ BucketedTimeSeries<VT, CT>::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<VT, CT>::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<VT, CT>::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<VT, CT>::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<VT, CT>::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();
index 57307e5d108005c1544b5d9ec072b9802a10ec48..0b531d8fa096cc31478f590069116b112749afca 100644 (file)
@@ -271,7 +271,7 @@ class BucketedTimeSeries {
    */
   template <typename ReturnType = double, typename Interval = Duration>
   ReturnType rate() const {
-    return rateHelper<ReturnType, Interval>(total_.sum, elapsed());
+    return rateHelper<ReturnType, Interval>(ReturnType(total_.sum), elapsed());
   }
 
   /*
@@ -288,7 +288,8 @@ class BucketedTimeSeries {
    */
   template <typename ReturnType = double, typename Interval = Duration>
   ReturnType countRate() const {
-    return rateHelper<ReturnType, Interval>(total_.count, elapsed());
+    return rateHelper<ReturnType, Interval>(
+        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<ReturnType, Interval>(intervalCount, interval);
+    return rateHelper<ReturnType, Interval>(
+        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) {
index fbb259831d750268a25a30a6eefea1e784833769..a6daa374b0f41948388f878be94a28728990c1e1 100644 (file)
@@ -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<ValueType>::max();
     }
 
-    return min_ + (idx * bucketSize_);
+    return ValueType(min_ + (idx * bucketSize_));
   }
 
   /**
index 8451af5c728b0ba5931f80686adb8968e8e85f6e..11b2afd5f9795b255b41c60aea5f7ade9b968872 100644 (file)
@@ -75,7 +75,7 @@ void MultiLevelTimeSeries<VT, CT>::addValue(
     TimePoint now,
     const ValueType& val,
     uint64_t times) {
-  addValueAggregated(now, val * times, times);
+  addValueAggregated(now, val * ValueType(times), times);
 }
 
 template <typename VT, typename CT>
index ff0a634c7d77fc9a6a75234e9b5c614e52035b2f..109c63f515a51fc7a858d6f3c71a6763f63aa7b7 100644 (file)
@@ -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<int,1,32> 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) {
index acd40305ee70fb61ca33c4659491c8ca6ed959d3..dba0d35c6ef1375df42f0d4af5a2e480829701db 100644 (file)
@@ -106,14 +106,14 @@ std::vector<T> cornerValues() {
   std::vector<T> rv;
   for (T i = 1; i < 24; ++i) {
     rv.push_back(i);
-    rv.push_back(std::numeric_limits<T>::max() / i);
-    rv.push_back(std::numeric_limits<T>::max() - i);
-    rv.push_back(std::numeric_limits<T>::max() / 2 - i);
+    rv.push_back(T(std::numeric_limits<T>::max() / i));
+    rv.push_back(T(std::numeric_limits<T>::max() - i));
+    rv.push_back(T(std::numeric_limits<T>::max() / T(2) - i));
     if (std::is_signed<T>::value) {
       rv.push_back(-i);
-      rv.push_back(std::numeric_limits<T>::min() / i);
-      rv.push_back(std::numeric_limits<T>::min() + i);
-      rv.push_back(std::numeric_limits<T>::min() / 2 + i);
+      rv.push_back(T(std::numeric_limits<T>::min() / i));
+      rv.push_back(T(std::numeric_limits<T>::min() + i));
+      rv.push_back(T(std::numeric_limits<T>::min() / T(2) + i));
     }
   }
   return rv;