diff options
author | Alexander Smirnov <alex@ydb.tech> | 2024-11-20 11:14:58 +0000 |
---|---|---|
committer | Alexander Smirnov <alex@ydb.tech> | 2024-11-20 11:14:58 +0000 |
commit | 31773f157bf8164364649b5f470f52dece0a4317 (patch) | |
tree | 33d0f7eef45303ab68cf08ab381ce5e5e36c5240 /util | |
parent | 2c7938962d8689e175574fc1e817c05049f27905 (diff) | |
parent | eff600952d5dfe17942f38f510a8ac2b203bb3a5 (diff) | |
download | ydb-31773f157bf8164364649b5f470f52dece0a4317.tar.gz |
Merge branch 'rightlib' into mergelibs-241120-1113
Diffstat (limited to 'util')
54 files changed, 789 insertions, 371 deletions
diff --git a/util/charset/unicode_table.h b/util/charset/unicode_table.h index 3876d7d1b7..3479fef5ef 100644 --- a/util/charset/unicode_table.h +++ b/util/charset/unicode_table.h @@ -101,15 +101,17 @@ namespace NUnicodeTable { } inline TValueRef Get(size_t key, TValueRef value) const { - if (key >= Size()) + if (key >= Size()) { return value; + } return GetImpl(key); } inline TValueRef Get(size_t key, size_t defaultKey) const { - if (key >= Size()) + if (key >= Size()) { return Get(defaultKey); + } return GetImpl(key); } diff --git a/util/charset/unidata.h b/util/charset/unidata.h index 68c084129b..4c676c4d9c 100644 --- a/util/charset/unidata.h +++ b/util/charset/unidata.h @@ -401,8 +401,9 @@ inline bool IsPrint(wchar32 ch) { } inline bool IsRomanDigit(wchar32 ch) { - if (NUnicode::CharHasType(ch, SHIFT(Nl_LETTER)) && 0x2160 <= ch && ch <= 0x2188) + if (NUnicode::CharHasType(ch, SHIFT(Nl_LETTER)) && 0x2160 <= ch && ch <= 0x2188) { return true; + } if (ch < 127) { switch (static_cast<char>(::ToLower(ch))) { case 'i': diff --git a/util/charset/utf8.cpp b/util/charset/utf8.cpp index b1ccb00e21..3423a981e5 100644 --- a/util/charset/utf8.cpp +++ b/util/charset/utf8.cpp @@ -35,8 +35,9 @@ namespace { } cNew = ConvertChar(conversion, c); - if (cNew != c) + if (cNew != c) { break; + } p += cLen; } if (p == end) { diff --git a/util/charset/utf8.h b/util/charset/utf8.h index b105d8db9d..c1ffdd072f 100644 --- a/util/charset/utf8.h +++ b/util/charset/utf8.h @@ -37,18 +37,19 @@ inline size_t UTF8RuneLen(const unsigned char lead_byte) { } inline size_t UTF8RuneLenByUCS(wchar32 rune) { - if (rune < 0x80) + if (rune < 0x80) { return 1U; - else if (rune < 0x800) + } else if (rune < 0x800) { return 2U; - else if (rune < 0x10000) + } else if (rune < 0x10000) { return 3U; - else if (rune < 0x200000) + } else if (rune < 0x200000) { return 4U; - else if (rune < 0x4000000) + } else if (rune < 0x4000000) { return 5U; - else + } else { return 6U; + } } inline void PutUTF8LeadBits(wchar32& rune, unsigned char c, size_t len) { @@ -193,37 +194,45 @@ inline RECODE_RESULT SafeReadUTF8Char(wchar32& rune, size_t& rune_len, const uns wchar32 _rune; size_t _len = UTF8RuneLen(*s); - if (s + _len > end) + if (s + _len > end) { return RECODE_EOINPUT; // [EOINPUT] - if (_len == 0) + } + if (_len == 0) { return RECODE_BROKENSYMBOL; // [BROKENSYMBOL] in first byte - _rune = *s++; // [00000000 0XXXXXXX] + } + _rune = *s++; // [00000000 0XXXXXXX] if (_len > 1) { _rune &= UTF8LeadByteMask(_len); unsigned char ch = *s++; - if (!IsUTF8ContinuationByte(ch)) + if (!IsUTF8ContinuationByte(ch)) { return RECODE_BROKENSYMBOL; // [BROKENSYMBOL] in second byte - PutUTF8SixBits(_rune, ch); // [00000XXX XXYYYYYY] + } + PutUTF8SixBits(_rune, ch); // [00000XXX XXYYYYYY] if (_len > 2) { ch = *s++; - if (!IsUTF8ContinuationByte(ch)) + if (!IsUTF8ContinuationByte(ch)) { return RECODE_BROKENSYMBOL; // [BROKENSYMBOL] in third byte - PutUTF8SixBits(_rune, ch); // [XXXXYYYY YYZZZZZZ] + } + PutUTF8SixBits(_rune, ch); // [XXXXYYYY YYZZZZZZ] if (_len > 3) { ch = *s; - if (!IsUTF8ContinuationByte(ch)) + if (!IsUTF8ContinuationByte(ch)) { return RECODE_BROKENSYMBOL; // [BROKENSYMBOL] in fourth byte - PutUTF8SixBits(_rune, ch); // [XXXYY YYYYZZZZ ZZQQQQQQ] - if (!IsValidUTF8Rune<4, strictMode>(_rune)) + } + PutUTF8SixBits(_rune, ch); // [XXXYY YYYYZZZZ ZZQQQQQQ] + if (!IsValidUTF8Rune<4, strictMode>(_rune)) { return RECODE_BROKENSYMBOL; + } } else { - if (!IsValidUTF8Rune<3, strictMode>(_rune)) + if (!IsValidUTF8Rune<3, strictMode>(_rune)) { return RECODE_BROKENSYMBOL; + } } } else { - if (!IsValidUTF8Rune<2, strictMode>(_rune)) + if (!IsValidUTF8Rune<2, strictMode>(_rune)) { return RECODE_BROKENSYMBOL; + } } } rune_len = _len; @@ -315,23 +324,26 @@ Y_FORCE_INLINE RECODE_RESULT ReadUTF8CharAndAdvance(wchar32& rune, const unsigne inline RECODE_RESULT SafeWriteUTF8Char(wchar32 rune, size_t& rune_len, unsigned char* s, size_t tail) { rune_len = 0; if (rune < 0x80) { - if (tail <= 0) + if (tail <= 0) { return RECODE_EOOUTPUT; + } *s = static_cast<unsigned char>(rune); rune_len = 1; return RECODE_OK; } if (rune < 0x800) { - if (tail <= 1) + if (tail <= 1) { return RECODE_EOOUTPUT; + } *s++ = static_cast<unsigned char>(0xC0 | (rune >> 6)); *s = static_cast<unsigned char>(0x80 | (rune & 0x3F)); rune_len = 2; return RECODE_OK; } if (rune < 0x10000) { - if (tail <= 2) + if (tail <= 2) { return RECODE_EOOUTPUT; + } *s++ = static_cast<unsigned char>(0xE0 | (rune >> 12)); *s++ = static_cast<unsigned char>(0x80 | ((rune >> 6) & 0x3F)); *s = static_cast<unsigned char>(0x80 | (rune & 0x3F)); @@ -339,8 +351,9 @@ inline RECODE_RESULT SafeWriteUTF8Char(wchar32 rune, size_t& rune_len, unsigned return RECODE_OK; } /*if (rune < 0x200000)*/ { - if (tail <= 3) + if (tail <= 3) { return RECODE_EOOUTPUT; + } *s++ = static_cast<unsigned char>(0xF0 | ((rune >> 18) & 0x07)); *s++ = static_cast<unsigned char>(0x80 | ((rune >> 12) & 0x3F)); *s++ = static_cast<unsigned char>(0x80 | ((rune >> 6) & 0x3F)); diff --git a/util/charset/wide.cpp b/util/charset/wide.cpp index 81d59bf1a2..535e8ef10f 100644 --- a/util/charset/wide.cpp +++ b/util/charset/wide.cpp @@ -23,10 +23,11 @@ namespace { case '\"': return Y_ARRAY_SIZE(QUOT); default: - if (insertBr && (c == '\r' || c == '\n')) + if (insertBr && (c == '\r' || c == '\n')) { return Y_ARRAY_SIZE(BR); - else + } else { return 1; + } } } } // namespace @@ -579,11 +580,13 @@ void EscapeHtmlChars(TUtf16String& str) { const TUtf16String& cs = str; - for (size_t i = 0; i < cs.size(); ++i) + for (size_t i = 0; i < cs.size(); ++i) { escapedLen += EscapedLen<insertBr>(cs[i]); + } - if (escapedLen == cs.size()) + if (escapedLen == cs.size()) { return; + } TUtf16String res; res.reserve(escapedLen); @@ -609,8 +612,9 @@ void EscapeHtmlChars(TUtf16String& str) { if (insertBr && (cs[i] == '\r' || cs[i] == '\n')) { ent = &br; break; - } else + } else { continue; + } } res.append(cs.begin() + start, cs.begin() + i); diff --git a/util/charset/wide.h b/util/charset/wide.h index c2a8d00372..4792a65953 100644 --- a/util/charset/wide.h +++ b/util/charset/wide.h @@ -81,8 +81,9 @@ inline const wchar32* SkipSymbol(const wchar32* begin, const wchar32* end) noexc inline wchar32 ReadSymbol(const wchar16* begin, const wchar16* end) noexcept { Y_ASSERT(begin < end); if (IsW16SurrogateLead(*begin)) { - if (begin + 1 < end && IsW16SurrogateTail(*(begin + 1))) + if (begin + 1 < end && IsW16SurrogateTail(*(begin + 1))) { return ::NDetail::ReadSurrogatePair(begin); + } return BROKEN_RUNE; } else if (IsW16SurrogateTail(*begin)) { @@ -210,8 +211,9 @@ inline bool WriteSymbol(wchar32 s, wchar16*& dest, const wchar16* destEnd) noexc return true; } - if (dest + 2 > destEnd) + if (dest + 2 > destEnd) { return false; + } ::NDetail::WriteSurrogatePair(s, dest); } else { @@ -362,8 +364,9 @@ inline TUtf16String UTF8ToWide(const char* text, size_t len) { TUtf16String w = TUtf16String::Uninitialized(len); size_t written; size_t pos = UTF8ToWideImpl<robust>(text, len, w.begin(), written); - if (pos != len) + if (pos != len) { ythrow yexception() << "failed to decode UTF-8 string at pos " << pos << ::NDetail::InStringMsg(text, len); + } Y_ASSERT(w.size() >= written); w.remove(written); return w; @@ -707,15 +710,17 @@ inline TUtf32String ASCIIToUTF32(const TStringBuf s) { //! returns @c true if string contains whitespace characters only inline bool IsSpace(const wchar16* s, size_t n) { - if (n == 0) + if (n == 0) { return false; + } Y_ASSERT(s); const wchar16* const e = s + n; for (const wchar16* p = s; p != e; ++p) { - if (!IsWhitespace(*p)) + if (!IsWhitespace(*p)) { return false; + } } return true; } @@ -879,8 +884,9 @@ inline bool IsValidUTF16(const wchar16* b, const wchar16* e) { Y_ENSURE(b <= e, TStringBuf("invalid iterators")); while (b < e) { wchar32 symbol = ReadSymbolAndAdvance(b, e); - if (symbol == BROKEN_RUNE) + if (symbol == BROKEN_RUNE) { return false; + } } return true; } diff --git a/util/datetime/parser.h b/util/datetime/parser.h index 43b6df8da2..eaffa03818 100644 --- a/util/datetime/parser.h +++ b/util/datetime/parser.h @@ -21,49 +21,60 @@ struct TDateTimeFields { i32 ZoneOffsetMinutes; void SetLooseYear(ui32 year) { - if (year < 60) + if (year < 60) { year += 100; - if (year < 160) + } + if (year < 160) { year += 1900; + } Year = year; } bool IsOk() const noexcept { - if (Year < 1970) + if (Year < 1970) { return false; - if (Month < 1 || Month > 12) + } + if (Month < 1 || Month > 12) { return false; + } unsigned int maxMonthDay = 31; if (Month == 4 || Month == 6 || Month == 9 || Month == 11) { maxMonthDay = 30; } else if (Month == 2) { - if (Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0)) + if (Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0)) { // leap year maxMonthDay = 29; - else + } else { maxMonthDay = 28; + } } - if (Day > maxMonthDay) + if (Day > maxMonthDay) { return false; + } - if (Hour > 23) + if (Hour > 23) { return false; + } - if (Minute > 59) + if (Minute > 59) { return false; + } // handle leap second which is explicitly allowed by ISO 8601:2004(E) $2.2.2 // https://datatracker.ietf.org/doc/html/rfc3339#section-5.6 - if (Second > 60) + if (Second > 60) { return false; + } - if (MicroSecond > 999999) + if (MicroSecond > 999999) { return false; + } if (Year == 1970 && Month == 1 && Day == 1) { - if ((i64)(3600 * Hour + 60 * Minute + Second) < (60 * ZoneOffsetMinutes)) + if ((i64)(3600 * Hour + 60 * Minute + Second) < (60 * ZoneOffsetMinutes)) { return false; + } } return true; @@ -71,14 +82,16 @@ struct TDateTimeFields { TInstant ToInstant(TInstant defaultValue) const { time_t tt = ToTimeT(-1); - if (tt == -1) + if (tt == -1) { return defaultValue; + } return TInstant::Seconds(tt) + TDuration::MicroSeconds(MicroSecond); } time_t ToTimeT(time_t defaultValue) const { - if (!IsOk()) + if (!IsOk()) { return defaultValue; + } struct tm tm; Zero(tm); tm.tm_year = Year - 1900; @@ -88,8 +101,9 @@ struct TDateTimeFields { tm.tm_min = Minute; tm.tm_sec = Second; time_t tt = TimeGM(&tm); - if (tt == -1) + if (tt == -1) { return defaultValue; + } return tt - ZoneOffsetMinutes * 60; } }; @@ -118,8 +132,9 @@ protected: } inline TInstant GetResult(int firstFinalState, TInstant defaultValue) const { - if (cs < firstFinalState) + if (cs < firstFinalState) { return defaultValue; + } return DateTimeFields.ToInstant(defaultValue); } }; @@ -177,47 +192,58 @@ struct TDateTimeFieldsDeprecated { i32 ZoneOffsetMinutes; void SetLooseYear(ui32 year) { - if (year < 60) + if (year < 60) { year += 100; - if (year < 160) + } + if (year < 160) { year += 1900; + } Year = year; } bool IsOk() const noexcept { - if (Year < 1970) + if (Year < 1970) { return false; - if (Month < 1 || Month > 12) + } + if (Month < 1 || Month > 12) { return false; + } unsigned int maxMonthDay = 31; if (Month == 4 || Month == 6 || Month == 9 || Month == 11) { maxMonthDay = 30; } else if (Month == 2) { - if (Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0)) + if (Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0)) { // leap year maxMonthDay = 29; - else + } else { maxMonthDay = 28; + } } - if (Day > maxMonthDay) + if (Day > maxMonthDay) { return false; + } - if (Hour > 23) + if (Hour > 23) { return false; + } - if (Minute > 59) + if (Minute > 59) { return false; + } - if (Second > 60) + if (Second > 60) { return false; + } - if (MicroSecond > 999999) + if (MicroSecond > 999999) { return false; + } if (Year == 1970 && Month == 1 && Day == 1) { - if ((i64)(3600 * Hour + 60 * Minute + Second) < (60 * ZoneOffsetMinutes)) + if ((i64)(3600 * Hour + 60 * Minute + Second) < (60 * ZoneOffsetMinutes)) { return false; + } } return true; @@ -225,14 +251,16 @@ struct TDateTimeFieldsDeprecated { TInstant ToInstant(TInstant defaultValue) const { time_t tt = ToTimeT(-1); - if (tt == -1) + if (tt == -1) { return defaultValue; + } return TInstant::Seconds(tt) + TDuration::MicroSeconds(MicroSecond); } time_t ToTimeT(time_t defaultValue) const { - if (!IsOk()) + if (!IsOk()) { return defaultValue; + } struct tm tm; Zero(tm); tm.tm_year = Year - 1900; @@ -242,8 +270,9 @@ struct TDateTimeFieldsDeprecated { tm.tm_min = Minute; tm.tm_sec = Second; time_t tt = TimeGM(&tm); - if (tt == -1) + if (tt == -1) { return defaultValue; + } return tt - ZoneOffsetMinutes * 60; } }; @@ -272,8 +301,9 @@ protected: } inline TInstant GetResult(int firstFinalState, TInstant defaultValue) const { - if (cs < firstFinalState) + if (cs < firstFinalState) { return defaultValue; + } return DateTimeFields.ToInstant(defaultValue); } }; diff --git a/util/digest/city.cpp b/util/digest/city.cpp index c0c7c1a2e9..0976169447 100644 --- a/util/digest/city.cpp +++ b/util/digest/city.cpp @@ -28,6 +28,7 @@ // compromising on hash quality. #include "city.h" +#include "city_streaming.h" using uint8 = ui8; using uint32 = ui32; @@ -307,3 +308,64 @@ uint128 CityHash128(const char* s, size_t len) noexcept { return CityHash128WithSeed(s, len, uint128(k0, k1)); } } + +TStreamingCityHash64::TStreamingCityHash64(size_t len, const char *head64, const char *tail64) { + Y_ASSERT(len > 64); + x = UNALIGNED_LOAD64(head64); + y = UNALIGNED_LOAD64(tail64 + 48) ^ k1; + z = UNALIGNED_LOAD64(tail64 + 8) ^ k0; + v = WeakHashLen32WithSeeds(tail64, len, y); + w = WeakHashLen32WithSeeds(tail64 + 32, len * k1, k0); + z += ShiftMix(v.second) * k1; + x = Rotate(z + x, 39) * k1; + y = Rotate(y, 33) * k1; + Rest64_ = (len - 1) / 64; + UnalignBufSz_ = 0; +} + +void TStreamingCityHash64::Process(const char *s, size_t avail) { + if (Y_UNLIKELY(!Rest64_)) return; + if (UnalignBufSz_) { + if (UnalignBufSz_ + avail < 64) { + memcpy(&UnalignBuf_[UnalignBufSz_], s, avail); + UnalignBufSz_ += avail; + return; + } else { + memcpy(&UnalignBuf_[UnalignBufSz_], s, 64 - UnalignBufSz_); + x = Rotate(x + y + v.first + UNALIGNED_LOAD64(UnalignBuf_ + 16), 37) * k1; + y = Rotate(y + v.second + UNALIGNED_LOAD64(UnalignBuf_ + 48), 42) * k1; + x ^= w.second; + y ^= v.first; + z = Rotate(z ^ w.first, 33); + v = WeakHashLen32WithSeeds(UnalignBuf_, v.second * k1, x + w.first); + w = WeakHashLen32WithSeeds(UnalignBuf_ + 32, z + w.second, y); + DoSwap(z, x); + s += 64 - UnalignBufSz_; + avail -= 64 - UnalignBufSz_; + Rest64_--; + UnalignBufSz_ = 0; + } + } + while(Rest64_ && avail >= 64) { + x = Rotate(x + y + v.first + UNALIGNED_LOAD64(s + 16), 37) * k1; + y = Rotate(y + v.second + UNALIGNED_LOAD64(s + 48), 42) * k1; + x ^= w.second; + y ^= v.first; + z = Rotate(z ^ w.first, 33); + v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first); + w = WeakHashLen32WithSeeds(s + 32, z + w.second, y); + DoSwap(z, x); + s += 64; + avail -= 64; + Rest64_--; + } + if (Rest64_ && avail) { + memcpy(UnalignBuf_, s, avail); + UnalignBufSz_ = avail; + } +} + +uint64 TStreamingCityHash64::operator() () { + return HashLen16(HashLen16(v.first, w.first) + ShiftMix(y) * k1 + z, + HashLen16(v.second, w.second) + x); +} diff --git a/util/digest/city_streaming.h b/util/digest/city_streaming.h new file mode 100644 index 0000000000..f9c5209e0a --- /dev/null +++ b/util/digest/city_streaming.h @@ -0,0 +1,21 @@ +#pragma once +#include <util/digest/city.h> + +/** + * (partially) streaming version of CityHash64 for large data. + * You need to know length and first/last 64 bytes. + * Those bytes should be passed twice: in constructor and thru process(). + * Length must be STRICTLY larger than 64 bytes. + * XXX: Dont use CityHash64 if you can use something else and need streaming + */ +class TStreamingCityHash64 { + ui64 x, y, z; + std::pair<ui64, ui64> v, w; + char UnalignBuf_[64]; + size_t UnalignBufSz_, Rest64_; + +public: + TStreamingCityHash64(size_t len, const char* head64, const char* tail64); + void Process(const char* s, size_t avail); + ui64 operator()(); +}; diff --git a/util/draft/enum.h b/util/draft/enum.h index 18002b7df2..e33cfea02c 100644 --- a/util/draft/enum.h +++ b/util/draft/enum.h @@ -21,18 +21,22 @@ class TEnumNotFoundException: public yexception { template <class K1, class K2, class V> const V* FindEnumFromStringImpl(K1 key, const std::pair<K2, V>* entries, size_t arraySize) { - for (size_t i = 0; i < arraySize; i++) - if (entries[i].first == key) + for (size_t i = 0; i < arraySize; i++) { + if (entries[i].first == key) { return &entries[i].second; + } + } return nullptr; } // special version for const char* template <class V> const V* FindEnumFromStringImpl(const char* key, const std::pair<const char*, V>* entries, size_t arraySize) { - for (size_t i = 0; i < arraySize; i++) - if (entries[i].first && key && !strcmp(entries[i].first, key)) + for (size_t i = 0; i < arraySize; i++) { + if (entries[i].first && key && !strcmp(entries[i].first, key)) { return &entries[i].second; + } + } return nullptr; } @@ -40,8 +44,9 @@ template <class K, class V> TString PrintEnumItemsImpl(const std::pair<K, V>* entries, size_t arraySize) { TString result; TStringOutput out(result); - for (size_t i = 0; i < arraySize; i++) + for (size_t i = 0; i < arraySize; i++) { out << (i ? ", " : "") << "'" << entries[i].first << "'"; + } return result; } @@ -50,30 +55,35 @@ template <class V> TString PrintEnumItemsImpl(const std::pair<const char*, V>* entries, size_t arraySize) { TString result; TStringOutput out(result); - for (size_t i = 0; i < arraySize; i++) + for (size_t i = 0; i < arraySize; i++) { out << (i ? ", " : "") << "'" << (entries[i].first ? entries[i].first : "<null>") << "'"; + } return result; } template <class K1, class K2, class V> const V* EnumFromStringImpl(K1 key, const std::pair<K2, V>* entries, size_t arraySize) { const V* res = FindEnumFromStringImpl(key, entries, arraySize); - if (res) + if (res) { return res; + } ythrow TEnumNotFoundException() << "Key '" << key << "' not found in enum. Valid options are: " << PrintEnumItemsImpl(entries, arraySize) << ". "; } template <class K, class V> const K* EnumToStringImpl(V value, const std::pair<K, V>* entries, size_t arraySize) { - for (size_t i = 0; i < arraySize; i++) - if (entries[i].second == value) + for (size_t i = 0; i < arraySize; i++) { + if (entries[i].second == value) { return &entries[i].first; + } + } TEnumNotFoundException exc; exc << "Value '" << int(value) << "' not found in enum. Valid values are: "; - for (size_t i = 0; i < arraySize; i++) + for (size_t i = 0; i < arraySize; i++) { exc << (i ? ", " : "") << int(entries[i].second); + } exc << ". "; ythrow exc; } @@ -128,8 +138,9 @@ inline void SetEnumFlags(TStringBuf optSpec, std::bitset<B>& flags, bool allIfEm flags.reset(); for (const auto& it : StringSplitter(optSpec).Split(',')) { E e; - if (!TryFromString(it.Token(), e)) + if (!TryFromString(it.Token(), e)) { ythrow yexception() << "Unknown enum value '" << it.Token() << "'"; + } flags.set((size_t)e); } } diff --git a/util/draft/holder_vector.h b/util/draft/holder_vector.h index 1c62055bd9..3e31b54a91 100644 --- a/util/draft/holder_vector.h +++ b/util/draft/holder_vector.h @@ -20,8 +20,9 @@ public: void Clear() { for (typename TBase::iterator it = TBase::begin(); it != TBase::end(); ++it) { - if (*it) + if (*it) { D::Destroy(*it); + } } TBase::clear(); } @@ -35,8 +36,9 @@ public: try { TBase::push_back(t); } catch (...) { - if (t) + if (t) { D::Destroy(t); + } throw; } } diff --git a/util/draft/matrix.h b/util/draft/matrix.h index 154d00b35e..f6d7f1ad15 100644 --- a/util/draft/matrix.h +++ b/util/draft/matrix.h @@ -96,8 +96,9 @@ public: } void Fill(T value) { - for (T *p = Arr, *end = Arr + M * N; p < end; ++p) + for (T *p = Arr, *end = Arr + M * N; p < end; ++p) { *p = value; + } } private: diff --git a/util/draft/memory.h b/util/draft/memory.h index 0a9722bb36..c39cf1b5ef 100644 --- a/util/draft/memory.h +++ b/util/draft/memory.h @@ -15,8 +15,9 @@ template <size_t Size> inline bool IsZero(const char* p) { size_t sizeInUI64 = Size / 8; const char* pEndUi64 = p + sizeInUI64 * 8; - if (sizeInUI64 && !IsZero<ui64>((const ui64*)p, (const ui64*)pEndUi64)) + if (sizeInUI64 && !IsZero<ui64>((const ui64*)p, (const ui64*)pEndUi64)) { return false; + } return IsZero(pEndUi64, p + Size); } diff --git a/util/folder/dirent_win.c b/util/folder/dirent_win.c index cabab6bbf9..8eed4801c7 100644 --- a/util/folder/dirent_win.c +++ b/util/folder/dirent_win.c @@ -59,8 +59,9 @@ struct DIR* opendir(const char* dirname) { } int closedir(struct DIR* dir) { - if (dir->sh != INVALID_HANDLE_VALUE) + if (dir->sh != INVALID_HANDLE_VALUE) { FindClose(dir->sh); + } free(dir->fff_templ); free(dir->readdir_buf); free(dir); @@ -109,8 +110,9 @@ struct dirent* readdir(struct DIR* dir) { struct dirent* res; if (!dir->readdir_buf) { dir->readdir_buf = (struct dirent*)malloc(sizeof(struct dirent)); - if (dir->readdir_buf == 0) + if (dir->readdir_buf == 0) { return 0; + } } readdir_r(dir, dir->readdir_buf, &res); return res; diff --git a/util/folder/dirut.cpp b/util/folder/dirut.cpp index a1a2ace9ca..a3e804f1e8 100644 --- a/util/folder/dirut.cpp +++ b/util/folder/dirut.cpp @@ -12,15 +12,18 @@ #include <util/system/yassert.h> void SlashFolderLocal(TString& folder) { - if (!folder) + if (!folder) { return; + } #ifdef _win32_ size_t pos; - while ((pos = folder.find('/')) != TString::npos) + while ((pos = folder.find('/')) != TString::npos) { folder.replace(pos, 1, LOCSLASH_S); + } #endif - if (folder[folder.size() - 1] != LOCSLASH_C) + if (folder[folder.size() - 1] != LOCSLASH_C) { folder.append(LOCSLASH_S); + } } #ifndef _win32_ @@ -36,8 +39,9 @@ bool resolvepath(TString& folder, const TString& home) { } // may be from windows char* ptr = folder.begin(); - while ((ptr = strchr(ptr, '\\')) != nullptr) + while ((ptr = strchr(ptr, '\\')) != nullptr) { *ptr = '/'; + } if (folder.at(0) == '~') { if (folder.length() == 1 || folder.at(1) == '/') { @@ -46,14 +50,16 @@ bool resolvepath(TString& folder, const TString& home) { char* buf = (char*)alloca(folder.length() + 1); strcpy(buf, folder.data() + 1); char* p = strchr(buf, '/'); - if (p) + if (p) { *p++ = 0; + } passwd* pw = getpwnam(buf); if (pw) { folder = pw->pw_dir; folder += "/"; - if (p) + if (p) { folder += p; + } } else { return false; // unknown user } @@ -75,8 +81,9 @@ bool resolvepath(TString& folder, const TString& home) { for (char* s = path; s;) { pp[i++] = s; s = strchr(s, '/'); - if (s) + if (s) { *s++ = 0; + } } for (int j = 1; j < i;) { @@ -108,8 +115,9 @@ bool resolvepath(TString& folder, const TString& home) { --j; } } - } else + } else { ++j; + } } char* s = newpath; @@ -160,24 +168,31 @@ static int next_dir(T*& ptr) { ++has_ctrl; break; default: - if (c == 127 || c < ' ') + if (c == 127 || c < ' ') { ++has_ctrl; - else + } else { ++has_letter; + } } } - if (*ptr) + if (*ptr) { ++ptr; - if (has_ctrl) + } + if (has_ctrl) { return dt_error; - if (has_letter) + } + if (has_letter) { return dt_dir; - if (has_dot && has_blank) + } + if (has_dot && has_blank) { return dt_error; - if (has_dot == 1) + } + if (has_dot == 1) { return dt_empty; - if (has_dot == 2) + } + if (has_dot == 2) { return dt_up; + } return dt_error; } @@ -193,15 +208,18 @@ using disk_type = enum { template <typename T> static int skip_disk(T*& ptr) { int result = dk_noflags; - if (!*ptr) + if (!*ptr) { return result; + } if (ptr[0] == '\\' && ptr[1] == '\\') { result |= dk_unc | dk_fromroot; ptr += 2; - if (next_dir(ptr) != dt_dir) + if (next_dir(ptr) != dt_dir) { return dk_error; // has no host name - if (next_dir(ptr) != dt_dir) + } + if (next_dir(ptr) != dt_dir) { return dk_error; // has no share name + } } else { if (*ptr && *(ptr + 1) == ':') { result |= dk_hasdrive; @@ -225,12 +243,14 @@ int correctpath(char* cpath, const char* path) { int counter = 0; while (*ptr) { char c = *ptr; - if (c == '/') + if (c == '/') { c = '\\'; - if (c == '\\') + } + if (c == '\\') { ++counter; - else + } else { counter = 0; + } if (counter <= 1) { *cptr = c; ++cptr; @@ -241,8 +261,9 @@ int correctpath(char* cpath, const char* path) { // replace '/' by '\' int dk = skip_disk(cpath); - if (dk == dk_error) + if (dk == dk_error) { return 0; + } char* ptr1 = ptr = cpath; int level = 0; @@ -260,10 +281,11 @@ int correctpath(char* cpath, const char* path) { if (level >= 0) { *--ptr1 = 0; ptr1 = strrchr(cpath, '\\'); - if (!ptr1) + if (!ptr1) { ptr1 = cpath; - else + } else { ++ptr1; + } memmove(ptr1, ptr, strlen(ptr) + 1); ptr = ptr1; break; @@ -273,8 +295,9 @@ int correctpath(char* cpath, const char* path) { return 1; } } - if (dk & dk_fromroot) + if (dk & dk_fromroot) { return 0; + } break; case dt_error: default: @@ -283,8 +306,9 @@ int correctpath(char* cpath, const char* path) { ptr1 = ptr; } - if ((ptr > cpath || ptr == cpath && dk & dk_unc) && *(ptr - 1) == '\\') + if ((ptr > cpath || ptr == cpath && dk & dk_unc) && *(ptr - 1) == '\\') { *(ptr - 1) = 0; + } return 1; } @@ -294,54 +318,63 @@ static inline int normchar(unsigned char c) { static inline char* strslashcat(char* a, const char* b) { size_t len = strlen(a); - if (len && a[len - 1] != '\\') + if (len && a[len - 1] != '\\') { a[len++] = '\\'; + } strcpy(a + len, b); return a; } int resolvepath(char* apath, const char* rpath, const char* cpath) { const char* redisk = rpath; - if (!rpath || !*rpath) + if (!rpath || !*rpath) { return 0; + } int rdt = skip_disk(redisk); - if (rdt == dk_error) + if (rdt == dk_error) { return 0; + } if (rdt & dk_unc || rdt & dk_hasdrive && rdt & dk_fromroot) { return correctpath(apath, rpath); } const char* cedisk = cpath; - if (!cpath || !*cpath) + if (!cpath || !*cpath) { return 0; + } int cdt = skip_disk(cedisk); - if (cdt == dk_error) + if (cdt == dk_error) { return 0; + } char* tpath = (char*)alloca(strlen(rpath) + strlen(cpath) + 3); // rdt&dk_hasdrive && !rdt&dk_fromroot if (rdt & dk_hasdrive) { - if (!(cdt & dk_fromroot)) + if (!(cdt & dk_fromroot)) { return 0; - if (cdt & dk_hasdrive && normchar(*rpath) != normchar(*cpath)) + } + if (cdt & dk_hasdrive && normchar(*rpath) != normchar(*cpath)) { return 0; + } memcpy(tpath, rpath, 2); memcpy(tpath + 2, cedisk, strlen(cedisk) + 1); strslashcat(tpath, redisk); // !rdt&dk_hasdrive && rdt&dk_fromroot } else if (rdt & dk_fromroot) { - if (!(cdt & dk_hasdrive) && !(cdt & dk_unc)) + if (!(cdt & dk_hasdrive) && !(cdt & dk_unc)) { return 0; + } memcpy(tpath, cpath, cedisk - cpath); tpath[cedisk - cpath] = 0; strslashcat(tpath, redisk); // !rdt&dk_hasdrive && !rdt&dk_fromroot } else { - if (!(cdt & dk_fromroot) || !(cdt & dk_hasdrive) && !(cdt & dk_unc)) + if (!(cdt & dk_fromroot) || !(cdt & dk_hasdrive) && !(cdt & dk_unc)) { return 0; + } strslashcat(strcpy(tpath, cpath), redisk); } @@ -388,8 +421,9 @@ void RemoveDirWithContents(TString dirName) { case FTS_DP: case FTS_SL: case FTS_SLNONE: - if (!NFs::Remove(it->fts_path)) + if (!NFs::Remove(it->fts_path)) { ythrow TSystemError() << "error while removing " << it->fts_path; + } break; } } @@ -415,11 +449,13 @@ TString RealPath(const TString& path) { } TString RealLocation(const TString& path) { - if (NFs::Exists(path)) + if (NFs::Exists(path)) { return RealPath(path); + } TString dirpath = GetDirName(path); - if (NFs::Exists(dirpath)) + if (NFs::Exists(dirpath)) { return RealPath(dirpath) + GetDirectorySeparatorS() + GetFileNameComponent(path.data()); + } ythrow TFileError() << "RealLocation failed \"" << path << "\""; } @@ -437,14 +473,18 @@ int MakeTempDir(char path[/*FILENAME_MAX*/], const char* prefix) { prefix = sysTmp.data(); } - if ((ret = ResolvePath(prefix, nullptr, path, 1)) != 0) + if ((ret = ResolvePath(prefix, nullptr, path, 1)) != 0) { return ret; - if (!TFileStat(path).IsDir()) + } + if (!TFileStat(path).IsDir()) { return ENOENT; - if ((strlcat(path, "tmpXXXXXX", FILENAME_MAX) > FILENAME_MAX - 100)) + } + if ((strlcat(path, "tmpXXXXXX", FILENAME_MAX) > FILENAME_MAX - 100)) { return EINVAL; - if (!(mkdtemp(path))) + } + if (!(mkdtemp(path))) { return errno ? errno : EINVAL; + } strcat(path, LOCSLASH_S); return 0; } @@ -459,13 +499,14 @@ TString GetHomeDir() { #ifndef _win32_ passwd* pw = nullptr; s = getenv("USER"); - if (s) + if (s) { pw = getpwnam(s.data()); - else + } else { pw = getpwuid(getuid()); - if (pw) + } + if (pw) { s = pw->pw_dir; - else + } else #endif { char* cur_dir = getcwd(nullptr, 0); @@ -494,8 +535,9 @@ const char* GetFileNameComponent(const char* f) { #ifdef _win_ // "/" is also valid char separator on Windows const char* p2 = strrchr(f, '/'); - if (p2 > p) + if (p2 > p) { p = p2; + } #endif if (p) { @@ -561,20 +603,24 @@ int ResolvePath(const char* rel, const char* abs, char res[/*MAXPATHLEN*/], bool size_t len; *res = 0; - if (!rel || !*rel) + if (!rel || !*rel) { return EINVAL; + } if (!IsAbsolutePath(rel) && IsAbsolutePath(abs)) { len = strlcpy(t, abs, sizeof(t)); - if (len >= sizeof(t) - 3) + if (len >= sizeof(t) - 3) { return EINVAL; - if (t[len - 1] != LOCSLASH_C) + } + if (t[len - 1] != LOCSLASH_C) { t[len++] = LOCSLASH_C; + } len += strlcpy(t + len, rel, sizeof(t) - len); } else { len = strlcpy(t, rel, sizeof(t)); } - if (len >= sizeof(t) - 3) + if (len >= sizeof(t) - 3) { return EINVAL; + } if (isdir && t[len - 1] != LOCSLASH_C) { t[len++] = LOCSLASH_C; t[len] = 0; @@ -603,8 +649,9 @@ int ResolvePath(const char* rel, const char* abs, char res[/*MAXPATHLEN*/], bool TString ResolvePath(const char* rel, const char* abs, bool isdir) { char buf[PATH_MAX]; - if (ResolvePath(rel, abs, buf, isdir)) + if (ResolvePath(rel, abs, buf, isdir)) { ythrow yexception() << "cannot resolve path: \"" << rel << "\""; + } return buf; } diff --git a/util/folder/dirut.h b/util/folder/dirut.h index 2537027b12..ccdfc94ed8 100644 --- a/util/folder/dirut.h +++ b/util/folder/dirut.h @@ -105,12 +105,14 @@ public: } const char* Check(const char* fname) const { - if (!fname || !*fname) + if (!fname || !*fname) { return nullptr; + } if (Strict) { NFs::EnsureExists(fname); - } else if (!NFs::Exists(fname)) + } else if (!NFs::Exists(fname)) { fname = nullptr; + } return fname; } diff --git a/util/generic/bitmap.h b/util/generic/bitmap.h index 929f23a883..3116c8dd19 100644 --- a/util/generic/bitmap.h +++ b/util/generic/bitmap.h @@ -350,19 +350,21 @@ public: ~TReference() = default; Y_FORCE_INLINE TReference& operator=(bool val) { - if (val) + if (val) { *Chunk |= static_cast<TChunk>(1) << Offset; - else + } else { *Chunk &= ~(static_cast<TChunk>(1) << Offset); + } return *this; } Y_FORCE_INLINE TReference& operator=(const TReference& ref) { - if (ref) + if (ref) { *Chunk |= static_cast<TChunk>(1) << Offset; - else + } else { *Chunk &= ~(static_cast<TChunk>(1) << Offset); + } return *this; } @@ -407,8 +409,9 @@ private: TChunk updateMask = FullChunk << bitOffset; if (chunk == endChunk) { updateMask ^= FullChunk << endBitOffset; - if (!updateMask) + if (!updateMask) { break; + } } Mask.Data[chunk] = TUpdateOp::Op(Mask.Data[chunk], updateMask); bitOffset = 0; @@ -570,16 +573,18 @@ public: static_assert(std::is_unsigned<TTo>::value, "expect std::is_unsigned<TTo>::value"); to = 0; size_t chunkpos = pos >> DivCount; - if (chunkpos >= Mask.GetChunkCapacity()) + if (chunkpos >= Mask.GetChunkCapacity()) { return; + } if ((pos & ModMask) == 0) { - if (sizeof(TChunk) >= sizeof(TTo)) + if (sizeof(TChunk) >= sizeof(TTo)) { to = (TTo)Mask.Data[chunkpos]; - else // if (sizeof(TChunk) < sizeof(TTo)) + } else { // if (sizeof(TChunk) < sizeof(TTo)) NBitMapPrivate::CopyData(&to, 1, Mask.Data + chunkpos, Min(((sizeof(TTo) * 8) >> DivCount), Mask.GetChunkCapacity() - chunkpos)); - } else if ((pos & (sizeof(TTo) * 8 - 1)) == 0 && sizeof(TChunk) >= 2 * sizeof(TTo)) + } + } else if ((pos & (sizeof(TTo) * 8 - 1)) == 0 && sizeof(TChunk) >= 2 * sizeof(TTo)) { to = (TTo)(Mask.Data[chunkpos] >> (pos & ModMask)); - else { + } else { static constexpr size_t copyToSize = (sizeof(TChunk) >= sizeof(TTo)) ? (sizeof(TChunk) / sizeof(TTo)) + 2 : 3; TTo temp[copyToSize] = {0, 0}; // or use non defined by now TBitmap<copyToSize, TTo>::CopyData,RShift(pos & ModMask),Export(0,to) @@ -621,17 +626,20 @@ public: Y_FORCE_INLINE size_t ValueBitCount() const { size_t nonZeroChunk = Mask.GetChunkCapacity() - 1; - while (nonZeroChunk != 0 && !Mask.Data[nonZeroChunk]) + while (nonZeroChunk != 0 && !Mask.Data[nonZeroChunk]) { --nonZeroChunk; + } return nonZeroChunk || Mask.Data[nonZeroChunk] ? nonZeroChunk * BitsPerChunk + GetValueBitCount(TIntType(Mask.Data[nonZeroChunk])) : 0; } Y_PURE_FUNCTION Y_FORCE_INLINE bool Empty() const { - for (size_t i = 0; i < Mask.GetChunkCapacity(); ++i) - if (Mask.Data[i]) + for (size_t i = 0; i < Mask.GetChunkCapacity(); ++i) { + if (Mask.Data[i]) { return false; + } + } return true; } @@ -679,11 +687,13 @@ public: TThis& And(const TThis& bitmap) { // Don't expand capacity here, because resulting bits in positions, // which are greater then size of one of these bitmaps, will be zero - for (size_t i = 0; i < Min(bitmap.Mask.GetChunkCapacity(), Mask.GetChunkCapacity()); ++i) + for (size_t i = 0; i < Min(bitmap.Mask.GetChunkCapacity(), Mask.GetChunkCapacity()); ++i) { Mask.Data[i] &= bitmap.Mask.Data[i]; + } // Clear bits if current bitmap size is greater than AND-ed one - for (size_t i = bitmap.Mask.GetChunkCapacity(); i < Mask.GetChunkCapacity(); ++i) + for (size_t i = bitmap.Mask.GetChunkCapacity(); i < Mask.GetChunkCapacity(); ++i) { Mask.Data[i] = 0; + } return *this; } @@ -694,8 +704,9 @@ public: Y_FORCE_INLINE TThis& And(const TChunk& val) { Mask.Data[0] &= val; - for (size_t i = 1; i < Mask.GetChunkCapacity(); ++i) + for (size_t i = 1; i < Mask.GetChunkCapacity(); ++i) { Mask.Data[i] = 0; + } return *this; } @@ -704,8 +715,9 @@ public: if (valueBitCount) { // Memory optimization: expand size only for non-zero bits Reserve(valueBitCount); - for (size_t i = 0; i < Min(bitmap.Mask.GetChunkCapacity(), Mask.GetChunkCapacity()); ++i) + for (size_t i = 0; i < Min(bitmap.Mask.GetChunkCapacity(), Mask.GetChunkCapacity()); ++i) { Mask.Data[i] |= bitmap.Mask.Data[i]; + } } return *this; } @@ -723,8 +735,9 @@ public: TThis& Xor(const TThis& bitmap) { Reserve(bitmap.Size()); - for (size_t i = 0; i < bitmap.Mask.GetChunkCapacity(); ++i) + for (size_t i = 0; i < bitmap.Mask.GetChunkCapacity(); ++i) { Mask.Data[i] ^= bitmap.Mask.Data[i]; + } return *this; } @@ -740,8 +753,9 @@ public: } TThis& SetDifference(const TThis& bitmap) { - for (size_t i = 0; i < Min(bitmap.Mask.GetChunkCapacity(), Mask.GetChunkCapacity()); ++i) + for (size_t i = 0; i < Min(bitmap.Mask.GetChunkCapacity(), Mask.GetChunkCapacity()); ++i) { Mask.Data[i] &= ~bitmap.Mask.Data[i]; + } return *this; } @@ -756,8 +770,9 @@ public: } Y_FORCE_INLINE TThis& Flip() { - for (size_t i = 0; i < Mask.GetChunkCapacity(); ++i) + for (size_t i = 0; i < Mask.GetChunkCapacity(); ++i) { Mask.Data[i] = ~Mask.Data[i]; + } Mask.Sanitize(); return *this; } @@ -779,13 +794,16 @@ public: Mask.Data[i] = Mask.Data[i - eshift]; } } else { - for (size_t i = Mask.GetChunkCapacity() - 1; i > eshift; --i) + for (size_t i = Mask.GetChunkCapacity() - 1; i > eshift; --i) { Mask.Data[i] = (Mask.Data[i - eshift] << offset) | (Mask.Data[i - eshift - 1] >> subOffset); - if (eshift < Mask.GetChunkCapacity()) + } + if (eshift < Mask.GetChunkCapacity()) { Mask.Data[eshift] = Mask.Data[0] << offset; + } } - for (size_t i = 0; i < Min(eshift, Mask.GetChunkCapacity()); ++i) + for (size_t i = 0; i < Min(eshift, Mask.GetChunkCapacity()); ++i) { Mask.Data[i] = 0; + } // Cleanup extra high bits in the storage Mask.Sanitize(); @@ -810,13 +828,15 @@ public: } } else { const size_t subOffset = BitsPerChunk - offset; - for (size_t i = 0; i < limit; ++i) + for (size_t i = 0; i < limit; ++i) { Mask.Data[i] = (Mask.Data[i + eshift] >> offset) | (Mask.Data[i + eshift + 1] << subOffset); + } Mask.Data[limit] = Mask.Data[Mask.GetChunkCapacity() - 1] >> offset; } - for (size_t i = limit + 1; i < Mask.GetChunkCapacity(); ++i) + for (size_t i = limit + 1; i < Mask.GetChunkCapacity(); ++i) { Mask.Data[i] = 0; + } } } return *this; @@ -826,8 +846,9 @@ public: // This method is optimized combination of Or() and LShift(), which allows reducing memory allocation // when combining long dynamic bitmaps. TThis& Or(const TThis& bitmap, size_t offset) { - if (0 == offset) + if (0 == offset) { return Or(bitmap); + } const size_t otherValueBitCount = bitmap.ValueBitCount(); // Continue only if OR-ed bitmap have non-zero bits @@ -848,8 +869,9 @@ public: for (; i < Min(bitmap.Mask.GetChunkCapacity() + chunkShift, Mask.GetChunkCapacity()); ++i) { Mask.Data[i] |= (bitmap.Mask.Data[i - chunkShift] << subShift) | (bitmap.Mask.Data[i - chunkShift - 1] >> subOffset); } - if (i < Mask.GetChunkCapacity()) + if (i < Mask.GetChunkCapacity()) { Mask.Data[i] |= bitmap.Mask.Data[i - chunkShift - 1] >> subOffset; + } } } @@ -859,19 +881,22 @@ public: bool Equal(const TThis& bitmap) const { if (Mask.GetChunkCapacity() > bitmap.Mask.GetChunkCapacity()) { for (size_t i = bitmap.Mask.GetChunkCapacity(); i < Mask.GetChunkCapacity(); ++i) { - if (0 != Mask.Data[i]) + if (0 != Mask.Data[i]) { return false; + } } } else if (Mask.GetChunkCapacity() < bitmap.Mask.GetChunkCapacity()) { for (size_t i = Mask.GetChunkCapacity(); i < bitmap.Mask.GetChunkCapacity(); ++i) { - if (0 != bitmap.Mask.Data[i]) + if (0 != bitmap.Mask.Data[i]) { return false; + } } } size_t size = Min(Mask.GetChunkCapacity(), bitmap.Mask.GetChunkCapacity()); for (size_t i = 0; i < size; ++i) { - if (Mask.Data[i] != bitmap.Mask.Data[i]) + if (Mask.Data[i] != bitmap.Mask.Data[i]) { return false; + } } return true; } @@ -884,18 +909,21 @@ public: int Compare(const TThis& bitmap) const { size_t size = Min(Mask.GetChunkCapacity(), bitmap.Mask.GetChunkCapacity()); int res = ::memcmp(Mask.Data, bitmap.Mask.Data, size * sizeof(TChunk)); - if (0 != res || Mask.GetChunkCapacity() == bitmap.Mask.GetChunkCapacity()) + if (0 != res || Mask.GetChunkCapacity() == bitmap.Mask.GetChunkCapacity()) { return res; + } if (Mask.GetChunkCapacity() > bitmap.Mask.GetChunkCapacity()) { for (size_t i = bitmap.Mask.GetChunkCapacity(); i < Mask.GetChunkCapacity(); ++i) { - if (0 != Mask.Data[i]) + if (0 != Mask.Data[i]) { return 1; + } } } else { for (size_t i = Mask.GetChunkCapacity(); i < bitmap.Mask.GetChunkCapacity(); ++i) { - if (0 != bitmap.Mask.Data[i]) + if (0 != bitmap.Mask.Data[i]) { return -1; + } } } return 0; @@ -953,8 +981,9 @@ public: Y_FORCE_INLINE size_t Count() const { size_t count = 0; - for (size_t i = 0; i < Mask.GetChunkCapacity(); ++i) + for (size_t i = 0; i < Mask.GetChunkCapacity(); ++i) { count += ::NBitMapPrivate::CountBitsPrivate(Mask.Data[i]); + } return count; } diff --git a/util/generic/bitops.h b/util/generic/bitops.h index 0a2396bfee..601daf7a30 100644 --- a/util/generic/bitops.h +++ b/util/generic/bitops.h @@ -276,13 +276,16 @@ Y_FORCE_INLINE ui64 MostSignificantBit(ui64 v) { ui64 res = v ? (63 - __builtin_clzll(v)) : 0; #elif defined(_MSC_VER) && defined(_64_) unsigned long res = 0; - if (v) + if (v) { _BitScanReverse64(&res, v); + } #else ui64 res = 0; - if (v) - while (v >>= 1) + if (v) { + while (v >>= 1) { ++res; + } + } #endif return res; } @@ -295,8 +298,9 @@ Y_FORCE_INLINE ui64 LeastSignificantBit(ui64 v) { ui64 res = v ? __builtin_ffsll(v) - 1 : 0; #elif defined(_MSC_VER) && defined(_64_) unsigned long res = 0; - if (v) + if (v) { _BitScanForward64(&res, v); + } #else ui64 res = 0; if (v) { diff --git a/util/generic/function_ref_ut.cpp b/util/generic/function_ref_ut.cpp index 45506beeeb..171671d7ea 100644 --- a/util/generic/function_ref_ut.cpp +++ b/util/generic/function_ref_ut.cpp @@ -20,8 +20,9 @@ Y_UNIT_TEST_SUITE(TestFunctionRef) { } int F1(bool x) { - if (x) + if (x) { throw 19; + } return 42; } diff --git a/util/generic/hash_table.h b/util/generic/hash_table.h index 5976881a71..b33ad4f596 100644 --- a/util/generic/hash_table.h +++ b/util/generic/hash_table.h @@ -634,9 +634,11 @@ public: } iterator begin() { - for (size_type n = 0; n < buckets.size(); ++n) /*y*/ - if (buckets[n]) + for (size_type n = 0; n < buckets.size(); ++n) { /*y*/ + if (buckets[n]) { return iterator(buckets[n]); /*y*/ + } + } return end(); } @@ -645,9 +647,11 @@ public: } /*y*/ const_iterator begin() const { - for (size_type n = 0; n < buckets.size(); ++n) /*y*/ - if (buckets[n]) + for (size_type n = 0; n < buckets.size(); ++n) { /*y*/ + if (buckets[n]) { return const_iterator(buckets[n]); /*y*/ + } + } return end(); } @@ -662,9 +666,11 @@ public: size_type bucket_size(size_type bucket) const { size_type result = 0; - if (const node* cur = buckets[bucket]) - for (; !((uintptr_t)cur & 1); cur = cur->next) + if (const node* cur = buckets[bucket]) { + for (; !((uintptr_t)cur & 1); cur = cur->next) { result += 1; + } + } return result; } @@ -731,14 +737,16 @@ public: template <class InputIterator> void insert_unique(InputIterator f, InputIterator l, std::input_iterator_tag) { - for (; f != l; ++f) + for (; f != l; ++f) { insert_unique(*f); + } } template <class InputIterator> void insert_equal(InputIterator f, InputIterator l, std::input_iterator_tag) { - for (; f != l; ++f) + for (; f != l; ++f) { insert_equal(*f); + } } template <class ForwardIterator> @@ -746,8 +754,9 @@ public: difference_type n = std::distance(f, l); reserve(num_elements + n); - for (; n > 0; --n, ++f) + for (; n > 0; --n, ++f) { insert_unique_noresize(*f); + } } template <class ForwardIterator> @@ -755,8 +764,9 @@ public: difference_type n = std::distance(f, l); reserve(num_elements + n); - for (; n > 0; --n, ++f) + for (; n > 0; --n, ++f) { emplace_equal_noresize(*f); + } } template <class OtherValue> @@ -794,10 +804,13 @@ public: const size_type n = bkt_num_key(key); size_type result = 0; - if (const node* cur = buckets[n]) - for (; !((uintptr_t)cur & 1); cur = cur->next) - if (equals(get_key(cur->val), key)) + if (const node* cur = buckets[n]) { + for (; !((uintptr_t)cur & 1); cur = cur->next) { + if (equals(get_key(cur->val), key)) { ++result; + } + } + } return result; } @@ -834,8 +847,9 @@ public: * the nodes at once. */ void release_nodes() { - if (empty()) + if (empty()) { return; /* Need this check because empty buckets may reside in read-only memory. */ + } clear_buckets(buckets); num_elements = 0; @@ -877,8 +891,9 @@ public: * downsizing. */ Y_REINITIALIZES_OBJECT void clear() { - if (num_elements) + if (num_elements) { clear((num_elements * 2 + buckets.size()) / 3); + } } private: @@ -964,8 +979,9 @@ __yhashtable_iterator<V>& __yhashtable_iterator<V>::operator++() { cur = cur->next; if ((uintptr_t)cur & 1) { node** bucket = (node**)((uintptr_t)cur & ~1); - while (*bucket == nullptr) + while (*bucket == nullptr) { ++bucket; + } Y_ASSERT(*bucket != nullptr); cur = (node*)((uintptr_t)*bucket & ~1); } @@ -985,8 +1001,9 @@ __yhashtable_const_iterator<V>& __yhashtable_const_iterator<V>::operator++() { cur = cur->next; if ((uintptr_t)cur & 1) { node** bucket = (node**)((uintptr_t)cur & ~1); - while (*bucket == nullptr) + while (*bucket == nullptr) { ++bucket; + } Y_ASSERT(*bucket != nullptr); cur = (node*)((uintptr_t)*bucket & ~1); } @@ -1010,10 +1027,13 @@ std::pair<typename THashTable<V, K, HF, Ex, Eq, A>::iterator, bool> THashTable<V const size_type n = bkt_num(tmp->val); node* first = buckets[n]; - if (first) /*y*/ - for (node* cur = first; !((uintptr_t)cur & 1); cur = cur->next) /*y*/ - if (equals(get_key(cur->val), get_key(tmp->val))) + if (first) { /*y*/ + for (node* cur = first; !((uintptr_t)cur & 1); cur = cur->next) { /*y*/ + if (equals(get_key(cur->val), get_key(tmp->val))) { return std::pair<iterator, bool>(iterator(cur), false); /*y*/ + } + } + } guard.release(); tmp->next = first ? first : (node*)((uintptr_t)&buckets[n + 1] | 1); /*y*/ @@ -1028,10 +1048,13 @@ std::pair<typename THashTable<V, K, HF, Ex, Eq, A>::iterator, bool> THashTable<V const size_type n = bkt_num(obj); node* first = buckets[n]; - if (first) /*y*/ - for (node* cur = first; !((uintptr_t)cur & 1); cur = cur->next) /*y*/ - if (equals(get_key(cur->val), get_key(obj))) + if (first) { /*y*/ + for (node* cur = first; !((uintptr_t)cur & 1); cur = cur->next) { /*y*/ + if (equals(get_key(cur->val), get_key(obj))) { return std::pair<iterator, bool>(iterator(cur), false); /*y*/ + } + } + } node* tmp = new_node(obj); tmp->next = first ? first : (node*)((uintptr_t)&buckets[n + 1] | 1); /*y*/ @@ -1049,8 +1072,8 @@ __yhashtable_iterator<V> THashTable<V, K, HF, Ex, Eq, A>::emplace_equal_noresize const size_type n = bkt_num(tmp->val); node* first = buckets[n]; - if (first) /*y*/ - for (node* cur = first; !((uintptr_t)cur & 1); cur = cur->next) /*y*/ + if (first) { /*y*/ + for (node* cur = first; !((uintptr_t)cur & 1); cur = cur->next) { /*y*/ if (equals(get_key(cur->val), get_key(tmp->val))) { guard.release(); tmp->next = cur->next; @@ -1058,6 +1081,8 @@ __yhashtable_iterator<V> THashTable<V, K, HF, Ex, Eq, A>::emplace_equal_noresize ++num_elements; return iterator(tmp); /*y*/ } + } + } guard.release(); tmp->next = first ? first : (node*)((uintptr_t)&buckets[n + 1] | 1); /*y*/ @@ -1074,10 +1099,13 @@ typename THashTable<V, K, HF, Ex, Eq, A>::reference THashTable<V, K, HF, Ex, Eq, size_type n = bkt_num_key(get_key(v)); node* first = buckets[n]; - if (first) /*y*/ - for (node* cur = first; !((uintptr_t)cur & 1); cur = cur->next) /*y*/ - if (equals(get_key(cur->val), get_key(v))) + if (first) { /*y*/ + for (node* cur = first; !((uintptr_t)cur & 1); cur = cur->next) { /*y*/ + if (equals(get_key(cur->val), get_key(v))) { return cur->val; + } + } + } node* tmp = new_node(v); tmp->next = first ? first : (node*)((uintptr_t)&buckets[n + 1] | 1); /*y*/ @@ -1093,10 +1121,13 @@ __yhashtable_iterator<V> THashTable<V, K, HF, Ex, Eq, A>::find_i(const OtherKey& ins = &buckets[n]; node* first = buckets[n]; - if (first) /*y*/ - for (node* cur = first; !((uintptr_t)cur & 1); cur = cur->next) /*y*/ - if (equals(get_key(cur->val), key)) + if (first) { /*y*/ + for (node* cur = first; !((uintptr_t)cur & 1); cur = cur->next) { /*y*/ + if (equals(get_key(cur->val), key)) { return iterator(cur); /*y*/ + } + } + } return end(); } @@ -1115,19 +1146,24 @@ std::pair<__yhashtable_iterator<V>, __yhashtable_iterator<V>> THashTable<V, K, H ins = &buckets[n]; node* first = buckets[n]; - if (first) /*y*/ + if (first) { /*y*/ for (; !((uintptr_t)first & 1); first = first->next) { /*y*/ if (equals(get_key(first->val), key)) { - for (node* cur = first->next; !((uintptr_t)cur & 1); cur = cur->next) - if (!equals(get_key(cur->val), key)) + for (node* cur = first->next; !((uintptr_t)cur & 1); cur = cur->next) { + if (!equals(get_key(cur->val), key)) { return pii(iterator(first), iterator(cur)); /*y*/ - for (size_type m = n + 1; m < buckets.size(); ++m) /*y*/ - if (buckets[m]) + } + } + for (size_type m = n + 1; m < buckets.size(); ++m) { /*y*/ + if (buckets[m]) { return pii(iterator(first), /*y*/ iterator(buckets[m])); /*y*/ - return pii(iterator(first), end()); /*y*/ + } + } + return pii(iterator(first), end()); /*y*/ } } + } return pii(end(), end()); } @@ -1138,20 +1174,25 @@ std::pair<__yhashtable_const_iterator<V>, __yhashtable_const_iterator<V>> THashT const size_type n = bkt_num_key(key); const node* first = buckets[n]; - if (first) /*y*/ + if (first) { /*y*/ for (; !((uintptr_t)first & 1); first = first->next) { /*y*/ if (equals(get_key(first->val), key)) { - for (const node* cur = first->next; !((uintptr_t)cur & 1); cur = cur->next) - if (!equals(get_key(cur->val), key)) - return pii(const_iterator(first), /*y*/ - const_iterator(cur)); /*y*/ - for (size_type m = n + 1; m < buckets.size(); ++m) /*y*/ - if (buckets[m]) + for (const node* cur = first->next; !((uintptr_t)cur & 1); cur = cur->next) { + if (!equals(get_key(cur->val), key)) { + return pii(const_iterator(first), /*y*/ + const_iterator(cur)); /*y*/ + } + } + for (size_type m = n + 1; m < buckets.size(); ++m) { /*y*/ + if (buckets[m]) { return pii(const_iterator(first /*y*/), const_iterator(buckets[m] /*y*/)); + } + } return pii(const_iterator(first /*y*/), end()); } } + } return pii(end(), end()); } @@ -1249,16 +1290,18 @@ void THashTable<V, K, HF, Ex, Eq, A>::erase(iterator first, iterator last) { size_type f_bucket = first.cur ? bkt_num(first.cur->val) : buckets.size(); /*y*/ size_type l_bucket = last.cur ? bkt_num(last.cur->val) : buckets.size(); /*y*/ - if (first.cur == last.cur) + if (first.cur == last.cur) { return; - else if (f_bucket == l_bucket) + } else if (f_bucket == l_bucket) { erase_bucket(f_bucket, first.cur, last.cur); - else { + } else { erase_bucket(f_bucket, first.cur, nullptr); - for (size_type n = f_bucket + 1; n < l_bucket; ++n) + for (size_type n = f_bucket + 1; n < l_bucket; ++n) { erase_bucket(n, nullptr); - if (l_bucket != buckets.size()) /*y*/ + } + if (l_bucket != buckets.size()) { /*y*/ erase_bucket(l_bucket, last.cur); + } } } @@ -1277,8 +1320,9 @@ template <class V, class K, class HF, class Ex, class Eq, class A> bool THashTable<V, K, HF, Ex, Eq, A>::reserve(size_type num_elements_hint) { const size_type old_n = buckets.size(); /*y*/ if (num_elements_hint + 1 > old_n) { - if (old_n != 1 && num_elements_hint <= old_n) // TODO: this if is for backwards compatibility down to order-in-buckets level. Can be safely removed. + if (old_n != 1 && num_elements_hint <= old_n) { // TODO: this if is for backwards compatibility down to order-in-buckets level. Can be safely removed. return false; + } const TBucketDivisor n = HashBucketCountExt(num_elements_hint + 1, buckets.BucketDivisorHint() + 1); if (n() > old_n) { @@ -1325,9 +1369,9 @@ bool THashTable<V, K, HF, Ex, Eq, A>::reserve(size_type num_elements_hint) { template <class V, class K, class HF, class Ex, class Eq, class A> void THashTable<V, K, HF, Ex, Eq, A>::erase_bucket(const size_type n, node* first, node* last) { node* cur = buckets[n]; - if (cur == first) + if (cur == first) { erase_bucket(n, last); - else { + } else { node* next; for (next = cur->next; next != first; cur = next, next = cur->next) ; diff --git a/util/generic/ptr.h b/util/generic/ptr.h index 703e61e68e..7057949bc4 100644 --- a/util/generic/ptr.h +++ b/util/generic/ptr.h @@ -1035,8 +1035,9 @@ class TCopyClone { public: template <class T> static inline T* Copy(T* t) { - if (t) + if (t) { return t->Clone(); + } return nullptr; } }; @@ -1045,8 +1046,9 @@ class TCopyNew { public: template <class T> static inline T* Copy(T* t) { - if (t) + if (t) { return new T(*t); + } return nullptr; } }; @@ -1115,8 +1117,9 @@ public: #endif private: inline void DoDestroy() noexcept { - if (T_) + if (T_) { D::Destroy(T_); + } } private: diff --git a/util/generic/strbuf.h b/util/generic/strbuf.h index 3f946775dc..6806950dc3 100644 --- a/util/generic/strbuf.h +++ b/util/generic/strbuf.h @@ -282,8 +282,9 @@ public: // s.TrySplitOn(s.find('z'), ...) is false, but s.TrySplitOn(100500, ...) is true. bool TrySplitOn(size_t pos, TdSelf& l, TdSelf& r, size_t len = 1) const noexcept { - if (TBase::npos == pos) + if (TBase::npos == pos) { return false; + } DoSplitOn(pos, l, r, len); return true; diff --git a/util/generic/ymath.cpp b/util/generic/ymath.cpp index 31270728f4..a28a71b0e0 100644 --- a/util/generic/ymath.cpp +++ b/util/generic/ymath.cpp @@ -13,15 +13,17 @@ float Exp2f(float x) { double Erf(double x) { static constexpr double _M_2_SQRTPI = 1.12837916709551257390; static constexpr double eps = 1.0e-7; - if (fabs(x) >= 3.75) + if (fabs(x) >= 3.75) { return x > 0 ? 1.0 : -1.0; + } double r = _M_2_SQRTPI * x; double f = r; for (int i = 1;; ++i) { r *= -x * x / i; f += r / (2 * i + 1); - if (fabs(r) < eps * (2 * i + 1)) + if (fabs(r) < eps * (2 * i + 1)) { break; + } } return f; } diff --git a/util/memory/segmented_string_pool.h b/util/memory/segmented_string_pool.h index a40aa408f5..4adcbb023c 100644 --- a/util/memory/segmented_string_pool.h +++ b/util/memory/segmented_string_pool.h @@ -47,13 +47,15 @@ protected: protected: void check_capacity(size_t len) { if (Y_UNLIKELY(!last_free || len > last_free)) { - if (curseg != segs.end() && curseg->freepos > 0) + if (curseg != segs.end() && curseg->freepos > 0) { ++curseg; + } last_free = (len > segment_size ? len : segment_size); if (curseg == segs.end() || curseg->_size < last_free) { segs.push_back(seg_inf(seg_allocator.allocate(last_free), last_free)); - if (Y_UNLIKELY(Name)) + if (Y_UNLIKELY(Name)) { printf("Pool \"%s\" was increased by %" PRISZT " bytes to %" PRISZT " Mb.\n", Name, last_free * sizeof(T), capacity() / 0x100000); + } curseg = segs.end() - 1; } Y_ASSERT(curseg->freepos == 0); @@ -78,8 +80,9 @@ public: check_capacity(len); ui8* rv = (ui8*)curseg->data + curseg->freepos; last_ins_size = sizeof(T) * len; - if (src) + if (src) { memcpy(rv, src, last_ins_size); + } curseg->freepos += last_ins_size, last_free -= len; return (T*)rv; } @@ -99,32 +102,38 @@ public: return segment_size; } bool contains(const T* ptr) const { - for (seg_const_iterator i = segs.begin(), ie = segs.end(); i != ie; ++i) - if ((char*)ptr >= (char*)i->data && (char*)ptr < (char*)i->data + i->freepos) + for (seg_const_iterator i = segs.begin(), ie = segs.end(); i != ie; ++i) { + if ((char*)ptr >= (char*)i->data && (char*)ptr < (char*)i->data + i->freepos) { return true; + } + } return false; } size_t size() const { size_t r = 0; - for (seg_const_iterator i = segs.begin(); i != segs.end(); ++i) + for (seg_const_iterator i = segs.begin(); i != segs.end(); ++i) { r += i->freepos; + } return r; } size_t capacity() const { return segs.size() * segment_size * sizeof(T); } void restart() { - if (curseg != segs.end()) + if (curseg != segs.end()) { ++curseg; - for (seg_iterator i = segs.begin(); i != curseg; ++i) + } + for (seg_iterator i = segs.begin(); i != curseg; ++i) { i->freepos = 0; + } curseg = segs.begin(); last_free = 0; last_ins_size = 0; } void clear() { - for (seg_iterator i = segs.begin(); i != segs.end(); ++i) + for (seg_iterator i = segs.begin(); i != segs.end(); ++i) { seg_allocator.deallocate(i->data, i->_size); + } segs.clear(); curseg = segs.begin(); last_free = 0; @@ -166,8 +175,9 @@ public: } char* append(const char* src, size_t len) { char* rv = _Base::append(nullptr, len + 1); - if (src) + if (src) { memcpy(rv, src, len); + } rv[len] = 0; return rv; } diff --git a/util/network/hostip.cpp b/util/network/hostip.cpp index cb8d43bf90..e13ccc2b82 100644 --- a/util/network/hostip.cpp +++ b/util/network/hostip.cpp @@ -53,15 +53,18 @@ int NResolver::GetHostIP(const char* hostname, ui32* ip, size_t* slots) { #else hostent* hostent = gethostbyname(hostname); - if (!hostent) + if (!hostent) { return GetDnsError(); + } - if (hostent->h_addrtype != AF_INET || (unsigned)hostent->h_length < sizeof(ui32)) + if (hostent->h_addrtype != AF_INET || (unsigned)hostent->h_length < sizeof(ui32)) { return HOST_NOT_FOUND; + } char** cur = hostent->h_addr_list; - for (i = 0; i < *slots && *cur; i++, cur++, ipsFound++) + for (i = 0; i < *slots && *cur; i++, cur++, ipsFound++) { ip[i] = *(ui32*)*cur; + } #endif for (i = 0; i < ipsFound; i++) { ip[i] = InetToHost(ip[i]); diff --git a/util/network/pair.cpp b/util/network/pair.cpp index 9751ef5c96..de07d5f35c 100644 --- a/util/network/pair.cpp +++ b/util/network/pair.cpp @@ -47,17 +47,21 @@ int SocketPair(SOCKET socks[2], bool overlapped, bool cloexec) { } do { - if (listen(listener, 1) == SOCKET_ERROR) + if (listen(listener, 1) == SOCKET_ERROR) { break; + } - if ((socks[0] = WSASocket(AF_INET, SOCK_STREAM, 0, nullptr, 0, flags)) == INVALID_SOCKET) + if ((socks[0] = WSASocket(AF_INET, SOCK_STREAM, 0, nullptr, 0, flags)) == INVALID_SOCKET) { break; + } - if (connect(socks[0], (const struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) + if (connect(socks[0], (const struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) { break; + } - if ((socks[1] = accept(listener, nullptr, nullptr)) == INVALID_SOCKET) + if ((socks[1] = accept(listener, nullptr, nullptr)) == INVALID_SOCKET) { break; + } closesocket(listener); diff --git a/util/network/sock.h b/util/network/sock.h index b9b73b2d37..65ccd5e0e9 100644 --- a/util/network/sock.h +++ b/util/network/sock.h @@ -106,13 +106,15 @@ struct TSockAddrLocal: public ISockAddr { int ret = 0; // 1. open file TFileHandle f(Path, OpenExisting | RdOnly); - if (!f.IsOpen()) + if (!f.IsOpen()) { return -errno; + } // 2. read the port from file ret = f.Read(&in.sin_port, sizeof(in.sin_port)); - if (ret != sizeof(in.sin_port)) + if (ret != sizeof(in.sin_port)) { return -(errno ? errno : EFAULT); + } } return 0; @@ -123,24 +125,28 @@ struct TSockAddrLocal: public ISockAddr { int ret = 0; // 1. open file TFileHandle f(Path, CreateAlways | WrOnly); - if (!f.IsOpen()) + if (!f.IsOpen()) { return -errno; + } // 2. find port and bind to it in.sin_port = 0; ret = bind(s, SockAddr(), Len()); - if (ret != 0) + if (ret != 0) { return -WSAGetLastError(); + } int size = Size(); ret = getsockname(s, (struct sockaddr*)(&in), &size); - if (ret != 0) + if (ret != 0) { return -WSAGetLastError(); + } // 3. write port to file ret = f.Write(&(in.sin_port), sizeof(in.sin_port)); - if (ret != sizeof(in.sin_port)) + if (ret != sizeof(in.sin_port)) { return -errno; + } return 0; } @@ -208,12 +214,14 @@ struct TSockAddrLocal: public sockaddr_un, public ISockAddr { (void)unlink(sun_path); int ret = bind(s, SockAddr(), Len()); - if (ret < 0) + if (ret < 0) { return -errno; + } ret = Chmod(sun_path, mode); - if (ret < 0) + if (ret < 0) { return -errno; + } return 0; } }; @@ -266,12 +274,14 @@ struct TSockAddrInet: public sockaddr_in, public ISockAddr { int Bind(SOCKET s, ui16 mode) const override { Y_UNUSED(mode); int ret = bind(s, SockAddr(), Len()); - if (ret < 0) + if (ret < 0) { return -errno; + } socklen_t len = Len(); - if (getsockname(s, (struct sockaddr*)(SockAddr()), &len) < 0) + if (getsockname(s, (struct sockaddr*)(SockAddr()), &len) < 0) { return -WSAGetLastError(); + } return 0; } @@ -377,13 +387,15 @@ public: } void CheckSock() { - if ((SOCKET) * this == INVALID_SOCKET) + if ((SOCKET) * this == INVALID_SOCKET) { ythrow TSystemError() << "no socket"; + } } static ssize_t Check(ssize_t ret, const char* op = "") { - if (ret < 0) + if (ret < 0) { ythrow TSystemError(-(int)ret) << "socket operation " << op; + } return ret; } }; @@ -436,36 +448,41 @@ public: ssize_t Send(const void* msg, size_t len, int flags = 0) { const ssize_t ret = send((SOCKET) * this, (const char*)msg, (int)len, flags); - if (ret < 0) + if (ret < 0) { return -errno; + } return ret; } ssize_t Recv(void* buf, size_t len, int flags = 0) { const ssize_t ret = recv((SOCKET) * this, (char*)buf, (int)len, flags); - if (ret < 0) + if (ret < 0) { return -errno; + } return ret; } int Connect(const ISockAddr* addr) { int ret = addr->ResolveAddr(); - if (ret < 0) + if (ret < 0) { return -errno; + } ret = connect((SOCKET) * this, addr->SockAddr(), addr->Len()); - if (ret < 0) + if (ret < 0) { return -errno; + } return ret; } int Listen(int backlog) { int ret = listen((SOCKET) * this, backlog); - if (ret < 0) + if (ret < 0) { return -errno; + } return ret; } @@ -479,8 +496,9 @@ public: s = accept((SOCKET) * this, nullptr, nullptr); } - if (s == INVALID_SOCKET) + if (s == INVALID_SOCKET) { return -errno; + } TSocketHolder sock(s); acceptedSock->Swap(sock); diff --git a/util/network/socket.cpp b/util/network/socket.cpp index 0d86ceadfd..ba9c3f7d42 100644 --- a/util/network/socket.cpp +++ b/util/network/socket.cpp @@ -110,15 +110,18 @@ static int convert_events(int events, const evpair* evpairs, size_t nevpairs, bo if (events & event) { events ^= event; long winEvent = evpairs[i].winevent; - if (winEvent == -1) + if (winEvent == -1) { return -1; - if (winEvent == 0) + } + if (winEvent == 0) { continue; + } result |= winEvent; } } - if (events != 0 && !ignoreUnknown) + if (events != 0 && !ignoreUnknown) { return -1; + } return result; } @@ -199,12 +202,13 @@ int poll(struct pollfd fds[], nfds_t nfds, int timeout) noexcept { HANDLE events[] = {event.Get()}; DWORD wait_result = WSAWaitForMultipleEvents(1, events, TRUE, timeout, FALSE); - if (wait_result == WSA_WAIT_TIMEOUT) + if (wait_result == WSA_WAIT_TIMEOUT) { return 0; - else if (wait_result == WSA_WAIT_EVENT_0) { + } else if (wait_result == WSA_WAIT_EVENT_0) { for (pollfd* fd = fds; fd < fds + nfds; ++fd) { - if (fd->revents == POLLNVAL) + if (fd->revents == POLLNVAL) { continue; + } WSANETWORKEVENTS network_events; if (WSAEnumNetworkEvents(fd->fd, event.Get(), &network_events)) { errno = EIO; @@ -217,8 +221,9 @@ int poll(struct pollfd fds[], nfds_t nfds, int timeout) noexcept { break; } } - if (fd->revents == POLLERR) + if (fd->revents == POLLERR) { continue; + } if (network_events.lNetworkEvents) { fd->revents = static_cast<short>(convert_events(network_events.lNetworkEvents, evpairs_to_unix, nevpairs_to_unix, true)); if (fd->revents & POLLHUP) { @@ -227,9 +232,11 @@ int poll(struct pollfd fds[], nfds_t nfds, int timeout) noexcept { } } int chanded_sockets = 0; - for (pollfd* fd = fds; fd < fds + nfds; ++fd) - if (fd->revents != 0) + for (pollfd* fd = fds; fd < fds + nfds; ++fd) { + if (fd->revents != 0) { ++chanded_sockets; + } + } return chanded_sockets; } else { errno = EIO; diff --git a/util/network/socket_ut.cpp b/util/network/socket_ut.cpp index b49ca639cc..f8b97c3992 100644 --- a/util/network/socket_ut.cpp +++ b/util/network/socket_ut.cpp @@ -270,8 +270,9 @@ void TPollTest::TestPollInOut() { if (i % 5 == 0 || i % 5 == 2) { char buffer = 'c'; - if (send(*clientSocket, &buffer, 1, 0) == -1) + if (send(*clientSocket, &buffer, 1, 0) == -1) { ythrow yexception() << "Can not send (" << LastSystemErrorText() << ")"; + } } TSimpleSharedPtr<TSocketHolder> connectedSocket(new TSocketHolder(AcceptConnection(serverSocket))); @@ -287,8 +288,9 @@ void TPollTest::TestPollInOut() { for (size_t i = 0; i < connectedSockets.size(); ++i) { pollfd fd = {(i % 5 == 4) ? INVALID_SOCKET : static_cast<SOCKET>(*connectedSockets[i]), POLLIN | POLLOUT, 0}; fds.push_back(fd); - if (i % 5 != 4) + if (i % 5 != 4) { ++expectedCount; + } } int polledCount = poll(&fds[0], fds.size(), INFTIM); diff --git a/util/stream/format.h b/util/stream/format.h index c6ee9c720f..81dd686a8c 100644 --- a/util/stream/format.h +++ b/util/stream/format.h @@ -45,8 +45,9 @@ namespace NFormatPrivate { template <typename T> static inline void WriteChars(T& os, char c, size_t count) { - if (count == 0) + if (count == 0) { return; + } TTempBuf buf(count); memset(buf.Data(), c, count); StreamWrite(os, buf.Data(), count); diff --git a/util/string/cast.h b/util/string/cast.h index da99a02f92..65c92f9a4b 100644 --- a/util/string/cast.h +++ b/util/string/cast.h @@ -217,6 +217,7 @@ inline ::NPrivate::TFromString<typename T::TChar> FromString(const T& s) { } // Conversion exception free versions +// But can throw other exceptions, e.g. std::bad_alloc when allocating memory for the new 'result' value. template <typename T, typename TChar> bool TryFromStringImpl(const TChar* data, size_t len, T& result); diff --git a/util/string/join.h b/util/string/join.h index f0d28df291..60bc71da98 100644 --- a/util/string/join.h +++ b/util/string/join.h @@ -207,8 +207,9 @@ struct TRangeJoiner { if (rangeJoiner.b != rangeJoiner.e) { stream << *rangeJoiner.b; - for (auto it = std::next(rangeJoiner.b); it != rangeJoiner.e; ++it) + for (auto it = std::next(rangeJoiner.b); it != rangeJoiner.e; ++it) { stream << rangeJoiner.delim << *it; + } } return stream; } diff --git a/util/string/split.h b/util/string/split.h index 2000498591..844d3d6722 100644 --- a/util/string/split.h +++ b/util/string/split.h @@ -205,8 +205,9 @@ struct TFindFirstOf { inline Char* FindFirstOf(Char* b, Char* e) const noexcept { Char* ret = b; for (; ret != e; ++ret) { - if (NStringSplitPrivate::Find(Set, *ret)) + if (NStringSplitPrivate::Find(Set, *ret)) { break; + } } return ret; } @@ -398,8 +399,9 @@ struct TSimplePusher { template <class T> static inline void Split(char* buf, char ch, T* res) { res->resize(0); - if (*buf == 0) + if (*buf == 0) { return; + } TCharDelimiter<char> delim(ch); TSimplePusher<T> pusher = {res}; diff --git a/util/string/util.h b/util/string/util.h index 47651adb71..4b79d768bf 100644 --- a/util/string/util.h +++ b/util/string/util.h @@ -18,8 +18,9 @@ int a2i(const TString& s); template <class T> inline void RemoveIfLast(T& s, int c) { const size_t length = s.length(); - if (length && s[length - 1] == c) + if (length && s[length - 1] == c) { s.remove(length - 1); + } } /// Adds lastCh symbol to the the of the string if it is not already there. @@ -72,28 +73,32 @@ public: /// That is, skip all characters not in table /// [DIFFERENCE FOR NOT_FOUND CASE: Returns end of string, not NULL] const char* brk(const char* s) const { - while (c_chars_table[(ui8)*s]) + while (c_chars_table[(ui8)*s]) { ++s; + } return s; } const char* brk(const char* s, const char* e) const { - while (s < e && c_chars_table[(ui8)*s]) + while (s < e && c_chars_table[(ui8)*s]) { ++s; + } return s; } /// Return first character not in table, like strpbrk() for inverted table. /// That is, skip all characters in table const char* cbrk(const char* s) const { - while (chars_table[(ui8)*s]) + while (chars_table[(ui8)*s]) { ++s; + } return s; } const char* cbrk(const char* s, const char* e) const { - while (s < e && chars_table[(ui8)*s]) + while (s < e && chars_table[(ui8)*s]) { ++s; + } return s; } @@ -131,8 +136,9 @@ public: /// strsep + remember character that was destroyed char* sep(char*& s, char& sep_char) const { - if (!s) + if (!s) { return nullptr; + } char* ret = s; char* next = brk(ret); if (*next) { @@ -161,17 +167,20 @@ public: } void Do(char* s) const { - for (; *s; s++) + for (; *s; s++) { *s = ConvertChar(*s); + } } void Do(const char* src, char* dst) const { - for (; *src; src++) + for (; *src; src++) { *dst++ = ConvertChar(*src); + } *dst = 0; } void Do(char* s, size_t l) const { - for (size_t i = 0; i < l && s[i]; i++) + for (size_t i = 0; i < l && s[i]; i++) { s[i] = ConvertChar(s[i]); + } } void Do(TString& str) const; @@ -185,8 +194,9 @@ private: template <typename TStringType> void RemoveAll(TStringType& str, typename TStringType::char_type ch) { size_t pos = str.find(ch); // 'find' to avoid cloning of string in 'TString.begin()' - if (pos == TStringType::npos) + if (pos == TStringType::npos) { return; + } typename TStringType::iterator begin = str.begin(); typename TStringType::iterator end = begin + str.length(); diff --git a/util/string/vector.h b/util/string/vector.h index f3cc46b35f..6a3029cdd0 100644 --- a/util/string/vector.h +++ b/util/string/vector.h @@ -68,8 +68,9 @@ SplitString(const typename ::NPrivate::TStringDeducer<C>::type& str, const C* de template <class TIter> inline TString JoinStrings(TIter begin, TIter end, const TStringBuf delim) { - if (begin == end) + if (begin == end) { return TString(); + } TString result = ToString(*begin); @@ -83,8 +84,9 @@ inline TString JoinStrings(TIter begin, TIter end, const TStringBuf delim) { template <class TIter> inline TUtf16String JoinStrings(TIter begin, TIter end, const TWtringBuf delim) { - if (begin == end) + if (begin == end) { return TUtf16String(); + } TUtf16String result = ToWtring(*begin); diff --git a/util/system/dynlib.cpp b/util/system/dynlib.cpp index 9d2541c25f..55348288c8 100644 --- a/util/system/dynlib.cpp +++ b/util/system/dynlib.cpp @@ -34,10 +34,12 @@ inline TString DLLERR() { char* msg = 0; DWORD cnt = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char*)&msg, 0, nullptr); - if (!msg) + if (!msg) { return "DLLERR() unknown error"; - while (cnt && isspace(msg[cnt - 1])) + } + while (cnt && isspace(msg[cnt - 1])) { --cnt; + } TString err(msg, 0, cnt); LocalFree(msg); return err; diff --git a/util/system/dynlib.h b/util/system/dynlib.h index 66eaf4a5c1..03e4b3dff8 100644 --- a/util/system/dynlib.h +++ b/util/system/dynlib.h @@ -55,18 +55,20 @@ public: TExternalSymbol(const TExternalSymbol& es) { PLib = nullptr; DLib = nullptr; - if (es.IsDynamic()) + if (es.IsDynamic()) { Open(es.LibName().data(), es.VtblName().data()); - else if (es.IsStatic()) + } else if (es.IsStatic()) { SetSym(es.Symbol()); + } } TExternalSymbol& operator=(const TExternalSymbol& es) { if (this != &es) { Close(); - if (es.IsDynamic()) + if (es.IsDynamic()) { Open(es.LibName().data(), es.VtblName().data()); - else if (es.IsStatic()) + } else if (es.IsStatic()) { SetSym(es.Symbol()); + } } return *this; } @@ -75,8 +77,9 @@ public: } // set the symbol from dynamic source void Open(const char* lib_name, const char* vtbl_name) { - if (DLib != nullptr || PLib != nullptr) + if (DLib != nullptr || PLib != nullptr) { return; + } try { DLib = new TDynamicLibrary(); DLib->Open(lib_name); @@ -91,8 +94,9 @@ public: } // set the symbol from static source void SetSym(TLib* pl) noexcept { - if (DLib == nullptr && PLib == nullptr) + if (DLib == nullptr && PLib == nullptr) { PLib = pl; + } } void Close() noexcept { delete DLib; diff --git a/util/system/error.cpp b/util/system/error.cpp index 164921af9e..52b1bbb104 100644 --- a/util/system/error.cpp +++ b/util/system/error.cpp @@ -24,13 +24,15 @@ int LastSystemError() { #if defined(_win_) int ret = GetLastError(); - if (ret) + if (ret) { return ret; + } ret = WSAGetLastError(); - if (ret) + if (ret) { return ret; + } // when descriptors number are over maximum, errno set in this variable ret = *(_errno()); return ret; @@ -68,8 +70,9 @@ static char* Strip(char* s) { size_t len = strlen(s); const char* ptr = s; Strip(ptr, len); - if (ptr != s) + if (ptr != s) { memmove(s, ptr, len); + } s[len] = 0; return s; } diff --git a/util/system/filemap.h b/util/system/filemap.h index 25a7911715..200774593b 100644 --- a/util/system/filemap.h +++ b/util/system/filemap.h @@ -233,8 +233,9 @@ public: return Size_; } const T& GetAt(size_t pos) const { - if (pos < Size_) + if (pos < Size_) { return Ptr_[pos]; + } return Dummy(); } void SetDummy(const T& n_Dummy) { @@ -334,8 +335,9 @@ public: TMappedArray(size_t siz = 0) : TMappedAllocation(0) { - if (siz) + if (siz) { Create(siz); + } } ~TMappedArray() { Destroy(); @@ -343,18 +345,21 @@ public: T* Create(size_t siz) { Y_ASSERT(MappedSize() == 0 && Ptr() == nullptr); T* arr = (T*)Alloc((sizeof(T) * siz)); - if (!arr) + if (!arr) { return nullptr; + } Y_ASSERT(MappedSize() == sizeof(T) * siz); - for (size_t n = 0; n < siz; n++) + for (size_t n = 0; n < siz; n++) { new (&arr[n]) T(); + } return arr; } void Destroy() { T* arr = (T*)Ptr(); if (arr) { - for (size_t n = 0; n < size(); n++) + for (size_t n = 0; n < size(); n++) { arr[n].~T(); + } Dealloc(); } } diff --git a/util/system/fs_win.cpp b/util/system/fs_win.cpp index ff8a254782..65e695bee4 100644 --- a/util/system/fs_win.cpp +++ b/util/system/fs_win.cpp @@ -12,8 +12,9 @@ namespace NFsPrivate { static LPCWSTR UTF8ToWCHAR(const TStringBuf str, TUtf16String& wstr) { wstr.resize(str.size()); size_t written = 0; - if (!UTF8ToWide(str.data(), str.size(), wstr.begin(), written)) + if (!UTF8ToWide(str.data(), str.size(), wstr.begin(), written)) { return nullptr; + } wstr.erase(written); static_assert(sizeof(WCHAR) == sizeof(wchar16), "expect sizeof(WCHAR) == sizeof(wchar16)"); return (const WCHAR*)wstr.data(); @@ -64,8 +65,9 @@ namespace NFsPrivate { fad.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; ::SetFileAttributesW(wname, fad.dwFileAttributes); } - if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { return ::RemoveDirectoryW(wname) != 0; + } return ::DeleteFileW(wname) != 0; } @@ -76,8 +78,9 @@ namespace NFsPrivate { TString tName(targetName); { size_t pos; - while ((pos = tName.find('/')) != TString::npos) + while ((pos = tName.find('/')) != TString::npos) { tName.replace(pos, 1, LOCSLASH_S); + } } TUtf16String tstr; LPCWSTR wname = UTF8ToWCHAR(tName, tstr); @@ -127,8 +130,9 @@ namespace NFsPrivate { TTempBuf result; LPWSTR buf = reinterpret_cast<LPWSTR>(result.Data()); int r = GetCurrentDirectoryW(result.Size() / sizeof(WCHAR), buf); - if (r == 0) + if (r == 0) { throw TIoSystemError() << "failed to GetCurrentDirectory"; + } return WCHARToUTF8(buf, r); } diff --git a/util/system/fs_win_ut.cpp b/util/system/fs_win_ut.cpp index 5317344cef..ce9c0d86e5 100644 --- a/util/system/fs_win_ut.cpp +++ b/util/system/fs_win_ut.cpp @@ -20,8 +20,9 @@ static void Touch(const TFsPath& path) { static LPCWSTR UTF8ToWCHAR(const TStringBuf str, TUtf16String& wstr) { wstr.resize(str.size()); size_t written = 0; - if (!UTF8ToWide(str.data(), str.size(), wstr.begin(), written)) + if (!UTF8ToWide(str.data(), str.size(), wstr.begin(), written)) { return nullptr; + } wstr.erase(written); static_assert(sizeof(WCHAR) == sizeof(wchar16), "expect sizeof(WCHAR) == sizeof(wchar16)"); return (const WCHAR*)wstr.data(); diff --git a/util/system/fstat.cpp b/util/system/fstat.cpp index cfc5bed323..55d95463cf 100644 --- a/util/system/fstat.cpp +++ b/util/system/fstat.cpp @@ -44,8 +44,9 @@ static ui32 GetWinFileType(DWORD fileAttributes, ULONG reparseTag) { static ui32 GetFileMode(DWORD fileAttributes, ULONG reparseTag) { ui32 mode = 0; - if (fileAttributes == 0xFFFFFFFF) + if (fileAttributes == 0xFFFFFFFF) { return mode; + } mode |= GetWinFileType(fileAttributes, reparseTag); @@ -229,8 +230,9 @@ bool TFileStat::IsSymlink() const noexcept { i64 GetFileLength(FHANDLE fd) { #if defined(_win_) LARGE_INTEGER pos; - if (!::GetFileSizeEx(fd, &pos)) + if (!::GetFileSizeEx(fd, &pos)) { return -1L; + } return pos.QuadPart; #elif defined(_unix_) struct stat statbuf; @@ -252,8 +254,9 @@ i64 GetFileLength(const char* name) { #if defined(_win_) WIN32_FIND_DATA fData; HANDLE h = FindFirstFileA(name, &fData); - if (h == INVALID_HANDLE_VALUE) + if (h == INVALID_HANDLE_VALUE) { return -1; + } FindClose(h); return (((i64)fData.nFileSizeHigh) * (i64(MAXDWORD) + 1)) + (i64)fData.nFileSizeLow; #elif defined(_unix_) diff --git a/util/system/mlock.cpp b/util/system/mlock.cpp index 27895bbacc..3205e188a8 100644 --- a/util/system/mlock.cpp +++ b/util/system/mlock.cpp @@ -34,12 +34,15 @@ void LockMemory(const void* addr, size_t len) { #elif defined(_win_) HANDLE hndl = GetCurrentProcess(); SIZE_T min, max; - if (!GetProcessWorkingSetSize(hndl, &min, &max)) + if (!GetProcessWorkingSetSize(hndl, &min, &max)) { ythrow yexception() << LastSystemErrorText(); - if (!SetProcessWorkingSetSize(hndl, min + len, max + len)) + } + if (!SetProcessWorkingSetSize(hndl, min + len, max + len)) { ythrow yexception() << LastSystemErrorText(); - if (!VirtualLock((LPVOID)addr, len)) + } + if (!VirtualLock((LPVOID)addr, len)) { ythrow yexception() << LastSystemErrorText(); + } #endif } @@ -58,12 +61,15 @@ void UnlockMemory(const void* addr, size_t len) { #elif defined(_win_) HANDLE hndl = GetCurrentProcess(); SIZE_T min, max; - if (!GetProcessWorkingSetSize(hndl, &min, &max)) + if (!GetProcessWorkingSetSize(hndl, &min, &max)) { ythrow yexception() << LastSystemErrorText(); - if (!SetProcessWorkingSetSize(hndl, min - len, max - len)) + } + if (!SetProcessWorkingSetSize(hndl, min - len, max - len)) { ythrow yexception() << LastSystemErrorText(); - if (!VirtualUnlock((LPVOID)addr, len)) + } + if (!VirtualUnlock((LPVOID)addr, len)) { ythrow yexception() << LastSystemErrorText(); + } #endif } diff --git a/util/system/protect.cpp b/util/system/protect.cpp index 6e435e648e..271a275722 100644 --- a/util/system/protect.cpp +++ b/util/system/protect.cpp @@ -88,7 +88,8 @@ void ProtectMemory(void* addr, const size_t length, const EProtectMemory mode) { break; } DWORD oldMode = 0; - if (!VirtualProtect(addr, length, mpMode, &oldMode)) + if (!VirtualProtect(addr, length, mpMode, &oldMode)) { ythrow TSystemError() << "Memory protection failed for mode " << ModeToString(mode) << ". "; + } #endif } diff --git a/util/system/rusage.cpp b/util/system/rusage.cpp index 8bcaade7e3..2f9d861025 100644 --- a/util/system/rusage.cpp +++ b/util/system/rusage.cpp @@ -49,8 +49,9 @@ size_t TRusage::GetCurrentRSS() { struct mach_task_basic_info info; mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, - (task_info_t)&info, &infoCount) != KERN_SUCCESS) + (task_info_t)&info, &infoCount) != KERN_SUCCESS) { return (size_t)0L; /* Can't access? */ + } return (size_t)info.resident_size; #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) /* Linux ---------------------------------------------------- */ diff --git a/util/system/sem.cpp b/util/system/sem.cpp index 984e9d14c0..eb56da691b 100644 --- a/util/system/sem.cpp +++ b/util/system/sem.cpp @@ -70,12 +70,14 @@ namespace { size_t len = strlen(name); key = (char*)alloca(len + 1); strcpy(key, name); - if (len > MAX_PATH) + if (len > MAX_PATH) { *(key + MAX_PATH) = 0; + } char* p = key; while (*p) { - if (*p == '\\') + if (*p == '\\') { *p = '/'; + } ++p; } } diff --git a/util/system/shellcommand.cpp b/util/system/shellcommand.cpp index e4bfb165bc..51d91039bf 100644 --- a/util/system/shellcommand.cpp +++ b/util/system/shellcommand.cpp @@ -89,16 +89,18 @@ namespace { constexpr static size_t MAX_COMMAND_LINE = 32 * 1024; std::wstring GetWString(const char* astring) { - if (!astring) + if (!astring) { return std::wstring(); + } std::string str(astring); return std::wstring(str.begin(), str.end()); } std::string GetAString(const wchar_t* wstring) { - if (!wstring) + if (!wstring) { return std::string(); + } std::wstring str(wstring); return std::string(str.begin(), str.end()); @@ -130,8 +132,9 @@ public: bool Close() noexcept { bool ok = true; - if (Fd_ != INVALID_REALPIPEHANDLE) + if (Fd_ != INVALID_REALPIPEHANDLE) { ok = CloseHandle(Fd_); + } Fd_ = INVALID_REALPIPEHANDLE; return ok; } @@ -156,22 +159,25 @@ public: ssize_t Read(void* buffer, size_t byteCount) const noexcept { DWORD doneBytes; - if (!ReadFile(Fd_, buffer, byteCount, &doneBytes, nullptr)) + if (!ReadFile(Fd_, buffer, byteCount, &doneBytes, nullptr)) { return -1; + } return doneBytes; } ssize_t Write(const void* buffer, size_t byteCount) const noexcept { DWORD doneBytes; - if (!WriteFile(Fd_, buffer, byteCount, &doneBytes, nullptr)) + if (!WriteFile(Fd_, buffer, byteCount, &doneBytes, nullptr)) { return -1; + } return doneBytes; } static void Pipe(TRealPipeHandle& reader, TRealPipeHandle& writer, EOpenMode mode) { (void)mode; REALPIPEHANDLE fds[2]; - if (!CreatePipe(&fds[0], &fds[1], nullptr /* handles are not inherited */, 0)) + if (!CreatePipe(&fds[0], &fds[1], nullptr /* handles are not inherited */, 0)) { ythrow TFileError() << "failed to create a pipe"; + } TRealPipeHandle(fds[0]).Swap(reader); TRealPipeHandle(fds[1]).Swap(writer); } @@ -497,8 +503,9 @@ void TShellCommand::TImpl::StartProcess(TShellCommand::TImpl::TPipes& pipes) { } } if (InputMode != TShellCommandOptions::HANDLE_INHERIT) { - if (!SetHandleInformation(pipes.InputPipeFd[0], HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) + if (!SetHandleInformation(pipes.InputPipeFd[0], HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) { ythrow TSystemError() << "cannot set handle info"; + } } // A sockets do not work as std streams for some reason @@ -881,8 +888,9 @@ void TShellCommand::TImpl::Communicate(TProcessInfo* pi) { streamThreads.emplace_back(new TThread(&TImpl::WriteStream, &pumps[2])); } - for (auto& threadHolder : streamThreads) + for (auto& threadHolder : streamThreads) { threadHolder->Start(); + } #else TBuffer buffer(DATA_BUFFER_SIZE); TBuffer inputBuffer(DATA_BUFFER_SIZE); @@ -1042,8 +1050,9 @@ void TShellCommand::TImpl::Communicate(TProcessInfo* pi) { if (!GetExitCodeProcess(pi->Parent->Pid, &exitCode)) { ythrow yexception() << "GetExitCodeProcess: " << LastSystemErrorText(); } - if (exitCode == 0) + if (exitCode == 0) { cleanExit = true; + } processExitCode = static_cast<int>(exitCode); DBG(Cerr << "exit code: " << exitCode << Endl); } @@ -1056,11 +1065,13 @@ void TShellCommand::TImpl::Communicate(TProcessInfo* pi) { } #if defined(_win_) - for (auto& threadHolder : streamThreads) + for (auto& threadHolder : streamThreads) { threadHolder->Join(); + } for (const auto pump : pumps) { - if (!pump.InternalError.empty()) + if (!pump.InternalError.empty()) { throw yexception() << pump.InternalError; + } } #else // Now let's read remaining stdout/stderr diff --git a/util/system/shellcommand.h b/util/system/shellcommand.h index 6c2b9e276c..530178d60c 100644 --- a/util/system/shellcommand.h +++ b/util/system/shellcommand.h @@ -119,8 +119,9 @@ public: */ inline TShellCommandOptions& SetAsync(bool async) { AsyncMode = async; - if (AsyncMode) + if (AsyncMode) { PollDelayMs = 0; + } return *this; } @@ -215,8 +216,9 @@ public: */ inline TShellCommandOptions& SetUseShell(bool useShell) { UseShell = useShell; - if (!useShell) + if (!useShell) { QuoteArguments = false; + } return *this; } diff --git a/util/system/sysstat.cpp b/util/system/sysstat.cpp index db3338b02e..3486817484 100644 --- a/util/system/sysstat.cpp +++ b/util/system/sysstat.cpp @@ -11,8 +11,9 @@ int Chmod(const char* fname, int mode) { return -1; } ui32 fAttr = ::GetFileAttributesA(fname); - if (fAttr == 0xffffffff) + if (fAttr == 0xffffffff) { return -1; + } if (mode & _S_IWRITE) { fAttr &= ~FILE_ATTRIBUTE_READONLY; } else { diff --git a/util/system/user.cpp b/util/system/user.cpp index 05439f8939..53767e8ff9 100644 --- a/util/system/user.cpp +++ b/util/system/user.cpp @@ -25,10 +25,11 @@ TString GetUsername() { DWORD len = (DWORD)Min(nameBuf.Size(), size_t(32767)); if (!GetUserNameA(nameBuf.Data(), &len)) { DWORD err = GetLastError(); - if ((err == ERROR_INSUFFICIENT_BUFFER) && (nameBuf.Size() <= 32767)) + if ((err == ERROR_INSUFFICIENT_BUFFER) && (nameBuf.Size() <= 32767)) { nameBuf = TTempBuf((size_t)len); - else + } else { ythrow TSystemError(err) << " GetUserName failed"; + } } else { return TString(nameBuf.Data(), (size_t)(len - 1)); } diff --git a/util/system/ut/stdin_osfhandle/main.cpp b/util/system/ut/stdin_osfhandle/main.cpp index fe2ea836a9..cf364c7a7e 100644 --- a/util/system/ut/stdin_osfhandle/main.cpp +++ b/util/system/ut/stdin_osfhandle/main.cpp @@ -9,7 +9,8 @@ int main() { // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/get-osfhandle // _get_osfhandle returns INVALID_HANDLE_VALUE - 1 without any sign of error if specified fd was closed. // Working with such handle will lead to future various errors. - if (handle + 1 == (unsigned long long)INVALID_HANDLE_VALUE) + if (handle + 1 == (unsigned long long)INVALID_HANDLE_VALUE) { return 1; + } return 0; } diff --git a/util/thread/lfqueue.h b/util/thread/lfqueue.h index bfe88013fc..089f234741 100644 --- a/util/thread/lfqueue.h +++ b/util/thread/lfqueue.h @@ -72,8 +72,9 @@ class TLockFreeQueue: public TNonCopyable { void TryToFreeAsyncMemory() { const auto keepCounter = FreeingTaskCounter.load(); TRootNode* current = FreePtr.load(std::memory_order_acquire); - if (current == nullptr) + if (current == nullptr) { return; + } if (FreememCounter.load() == 1) { // we are the last thread, try to cleanup // check if another thread have cleaned up @@ -103,8 +104,9 @@ class TLockFreeQueue: public TNonCopyable { toDelete->ToDelete.store(lst, std::memory_order_release); for (auto freePtr = FreePtr.load();;) { toDelete->NextFree.store(freePtr, std::memory_order_release); - if (FreePtr.compare_exchange_weak(freePtr, toDelete)) + if (FreePtr.compare_exchange_weak(freePtr, toDelete)) { break; + } } } void AsyncUnref(TRootNode* toDelete, TListNode* lst) { @@ -148,15 +150,17 @@ class TLockFreeQueue: public TNonCopyable { Tail->Next.store(newCopy, std::memory_order_release); newCopy = Copy; Copy = nullptr; // do not destroy prev try - if (!newTail) + if (!newTail) { newTail = Tail; // tried to invert same list + } break; } TListNode* newElem = new TListNode(ptr->Data, newCopy); newCopy = newElem; ptr = ptr->Next.load(std::memory_order_acquire); - if (!newTail) + if (!newTail) { newTail = newElem; + } } EraseList(Copy); // copy was useless Copy = newCopy; @@ -176,8 +180,9 @@ class TLockFreeQueue: public TNonCopyable { for (TListNode* node = head;; node = node->Next.load(std::memory_order_acquire)) { newRoot->IncCount(node->Data); - if (node == tail) + if (node == tail) { break; + } } if (JobQueue.compare_exchange_weak(curRoot, newRoot)) { @@ -251,8 +256,9 @@ public: } template <typename TIter> void EnqueueAll(TIter dataBegin, TIter dataEnd) { - if (dataBegin == dataEnd) + if (dataBegin == dataEnd) { return; + } TIter i = dataBegin; TListNode* node = new TListNode(*i); @@ -272,8 +278,9 @@ public: TListNode* tail = curRoot->PopQueue.load(std::memory_order_acquire); if (tail) { // has elems to pop - if (!newRoot) + if (!newRoot) { newRoot = new TRootNode; + } newRoot->PushQueue.store(curRoot->PushQueue.load(std::memory_order_acquire), std::memory_order_release); newRoot->PopQueue.store(tail->Next.load(std::memory_order_acquire), std::memory_order_release); @@ -294,8 +301,9 @@ public: return false; // no elems to pop } - if (!newRoot) + if (!newRoot) { newRoot = new TRootNode; + } newRoot->PushQueue.store(nullptr, std::memory_order_release); listInvertor.DoCopy(curRoot->PushQueue.load(std::memory_order_acquire)); newRoot->PopQueue.store(listInvertor.Copy, std::memory_order_release); diff --git a/util/thread/lfstack.h b/util/thread/lfstack.h index effde7c706..b81c6403c9 100644 --- a/util/thread/lfstack.h +++ b/util/thread/lfstack.h @@ -30,12 +30,14 @@ class TLockFreeStack: TNonCopyable { void TryToFreeMemory() { TNode* current = FreePtr.load(std::memory_order_acquire); - if (!current) + if (!current) { return; + } if (DequeueCount.load() == 1) { // node current is in free list, we are the last thread so try to cleanup - if (FreePtr.compare_exchange_strong(current, nullptr)) + if (FreePtr.compare_exchange_strong(current, nullptr)) { EraseList(current); + } } } void EraseList(TNode* p) { @@ -54,8 +56,9 @@ class TLockFreeStack: TNonCopyable { // act as if *this != expected even if they are equal. // When a compare-and-exchange is in a loop, the weak version will yield better // performance on some platforms. - if (Head.compare_exchange_weak(headValue, head)) + if (Head.compare_exchange_weak(headValue, head)) { break; + } } } template <class U> @@ -115,8 +118,9 @@ public: // Dequeue()s in progress, put node to free list for (TNode* freePtr = FreePtr.load(std::memory_order_acquire);;) { current->Next.store(freePtr, std::memory_order_release); - if (FreePtr.compare_exchange_weak(freePtr, current)) + if (FreePtr.compare_exchange_weak(freePtr, current)) { break; + } } } return true; @@ -151,8 +155,9 @@ public: } for (TNode* freePtr = FreePtr.load(std::memory_order_acquire);;) { currentLast->Next.store(freePtr, std::memory_order_release); - if (FreePtr.compare_exchange_weak(freePtr, current)) + if (FreePtr.compare_exchange_weak(freePtr, current)) { break; + } } } return; diff --git a/util/ysafeptr.h b/util/ysafeptr.h index 22395ea3e3..ab5f26fb1b 100644 --- a/util/ysafeptr.h +++ b/util/ysafeptr.h @@ -33,10 +33,11 @@ private: #ifdef CHECK_YPTR2 static Y_POD_THREAD(bool) DisableThreadCheck; void CheckThreadId() { - if (dwThreadId == 0) + if (dwThreadId == 0) { dwThreadId = GetCurrentThreadId(); - else + } else { Y_ASSERT(dwThreadId == GetCurrentThreadId() || DisableThreadCheck); + } } void AddRef() { CheckThreadId(); @@ -69,14 +70,16 @@ private: void ReleaseRef() { CheckThreadId(); --RefData; - if (RefData == 0) + if (RefData == 0) { ReleaseRefComplete(); + } } void ReleaseObj(int nRef, int nMask) { CheckThreadId(); ObjData -= nRef; - if ((ObjData & nMask) == 0) + if ((ObjData & nMask) == 0) { ReleaseObjComplete(nMask); + } } protected: @@ -262,18 +265,21 @@ private: void AddRef(TUserObj* _ptr) { TRef p; - if (_ptr) + if (_ptr) { p.AddRef(CastToObjectBase(_ptr)); + } } void DecRef(TUserObj* _ptr) { TRef p; - if (_ptr) + if (_ptr) { p.DecRef(CastToObjectBase(_ptr)); + } } void Release(TUserObj* _ptr) { TRef p; - if (_ptr) + if (_ptr) { p.Release(CastToObjectBase(_ptr)); + } } protected: |