Commit 1c098e27 authored by Christopher Dykes's avatar Christopher Dykes Committed by Facebook Github Bot

More implicit truncation warning fixes

Summary:
This makes the changes required to compile Folly cleanly with the rest of MSVC's truncation warnings, 4244 & 4267.
Only another 2800 sign mismatch warnings left to go.

Reviewed By: yfeldblum

Differential Revision: D4257094

fbshipit-source-id: 1651eca875a31f53774d36c682f5e2745ddfcda5
parent 654cce1e
...@@ -84,7 +84,7 @@ BENCHMARK(FB_FOLLY_GLOBAL_BENCHMARK_BASELINE) { ...@@ -84,7 +84,7 @@ BENCHMARK(FB_FOLLY_GLOBAL_BENCHMARK_BASELINE) {
#endif #endif
} }
int getGlobalBenchmarkBaselineIndex() { size_t getGlobalBenchmarkBaselineIndex() {
const char *global = FB_STRINGIZE_X2(FB_FOLLY_GLOBAL_BENCHMARK_BASELINE); const char *global = FB_STRINGIZE_X2(FB_FOLLY_GLOBAL_BENCHMARK_BASELINE);
auto it = std::find_if( auto it = std::find_if(
benchmarks().begin(), benchmarks().begin(),
...@@ -94,7 +94,7 @@ int getGlobalBenchmarkBaselineIndex() { ...@@ -94,7 +94,7 @@ int getGlobalBenchmarkBaselineIndex() {
} }
); );
CHECK(it != benchmarks().end()); CHECK(it != benchmarks().end());
return it - benchmarks().begin(); return size_t(std::distance(benchmarks().begin(), it));
} }
#undef FB_STRINGIZE_X2 #undef FB_STRINGIZE_X2
...@@ -465,7 +465,7 @@ void runBenchmarks() { ...@@ -465,7 +465,7 @@ void runBenchmarks() {
// PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS. // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
unsigned int baselineIndex = getGlobalBenchmarkBaselineIndex(); size_t baselineIndex = getGlobalBenchmarkBaselineIndex();
auto const globalBaseline = auto const globalBaseline =
runBenchmarkGetNSPerIteration(get<2>(benchmarks()[baselineIndex]), 0); runBenchmarkGetNSPerIteration(get<2>(benchmarks()[baselineIndex]), 0);
......
...@@ -116,7 +116,7 @@ struct BenchmarkSuspender { ...@@ -116,7 +116,7 @@ struct BenchmarkSuspender {
BenchmarkSuspender(const BenchmarkSuspender &) = delete; BenchmarkSuspender(const BenchmarkSuspender &) = delete;
BenchmarkSuspender(BenchmarkSuspender && rhs) noexcept { BenchmarkSuspender(BenchmarkSuspender && rhs) noexcept {
start = rhs.start; start = rhs.start;
rhs.start.tv_nsec = rhs.start.tv_sec = 0; rhs.start = {0, 0};
} }
BenchmarkSuspender& operator=(const BenchmarkSuspender &) = delete; BenchmarkSuspender& operator=(const BenchmarkSuspender &) = delete;
...@@ -125,7 +125,7 @@ struct BenchmarkSuspender { ...@@ -125,7 +125,7 @@ struct BenchmarkSuspender {
tally(); tally();
} }
start = rhs.start; start = rhs.start;
rhs.start.tv_nsec = rhs.start.tv_sec = 0; rhs.start = {0, 0};
return *this; return *this;
} }
...@@ -138,7 +138,7 @@ struct BenchmarkSuspender { ...@@ -138,7 +138,7 @@ struct BenchmarkSuspender {
void dismiss() { void dismiss() {
assert(start.tv_nsec > 0 || start.tv_sec > 0); assert(start.tv_nsec > 0 || start.tv_sec > 0);
tally(); tally();
start.tv_nsec = start.tv_sec = 0; start = {0, 0};
} }
void rehire() { void rehire() {
......
...@@ -459,7 +459,7 @@ class BitIterator ...@@ -459,7 +459,7 @@ class BitIterator
other.bitOffset_ - bitOffset_; other.bitOffset_ - bitOffset_;
} }
unsigned int bitOffset_; size_t bitOffset_;
}; };
/** /**
......
...@@ -52,7 +52,7 @@ uint32_t crc32c_hw(const uint8_t *data, size_t nbytes, ...@@ -52,7 +52,7 @@ uint32_t crc32c_hw(const uint8_t *data, size_t nbytes,
// Process 8 bytes at a time until we have fewer than 8 bytes left. // Process 8 bytes at a time until we have fewer than 8 bytes left.
while (offset + sizeof(uint64_t) <= nbytes) { while (offset + sizeof(uint64_t) <= nbytes) {
const uint64_t* src = (const uint64_t*)(data + offset); const uint64_t* src = (const uint64_t*)(data + offset);
sum = _mm_crc32_u64(sum, *src); sum = uint32_t(_mm_crc32_u64(sum, *src));
offset += sizeof(uint64_t); offset += sizeof(uint64_t);
} }
......
...@@ -235,7 +235,7 @@ using IsAscii = std:: ...@@ -235,7 +235,7 @@ using IsAscii = std::
// The code in this file that uses tolower() really only cares about // The code in this file that uses tolower() really only cares about
// 7-bit ASCII characters, so we can take a nice shortcut here. // 7-bit ASCII characters, so we can take a nice shortcut here.
inline char tolower_ascii(char in) { inline char tolower_ascii(char in) {
return IsAscii::value ? in | 0x20 : std::tolower(in); return IsAscii::value ? in | 0x20 : char(std::tolower(in));
} }
inline bool bool_str_cmp(const char** b, size_t len, const char* value) { inline bool bool_str_cmp(const char** b, size_t len, const char* value) {
...@@ -365,7 +365,7 @@ Expected<Tgt, ConversionCode> str_to_floating(StringPiece* src) noexcept { ...@@ -365,7 +365,7 @@ Expected<Tgt, ConversionCode> str_to_floating(StringPiece* src) noexcept {
return makeUnexpected(ConversionCode::EMPTY_INPUT_STRING); return makeUnexpected(ConversionCode::EMPTY_INPUT_STRING);
} }
src->advance(length); src->advance(length);
return result; return Tgt(result);
} }
auto* e = src->end(); auto* e = src->end();
...@@ -423,7 +423,7 @@ Expected<Tgt, ConversionCode> str_to_floating(StringPiece* src) noexcept { ...@@ -423,7 +423,7 @@ Expected<Tgt, ConversionCode> str_to_floating(StringPiece* src) noexcept {
src->assign(b, e); src->assign(b, e);
return result; return Tgt(result);
} }
template Expected<float, ConversionCode> str_to_floating<float>( template Expected<float, ConversionCode> str_to_floating<float>(
...@@ -570,7 +570,7 @@ inline Expected<Tgt, ConversionCode> digits_to( ...@@ -570,7 +570,7 @@ inline Expected<Tgt, ConversionCode> digits_to(
if (sum >= OOR) { if (sum >= OOR) {
goto outOfRange; goto outOfRange;
} }
result = 1000 * result + sum; result = UT(1000 * result + sum);
break; break;
} }
case 2: { case 2: {
...@@ -580,7 +580,7 @@ inline Expected<Tgt, ConversionCode> digits_to( ...@@ -580,7 +580,7 @@ inline Expected<Tgt, ConversionCode> digits_to(
if (sum >= OOR) { if (sum >= OOR) {
goto outOfRange; goto outOfRange;
} }
result = 100 * result + sum; result = UT(100 * result + sum);
break; break;
} }
case 1: { case 1: {
...@@ -588,7 +588,7 @@ inline Expected<Tgt, ConversionCode> digits_to( ...@@ -588,7 +588,7 @@ inline Expected<Tgt, ConversionCode> digits_to(
if (sum >= OOR) { if (sum >= OOR) {
goto outOfRange; goto outOfRange;
} }
result = 10 * result + sum; result = UT(10 * result + sum);
break; break;
} }
default: default:
......
...@@ -383,12 +383,12 @@ inline uint32_t uint64ToBufferUnsafe(uint64_t v, char *const buffer) { ...@@ -383,12 +383,12 @@ inline uint32_t uint64ToBufferUnsafe(uint64_t v, char *const buffer) {
// Keep these together so a peephole optimization "sees" them and // Keep these together so a peephole optimization "sees" them and
// computes them in one shot. // computes them in one shot.
auto const q = v / 10; auto const q = v / 10;
auto const r = static_cast<uint32_t>(v % 10); auto const r = static_cast<char>(v % 10);
buffer[pos--] = '0' + r; buffer[pos--] = '0' + r;
v = q; v = q;
} }
// Last digit is trivial to handle // Last digit is trivial to handle
buffer[pos] = static_cast<uint32_t>(v) + '0'; buffer[pos] = static_cast<char>(v) + '0';
return result; return result;
} }
......
...@@ -655,7 +655,7 @@ private: ...@@ -655,7 +655,7 @@ private:
// small_[maxSmallSize]. // small_[maxSmallSize].
FBSTRING_ASSERT(s <= maxSmallSize); FBSTRING_ASSERT(s <= maxSmallSize);
constexpr auto shift = kIsLittleEndian ? 0 : 2; constexpr auto shift = kIsLittleEndian ? 0 : 2;
small_[maxSmallSize] = (maxSmallSize - s) << shift; small_[maxSmallSize] = char((maxSmallSize - s) << shift);
small_[s] = '\0'; small_[s] = '\0';
FBSTRING_ASSERT(category() == Category::isSmall && size() == s); FBSTRING_ASSERT(category() == Category::isSmall && size() == s);
} }
......
...@@ -29,7 +29,7 @@ namespace folly { ...@@ -29,7 +29,7 @@ namespace folly {
using namespace fileutil_detail; using namespace fileutil_detail;
int openNoInt(const char* name, int flags, mode_t mode) { int openNoInt(const char* name, int flags, mode_t mode) {
return wrapNoInt(open, name, flags, mode); return int(wrapNoInt(open, name, flags, mode));
} }
int closeNoInt(int fd) { int closeNoInt(int fd) {
...@@ -50,41 +50,41 @@ int closeNoInt(int fd) { ...@@ -50,41 +50,41 @@ int closeNoInt(int fd) {
} }
int fsyncNoInt(int fd) { int fsyncNoInt(int fd) {
return wrapNoInt(fsync, fd); return int(wrapNoInt(fsync, fd));
} }
int dupNoInt(int fd) { int dupNoInt(int fd) {
return wrapNoInt(dup, fd); return int(wrapNoInt(dup, fd));
} }
int dup2NoInt(int oldfd, int newfd) { int dup2NoInt(int oldfd, int newfd) {
return wrapNoInt(dup2, oldfd, newfd); return int(wrapNoInt(dup2, oldfd, newfd));
} }
int fdatasyncNoInt(int fd) { int fdatasyncNoInt(int fd) {
#if defined(__APPLE__) #if defined(__APPLE__)
return wrapNoInt(fcntl, fd, F_FULLFSYNC); return int(wrapNoInt(fcntl, fd, F_FULLFSYNC));
#elif defined(__FreeBSD__) || defined(_MSC_VER) #elif defined(__FreeBSD__) || defined(_MSC_VER)
return wrapNoInt(fsync, fd); return int(wrapNoInt(fsync, fd));
#else #else
return wrapNoInt(fdatasync, fd); return int(wrapNoInt(fdatasync, fd));
#endif #endif
} }
int ftruncateNoInt(int fd, off_t len) { int ftruncateNoInt(int fd, off_t len) {
return wrapNoInt(ftruncate, fd, len); return int(wrapNoInt(ftruncate, fd, len));
} }
int truncateNoInt(const char* path, off_t len) { int truncateNoInt(const char* path, off_t len) {
return wrapNoInt(truncate, path, len); return int(wrapNoInt(truncate, path, len));
} }
int flockNoInt(int fd, int operation) { int flockNoInt(int fd, int operation) {
return wrapNoInt(flock, fd, operation); return int(wrapNoInt(flock, fd, operation));
} }
int shutdownNoInt(int fd, int how) { int shutdownNoInt(int fd, int how) {
return wrapNoInt(portability::sockets::shutdown, fd, how); return int(wrapNoInt(portability::sockets::shutdown, fd, how));
} }
ssize_t readNoInt(int fd, void* buf, size_t count) { ssize_t readNoInt(int fd, void* buf, size_t count) {
......
...@@ -294,7 +294,7 @@ void FormatArg::validate(Type type) const { ...@@ -294,7 +294,7 @@ void FormatArg::validate(Type type) const {
namespace detail { namespace detail {
void insertThousandsGroupingUnsafe(char* start_buffer, char** end_buffer) { void insertThousandsGroupingUnsafe(char* start_buffer, char** end_buffer) {
uint32_t remaining_digits = *end_buffer - start_buffer; uint32_t remaining_digits = uint32_t(*end_buffer - start_buffer);
uint32_t separator_size = (remaining_digits - 1) / 3; uint32_t separator_size = (remaining_digits - 1) / 3;
uint32_t result_size = remaining_digits + separator_size; uint32_t result_size = remaining_digits + separator_size;
*end_buffer = *end_buffer + separator_size; *end_buffer = *end_buffer + separator_size;
......
...@@ -245,7 +245,7 @@ class GroupVarint<uint32_t> : public detail::GroupVarintBase<uint32_t> { ...@@ -245,7 +245,7 @@ class GroupVarint<uint32_t> : public detail::GroupVarintBase<uint32_t> {
private: private:
static uint8_t key(uint32_t x) { static uint8_t key(uint32_t x) {
// __builtin_clz is undefined for the x==0 case // __builtin_clz is undefined for the x==0 case
return 3 - (__builtin_clz(x|1) / 8); return uint8_t(3 - (__builtin_clz(x | 1) / 8));
} }
static size_t b0key(size_t x) { return x & 3; } static size_t b0key(size_t x) { return x & 3; }
static size_t b1key(size_t x) { return (x >> 2) & 3; } static size_t b1key(size_t x) { return (x >> 2) & 3; }
...@@ -409,7 +409,7 @@ class GroupVarint<uint64_t> : public detail::GroupVarintBase<uint64_t> { ...@@ -409,7 +409,7 @@ class GroupVarint<uint64_t> : public detail::GroupVarintBase<uint64_t> {
static uint8_t key(uint64_t x) { static uint8_t key(uint64_t x) {
// __builtin_clzll is undefined for the x==0 case // __builtin_clzll is undefined for the x==0 case
return 7 - (__builtin_clzll(x|1) / 8); return uint8_t(7 - (__builtin_clzll(x | 1) / 8));
} }
static uint8_t b0key(uint16_t x) { return x & 7; } static uint8_t b0key(uint16_t x) { return x & 7; }
......
...@@ -112,8 +112,9 @@ struct IndexedMemPool : boost::noncopyable { ...@@ -112,8 +112,9 @@ struct IndexedMemPool : boost::noncopyable {
static constexpr uint32_t maxIndexForCapacity(uint32_t capacity) { static constexpr uint32_t maxIndexForCapacity(uint32_t capacity) {
// index of uint32_t(-1) == UINT32_MAX is reserved for isAllocated tracking // index of uint32_t(-1) == UINT32_MAX is reserved for isAllocated tracking
return std::min(uint64_t(capacity) + (NumLocalLists - 1) * LocalListLimit, return uint32_t(std::min(
uint64_t(uint32_t(-1) - 1)); uint64_t(capacity) + (NumLocalLists - 1) * LocalListLimit,
uint64_t(uint32_t(-1) - 1)));
} }
static constexpr uint32_t capacityForMaxIndex(uint32_t maxIndex) { static constexpr uint32_t capacityForMaxIndex(uint32_t maxIndex) {
...@@ -217,7 +218,7 @@ struct IndexedMemPool : boost::noncopyable { ...@@ -217,7 +218,7 @@ struct IndexedMemPool : boost::noncopyable {
auto slot = reinterpret_cast<const Slot*>( auto slot = reinterpret_cast<const Slot*>(
reinterpret_cast<const char*>(elem) - offsetof(Slot, elem)); reinterpret_cast<const char*>(elem) - offsetof(Slot, elem));
auto rv = slot - slots_; auto rv = uint32_t(slot - slots_);
// this assert also tests that rv is in range // this assert also tests that rv is in range
assert(elem == &(*this)[rv]); assert(elem == &(*this)[rv]);
......
...@@ -1067,7 +1067,7 @@ class MPMCQueueBase<Derived<T, Atom, Dynamic>> : boost::noncopyable { ...@@ -1067,7 +1067,7 @@ class MPMCQueueBase<Derived<T, Atom, Dynamic>> : boost::noncopyable {
/// corresponding SingleElementQueue /// corresponding SingleElementQueue
uint32_t turn(uint64_t ticket, size_t cap) noexcept { uint32_t turn(uint64_t ticket, size_t cap) noexcept {
assert(cap != 0); assert(cap != 0);
return ticket / cap; return uint32_t(ticket / cap);
} }
/// Tries to obtain a push ticket for which SingleElementQueue::enqueue /// Tries to obtain a push ticket for which SingleElementQueue::enqueue
......
...@@ -129,7 +129,7 @@ void MemoryMapping::init(off_t offset, off_t length) { ...@@ -129,7 +129,7 @@ void MemoryMapping::init(off_t offset, off_t length) {
} }
if (pageSize == 0) { if (pageSize == 0) {
pageSize = sysconf(_SC_PAGESIZE); pageSize = off_t(sysconf(_SC_PAGESIZE));
} }
CHECK_GT(pageSize, 0); CHECK_GT(pageSize, 0);
...@@ -137,7 +137,7 @@ void MemoryMapping::init(off_t offset, off_t length) { ...@@ -137,7 +137,7 @@ void MemoryMapping::init(off_t offset, off_t length) {
CHECK_GE(offset, 0); CHECK_GE(offset, 0);
// Round down the start of the mapped region // Round down the start of the mapped region
size_t skipStart = offset % pageSize; off_t skipStart = offset % pageSize;
offset -= skipStart; offset -= skipStart;
mapLength_ = length; mapLength_ = length;
...@@ -206,7 +206,7 @@ off_t memOpChunkSize(off_t length, off_t pageSize) { ...@@ -206,7 +206,7 @@ off_t memOpChunkSize(off_t length, off_t pageSize) {
return chunkSize; return chunkSize;
} }
chunkSize = FLAGS_mlock_chunk_size; chunkSize = off_t(FLAGS_mlock_chunk_size);
off_t r = chunkSize % pageSize; off_t r = chunkSize % pageSize;
if (r) { if (r) {
chunkSize += (pageSize - r); chunkSize += (pageSize - r);
...@@ -231,7 +231,7 @@ bool memOpInChunks(std::function<int(void*, size_t)> op, ...@@ -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 // chunks breaks the locking into intervals and lets other threads do memory
// operations of their own. // operations of their own.
size_t chunkSize = memOpChunkSize(bufSize, pageSize); size_t chunkSize = memOpChunkSize(off_t(bufSize), pageSize);
char* addr = static_cast<char*>(mem); char* addr = static_cast<char*>(mem);
amountSucceeded = 0; amountSucceeded = 0;
...@@ -377,7 +377,7 @@ void mmapFileCopy(const char* src, const char* dest, mode_t mode) { ...@@ -377,7 +377,7 @@ void mmapFileCopy(const char* src, const char* dest, mode_t mode) {
MemoryMapping destMap( MemoryMapping destMap(
File(dest, O_RDWR | O_CREAT | O_TRUNC, mode), File(dest, O_RDWR | O_CREAT | O_TRUNC, mode),
0, 0,
srcMap.range().size(), off_t(srcMap.range().size()),
MemoryMapping::writable()); MemoryMapping::writable());
alignedForwardMemcpy(destMap.writableRange().data(), alignedForwardMemcpy(destMap.writableRange().data(),
......
...@@ -62,7 +62,7 @@ class SparseByteSet { ...@@ -62,7 +62,7 @@ class SparseByteSet {
if (r) { if (r) {
DCHECK_LT(size_, kCapacity); DCHECK_LT(size_, kCapacity);
dense_[size_] = i; dense_[size_] = i;
sparse_[i] = size_; sparse_[i] = uint8_t(size_);
size_++; size_++;
} }
return r; return r;
......
...@@ -196,7 +196,7 @@ void SpookyHashV1::Hash128( ...@@ -196,7 +196,7 @@ void SpookyHashV1::Hash128(
remainder = (length - ((const uint8_t *)end-(const uint8_t *)message)); remainder = (length - ((const uint8_t *)end-(const uint8_t *)message));
memcpy(buf, end, remainder); memcpy(buf, end, remainder);
memset(((uint8_t *)buf)+remainder, 0, sc_blockSize-remainder); memset(((uint8_t *)buf)+remainder, 0, sc_blockSize-remainder);
((uint8_t *)buf)[sc_blockSize-1] = remainder; ((uint8_t*)buf)[sc_blockSize - 1] = uint8_t(remainder);
Mix(buf, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); Mix(buf, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11);
// do some final mixing // do some final mixing
......
...@@ -198,7 +198,7 @@ void SpookyHashV2::Hash128( ...@@ -198,7 +198,7 @@ void SpookyHashV2::Hash128(
remainder = (length - ((const uint8_t *)end-(const uint8_t *)message)); remainder = (length - ((const uint8_t *)end-(const uint8_t *)message));
memcpy(buf, end, remainder); memcpy(buf, end, remainder);
memset(((uint8_t *)buf)+remainder, 0, sc_blockSize-remainder); memset(((uint8_t *)buf)+remainder, 0, sc_blockSize-remainder);
((uint8_t *)buf)[sc_blockSize-1] = remainder; ((uint8_t*)buf)[sc_blockSize - 1] = uint8_t(remainder);
// do some final mixing // do some final mixing
End(buf, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); End(buf, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11);
......
...@@ -285,7 +285,7 @@ double prettyToDouble(folly::StringPiece *const prettyString, ...@@ -285,7 +285,7 @@ double prettyToDouble(folly::StringPiece *const prettyString,
bestPrefixId = j; bestPrefixId = j;
} }
} else if (prettyString->startsWith(suffixes[j].suffix)) { } else if (prettyString->startsWith(suffixes[j].suffix)) {
int suffixLen = strlen(suffixes[j].suffix); int suffixLen = int(strlen(suffixes[j].suffix));
//We are looking for a longest suffix matching prefix of the string //We are looking for a longest suffix matching prefix of the string
//after numeric value. We need this in case suffixes have common prefix. //after numeric value. We need this in case suffixes have common prefix.
if (suffixLen > longestPrefixLen) { if (suffixLen > longestPrefixLen) {
......
...@@ -23,7 +23,7 @@ namespace folly { ...@@ -23,7 +23,7 @@ namespace folly {
namespace { namespace {
fbstring submatch(const boost::cmatch& m, size_t idx) { fbstring submatch(const boost::cmatch& m, int idx) {
auto& sub = m[idx]; auto& sub = m[idx];
return fbstring(sub.first, sub.second); return fbstring(sub.first, sub.second);
} }
......
...@@ -87,7 +87,7 @@ inline size_t encodeVarint(uint64_t val, uint8_t* buf) { ...@@ -87,7 +87,7 @@ inline size_t encodeVarint(uint64_t val, uint8_t* buf) {
*p++ = 0x80 | (val & 0x7f); *p++ = 0x80 | (val & 0x7f);
val >>= 7; val >>= 7;
} }
*p++ = val; *p++ = uint8_t(val);
return p - buf; return p - buf;
} }
......
...@@ -43,7 +43,7 @@ static CacheLocality getSystemLocalityInfo() { ...@@ -43,7 +43,7 @@ static CacheLocality getSystemLocalityInfo() {
} }
#endif #endif
long numCpus = sysconf(_SC_NPROCESSORS_CONF); size_t numCpus = sysconf(_SC_NPROCESSORS_CONF);
if (numCpus <= 0) { if (numCpus <= 0) {
// This shouldn't happen, but if it does we should try to keep // This shouldn't happen, but if it does we should try to keep
// going. We are probably not going to be able to parse /sys on // going. We are probably not going to be able to parse /sys on
...@@ -156,7 +156,7 @@ CacheLocality CacheLocality::readFromSysfsTree( ...@@ -156,7 +156,7 @@ CacheLocality CacheLocality::readFromSysfsTree(
// a sub-optimal ordering, but it won't crash // a sub-optimal ordering, but it won't crash
auto& lhsEquiv = equivClassesByCpu[lhs]; auto& lhsEquiv = equivClassesByCpu[lhs];
auto& rhsEquiv = equivClassesByCpu[rhs]; auto& rhsEquiv = equivClassesByCpu[rhs];
for (int i = std::min(lhsEquiv.size(), rhsEquiv.size()) - 1; for (int i = int(std::min(lhsEquiv.size(), rhsEquiv.size())) - 1;
i >= 0; i >= 0;
--i) { --i) {
if (lhsEquiv[i] != rhsEquiv[i]) { if (lhsEquiv[i] != rhsEquiv[i]) {
......
...@@ -148,7 +148,7 @@ template <template <typename> class Atom> ...@@ -148,7 +148,7 @@ template <template <typename> class Atom>
struct SequentialThreadId { struct SequentialThreadId {
/// Returns the thread id assigned to the current thread /// Returns the thread id assigned to the current thread
static size_t get() { static unsigned get() {
auto rv = currentId; auto rv = currentId;
if (UNLIKELY(rv == 0)) { if (UNLIKELY(rv == 0)) {
rv = currentId = ++prevId; rv = currentId = ++prevId;
...@@ -157,16 +157,16 @@ struct SequentialThreadId { ...@@ -157,16 +157,16 @@ struct SequentialThreadId {
} }
private: private:
static Atom<size_t> prevId; static Atom<unsigned> prevId;
static FOLLY_TLS size_t currentId; static FOLLY_TLS unsigned currentId;
}; };
template <template <typename> class Atom> template <template <typename> class Atom>
Atom<size_t> SequentialThreadId<Atom>::prevId(0); Atom<unsigned> SequentialThreadId<Atom>::prevId(0);
template <template <typename> class Atom> template <template <typename> class Atom>
FOLLY_TLS size_t SequentialThreadId<Atom>::currentId(0); FOLLY_TLS unsigned SequentialThreadId<Atom>::currentId(0);
// Suppress this instantiation in other translation units. It is // Suppress this instantiation in other translation units. It is
// instantiated in CacheLocality.cpp // instantiated in CacheLocality.cpp
...@@ -174,7 +174,7 @@ extern template struct SequentialThreadId<std::atomic>; ...@@ -174,7 +174,7 @@ extern template struct SequentialThreadId<std::atomic>;
#endif #endif
struct HashingThreadId { struct HashingThreadId {
static size_t get() { static unsigned get() {
pthread_t pid = pthread_self(); pthread_t pid = pthread_self();
uint64_t id = 0; uint64_t id = 0;
memcpy(&id, &pid, std::min(sizeof(pid), sizeof(id))); memcpy(&id, &pid, std::min(sizeof(pid), sizeof(id)));
...@@ -328,7 +328,8 @@ struct AccessSpreader { ...@@ -328,7 +328,8 @@ struct AccessSpreader {
assert(index < n); assert(index < n);
// as index goes from 0..n, post-transform value goes from // as index goes from 0..n, post-transform value goes from
// 0..numStripes // 0..numStripes
widthAndCpuToStripe[width][cpu] = (index * numStripes) / n; widthAndCpuToStripe[width][cpu] =
CompactStripe((index * numStripes) / n);
assert(widthAndCpuToStripe[width][cpu] < numStripes); assert(widthAndCpuToStripe[width][cpu] < numStripes);
} }
for (size_t cpu = n; cpu < kMaxCpus; ++cpu) { for (size_t cpu = n; cpu < kMaxCpus; ++cpu) {
......
...@@ -93,7 +93,7 @@ struct MemoryIdler { ...@@ -93,7 +93,7 @@ struct MemoryIdler {
// multiplying the duration by a floating point doesn't work, grr.. // multiplying the duration by a floating point doesn't work, grr..
auto extraFrac = auto extraFrac =
timeoutVariationFrac / std::numeric_limits<uint64_t>::max() * h; timeoutVariationFrac / std::numeric_limits<uint64_t>::max() * h;
uint64_t tics = idleTimeout.count() * (1 + extraFrac); auto tics = uint64_t(idleTimeout.count() * (1 + extraFrac));
idleTimeout = typename Clock::duration(tics); idleTimeout = typename Clock::duration(tics);
} }
......
...@@ -105,8 +105,8 @@ size_t qfind_first_byte_of_needles16(const StringPieceLite haystack, ...@@ -105,8 +105,8 @@ size_t qfind_first_byte_of_needles16(const StringPieceLite haystack,
// do an unaligned load for first block of haystack // do an unaligned load for first block of haystack
auto arr1 = _mm_loadu_si128( auto arr1 = _mm_loadu_si128(
reinterpret_cast<const __m128i*>(haystack.data())); reinterpret_cast<const __m128i*>(haystack.data()));
auto index = _mm_cmpestri(arr2, needles.size(), auto index =
arr1, haystack.size(), 0); _mm_cmpestri(arr2, int(needles.size()), arr1, int(haystack.size()), 0);
if (index < 16) { if (index < 16) {
return index; return index;
} }
...@@ -116,7 +116,8 @@ size_t qfind_first_byte_of_needles16(const StringPieceLite haystack, ...@@ -116,7 +116,8 @@ size_t qfind_first_byte_of_needles16(const StringPieceLite haystack,
for (; i < haystack.size(); i+= 16) { for (; i < haystack.size(); i+= 16) {
arr1 = arr1 =
_mm_load_si128(reinterpret_cast<const __m128i*>(haystack.data() + i)); _mm_load_si128(reinterpret_cast<const __m128i*>(haystack.data() + i));
index = _mm_cmpestri(arr2, needles.size(), arr1, haystack.size() - i, 0); index = _mm_cmpestri(
arr2, int(needles.size()), arr1, int(haystack.size() - i), 0);
if (index < 16) { if (index < 16) {
return i + index; return i + index;
} }
...@@ -159,8 +160,8 @@ size_t scanHaystackBlock(const StringPieceLite haystack, ...@@ -159,8 +160,8 @@ size_t scanHaystackBlock(const StringPieceLite haystack,
// This load is safe because needles.size() >= 16 // This load is safe because needles.size() >= 16
auto arr2 = _mm_loadu_si128( auto arr2 = _mm_loadu_si128(
reinterpret_cast<const __m128i*>(needles.data())); reinterpret_cast<const __m128i*>(needles.data()));
size_t b = _mm_cmpestri( size_t b =
arr2, 16, arr1, haystack.size() - blockStartIdx, 0); _mm_cmpestri(arr2, 16, arr1, int(haystack.size() - blockStartIdx), 0);
size_t j = nextAlignedIndex(needles.data()); size_t j = nextAlignedIndex(needles.data());
for (; j < needles.size(); j += 16) { for (; j < needles.size(); j += 16) {
...@@ -168,8 +169,11 @@ size_t scanHaystackBlock(const StringPieceLite haystack, ...@@ -168,8 +169,11 @@ size_t scanHaystackBlock(const StringPieceLite haystack,
reinterpret_cast<const __m128i*>(needles.data() + j)); reinterpret_cast<const __m128i*>(needles.data() + j));
auto index = _mm_cmpestri( auto index = _mm_cmpestri(
arr2, needles.size() - j, arr2,
arr1, haystack.size() - blockStartIdx, 0); int(needles.size() - j),
arr1,
int(haystack.size() - blockStartIdx),
0);
b = std::min<size_t>(index, b); b = std::min<size_t>(index, b);
} }
......
...@@ -44,8 +44,8 @@ typename std::enable_if<!std::is_same<typename std::remove_cv<ValueType>::type, ...@@ -44,8 +44,8 @@ typename std::enable_if<!std::is_same<typename std::remove_cv<ValueType>::type,
ReturnType>::type ReturnType>::type
avgHelper(ValueType sum, uint64_t count) { avgHelper(ValueType sum, uint64_t count) {
if (count == 0) { return ReturnType(0); } if (count == 0) { return ReturnType(0); }
const double sumf = sum; const double sumf = double(sum);
const double countf = count; const double countf = double(count);
return static_cast<ReturnType>(sumf / countf); return static_cast<ReturnType>(sumf / countf);
} }
......
...@@ -215,7 +215,7 @@ struct TurnSequencer { ...@@ -215,7 +215,7 @@ struct TurnSequencer {
/// Returns the least-most significant byte of the current uncompleted /// Returns the least-most significant byte of the current uncompleted
/// turn. The full 32 bit turn cannot be recovered. /// turn. The full 32 bit turn cannot be recovered.
uint8_t uncompletedTurnLSB() const noexcept { uint8_t uncompletedTurnLSB() const noexcept {
return state_.load(std::memory_order_acquire) >> kTurnShift; return uint8_t(state_.load(std::memory_order_acquire) >> kTurnShift);
} }
private: private:
......
...@@ -63,7 +63,7 @@ struct PoissonDistributionFunctor { ...@@ -63,7 +63,7 @@ struct PoissonDistributionFunctor {
struct UniformDistributionFunctor { struct UniformDistributionFunctor {
std::default_random_engine generator; std::default_random_engine generator;
std::uniform_int_distribution<> dist; std::uniform_int_distribution<milliseconds::rep> dist;
UniformDistributionFunctor(milliseconds minInterval, milliseconds maxInterval) UniformDistributionFunctor(milliseconds minInterval, milliseconds maxInterval)
: generator(Random::rand32()), : generator(Random::rand32()),
......
...@@ -616,7 +616,7 @@ struct AnyOfValidator final : IValidator { ...@@ -616,7 +616,7 @@ struct AnyOfValidator final : IValidator {
errors.emplace_back(*se); errors.emplace_back(*se);
} }
} }
const int success = validators_.size() - errors.size(); const auto success = validators_.size() - errors.size();
if (success == 0) { if (success == 0) {
return makeError("at least one valid schema", value); return makeError("at least one valid schema", value);
} else if (success > 1 && type_ == Type::EXACTLY_ONE) { } else if (success > 1 && type_ == Type::EXACTLY_ONE) {
......
...@@ -118,8 +118,8 @@ inline void EventBaseLoopControllerT<EventBaseT>::timedSchedule( ...@@ -118,8 +118,8 @@ inline void EventBaseLoopControllerT<EventBaseT>::timedSchedule(
.count() + .count() +
1; 1;
// If clock is not monotonic // If clock is not monotonic
delay_ms = std::max<decltype(delay_ms)>(delay_ms, 0L); delay_ms = std::max<decltype(delay_ms)>(delay_ms, 0);
eventBase_->tryRunAfterDelay(func, delay_ms); eventBase_->tryRunAfterDelay(func, uint32_t(delay_ms));
} }
} }
} // folly::fibers } // folly::fibers
...@@ -37,7 +37,7 @@ class RecordIOReader::Iterator : public boost::iterator_facade< ...@@ -37,7 +37,7 @@ class RecordIOReader::Iterator : public boost::iterator_facade<
bool equal(const Iterator& other) const { return range_ == other.range_; } bool equal(const Iterator& other) const { return range_ == other.range_; }
void increment() { void increment() {
size_t skip = recordio_helpers::headerSize() + recordAndPos_.first.size(); size_t skip = recordio_helpers::headerSize() + recordAndPos_.first.size();
recordAndPos_.second += skip; recordAndPos_.second += off_t(skip);
range_.advance(skip); range_.advance(skip);
advanceToValid(); advanceToValid();
} }
......
...@@ -54,7 +54,7 @@ void RecordIOWriter::write(std::unique_ptr<IOBuf> buf) { ...@@ -54,7 +54,7 @@ void RecordIOWriter::write(std::unique_ptr<IOBuf> buf) {
DCHECK_EQ(buf->computeChainDataLength(), totalLength); DCHECK_EQ(buf->computeChainDataLength(), totalLength);
// We're going to write. Reserve space for ourselves. // We're going to write. Reserve space for ourselves.
off_t pos = filePos_.fetch_add(totalLength); off_t pos = filePos_.fetch_add(off_t(totalLength));
#if FOLLY_HAVE_PWRITEV #if FOLLY_HAVE_PWRITEV
auto iov = buf->getIov(); auto iov = buf->getIov();
...@@ -100,7 +100,7 @@ void RecordIOReader::Iterator::advanceToValid() { ...@@ -100,7 +100,7 @@ void RecordIOReader::Iterator::advanceToValid() {
skipped -= headerSize(); skipped -= headerSize();
range_.advance(skipped); range_.advance(skipped);
recordAndPos_.first = record; recordAndPos_.first = record;
recordAndPos_.second += skipped; recordAndPos_.second += off_t(skipped);
} }
} }
...@@ -165,7 +165,7 @@ size_t prependHeader(std::unique_ptr<IOBuf>& buf, uint32_t fileId) { ...@@ -165,7 +165,7 @@ size_t prependHeader(std::unique_ptr<IOBuf>& buf, uint32_t fileId) {
memset(header, 0, sizeof(Header)); memset(header, 0, sizeof(Header));
header->magic = detail::Header::kMagic; header->magic = detail::Header::kMagic;
header->fileId = fileId; header->fileId = fileId;
header->dataLength = lengthAndHash.first; header->dataLength = uint32_t(lengthAndHash.first);
header->dataHash = lengthAndHash.second; header->dataHash = lengthAndHash.second;
header->headerHash = headerHash(*header); header->headerHash = headerHash(*header);
......
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
namespace folly { namespace folly {
ShutdownSocketSet::ShutdownSocketSet(size_t maxFd) ShutdownSocketSet::ShutdownSocketSet(int maxFd)
: maxFd_(maxFd), : maxFd_(maxFd),
data_(static_cast<std::atomic<uint8_t>*>( data_(static_cast<std::atomic<uint8_t>*>(
folly::checkedCalloc(maxFd, sizeof(std::atomic<uint8_t>)))), folly::checkedCalloc(maxFd, sizeof(std::atomic<uint8_t>)))),
...@@ -39,7 +39,7 @@ ShutdownSocketSet::ShutdownSocketSet(size_t maxFd) ...@@ -39,7 +39,7 @@ ShutdownSocketSet::ShutdownSocketSet(size_t maxFd)
void ShutdownSocketSet::add(int fd) { void ShutdownSocketSet::add(int fd) {
// Silently ignore any fds >= maxFd_, very unlikely // Silently ignore any fds >= maxFd_, very unlikely
DCHECK_GE(fd, 0); DCHECK_GE(fd, 0);
if (size_t(fd) >= maxFd_) { if (fd >= maxFd_) {
return; return;
} }
...@@ -53,7 +53,7 @@ void ShutdownSocketSet::add(int fd) { ...@@ -53,7 +53,7 @@ void ShutdownSocketSet::add(int fd) {
void ShutdownSocketSet::remove(int fd) { void ShutdownSocketSet::remove(int fd) {
DCHECK_GE(fd, 0); DCHECK_GE(fd, 0);
if (size_t(fd) >= maxFd_) { if (fd >= maxFd_) {
return; return;
} }
...@@ -81,7 +81,7 @@ retry: ...@@ -81,7 +81,7 @@ retry:
int ShutdownSocketSet::close(int fd) { int ShutdownSocketSet::close(int fd) {
DCHECK_GE(fd, 0); DCHECK_GE(fd, 0);
if (size_t(fd) >= maxFd_) { if (fd >= maxFd_) {
return folly::closeNoInt(fd); return folly::closeNoInt(fd);
} }
...@@ -113,7 +113,7 @@ retry: ...@@ -113,7 +113,7 @@ retry:
void ShutdownSocketSet::shutdown(int fd, bool abortive) { void ShutdownSocketSet::shutdown(int fd, bool abortive) {
DCHECK_GE(fd, 0); DCHECK_GE(fd, 0);
if (fd >= 0 && size_t(fd) >= maxFd_) { if (fd >= maxFd_) {
doShutdown(fd, abortive); doShutdown(fd, abortive);
return; return;
} }
...@@ -147,7 +147,7 @@ void ShutdownSocketSet::shutdown(int fd, bool abortive) { ...@@ -147,7 +147,7 @@ void ShutdownSocketSet::shutdown(int fd, bool abortive) {
} }
void ShutdownSocketSet::shutdownAll(bool abortive) { void ShutdownSocketSet::shutdownAll(bool abortive) {
for (size_t i = 0; i < maxFd_; ++i) { for (int i = 0; i < maxFd_; ++i) {
auto& sref = data_[i]; auto& sref = data_[i];
if (sref.load(std::memory_order_acquire) == IN_USE) { if (sref.load(std::memory_order_acquire) == IN_USE) {
shutdown(i, abortive); shutdown(i, abortive);
......
...@@ -37,7 +37,7 @@ class ShutdownSocketSet : private boost::noncopyable { ...@@ -37,7 +37,7 @@ class ShutdownSocketSet : private boost::noncopyable {
* applications, even if you increased the number of file descriptors * applications, even if you increased the number of file descriptors
* on your system. * on your system.
*/ */
explicit ShutdownSocketSet(size_t maxFd = 1 << 18); explicit ShutdownSocketSet(int maxFd = 1 << 18);
/** /**
* Add an already open socket to the list of sockets managed by * Add an already open socket to the list of sockets managed by
...@@ -112,7 +112,7 @@ class ShutdownSocketSet : private boost::noncopyable { ...@@ -112,7 +112,7 @@ class ShutdownSocketSet : private boost::noncopyable {
} }
}; };
const size_t maxFd_; const int maxFd_;
std::unique_ptr<std::atomic<uint8_t>[], Free> data_; std::unique_ptr<std::atomic<uint8_t>[], Free> data_;
folly::File nullFile_; folly::File nullFile_;
}; };
......
...@@ -553,10 +553,11 @@ dynamic parseNumber(Input& in) { ...@@ -553,10 +553,11 @@ dynamic parseNumber(Input& in) {
std::string decodeUnicodeEscape(Input& in) { std::string decodeUnicodeEscape(Input& in) {
auto hexVal = [&] (int c) -> uint16_t { auto hexVal = [&] (int c) -> uint16_t {
return c >= '0' && c <= '9' ? c - '0' : return uint16_t(
c >= '0' && c <= '9' ? c - '0' :
c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'a' && c <= 'f' ? c - 'a' + 10 :
c >= 'A' && c <= 'F' ? c - 'A' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 :
(in.error("invalid hex digit"), 0); (in.error("invalid hex digit"), 0));
}; };
auto readHex = [&]() -> uint16_t { auto readHex = [&]() -> uint16_t {
...@@ -689,7 +690,7 @@ void escapeString( ...@@ -689,7 +690,7 @@ void escapeString(
StringPiece input, StringPiece input,
std::string& out, std::string& out,
const serialization_opts& opts) { const serialization_opts& opts) {
auto hexDigit = [] (int c) -> char { auto hexDigit = [] (uint8_t c) -> char {
return c < 10 ? c + '0' : c - 10 + 'a'; return c < 10 ? c + '0' : c - 10 + 'a';
}; };
...@@ -728,7 +729,7 @@ void escapeString( ...@@ -728,7 +729,7 @@ void escapeString(
// with value > 127, so size > 1 byte // with value > 127, so size > 1 byte
char32_t v = decodeUtf8(p, e, opts.skip_invalid_utf8); char32_t v = decodeUtf8(p, e, opts.skip_invalid_utf8);
out.append("\\u"); out.append("\\u");
out.push_back(hexDigit(v >> 12)); out.push_back(hexDigit(uint8_t(v >> 12)));
out.push_back(hexDigit((v >> 8) & 0x0f)); out.push_back(hexDigit((v >> 8) & 0x0f));
out.push_back(hexDigit((v >> 4) & 0x0f)); out.push_back(hexDigit((v >> 4) & 0x0f));
out.push_back(hexDigit(v & 0x0f)); out.push_back(hexDigit(v & 0x0f));
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment