diff options
author | mvel <mvel@yandex-team.ru> | 2022-02-10 16:45:41 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:45:41 +0300 |
commit | 43f5a35593ebc9f6bcea619bb170394ea7ae468e (patch) | |
tree | e98df59de24d2ef7c77baed9f41e4875a2fef972 /util | |
parent | bd30392c4cc92487950adc375c07adf52da1d592 (diff) | |
download | ydb-43f5a35593ebc9f6bcea619bb170394ea7ae468e.tar.gz |
Restoring authorship annotation for <mvel@yandex-team.ru>. Commit 2 of 2.
Diffstat (limited to 'util')
74 files changed, 1048 insertions, 1048 deletions
diff --git a/util/datetime/base.cpp b/util/datetime/base.cpp index d49bfe80fd..38ecc3ab96 100644 --- a/util/datetime/base.cpp +++ b/util/datetime/base.cpp @@ -6,7 +6,7 @@ #include <util/system/compat.h> #include <util/memory/tempbuf.h> #include <util/generic/string.h> -#include <util/generic/strbuf.h> +#include <util/generic/strbuf.h> #include <util/generic/yexception.h> TString Strftime(const char* format, const struct tm* tm) { @@ -23,14 +23,14 @@ TString Strftime(const char* format, const struct tm* tm) { template <> TDuration FromStringImpl<TDuration, char>(const char* s, size_t len) { - return TDuration::Parse(TStringBuf(s, len)); + return TDuration::Parse(TStringBuf(s, len)); } template <> -bool TryFromStringImpl<TDuration, char>(const char* s, size_t len, TDuration& result) { - return TDuration::TryParse(TStringBuf(s, len), result); -} - +bool TryFromStringImpl<TDuration, char>(const char* s, size_t len, TDuration& result) { + return TDuration::TryParse(TStringBuf(s, len), result); +} + namespace { template <size_t N> struct TPad { diff --git a/util/datetime/base.h b/util/datetime/base.h index a16db8df98..5e902b8f63 100644 --- a/util/datetime/base.h +++ b/util/datetime/base.h @@ -167,10 +167,10 @@ public: return MicroSecondsOfSecond() * (TValue)1000; } - constexpr explicit operator bool() const noexcept { - return Value_; - } - + constexpr explicit operator bool() const noexcept { + return Value_; + } + protected: TValue Value_; // microseconds count }; @@ -311,7 +311,7 @@ public: static TDuration Parse(const TStringBuf input); static bool TryParse(const TStringBuf input, TDuration& result); - + // note global Out method is defined for TDuration, so it could be written to IOutputStream as text template <class T> diff --git a/util/datetime/base_ut.cpp b/util/datetime/base_ut.cpp index b8f92e7ebb..afc3f802eb 100644 --- a/util/datetime/base_ut.cpp +++ b/util/datetime/base_ut.cpp @@ -14,13 +14,13 @@ using namespace std::chrono_literals; -struct TTestTime { - const time_t T_ = 987654321; - const char* Date_ = "Thu Apr 19 04:25:21 2001\n"; - const char* SprintDate_ = "20010419"; - const long SprintSecs_ = 15921; - struct tm Tm_; - TTestTime() { +struct TTestTime { + const time_t T_ = 987654321; + const char* Date_ = "Thu Apr 19 04:25:21 2001\n"; + const char* SprintDate_ = "20010419"; + const long SprintSecs_ = 15921; + struct tm Tm_; + TTestTime() { Tm_.tm_sec = 21; Tm_.tm_min = 25; Tm_.tm_hour = 4; @@ -30,7 +30,7 @@ struct TTestTime { Tm_.tm_wday = 4; Tm_.tm_yday = 108; } -}; +}; namespace { inline void OldDate8601(char* buf, time_t when) { @@ -176,7 +176,7 @@ Y_UNIT_TEST_SUITE(TDateTimeTest) { a.tm_wday == b.tm_wday && a.tm_yday == b.tm_yday); } - + static inline TString Str(const struct tm& a) { return TStringBuilder() << "(" << a.tm_sec << ", " @@ -303,13 +303,13 @@ Y_UNIT_TEST_SUITE(TDateTimeTest) { return t0 && t1 && CompareTM(*t0, *t1) && (t0->tm_isdst == t1->tm_isdst) -#ifndef _win_ +#ifndef _win_ && (t0->tm_gmtoff == t1->tm_gmtoff) && TimeZoneEq(t0->tm_zone, t1->tm_zone) -#endif // _win_ +#endif // _win_ && true; } - + Y_UNIT_TEST(TestGmTimeR) { time_t starttime = static_cast<time_t>(Max<i64>(-12244089600LL, Min<time_t>())); // 1-Jan-1582 time_t finishtime = static_cast<time_t>(Min<i64>(0xFFFFFFFF * 20, Max<time_t>())); @@ -375,7 +375,7 @@ Y_UNIT_TEST_SUITE(DateTimeTest) { static const struct T { const char* const Str; const TDuration::TValue MicroSeconds; - const bool Parseable; + const bool Parseable; } tests[] = { {"0", 0, true}, {"1", 1000000, true}, @@ -385,21 +385,21 @@ Y_UNIT_TEST_SUITE(DateTimeTest) { }; for (const T* t = tests; t != std::end(tests); ++t) { - // FromString - bool parsed = false; - try { - TDuration time = FromString<TDuration>(t->Str); - parsed = true; - UNIT_ASSERT_EQUAL(t->MicroSeconds, time.MicroSeconds()); - } catch (const yexception&) { - UNIT_ASSERT_VALUES_EQUAL(parsed, t->Parseable); - } - // TryFromString - TDuration tryTime; - UNIT_ASSERT_VALUES_EQUAL(TryFromString<TDuration>(t->Str, tryTime), t->Parseable); - if (t->Parseable) { - UNIT_ASSERT_EQUAL(t->MicroSeconds, tryTime.MicroSeconds()); - } + // FromString + bool parsed = false; + try { + TDuration time = FromString<TDuration>(t->Str); + parsed = true; + UNIT_ASSERT_EQUAL(t->MicroSeconds, time.MicroSeconds()); + } catch (const yexception&) { + UNIT_ASSERT_VALUES_EQUAL(parsed, t->Parseable); + } + // TryFromString + TDuration tryTime; + UNIT_ASSERT_VALUES_EQUAL(TryFromString<TDuration>(t->Str, tryTime), t->Parseable); + if (t->Parseable) { + UNIT_ASSERT_EQUAL(t->MicroSeconds, tryTime.MicroSeconds()); + } } } @@ -430,22 +430,22 @@ Y_UNIT_TEST_SUITE(DateTimeTest) { } Y_UNIT_TEST(TestDurationMath) { - TDuration empty; - UNIT_ASSERT(!empty); - // ensure that this compiles too - if (empty) { - UNIT_ASSERT(false); - } - TDuration nonEmpty = TDuration::MicroSeconds(1); - UNIT_ASSERT(nonEmpty); - + TDuration empty; + UNIT_ASSERT(!empty); + // ensure that this compiles too + if (empty) { + UNIT_ASSERT(false); + } + TDuration nonEmpty = TDuration::MicroSeconds(1); + UNIT_ASSERT(nonEmpty); + UNIT_ASSERT_VALUES_EQUAL(TDuration::Seconds(110), TDuration::Seconds(77) + TDuration::Seconds(33)); // overflow UNIT_ASSERT_VALUES_EQUAL(TDuration::Max(), TDuration::Max() - TDuration::Seconds(1) + TDuration::Seconds(10)); // underflow UNIT_ASSERT_VALUES_EQUAL(TDuration::Zero(), TDuration::Seconds(20) - TDuration::Seconds(200)); - // division - UNIT_ASSERT_DOUBLES_EQUAL(TDuration::Minutes(1) / TDuration::Seconds(10), 6.0, 1e-9); + // division + UNIT_ASSERT_DOUBLES_EQUAL(TDuration::Minutes(1) / TDuration::Seconds(10), 6.0, 1e-9); } Y_UNIT_TEST(TestDurationGetters) { diff --git a/util/datetime/cputimer.cpp b/util/datetime/cputimer.cpp index a3e7c10d50..516d372c37 100644 --- a/util/datetime/cputimer.cpp +++ b/util/datetime/cputimer.cpp @@ -128,7 +128,7 @@ TTimeLogger::~TTimeLogger() { ui64 endCycles = GetCycleCount(); if (Verbose) { const char* prefix = (OK) ? "" : "!"; - fprintf(stderr, "%s%s ended: %.24s (%lu) (%d) (took %lus = %s)\n", + fprintf(stderr, "%s%s ended: %.24s (%lu) (%d) (took %lus = %s)\n", prefix, Message.data(), ctime(&tim), (unsigned long)tim, (int)getpid(), (unsigned long)tim - (unsigned long)Begin, FormatCycles(endCycles - BeginCycles).data()); fprintf(stderr, "%s=========================================================\n", prefix); diff --git a/util/datetime/parser.rl6 b/util/datetime/parser.rl6 index ac41dd380f..931f09eae1 100644 --- a/util/datetime/parser.rl6 +++ b/util/datetime/parser.rl6 @@ -790,11 +790,11 @@ TDuration TDurationParser::GetResult(TDuration defaultValue) const { bool TDuration::TryParse(const TStringBuf input, TDuration& result) { TDuration r = ::Parse<TDurationParser, TDuration>(input.data(), input.size(), TDuration::Max()); - if (r == TDuration::Max()) - return false; - result = r; - return true; -} + if (r == TDuration::Max()) + return false; + result = r; + return true; +} TDuration TDuration::Parse(const TStringBuf input) { return ParseUnsafe<TDurationParser, TDuration>(input.data(), input.size()); diff --git a/util/datetime/systime.cpp b/util/datetime/systime.cpp index 6df1ee2181..6ee7e8fc6e 100644 --- a/util/datetime/systime.cpp +++ b/util/datetime/systime.cpp @@ -131,10 +131,10 @@ struct tm* GmTimeR(const time_t* timer, struct tm* tmbuf) { return tmbuf; } - + TString CTimeR(const time_t* timer) { - char sTime[32]; - sTime[0] = 0; - ctime_r(timer, &sTime[0]); - return sTime; -} + char sTime[32]; + sTime[0] = 0; + ctime_r(timer, &sTime[0]); + return sTime; +} diff --git a/util/datetime/systime.h b/util/datetime/systime.h index 0cb962cdd0..491d36e802 100644 --- a/util/datetime/systime.h +++ b/util/datetime/systime.h @@ -8,7 +8,7 @@ // timegm and gmtime_r versions that don't need access to filesystem or a big stack time_t TimeGM(const struct tm* t); struct tm* GmTimeR(const time_t* timer, struct tm* tmbuf); -// safe version of ctime, convinient version of ctime_r +// safe version of ctime, convinient version of ctime_r TString CTimeR(const time_t* timer); #ifdef _win_ diff --git a/util/digest/fnv.h b/util/digest/fnv.h index efedb95ac9..87b41a3de7 100644 --- a/util/digest/fnv.h +++ b/util/digest/fnv.h @@ -66,8 +66,8 @@ template <class T> static constexpr T FnvHash(const void* buf, size_t len) { return FnvHash<T>((const unsigned char*)buf, (const unsigned char*)buf + len); } - -template <class T, class Buf> + +template <class T, class Buf> static constexpr T FnvHash(const Buf& buf) { return FnvHash<T>(buf.data(), buf.size() * sizeof(*buf.data())); -} +} diff --git a/util/digest/fnv_ut.cpp b/util/digest/fnv_ut.cpp index d295586efd..ce56642b3e 100644 --- a/util/digest/fnv_ut.cpp +++ b/util/digest/fnv_ut.cpp @@ -4,7 +4,7 @@ Y_UNIT_TEST_SUITE(TFnvTest) { Y_UNIT_TEST(TestFnv32) { - const auto h32 = ULL(2849763999); + const auto h32 = ULL(2849763999); UNIT_ASSERT_EQUAL(FnvHash<ui32>("1234567", 7), h32); UNIT_ASSERT_EQUAL(FnvHash<ui32>(TStringBuf("1234567")), h32); @@ -16,7 +16,7 @@ Y_UNIT_TEST_SUITE(TFnvTest) { const auto h64 = ULL(2449551094593701855); UNIT_ASSERT_EQUAL(FnvHash<ui64>("1234567", 7), h64); UNIT_ASSERT_EQUAL(FnvHash<ui64>(TStringBuf("1234567")), h64); - + UNIT_ASSERT_EQUAL(FnvHash<ui64>(nullptr, 0), FNV64INIT); UNIT_ASSERT_EQUAL(FnvHash<ui64>(TStringBuf()), FNV64INIT); } diff --git a/util/draft/enum.h b/util/draft/enum.h index 9778cbc590..18002b7df2 100644 --- a/util/draft/enum.h +++ b/util/draft/enum.h @@ -27,7 +27,7 @@ const V* FindEnumFromStringImpl(K1 key, const std::pair<K2, V>* entries, size_t return nullptr; } -// special version for const char* +// 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++) @@ -39,28 +39,28 @@ const V* FindEnumFromStringImpl(const char* key, const std::pair<const char*, V> 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++) - out << (i ? ", " : "") << "'" << entries[i].first << "'"; - return result; -} - -// special version for const char* + TStringOutput out(result); + for (size_t i = 0; i < arraySize; i++) + out << (i ? ", " : "") << "'" << entries[i].first << "'"; + return result; +} + +// special version for const char* 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++) + TStringOutput out(result); + for (size_t i = 0; i < arraySize; i++) out << (i ? ", " : "") << "'" << (entries[i].first ? entries[i].first : "<null>") << "'"; - return result; -} - + 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) return res; - + ythrow TEnumNotFoundException() << "Key '" << key << "' not found in enum. Valid options are: " << PrintEnumItemsImpl(entries, arraySize) << ". "; } @@ -69,13 +69,13 @@ const K* EnumToStringImpl(V value, const std::pair<K, V>* entries, size_t arrayS 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++) - exc << (i ? ", " : "") << int(entries[i].second); - exc << ". "; - ythrow exc; + + TEnumNotFoundException exc; + exc << "Value '" << int(value) << "' not found in enum. Valid values are: "; + for (size_t i = 0; i < arraySize; i++) + exc << (i ? ", " : "") << int(entries[i].second); + exc << ". "; + ythrow exc; } /////////////////////////////////// diff --git a/util/draft/holder_vector.h b/util/draft/holder_vector.h index 645b2c72fb..1c62055bd9 100644 --- a/util/draft/holder_vector.h +++ b/util/draft/holder_vector.h @@ -83,7 +83,7 @@ public: } using TBase::operator[]; - using TBase::operator bool; + using TBase::operator bool; using TBase::at; using TBase::back; using TBase::begin; diff --git a/util/draft/holder_vector_ut.cpp b/util/draft/holder_vector_ut.cpp index 9e71188536..f64393860a 100644 --- a/util/draft/holder_vector_ut.cpp +++ b/util/draft/holder_vector_ut.cpp @@ -6,13 +6,13 @@ Y_UNIT_TEST_SUITE(THolderVectorTest) { Y_UNIT_TEST(TestCreateEmpty) { THolderVector<int> ints; UNIT_ASSERT_EQUAL(ints.Size(), 0); - UNIT_ASSERT(!ints); + UNIT_ASSERT(!ints); } Y_UNIT_TEST(TestCreateNonEmpty) { THolderVector<int> ints(5); UNIT_ASSERT_EQUAL(ints.Size(), 5); - UNIT_ASSERT(ints); + UNIT_ASSERT(ints); for (size_t i = 0; i < ints.Size(); ++i) { UNIT_ASSERT_EQUAL(ints[i], (int*)nullptr); diff --git a/util/folder/filelist.cpp b/util/folder/filelist.cpp index 89810e64bf..b21fcdbf20 100644 --- a/util/folder/filelist.cpp +++ b/util/folder/filelist.cpp @@ -5,26 +5,26 @@ #include <util/system/defaults.h> void TFileEntitiesList::Fill(const TString& dirname, TStringBuf prefix, TStringBuf suffix, int depth, bool sort) { - TDirIterator::TOptions opts; - opts.SetMaxLevel(depth); + TDirIterator::TOptions opts; + opts.SetMaxLevel(depth); if (sort) { - opts.SetSortByName(); + opts.SetSortByName(); } - TDirIterator dir(dirname, opts); + TDirIterator dir(dirname, opts); Clear(); - size_t dirNameLength = dirname.length(); + size_t dirNameLength = dirname.length(); while (dirNameLength && (dirname[dirNameLength - 1] == '\\' || dirname[dirNameLength - 1] == '/')) { --dirNameLength; } for (auto file = dir.begin(); file != dir.end(); ++file) { - if (file->fts_pathlen == file->fts_namelen || file->fts_pathlen <= dirNameLength) { + if (file->fts_pathlen == file->fts_namelen || file->fts_pathlen <= dirNameLength) { continue; } - TStringBuf filename = file->fts_path + dirNameLength + 1; + TStringBuf filename = file->fts_path + dirNameLength + 1; if (filename.empty() || !filename.StartsWith(prefix) || !filename.EndsWith(suffix)) { continue; diff --git a/util/folder/fts.cpp b/util/folder/fts.cpp index 8f3f10c643..0e6a6f86eb 100644 --- a/util/folder/fts.cpp +++ b/util/folder/fts.cpp @@ -62,7 +62,7 @@ #ifndef _win_ -static const dird invalidDirD = -1; +static const dird invalidDirD = -1; dird get_cwdd() { return open(".", O_RDONLY, 0); @@ -88,7 +88,7 @@ int cmp_dird(dird fd1, dird fd2) { return fd1 - fd2; } -#else // ndef _win_ +#else // ndef _win_ int stat64UTF(const char* path, struct _stat64* _Stat) { int len_converted = MultiByteToWideChar(CP_UTF8, 0, path, -1, 0, 0); @@ -164,7 +164,7 @@ dird get_dird(char* path) { return ret; } -#endif // ndef _win_ +#endif // ndef _win_ #ifdef _win_ #define S_ISDIR(st_mode) ((st_mode & _S_IFMT) == _S_IFDIR) @@ -873,8 +873,8 @@ fts_build(FTS* sp, int type) dirp = nullptr; #ifdef _win_ close_dird(dirpd); - dirpd = invalidDirD; -#else + dirpd = invalidDirD; +#else Y_UNUSED(invalidDirD); #endif } else { diff --git a/util/folder/path_ut.cpp b/util/folder/path_ut.cpp index 65721bd5bb..e6a3451016 100644 --- a/util/folder/path_ut.cpp +++ b/util/folder/path_ut.cpp @@ -200,7 +200,7 @@ Y_UNIT_TEST_SUITE(TFsPathTests) { UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "/db/BASE/primus121-025-1380131338/test"); #endif } - + Y_UNIT_TEST(TestSlashesAndBasenameWin) { TFsPath p("\\db\\BASE\\primus121-025-1380131338\\\\"); TFsPath testP = p / "test"; diff --git a/util/generic/buffer_ut.cpp b/util/generic/buffer_ut.cpp index d4330dc100..437d7122ec 100644 --- a/util/generic/buffer_ut.cpp +++ b/util/generic/buffer_ut.cpp @@ -18,114 +18,114 @@ Y_UNIT_TEST_SUITE(TBufferTest) { } Y_UNIT_TEST(TestAppend) { - const char data[] = "1234567890qwertyuiop"; + const char data[] = "1234567890qwertyuiop"; - TBuffer buf(13); + TBuffer buf(13); TString str; - for (size_t i = 0; i < 10; ++i) { - for (size_t j = 0; j < sizeof(data) - 1; ++j) { - buf.Append(data, j); - buf.Append('q'); - str.append(data, j); - str.append('q'); - } - } + for (size_t i = 0; i < 10; ++i) { + for (size_t j = 0; j < sizeof(data) - 1; ++j) { + buf.Append(data, j); + buf.Append('q'); + str.append(data, j); + str.append('q'); + } + } UNIT_ASSERT_EQUAL(TString(buf.data(), buf.size()), str); } Y_UNIT_TEST(TestReset) { - char content[] = "some text"; - TBuffer buf; + char content[] = "some text"; + TBuffer buf; - buf.Append(content, sizeof(content)); - buf.Clear(); + buf.Append(content, sizeof(content)); + buf.Clear(); - UNIT_ASSERT(buf.Capacity() != 0); + UNIT_ASSERT(buf.Capacity() != 0); - buf.Append(content, sizeof(content)); - buf.Reset(); + buf.Append(content, sizeof(content)); + buf.Reset(); - UNIT_ASSERT_EQUAL(buf.Capacity(), 0); - } + UNIT_ASSERT_EQUAL(buf.Capacity(), 0); + } Y_UNIT_TEST(TestResize) { - char content[] = "some text"; - TBuffer buf; + char content[] = "some text"; + TBuffer buf; - buf.Resize(10); + buf.Resize(10); UNIT_ASSERT_VALUES_EQUAL(buf.size(), 10u); - buf.Resize(0); + buf.Resize(0); UNIT_ASSERT_VALUES_EQUAL(buf.size(), 0u); - buf.Resize(9); + buf.Resize(9); memcpy(buf.data(), content, 9); UNIT_ASSERT_VALUES_EQUAL(TString(buf.data(), buf.size()), "some text"); - buf.Resize(4); + buf.Resize(4); UNIT_ASSERT_VALUES_EQUAL(TString(buf.data(), buf.size()), "some"); - } + } Y_UNIT_TEST(TestReserve) { - TBuffer buf; - UNIT_ASSERT_EQUAL(buf.Capacity(), 0); + TBuffer buf; + UNIT_ASSERT_EQUAL(buf.Capacity(), 0); - buf.Reserve(4); - UNIT_ASSERT_EQUAL(buf.Capacity(), 4); + buf.Reserve(4); + UNIT_ASSERT_EQUAL(buf.Capacity(), 4); - buf.Reserve(6); - UNIT_ASSERT_EQUAL(buf.Capacity(), 8); + buf.Reserve(6); + UNIT_ASSERT_EQUAL(buf.Capacity(), 8); - buf.Reserve(32); - UNIT_ASSERT_EQUAL(buf.Capacity(), 32); + buf.Reserve(32); + UNIT_ASSERT_EQUAL(buf.Capacity(), 32); - buf.Reserve(33); - UNIT_ASSERT_EQUAL(buf.Capacity(), 64); - buf.Reserve(64); - UNIT_ASSERT_EQUAL(buf.Capacity(), 64); + buf.Reserve(33); + UNIT_ASSERT_EQUAL(buf.Capacity(), 64); + buf.Reserve(64); + UNIT_ASSERT_EQUAL(buf.Capacity(), 64); - buf.Resize(128); - UNIT_ASSERT_EQUAL(buf.Capacity(), 128); + buf.Resize(128); + UNIT_ASSERT_EQUAL(buf.Capacity(), 128); - buf.Append('a'); - UNIT_ASSERT_EQUAL(buf.Capacity(), 256); + buf.Append('a'); + UNIT_ASSERT_EQUAL(buf.Capacity(), 256); TString tmp1 = "abcdef"; buf.Append(tmp1.data(), tmp1.size()); - UNIT_ASSERT_EQUAL(buf.Capacity(), 256); + UNIT_ASSERT_EQUAL(buf.Capacity(), 256); TString tmp2 = "30498290sfokdsflj2308w"; - buf.Resize(1020); + buf.Resize(1020); buf.Append(tmp2.data(), tmp2.size()); - UNIT_ASSERT_EQUAL(buf.Capacity(), 2048); - } + UNIT_ASSERT_EQUAL(buf.Capacity(), 2048); + } Y_UNIT_TEST(TestShrinkToFit) { - TBuffer buf; + TBuffer buf; TString content = "some text"; buf.Append(content.data(), content.size()); - UNIT_ASSERT_EQUAL(buf.Size(), 9); - UNIT_ASSERT_EQUAL(buf.Capacity(), 16); + UNIT_ASSERT_EQUAL(buf.Size(), 9); + UNIT_ASSERT_EQUAL(buf.Capacity(), 16); - buf.ShrinkToFit(); - UNIT_ASSERT_EQUAL(buf.Size(), 9); - UNIT_ASSERT_EQUAL(buf.Capacity(), 9); + buf.ShrinkToFit(); + UNIT_ASSERT_EQUAL(buf.Size(), 9); + UNIT_ASSERT_EQUAL(buf.Capacity(), 9); UNIT_ASSERT_EQUAL(TString(buf.data(), buf.size()), content); - const size_t MB = 1024 * 1024; - buf.Resize(MB); - UNIT_ASSERT_EQUAL(buf.Capacity(), MB); - buf.ShrinkToFit(); - UNIT_ASSERT_EQUAL(buf.Capacity(), MB); - buf.Resize(MB + 100); - UNIT_ASSERT_EQUAL(buf.Capacity(), 2 * MB); - buf.ShrinkToFit(); - UNIT_ASSERT_EQUAL(buf.Capacity(), MB + 100); - } - -#if 0 + const size_t MB = 1024 * 1024; + buf.Resize(MB); + UNIT_ASSERT_EQUAL(buf.Capacity(), MB); + buf.ShrinkToFit(); + UNIT_ASSERT_EQUAL(buf.Capacity(), MB); + buf.Resize(MB + 100); + UNIT_ASSERT_EQUAL(buf.Capacity(), 2 * MB); + buf.ShrinkToFit(); + UNIT_ASSERT_EQUAL(buf.Capacity(), MB + 100); + } + +#if 0 Y_UNIT_TEST(TestAlignUp) { char content[] = "some text"; TBuffer buf; @@ -142,9 +142,9 @@ Y_UNIT_TEST(TestAlignUp) { UNIT_ASSERT(buf.Size() % 4 == 0); UNIT_ASSERT_VALUES_EQUAL(TString(~buf, +buf), "some text!!!1234"); } -#endif +#endif -#if 0 +#if 0 Y_UNIT_TEST(TestSpeed) { const char data[] = "1234567890qwertyuiop"; const size_t c = 100000; @@ -177,19 +177,19 @@ Y_UNIT_TEST(TestSpeed) { UNIT_ASSERT(t1 < t2); } -#endif +#endif Y_UNIT_TEST(TestFillAndChop) { - TBuffer buf; - buf.Append("Some ", 5); - buf.Fill('!', 5); - buf.Append(" text.", 6); + TBuffer buf; + buf.Append("Some ", 5); + buf.Fill('!', 5); + buf.Append(" text.", 6); UNIT_ASSERT_VALUES_EQUAL(TString(buf.data(), buf.size()), "Some !!!!! text."); - buf.Chop(5, 6); + buf.Chop(5, 6); UNIT_ASSERT_VALUES_EQUAL(TString(buf.data(), buf.size()), "Some text."); - } - + } + Y_UNIT_TEST(TestComparison) { TBuffer buf1("abcd", 4); TBuffer buf2("abcde", 5); diff --git a/util/generic/guid.h b/util/generic/guid.h index d2e884c83b..2bf6c8ad99 100644 --- a/util/generic/guid.h +++ b/util/generic/guid.h @@ -4,15 +4,15 @@ #include <util/str_stl.h> -/** - * UUID generation - * - * NOTE: It is not a real GUID (RFC 4122), as described in - * https://en.wikipedia.org/wiki/Universally_unique_identifier - * https://en.wikipedia.org/wiki/Globally_unique_identifier - * - * See https://clubs.at.yandex-team.ru/stackoverflow/10238/10240 - * and https://st.yandex-team.ru/IGNIETFERRO-768 for details. +/** + * UUID generation + * + * NOTE: It is not a real GUID (RFC 4122), as described in + * https://en.wikipedia.org/wiki/Universally_unique_identifier + * https://en.wikipedia.org/wiki/Globally_unique_identifier + * + * See https://clubs.at.yandex-team.ru/stackoverflow/10238/10240 + * and https://st.yandex-team.ru/IGNIETFERRO-768 for details. */ struct TGUID { ui32 dw[4] = {}; diff --git a/util/generic/map.h b/util/generic/map.h index 140c7668ce..b5001b56c0 100644 --- a/util/generic/map.h +++ b/util/generic/map.h @@ -37,7 +37,7 @@ public: inline explicit operator bool() const noexcept { return !this->empty(); } - + inline bool contains(const K& key) const { return this->find(key) != this->end(); } diff --git a/util/generic/map_ut.cpp b/util/generic/map_ut.cpp index 7808192e74..79e832b024 100644 --- a/util/generic/map_ut.cpp +++ b/util/generic/map_ut.cpp @@ -5,35 +5,35 @@ #include <algorithm> Y_UNIT_TEST_SUITE(TYMapTest) { - template <typename TAlloc> + template <typename TAlloc> void DoTestMap1(TMap<char, int, TLess<char>, TAlloc>& m); - template <typename TAlloc> + template <typename TAlloc> void DoTestMMap1(TMultiMap<char, int, TLess<char>, TAlloc>& mm); Y_UNIT_TEST(TestMap1) { - { + { TMap<char, int, TLess<char>> m; - DoTestMap1(m); + DoTestMap1(m); } - { - TMemoryPool p(100); + { + TMemoryPool p(100); TMap<char, int, TLess<char>, TPoolAllocator> m(&p); - DoTestMap1(m); - } - } + DoTestMap1(m); + } + } Y_UNIT_TEST(TestMMap1) { - { + { TMultiMap<char, int, TLess<char>> mm; - DoTestMMap1(mm); + DoTestMMap1(mm); } - { - TMemoryPool p(100); + { + TMemoryPool p(100); TMultiMap<char, int, TLess<char>, TPoolAllocator> mm(&p); - DoTestMMap1(mm); - } - } + DoTestMMap1(mm); + } + } template <typename TAlloc> void DoTestMap1(TMap<char, int, TLess<char>, TAlloc>& m) { diff --git a/util/generic/ptr.h b/util/generic/ptr.h index f75af6f862..19db0e3ec5 100644 --- a/util/generic/ptr.h +++ b/util/generic/ptr.h @@ -1119,7 +1119,7 @@ private: TPtr T_; }; -// saves .Get() on argument passing. Intended usage: Func(TPtrArg<X> p); ... TIntrusivePtr<X> p2; Func(p2); +// saves .Get() on argument passing. Intended usage: Func(TPtrArg<X> p); ... TIntrusivePtr<X> p2; Func(p2); template <class T> class TPtrArg { T* Ptr; diff --git a/util/generic/set.h b/util/generic/set.h index 42ecb2759e..4c437ca26f 100644 --- a/util/generic/set.h +++ b/util/generic/set.h @@ -19,7 +19,7 @@ public: return !this->empty(); } - template <class TheKey> + template <class TheKey> inline bool contains(const TheKey& key) const { return this->find(key) != this->end(); } diff --git a/util/generic/set_ut.cpp b/util/generic/set_ut.cpp index 6a8c503608..d2769d327f 100644 --- a/util/generic/set_ut.cpp +++ b/util/generic/set_ut.cpp @@ -77,23 +77,23 @@ Y_UNIT_TEST_SUITE(YSetTest) { TSet<int> const& crs = s; UNIT_ASSERT(!crs.contains(0)); - + s.insert(1); s.insert(42); s.insert(100); s.insert(2); - + UNIT_ASSERT(s.contains(1)); UNIT_ASSERT(s.contains(2)); UNIT_ASSERT(s.contains(42)); UNIT_ASSERT(s.contains(100)); } - + Y_UNIT_TEST(TestBounds) { int array1[] = {1, 3, 6, 7}; TSet<int> s(array1, array1 + sizeof(array1) / sizeof(array1[0])); TSet<int> const& crs = s; - + TSet<int>::iterator sit; TSet<int>::const_iterator scit; std::pair<TSet<int>::iterator, TSet<int>::iterator> pit; diff --git a/util/generic/strbase.h b/util/generic/strbase.h index a2b1ec160d..ab39fc7537 100644 --- a/util/generic/strbase.h +++ b/util/generic/strbase.h @@ -123,7 +123,7 @@ public: return std::basic_string<TCharType, TCharTraits, Allocator>(Ptr(), Len()); } - /** + /** * @param Pointer to character inside the string, or nullptr. * @return Offset from string beginning (in chars), or npos on nullptr. */ diff --git a/util/generic/strbuf.h b/util/generic/strbuf.h index d8e38a00c1..70b9360d58 100644 --- a/util/generic/strbuf.h +++ b/util/generic/strbuf.h @@ -434,19 +434,19 @@ public: } public: // string subsequences - /// Cut last @c shift characters (or less if length is less than @c shift) + /// Cut last @c shift characters (or less if length is less than @c shift) inline TdSelf& Chop(size_t shift) noexcept { this->remove_suffix(std::min(shift, size())); return *this; } - /// Cut first @c shift characters (or less if length is less than @c shift) + /// Cut first @c shift characters (or less if length is less than @c shift) inline TdSelf& Skip(size_t shift) noexcept { this->remove_prefix(std::min(shift, size())); return *this; } - /// Sets the start pointer to a position relative to the end + /// Sets the start pointer to a position relative to the end inline TdSelf& RSeek(size_t tailSize) noexcept { if (size() > tailSize) { //WARN: removing TStringView:: will lead to an infinite recursion diff --git a/util/generic/strbuf_ut.cpp b/util/generic/strbuf_ut.cpp index 6b6109a06f..69cde785af 100644 --- a/util/generic/strbuf_ut.cpp +++ b/util/generic/strbuf_ut.cpp @@ -56,10 +56,10 @@ Y_UNIT_TEST_SUITE(TStrBufTest) { UNIT_ASSERT_VALUES_EQUAL(str.After('x'), TStringBuf("qwerty")); UNIT_ASSERT_VALUES_EQUAL(str.After('y'), TStringBuf()); UNIT_ASSERT_STRINGS_EQUAL(str.After('='), str); - - // Also works properly on empty strings - TStringBuf empty; - UNIT_ASSERT_STRINGS_EQUAL(empty.After('x'), empty); + + // Also works properly on empty strings + TStringBuf empty; + UNIT_ASSERT_STRINGS_EQUAL(empty.After('x'), empty); } Y_UNIT_TEST(TestBefore) { @@ -168,10 +168,10 @@ Y_UNIT_TEST_SUITE(TStrBufTest) { rt = lt.SplitOff('r'); UNIT_ASSERT_EQUAL(lt, TStringBuf("qwe")); UNIT_ASSERT_EQUAL(rt, TStringBuf("ty")); - - rt = qw; - lt = rt.NextTok('r'); - TStringBuf ty = rt.NextTok('r'); // no 'r' in "ty" + + rt = qw; + lt = rt.NextTok('r'); + TStringBuf ty = rt.NextTok('r'); // no 'r' in "ty" UNIT_ASSERT_EQUAL(rt.size(), 0); UNIT_ASSERT_EQUAL(ty, TStringBuf("ty")); } diff --git a/util/generic/string_ut.h b/util/generic/string_ut.h index d98106ac1f..44bb10bdeb 100644 --- a/util/generic/string_ut.h +++ b/util/generic/string_ut.h @@ -526,9 +526,9 @@ public: void TestConstructors() { TStringType s0(nullptr); - UNIT_ASSERT(s0.size() == 0); + UNIT_ASSERT(s0.size() == 0); UNIT_ASSERT_EQUAL(s0, TStringType()); - + TStringType s; TStringType s1(*Data._0()); TStringType s2(Data._0()); @@ -895,8 +895,8 @@ public: TStringType sS = s2; // type 'TStringType' is used as is ComputeHash(sS); /*size_t hash_val = sS.hash(); - - try { + + try { //UNIT_ASSERT(hash_val == Data.HashOf_0123456()); } catch (...) { Cerr << hash_val << Endl; diff --git a/util/generic/utility_ut.cpp b/util/generic/utility_ut.cpp index 270f57e64a..8e9d5afff9 100644 --- a/util/generic/utility_ut.cpp +++ b/util/generic/utility_ut.cpp @@ -5,23 +5,23 @@ // DO_NOT_STYLE -class TTest { -public: - inline TTest(int val) - : Val(val) - { - } +class TTest { +public: + inline TTest(int val) + : Val(val) + { + } - inline void Swap(TTest& t) { - DoSwap(Val, t.Val); - } + inline void Swap(TTest& t) { + DoSwap(Val, t.Val); + } - int Val; + int Val; -private: - TTest(const TTest&); - TTest& operator=(const TTest&); -}; +private: + TTest(const TTest&); + TTest& operator=(const TTest&); +}; struct TUnorderedTag { TStringBuf Tag; @@ -34,7 +34,7 @@ static bool operator<(const TUnorderedTag, const TUnorderedTag) { static bool operator>(const TUnorderedTag, const TUnorderedTag) = delete; Y_UNIT_TEST_SUITE(TUtilityTest) { - + Y_UNIT_TEST(TestSwapPrimitive) { int i = 0; int j = 1; diff --git a/util/memory/blob_ut.cpp b/util/memory/blob_ut.cpp index 8764e1d205..023f9a0487 100644 --- a/util/memory/blob_ut.cpp +++ b/util/memory/blob_ut.cpp @@ -6,7 +6,7 @@ #include <util/folder/path.h> #include <util/stream/output.h> #include <util/stream/file.h> -#include <util/generic/buffer.h> +#include <util/generic/buffer.h> #include <util/generic/array_ref.h> Y_UNIT_TEST_SUITE(TBlobTest) { @@ -38,12 +38,12 @@ Y_UNIT_TEST_SUITE(TBlobTest) { Y_UNIT_TEST(TestFromString) { TString s("dsfkjhgsadftusadtf"); TBlob b(TBlob::FromString(s)); - + UNIT_ASSERT_EQUAL(TString((const char*)b.Data(), b.Size()), s); const auto expectedRef = TArrayRef<const ui8>{(ui8*)s.data(), s.size()}; UNIT_ASSERT_EQUAL(TArrayRef<const ui8>{b}, expectedRef); } - + Y_UNIT_TEST(TestFromBuffer) { const size_t sz = 1234u; TBuffer buf; diff --git a/util/network/sock_ut.cpp b/util/network/sock_ut.cpp index f64a4993db..fd8c783747 100644 --- a/util/network/sock_ut.cpp +++ b/util/network/sock_ut.cpp @@ -83,7 +83,7 @@ Y_UNIT_TEST_SUITE(TSocketTest) { cliSock.CheckSock(); servSock.CheckSock(); newSock.CheckSock(); - + // server int yes = 1; CheckedSetSockOpt(servSock, SOL_SOCKET, SO_REUSEADDR, yes, "servSock, SO_REUSEADDR"); diff --git a/util/network/socket.cpp b/util/network/socket.cpp index 9ad5ff276c..4f6e804346 100644 --- a/util/network/socket.cpp +++ b/util/network/socket.cpp @@ -432,22 +432,22 @@ void SetSocketPriority(SOCKET s, int priority) { #endif } -bool HasLocalAddress(SOCKET socket) { - TOpaqueAddr localAddr; - if (getsockname(socket, localAddr.MutableAddr(), localAddr.LenPtr()) != 0) { - ythrow TSystemError() << "HasLocalAddress: getsockname() failed. "; - } - if (IsLoopback(localAddr)) { - return true; - } - - TOpaqueAddr remoteAddr; - if (getpeername(socket, remoteAddr.MutableAddr(), remoteAddr.LenPtr()) != 0) { - ythrow TSystemError() << "HasLocalAddress: getpeername() failed. "; - } - return IsSame(localAddr, remoteAddr); -} - +bool HasLocalAddress(SOCKET socket) { + TOpaqueAddr localAddr; + if (getsockname(socket, localAddr.MutableAddr(), localAddr.LenPtr()) != 0) { + ythrow TSystemError() << "HasLocalAddress: getsockname() failed. "; + } + if (IsLoopback(localAddr)) { + return true; + } + + TOpaqueAddr remoteAddr; + if (getpeername(socket, remoteAddr.MutableAddr(), remoteAddr.LenPtr()) != 0) { + ythrow TSystemError() << "HasLocalAddress: getpeername() failed. "; + } + return IsSame(localAddr, remoteAddr); +} + namespace { #if defined(_linux_) #if !defined(TCP_FASTOPEN) diff --git a/util/network/socket.h b/util/network/socket.h index 646869bbaa..40c8648b40 100644 --- a/util/network/socket.h +++ b/util/network/socket.h @@ -118,7 +118,7 @@ int GetSocketToS(SOCKET s); int GetSocketToS(SOCKET s, const NAddr::IRemoteAddr* addr); void SetSocketPriority(SOCKET s, int priority); void SetTcpFastOpen(SOCKET s, int qlen); -/** +/** * Deprecated, consider using HasSocketDataToRead instead. **/ bool IsNotSocketClosedByOtherSide(SOCKET s); @@ -132,9 +132,9 @@ enum class ESocketReadStatus { **/ ESocketReadStatus HasSocketDataToRead(SOCKET s); /** - * Determines whether connection on socket is local (same machine) or not. - **/ -bool HasLocalAddress(SOCKET socket); + * Determines whether connection on socket is local (same machine) or not. + **/ +bool HasLocalAddress(SOCKET socket); /** * Runtime check if current kernel supports SO_REUSEPORT option. diff --git a/util/random/mersenne.h b/util/random/mersenne.h index b0296a6dfb..b2044604ac 100644 --- a/util/random/mersenne.h +++ b/util/random/mersenne.h @@ -10,21 +10,21 @@ namespace NPrivate { template <> struct TMersenneTraits<ui64> { - using TImpl = TMersenne64; + using TImpl = TMersenne64; }; template <> struct TMersenneTraits<ui32> { - using TImpl = TMersenne32; + using TImpl = TMersenne32; }; } class IInputStream; template <class T> -class TMersenne: public TCommonRNG<T, TMersenne<T>>, public ::NPrivate::TMersenneTraits<T>::TImpl { +class TMersenne: public TCommonRNG<T, TMersenne<T>>, public ::NPrivate::TMersenneTraits<T>::TImpl { public: - using TBase = typename ::NPrivate::TMersenneTraits<T>::TImpl; + using TBase = typename ::NPrivate::TMersenneTraits<T>::TImpl; inline TMersenne() noexcept { } diff --git a/util/stream/ios_ut.cpp b/util/stream/ios_ut.cpp index ada45c76e7..139f4296e5 100644 --- a/util/stream/ios_ut.cpp +++ b/util/stream/ios_ut.cpp @@ -52,7 +52,7 @@ public: UNIT_TEST_SUITE_REGISTRATION(TStreamsTest); -void TStreamsTest::TestIStreamOperators() { +void TStreamsTest::TestIStreamOperators() { TString data("first line\r\nsecond\t\xd1\x82\xd0\xb5\xd1\x81\xd1\x82 line\r\n 1 -4 59 4320000000009999999 c\n -1.5 1e-110"); TStringInput si(data); @@ -103,20 +103,20 @@ void TStreamsTest::TestStringStream() { UNIT_ASSERT_EQUAL(s.ReadLine(), "123.1"); UNIT_ASSERT_EQUAL(s.Str(), "qw\r\n1234\n34\r\n123.1"); - - // Test stream copying - TStringStream sc = s; - - s << "-666-" << 13; - sc << "-777-" << 0 << "JackPot"; - - UNIT_ASSERT_EQUAL(s.Str(), "qw\r\n1234\n34\r\n123.1-666-13"); - UNIT_ASSERT_EQUAL(sc.Str(), "qw\r\n1234\n34\r\n123.1-777-0JackPot"); - - TStringStream ss; - ss = s; - s << "... and some trash"; - UNIT_ASSERT_EQUAL(ss.Str(), "qw\r\n1234\n34\r\n123.1-666-13"); + + // Test stream copying + TStringStream sc = s; + + s << "-666-" << 13; + sc << "-777-" << 0 << "JackPot"; + + UNIT_ASSERT_EQUAL(s.Str(), "qw\r\n1234\n34\r\n123.1-666-13"); + UNIT_ASSERT_EQUAL(sc.Str(), "qw\r\n1234\n34\r\n123.1-777-0JackPot"); + + TStringStream ss; + ss = s; + s << "... and some trash"; + UNIT_ASSERT_EQUAL(ss.Str(), "qw\r\n1234\n34\r\n123.1-666-13"); } void TStreamsTest::TestGenericRead() { diff --git a/util/stream/str.h b/util/stream/str.h index 19bbc4643b..028bd572c0 100644 --- a/util/stream/str.h +++ b/util/stream/str.h @@ -4,10 +4,10 @@ #include "zerocopy_output.h" #include <util/generic/string.h> -#include <util/generic/noncopyable.h> +#include <util/generic/noncopyable.h> #include <util/generic/store_policy.h> -/** +/** * @addtogroup Streams_Strings * @{ */ @@ -54,11 +54,11 @@ protected: private: const TString* S_; size_t Pos_; - - friend class TStringStream; + + friend class TStringStream; }; -/** +/** * Stream for writing data into a string. */ class TStringOutput: public IZeroCopyOutput { @@ -131,7 +131,7 @@ public: , TStringOutput(*TEmbeddedString::Ptr()) { } - + inline TStringStream& operator=(const TStringStream& other) { // All references remain alive, we need to change position only Str() = other.Str(); @@ -139,7 +139,7 @@ public: return *this; } - + ~TStringStream() override; /** diff --git a/util/stream/zlib.h b/util/stream/zlib.h index 0961de7d4b..e7de7c81b7 100644 --- a/util/stream/zlib.h +++ b/util/stream/zlib.h @@ -37,9 +37,9 @@ namespace ZLib { }; } -/** +/** * Non-buffered ZLib decompressing stream. - * + * * Please don't use `TZLibDecompress` if you read text data from stream using * `ReadLine`, it is VERY slow (approx 10 times slower, according to synthetic * benchmark). For fast buffered ZLib stream reading use `TBufferedZLibDecompress` diff --git a/util/string/ascii.cpp b/util/string/ascii.cpp index 9f04f7ec4f..95edb95cc8 100644 --- a/util/string/ascii.cpp +++ b/util/string/ascii.cpp @@ -1,8 +1,8 @@ #include "ascii.h" -#include <util/system/yassert.h> -#include <util/system/compat.h> - +#include <util/system/yassert.h> +#include <util/system/compat.h> + // clang-format off extern const unsigned char NPrivate::ASCII_CLASS[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, @@ -22,7 +22,7 @@ extern const unsigned char NPrivate::ASCII_CLASS[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; - + extern const unsigned char NPrivate::ASCII_LOWER[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, @@ -46,14 +46,14 @@ extern const unsigned char NPrivate::ASCII_LOWER[256] = { int AsciiCompareIgnoreCase(const TStringBuf s1, const TStringBuf s2) noexcept { if (s1.size() <= s2.size()) { if (int cmp = strnicmp(s1.data(), s2.data(), s1.size())) { - return cmp; - } + return cmp; + } return (s1.size() < s2.size()) ? -1 : 0; - } - + } + Y_ASSERT(s1.size() > s2.size()); if (int cmp = strnicmp(s1.data(), s2.data(), s2.size())) { - return cmp; - } - return 1; -} + return cmp; + } + return 1; +} diff --git a/util/string/ascii.h b/util/string/ascii.h index 0bd70bc9ed..10344384d3 100644 --- a/util/string/ascii.h +++ b/util/string/ascii.h @@ -1,7 +1,7 @@ #pragma once #include <util/system/defaults.h> -#include <util/system/compat.h> +#include <util/system/compat.h> #include <util/generic/string.h> // ctype.h-like functions, locale-independent: @@ -156,72 +156,72 @@ template <class T> inline ::NPrivate::TDereferenced<T> AsciiToUpper(T c) noexcept { return IsAsciiLower(c) ? (c + ('A' - 'a')) : c; } - -/** - * ASCII case-insensitive string comparison (for proper UTF8 strings + +/** + * ASCII case-insensitive string comparison (for proper UTF8 strings * case-insensitive comparison consider using @c library/cpp/charset). * - * BUGS: Currently will NOT work properly with strings that contain - * 0-terminator character inside. See IGNIETFERRO-1641 for details. - * + * BUGS: Currently will NOT work properly with strings that contain + * 0-terminator character inside. See IGNIETFERRO-1641 for details. + * * @return true iff @c s1 ans @c s2 are case-insensitively equal. */ -static inline bool AsciiEqualsIgnoreCase(const char* s1, const char* s2) noexcept { - return stricmp(s1, s2) == 0; -} - -/** - * ASCII case-insensitive string comparison (for proper UTF8 strings +static inline bool AsciiEqualsIgnoreCase(const char* s1, const char* s2) noexcept { + return stricmp(s1, s2) == 0; +} + +/** + * ASCII case-insensitive string comparison (for proper UTF8 strings * case-insensitive comparison consider using @c library/cpp/charset). * - * BUGS: Currently will NOT work properly with strings that contain - * 0-terminator character inside. See IGNIETFERRO-1641 for details. - * + * BUGS: Currently will NOT work properly with strings that contain + * 0-terminator character inside. See IGNIETFERRO-1641 for details. + * * @return true iff @c s1 ans @c s2 are case-insensitively equal. */ static inline bool AsciiEqualsIgnoreCase(const TStringBuf s1, const TStringBuf s2) noexcept { return (s1.size() == s2.size()) && strnicmp(s1.data(), s2.data(), s1.size()) == 0; -} - -/** - * ASCII case-insensitive string comparison (for proper UTF8 strings +} + +/** + * ASCII case-insensitive string comparison (for proper UTF8 strings * case-insensitive comparison consider using @c library/cpp/charset). * - * BUGS: Currently will NOT work properly with strings that contain - * 0-terminator character inside. See IGNIETFERRO-1641 for details. - * + * BUGS: Currently will NOT work properly with strings that contain + * 0-terminator character inside. See IGNIETFERRO-1641 for details. + * * @return 0 if strings are equal, negative if @c s1 < @c s2 * and positive otherwise. * (same value as @c stricmp does). */ -static inline int AsciiCompareIgnoreCase(const char* s1, const char* s2) noexcept { - return stricmp(s1, s2); -} - -/** - * ASCII case-insensitive string comparison (for proper UTF8 strings +static inline int AsciiCompareIgnoreCase(const char* s1, const char* s2) noexcept { + return stricmp(s1, s2); +} + +/** + * ASCII case-insensitive string comparison (for proper UTF8 strings * case-insensitive comparison consider using @c library/cpp/charset). * - * BUGS: Currently will NOT work properly with strings that contain - * 0-terminator character inside. See IGNIETFERRO-1641 for details. - * - * @return - * - zero if strings are equal - * - negative if @c s1 < @c s2 - * - positive otherwise, - * similar to stricmp. + * BUGS: Currently will NOT work properly with strings that contain + * 0-terminator character inside. See IGNIETFERRO-1641 for details. + * + * @return + * - zero if strings are equal + * - negative if @c s1 < @c s2 + * - positive otherwise, + * similar to stricmp. */ Y_PURE_FUNCTION int AsciiCompareIgnoreCase(const TStringBuf s1, const TStringBuf s2) noexcept; /** - * ASCII case-sensitive string comparison (for proper UTF8 strings - * case-sensitive comparison consider using @c library/cpp/charset). - * - * BUGS: Currently will NOT work properly with strings that contain - * 0-terminator character inside. See IGNIETFERRO-1641 for details. - * - * @return true iff @c s2 are case-sensitively prefix of @c s1. - */ + * ASCII case-sensitive string comparison (for proper UTF8 strings + * case-sensitive comparison consider using @c library/cpp/charset). + * + * BUGS: Currently will NOT work properly with strings that contain + * 0-terminator character inside. See IGNIETFERRO-1641 for details. + * + * @return true iff @c s2 are case-sensitively prefix of @c s1. + */ static inline bool AsciiHasPrefix(const TStringBuf s1, const TStringBuf s2) noexcept { return (s1.size() >= s2.size()) && memcmp(s1.data(), s2.data(), s2.size()) == 0; } diff --git a/util/string/ascii_ut.cpp b/util/string/ascii_ut.cpp index 41732f6f4e..89069fee50 100644 --- a/util/string/ascii_ut.cpp +++ b/util/string/ascii_ut.cpp @@ -61,14 +61,14 @@ Y_UNIT_TEST_SUITE(TAsciiTest) { UNIT_ASSERT(!IsAsciiPunct(i)); } } - + Y_UNIT_TEST(CompareTest) { - UNIT_ASSERT(AsciiEqualsIgnoreCase("qqq", "qQq")); + UNIT_ASSERT(AsciiEqualsIgnoreCase("qqq", "qQq")); UNIT_ASSERT(AsciiEqualsIgnoreCase("qqq", TStringBuf("qQq"))); TString qq = "qq"; TString qQ = "qQ"; - UNIT_ASSERT(AsciiEqualsIgnoreCase(qq, qQ)); - + UNIT_ASSERT(AsciiEqualsIgnoreCase(qq, qQ)); + TString x = "qqqA"; TString y = "qQqB"; TString z = "qQnB"; @@ -77,13 +77,13 @@ Y_UNIT_TEST_SUITE(TAsciiTest) { TStringBuf xs = TStringBuf(x.data(), 3); TStringBuf ys = TStringBuf(y.data(), 3); TStringBuf zs = TStringBuf(z.data(), 3); - UNIT_ASSERT(AsciiCompareIgnoreCase(xs, ys) == 0); - UNIT_ASSERT(AsciiCompareIgnoreCase(xs, zs) > 0); - UNIT_ASSERT(AsciiCompareIgnoreCase(xs, zz) < 0); - UNIT_ASSERT(AsciiCompareIgnoreCase(zzz, zz) > 0); - - UNIT_ASSERT(AsciiCompareIgnoreCase("qqQ", "qq") > 0); - UNIT_ASSERT(AsciiCompareIgnoreCase("qq", "qq") == 0); + UNIT_ASSERT(AsciiCompareIgnoreCase(xs, ys) == 0); + UNIT_ASSERT(AsciiCompareIgnoreCase(xs, zs) > 0); + UNIT_ASSERT(AsciiCompareIgnoreCase(xs, zz) < 0); + UNIT_ASSERT(AsciiCompareIgnoreCase(zzz, zz) > 0); + + UNIT_ASSERT(AsciiCompareIgnoreCase("qqQ", "qq") > 0); + UNIT_ASSERT(AsciiCompareIgnoreCase("qq", "qq") == 0); UNIT_ASSERT_EQUAL(AsciiHasPrefix("qweasd", "qwe"), true); UNIT_ASSERT_EQUAL(AsciiHasPrefix("qweasd", "qWe"), false); @@ -94,5 +94,5 @@ Y_UNIT_TEST_SUITE(TAsciiTest) { UNIT_ASSERT_EQUAL(AsciiHasSuffixIgnoreCase("qweasd", "asD"), true); UNIT_ASSERT_EQUAL(AsciiHasSuffixIgnoreCase("qweasd", "ast"), false); - } + } } diff --git a/util/string/cast.cpp b/util/string/cast.cpp index 7443dbafb0..aa1e65a8e9 100644 --- a/util/string/cast.cpp +++ b/util/string/cast.cpp @@ -308,7 +308,7 @@ namespace { TUnsigned result; EParseStatus error = TBasicIntParser<TUnsigned, base, TChar>::Parse(&pos, end, max, &result); if (error != PS_OK) { - *ppos = pos; + *ppos = pos; return error; } @@ -484,38 +484,38 @@ size_t ToStringImpl<bool>(bool t, char* buf, size_t len) { */ template <> -bool TryFromStringImpl<bool>(const char* data, size_t len, bool& result) { +bool TryFromStringImpl<bool>(const char* data, size_t len, bool& result) { if (len == 1) { if (data[0] == '0') { - result = false; - return true; + result = false; + return true; } else if (data[0] == '1') { - result = true; + result = true; return true; } } TStringBuf buf(data, len); - if (IsTrue(buf)) { - result = true; + if (IsTrue(buf)) { + result = true; + return true; + } else if (IsFalse(buf)) { + result = false; return true; - } else if (IsFalse(buf)) { - result = false; - return true; } - return false; + return false; } -template <> -bool FromStringImpl<bool>(const char* data, size_t len) { - bool result; +template <> +bool FromStringImpl<bool>(const char* data, size_t len) { + bool result; if (!TryFromStringImpl<bool>(data, len, result)) { ythrow TFromStringException() << TStringBuf("Cannot parse bool(") << TStringBuf(data, len) << TStringBuf("). "); } - return result; -} - + return result; +} + template <> TString FromStringImpl<TString>(const char* data, size_t len) { return TString(data, len); @@ -541,8 +541,8 @@ TWtringBuf FromStringImpl<TWtringBuf>(const wchar16* data, size_t len) { return TWtringBuf(data, len); } -// Try-versions -template <> +// Try-versions +template <> bool TryFromStringImpl<TStringBuf>(const char* data, size_t len, TStringBuf& result) { result = {data, len}; return true; @@ -551,10 +551,10 @@ bool TryFromStringImpl<TStringBuf>(const char* data, size_t len, TStringBuf& res template <> bool TryFromStringImpl<TString>(const char* data, size_t len, TString& result) { result = TString(data, len); - return true; -} - -template <> + return true; +} + +template <> bool TryFromStringImpl<std::string>(const char* data, size_t len, std::string& result) { result.assign(data, len); return true; @@ -569,9 +569,9 @@ bool TryFromStringImpl<TWtringBuf>(const wchar16* data, size_t len, TWtringBuf& template <> bool TryFromStringImpl<TUtf16String>(const wchar16* data, size_t len, TUtf16String& result) { result = TUtf16String(data, len); - return true; -} - + return true; +} + #define DEF_INT_SPEC_III(CHAR, TYPE, ITYPE, BOUNDS, BASE) \ template <> \ TYPE IntFromString<TYPE, BASE>(const CHAR* data, size_t len) { \ @@ -641,48 +641,48 @@ DEF_FLT_SPEC(long double) #undef DEF_FLT_SPEC // Using StrToD for float and double because it is faster than sscanf. -// Exception-free, specialized for float types +// Exception-free, specialized for float types template <> -bool TryFromStringImpl<double>(const char* data, size_t len, double& result) { - if (!len) { - return false; - } - +bool TryFromStringImpl<double>(const char* data, size_t len, double& result) { + if (!len) { + return false; + } + char* se = nullptr; - double d = StrToD(data, data + len, &se); - - if (se != data + len) { - return false; - } - result = d; - return true; -} - -template <> -bool TryFromStringImpl<float>(const char* data, size_t len, float& result) { - double d; - if (TryFromStringImpl<double>(data, len, d)) { - result = static_cast<float>(d); - return true; - } - return false; -} - -template <> -bool TryFromStringImpl<long double>(const char* data, size_t len, long double& result) { - double d; - if (TryFromStringImpl<double>(data, len, d)) { - result = static_cast<long double>(d); - return true; - } - return false; -} - -// Exception-throwing, specialized for float types -template <> + double d = StrToD(data, data + len, &se); + + if (se != data + len) { + return false; + } + result = d; + return true; +} + +template <> +bool TryFromStringImpl<float>(const char* data, size_t len, float& result) { + double d; + if (TryFromStringImpl<double>(data, len, d)) { + result = static_cast<float>(d); + return true; + } + return false; +} + +template <> +bool TryFromStringImpl<long double>(const char* data, size_t len, long double& result) { + double d; + if (TryFromStringImpl<double>(data, len, d)) { + result = static_cast<long double>(d); + return true; + } + return false; +} + +// Exception-throwing, specialized for float types +template <> double FromStringImpl<double>(const char* data, size_t len) { - double d = 0.0; - if (!TryFromStringImpl(data, len, d)) { + double d = 0.0; + if (!TryFromStringImpl(data, len, d)) { ythrow TFromStringException() << TStringBuf("cannot parse float(") << TStringBuf(data, len) << TStringBuf(")"); } return d; @@ -690,7 +690,7 @@ double FromStringImpl<double>(const char* data, size_t len) { template <> float FromStringImpl<float>(const char* data, size_t len) { - return static_cast<float>(FromStringImpl<double>(data, len)); + return static_cast<float>(FromStringImpl<double>(data, len)); } double StrToD(const char* b, const char* e, char** se) { diff --git a/util/string/cast.h b/util/string/cast.h index 860af45dd6..90e925c194 100644 --- a/util/string/cast.h +++ b/util/string/cast.h @@ -14,7 +14,7 @@ template <class T> size_t ToStringImpl(T t, char* buf, size_t len); -/** +/** * Converts @c t to string writing not more than @c len bytes to output buffer @c buf. * No NULL terminator appended! Throws exception on buffer overflow. * @return number of bytes written @@ -215,27 +215,27 @@ inline ::NPrivate::TFromString<typename T::TChar> FromString(const T& s) { return ::NPrivate::TFromString<typename T::TChar>(s.data(), s.size()); } -// Conversion exception free versions -template <typename T, typename TChar> -bool TryFromStringImpl(const TChar* data, size_t len, T& result); - -/** - * @param data Source string buffer pointer - * @param len Source string length, in characters - * @param result Place to store conversion result value. - * If conversion error occurs, no value stored in @c result - * @return @c true in case of successful conversion, @c false otherwise - **/ -template <typename T, typename TChar> -inline bool TryFromString(const TChar* data, size_t len, T& result) { - return TryFromStringImpl<T>(data, len, result); -} - -template <typename T, typename TChar> -inline bool TryFromString(const TChar* data, T& result) { +// Conversion exception free versions +template <typename T, typename TChar> +bool TryFromStringImpl(const TChar* data, size_t len, T& result); + +/** + * @param data Source string buffer pointer + * @param len Source string length, in characters + * @param result Place to store conversion result value. + * If conversion error occurs, no value stored in @c result + * @return @c true in case of successful conversion, @c false otherwise + **/ +template <typename T, typename TChar> +inline bool TryFromString(const TChar* data, size_t len, T& result) { + return TryFromStringImpl<T>(data, len, result); +} + +template <typename T, typename TChar> +inline bool TryFromString(const TChar* data, T& result) { return TryFromString<T>(data, std::char_traits<TChar>::length(data), result); -} - +} + template <class T, class TChar> inline bool TryFromString(const TChar* data, const size_t len, T& result, const T& def) { if (TryFromString<T>(data, len, result)) { @@ -245,31 +245,31 @@ inline bool TryFromString(const TChar* data, const size_t len, T& result, const return false; } -template <class T> -inline bool TryFromString(const TStringBuf& s, T& result) { +template <class T> +inline bool TryFromString(const TStringBuf& s, T& result) { return TryFromString<T>(s.data(), s.size(), result); -} - -template <class T> +} + +template <class T> inline bool TryFromString(const TString& s, T& result) { return TryFromString<T>(s.data(), s.size(), result); -} - -template <class T> +} + +template <class T> inline bool TryFromString(const std::string& s, T& result) { return TryFromString<T>(s.data(), s.size(), result); } template <class T> -inline bool TryFromString(const TWtringBuf& s, T& result) { +inline bool TryFromString(const TWtringBuf& s, T& result) { return TryFromString<T>(s.data(), s.size(), result); -} - -template <class T> +} + +template <class T> inline bool TryFromString(const TUtf16String& s, T& result) { return TryFromString<T>(s.data(), s.size(), result); -} - +} + template <class T, class TStringType> inline bool TryFromStringWithDefault(const TStringType& s, T& result, const T& def) { return TryFromString<T>(s.data(), s.size(), result, def); diff --git a/util/string/cast_ut.cpp b/util/string/cast_ut.cpp index 56daa2dfec..033450c38c 100644 --- a/util/string/cast_ut.cpp +++ b/util/string/cast_ut.cpp @@ -3,16 +3,16 @@ #include <library/cpp/testing/unittest/registar.h> #include <util/charset/wide.h> -#include <util/system/defaults.h> +#include <util/system/defaults.h> #include <limits> -// positive test (return true or no exception) +// positive test (return true or no exception) #define test1(t, v) \ F<t>().CheckTryOK(v); \ F<t>().CheckOK(v) -// negative test (return false or exception) +// negative test (return false or exception) #define test2(t, v) \ F<t>().CheckTryFail(v); \ F<t>().CheckExc(v) @@ -22,7 +22,7 @@ #define HEX_MACROS_MAP(mac, type, val) mac(type, val, 2) mac(type, val, 8) mac(type, val, 10) mac(type, val, 16) #define OK_HEX_CHECK(type, val, base) UNIT_ASSERT_EQUAL((IntFromStringForCheck<base>(IntToString<base>(val))), val); -#define EXC_HEX_CHECK(type, val, base) UNIT_ASSERT_EXCEPTION((IntFromString<type, base>(IntToString<base>(val))), yexception); +#define EXC_HEX_CHECK(type, val, base) UNIT_ASSERT_EXCEPTION((IntFromString<type, base>(IntToString<base>(val))), yexception); #define TRY_HEX_MACROS_MAP(mac, type, val, result, def) \ mac(type, val, result, def, 2) \ @@ -53,33 +53,33 @@ struct TRet { } template <class B> - inline void CheckOK(B v) { + inline void CheckOK(B v) { UNIT_ASSERT_VALUES_EQUAL(FromString<A>(ToString(v)), v); // char UNIT_ASSERT_VALUES_EQUAL(FromString<A>(ToWtring(v)), v); // wide char - HEX_MACROS_MAP(OK_HEX_CHECK, A, v); + HEX_MACROS_MAP(OK_HEX_CHECK, A, v); } template <class B> - inline void CheckExc(B v) { - UNIT_ASSERT_EXCEPTION(FromString<A>(ToString(v)), yexception); // char - UNIT_ASSERT_EXCEPTION(FromString<A>(ToWtring(v)), yexception); // wide char - HEX_MACROS_MAP(EXC_HEX_CHECK, A, v); - } - - template <class B> - inline void CheckTryOK(B v) { + inline void CheckExc(B v) { + UNIT_ASSERT_EXCEPTION(FromString<A>(ToString(v)), yexception); // char + UNIT_ASSERT_EXCEPTION(FromString<A>(ToWtring(v)), yexception); // wide char + HEX_MACROS_MAP(EXC_HEX_CHECK, A, v); + } + + template <class B> + inline void CheckTryOK(B v) { static const A defaultV = 42; - A convV; + A convV; UNIT_ASSERT_VALUES_EQUAL(TryFromString<A>(ToString(v), convV), true); // char UNIT_ASSERT_VALUES_EQUAL(v, convV); UNIT_ASSERT_VALUES_EQUAL(TryFromString<A>(ToWtring(v), convV), true); // wide char UNIT_ASSERT_VALUES_EQUAL(v, convV); - + TRY_HEX_MACROS_MAP(TRY_OK_HEX_CHECK, A, v, convV, defaultV); - } - - template <class B> - inline void CheckTryFail(B v) { + } + + template <class B> + inline void CheckTryFail(B v) { static const A defaultV = 42; A convV = defaultV; // to check that original value is not trashed on bad cast UNIT_ASSERT_VALUES_EQUAL(TryFromString<A>(ToString(v), convV), false); // char @@ -88,35 +88,35 @@ struct TRet { UNIT_ASSERT_VALUES_EQUAL(defaultV, convV); TRY_HEX_MACROS_MAP(TRY_FAIL_HEX_CHECK, A, v, convV, defaultV); - } + } }; template <> struct TRet<bool> { template <class B> - inline void CheckOK(B v) { + inline void CheckOK(B v) { UNIT_ASSERT_VALUES_EQUAL(FromString<bool>(ToString(v)), v); } template <class B> - inline void CheckTryOK(B v) { - B convV; + inline void CheckTryOK(B v) { + B convV; UNIT_ASSERT_VALUES_EQUAL(TryFromString<bool>(ToString(v), convV), true); UNIT_ASSERT_VALUES_EQUAL(v, convV); - } - - template <class B> - inline void CheckExc(B v) { + } + + template <class B> + inline void CheckExc(B v) { UNIT_ASSERT_EXCEPTION(FromString<bool>(ToString(v)), yexception); } - - template <class B> - inline void CheckTryFail(B v) { + + template <class B> + inline void CheckTryFail(B v) { static const bool defaultV = false; bool convV = defaultV; UNIT_ASSERT_VALUES_EQUAL(TryFromString<bool>(ToString(v), convV), false); UNIT_ASSERT_VALUES_EQUAL(defaultV, convV); - } + } }; template <class A> @@ -125,30 +125,30 @@ inline TRet<A> F() { }; #if 0 -template <class T> +template <class T> inline void CheckConvertToBuffer(const T& value, const size_t size, const TString& canonValue) { - const size_t maxSize = 256; - char buffer[maxSize]; - const char magic = 0x7F; - memset(buffer, magic, maxSize); - size_t length = 0; - if (canonValue.size() > size) { // overflow will occur - UNIT_ASSERT_EXCEPTION(length = ToString(value, buffer, size), yexception); - // check that no bytes after size was trashed - for (size_t i = size; i < maxSize; ++i) + const size_t maxSize = 256; + char buffer[maxSize]; + const char magic = 0x7F; + memset(buffer, magic, maxSize); + size_t length = 0; + if (canonValue.size() > size) { // overflow will occur + UNIT_ASSERT_EXCEPTION(length = ToString(value, buffer, size), yexception); + // check that no bytes after size was trashed + for (size_t i = size; i < maxSize; ++i) UNIT_ASSERT_VALUES_EQUAL(buffer[i], magic); - } else { - length = ToString(value, buffer, size); - UNIT_ASSERT(length < maxSize); - // check that no bytes after length was trashed - for (size_t i = length; i < maxSize; ++i) + } else { + length = ToString(value, buffer, size); + UNIT_ASSERT(length < maxSize); + // check that no bytes after length was trashed + for (size_t i = length; i < maxSize; ++i) UNIT_ASSERT_VALUES_EQUAL(buffer[i], magic); - TStringBuf result(buffer, length); + TStringBuf result(buffer, length); UNIT_ASSERT_VALUES_EQUAL(result, TStringBuf(canonValue)); - } -} + } +} #endif - + Y_UNIT_TEST_SUITE(TCastTest) { template <class A> inline TRet<A> F() { @@ -332,14 +332,14 @@ Y_UNIT_TEST_SUITE(TCastTest) { CheckConvertToBuffer<float>(1.f, 5, "1"); CheckConvertToBuffer<float>(1.005f, 3, "1.005"); CheckConvertToBuffer<float>(1.00000000f, 3, "1"); - + CheckConvertToBuffer<double>(1.f, 5, "1"); CheckConvertToBuffer<double>(1.005f, 3, "1.005"); CheckConvertToBuffer<double>(1.00000000f, 3, "1"); - + CheckConvertToBuffer<int>(2, 5, "2"); CheckConvertToBuffer<int>(1005, 3, "1005"); - + CheckConvertToBuffer<size_t>(2, 5, "2"); CheckConvertToBuffer<ui64>(1005000000000000ull, 32, "1005000000000000"); CheckConvertToBuffer<ui64>(1005000000000000ull, 3, "1005000000000000"); @@ -348,29 +348,29 @@ Y_UNIT_TEST_SUITE(TCastTest) { // UNIT_ASSERT_EXCEPTION(FromString<double>(longNumber), yexception); } #endif - + Y_UNIT_TEST(TestWide) { TUtf16String iw = u"-100500"; int iv = 0; UNIT_ASSERT_VALUES_EQUAL(TryFromString(iw, iv), true); UNIT_ASSERT_VALUES_EQUAL(iv, -100500); - + ui64 uv = 0; TUtf16String uw = u"21474836470"; UNIT_ASSERT_VALUES_EQUAL(TryFromString(uw, uv), true); UNIT_ASSERT_VALUES_EQUAL(uv, 21474836470ull); - + TWtringBuf bw(uw.data(), uw.size()); uv = 0; UNIT_ASSERT_VALUES_EQUAL(TryFromString(uw, uv), true); UNIT_ASSERT_VALUES_EQUAL(uv, 21474836470ull); - + const wchar16* beg = uw.data(); uv = 0; UNIT_ASSERT_VALUES_EQUAL(TryFromString(beg, uw.size(), uv), true); UNIT_ASSERT_VALUES_EQUAL(uv, 21474836470ull); } - + Y_UNIT_TEST(TestDefault) { size_t res = 0; const size_t def1 = 42; @@ -438,17 +438,17 @@ Y_UNIT_TEST_SUITE(TCastTest) { } Y_UNIT_TEST(TestBool) { - // True cases - UNIT_ASSERT_VALUES_EQUAL(FromString<bool>("yes"), true); - UNIT_ASSERT_VALUES_EQUAL(FromString<bool>("1"), true); - // False cases - UNIT_ASSERT_VALUES_EQUAL(FromString<bool>("no"), false); - UNIT_ASSERT_VALUES_EQUAL(FromString<bool>("0"), false); - // Strange cases - UNIT_ASSERT_EXCEPTION(FromString<bool>(""), yexception); - UNIT_ASSERT_EXCEPTION(FromString<bool>("something"), yexception); - } - + // True cases + UNIT_ASSERT_VALUES_EQUAL(FromString<bool>("yes"), true); + UNIT_ASSERT_VALUES_EQUAL(FromString<bool>("1"), true); + // False cases + UNIT_ASSERT_VALUES_EQUAL(FromString<bool>("no"), false); + UNIT_ASSERT_VALUES_EQUAL(FromString<bool>("0"), false); + // Strange cases + UNIT_ASSERT_EXCEPTION(FromString<bool>(""), yexception); + UNIT_ASSERT_EXCEPTION(FromString<bool>("something"), yexception); + } + Y_UNIT_TEST(TestAutoDetectType) { UNIT_ASSERT_DOUBLES_EQUAL((float)FromString("0.0001"), 0.0001, EPS); UNIT_ASSERT_DOUBLES_EQUAL((double)FromString("0.0015", sizeof("0.0015") - 2), 0.001, EPS); @@ -463,52 +463,52 @@ Y_UNIT_TEST_SUITE(TCastTest) { ui16 wideCharacterCode = FromString(u"125"); UNIT_ASSERT_VALUES_EQUAL(integer, wideCharacterCode); } - + static void CheckMessage(TFromStringException& exc, const TString& phrase) { TString message = exc.what(); - if (!message.Contains(phrase)) { - Cerr << message << Endl; - UNIT_ASSERT(false); - } - } - + if (!message.Contains(phrase)) { + Cerr << message << Endl; + UNIT_ASSERT(false); + } + } + Y_UNIT_TEST(ErrorMessages) { - try { - FromString<ui32>(""); - UNIT_ASSERT(false); + try { + FromString<ui32>(""); + UNIT_ASSERT(false); } catch (TFromStringException& e) { - CheckMessage(e, "empty string as number"); - } - - try { - FromString<ui32>("-"); - UNIT_ASSERT(false); + CheckMessage(e, "empty string as number"); + } + + try { + FromString<ui32>("-"); + UNIT_ASSERT(false); } catch (TFromStringException& e) { - // Unsigned should have no sign at all, so - is not expected - CheckMessage(e, "Unexpected symbol \"-\" at pos 0 in string \"-\""); - } - - try { - FromString<i32>("-"); - UNIT_ASSERT(false); + // Unsigned should have no sign at all, so - is not expected + CheckMessage(e, "Unexpected symbol \"-\" at pos 0 in string \"-\""); + } + + try { + FromString<i32>("-"); + UNIT_ASSERT(false); } catch (TFromStringException& e) { - CheckMessage(e, "Cannot parse string \"-\" as number"); - } - - try { - FromString<i32>("+"); - UNIT_ASSERT(false); + CheckMessage(e, "Cannot parse string \"-\" as number"); + } + + try { + FromString<i32>("+"); + UNIT_ASSERT(false); } catch (TFromStringException& e) { - CheckMessage(e, "Cannot parse string \"+\" as number"); - } - - try { - FromString<ui32>("0.328413745072"); - UNIT_ASSERT(false); + CheckMessage(e, "Cannot parse string \"+\" as number"); + } + + try { + FromString<ui32>("0.328413745072"); + UNIT_ASSERT(false); } catch (TFromStringException& e) { - CheckMessage(e, "Unexpected symbol \".\" at pos 1 in string \"0.328413745072\""); - } - } + CheckMessage(e, "Unexpected symbol \".\" at pos 1 in string \"0.328413745072\""); + } + } Y_UNIT_TEST(TryStringBuf) { { diff --git a/util/string/hex.h b/util/string/hex.h index c4605c6087..af3d2d528f 100644 --- a/util/string/hex.h +++ b/util/string/hex.h @@ -1,7 +1,7 @@ #pragma once #include <util/generic/string.h> -#include <util/generic/yexception.h> +#include <util/generic/yexception.h> #include <util/system/yassert.h> inline static char DigitToChar(unsigned char digit) { diff --git a/util/string/strip.cpp b/util/string/strip.cpp index bcc63f0e81..c921571cf0 100644 --- a/util/string/strip.cpp +++ b/util/string/strip.cpp @@ -8,10 +8,10 @@ bool Collapse(const TString& from, TString& to, size_t maxLen) { } void CollapseText(const TString& from, TString& to, size_t maxLen) { - Collapse(from, to, maxLen); + Collapse(from, to, maxLen); StripInPlace(to); if (to.size() >= maxLen) { - to.remove(maxLen - 5); // " ..." + to.remove(maxLen - 5); // " ..." ReverseInPlace(to); size_t pos = to.find_first_of(" .,;"); if (pos != TString::npos && pos < 32) { diff --git a/util/string/strip.h b/util/string/strip.h index eb9b684941..d5ef6da96d 100644 --- a/util/string/strip.h +++ b/util/string/strip.h @@ -170,29 +170,29 @@ static inline T StripStringRight(const T& from) { template <class T, class TStripCriterion> static inline T StripStringLeft(const T& from, TStripCriterion&& criterion) { return TStripImpl<true, false>::StripString(from, criterion); -} - +} + template <class T, class TStripCriterion> static inline T StripStringRight(const T& from, TStripCriterion&& criterion) { return TStripImpl<false, true>::StripString(from, criterion); -} - +} + /// Copies the given string removing leading and trailing spaces. static inline bool Strip(const TString& from, TString& to) { - return StripString(from, to); -} + return StripString(from, to); +} /// Removes leading and trailing spaces from the string. inline TString& StripInPlace(TString& s) { - Strip(s, s); - return s; -} + Strip(s, s); + return s; +} /// Returns a copy of the given string with removed leading and trailing spaces. inline TString Strip(const TString& s) Y_WARN_UNUSED_RESULT; inline TString Strip(const TString& s) { TString ret = s; - Strip(ret, ret); + Strip(ret, ret); return ret; } @@ -234,7 +234,7 @@ bool Collapse(const TString& from, TString& to, size_t maxLen = 0); /// Replaces several consequtive space symbols with one (processing is limited to maxLen bytes) inline TString& CollapseInPlace(TString& s, size_t maxLen = 0) { - Collapse(s, s, maxLen); + Collapse(s, s, maxLen); return s; } @@ -242,7 +242,7 @@ inline TString& CollapseInPlace(TString& s, size_t maxLen = 0) { inline TString Collapse(const TString& s, size_t maxLen = 0) Y_WARN_UNUSED_RESULT; inline TString Collapse(const TString& s, size_t maxLen) { TString ret; - Collapse(s, ret, maxLen); + Collapse(s, ret, maxLen); return ret; } @@ -252,6 +252,6 @@ void CollapseText(const TString& from, TString& to, size_t maxLen); /// @details An ellipsis is inserted at the end of the truncated line. inline void CollapseText(TString& s, size_t maxLen) { TString to; - CollapseText(s, to, maxLen); + CollapseText(s, to, maxLen); s = to; } diff --git a/util/string/strip_ut.cpp b/util/string/strip_ut.cpp index 0a6b8e362f..d1029d1498 100644 --- a/util/string/strip_ut.cpp +++ b/util/string/strip_ut.cpp @@ -6,25 +6,25 @@ Y_UNIT_TEST_SUITE(TStripStringTest) { Y_UNIT_TEST(TestStrip) { - struct TTest { + struct TTest { const char* Str; const char* StripLeftRes; const char* StripRightRes; const char* StripRes; - }; - static const TTest tests[] = { - {" 012 ", "012 ", " 012", "012"}, - {" 012", "012", " 012", "012"}, - {"012\t\t", "012\t\t", "012", "012"}, - {"\t012\t", "012\t", "\t012", "012"}, - {"012", "012", "012", "012"}, - {"012\r\n", "012\r\n", "012", "012"}, - {"\n012\r", "012\r", "\n012", "012"}, - {"\n \t\r", "", "", ""}, - {"", "", "", ""}, - {"abc", "abc", "abc", "abc"}, - {"a c", "a c", "a c", "a c"}, - }; + }; + static const TTest tests[] = { + {" 012 ", "012 ", " 012", "012"}, + {" 012", "012", " 012", "012"}, + {"012\t\t", "012\t\t", "012", "012"}, + {"\t012\t", "012\t", "\t012", "012"}, + {"012", "012", "012", "012"}, + {"012\r\n", "012\r\n", "012", "012"}, + {"\n012\r", "012\r", "\n012", "012"}, + {"\n \t\r", "", "", ""}, + {"", "", "", ""}, + {"abc", "abc", "abc", "abc"}, + {"a c", "a c", "a c", "a c"}, + }; for (const auto& test : tests) { TString inputStr(test.Str); @@ -45,16 +45,16 @@ Y_UNIT_TEST_SUITE(TStripStringTest) { } Y_UNIT_TEST(TestCustomStrip) { - struct TTest { + struct TTest { const char* Str; const char* Result; - }; - static const TTest tests[] = { - {"//012//", "012"}, - {"//012", "012"}, - {"012", "012"}, - {"012//", "012"}, - }; + }; + static const TTest tests[] = { + {"//012//", "012"}, + {"//012", "012"}, + {"012", "012"}, + {"012//", "012"}, + }; for (auto test : tests) { UNIT_ASSERT_EQUAL( @@ -64,28 +64,28 @@ Y_UNIT_TEST_SUITE(TStripStringTest) { } Y_UNIT_TEST(TestCustomStripLeftRight) { - struct TTest { - const char* Str; - const char* ResultLeft; - const char* ResultRight; - }; - static const TTest tests[] = { - {"//012//", "012//", "//012"}, - {"//012", "012", "//012"}, - {"012", "012", "012"}, - {"012//", "012//", "012"}, - }; - + struct TTest { + const char* Str; + const char* ResultLeft; + const char* ResultRight; + }; + static const TTest tests[] = { + {"//012//", "012//", "//012"}, + {"//012", "012", "//012"}, + {"012", "012", "012"}, + {"012//", "012//", "012"}, + }; + for (const auto& test : tests) { - UNIT_ASSERT_EQUAL( + UNIT_ASSERT_EQUAL( StripStringLeft(TString(test.Str), EqualsStripAdapter('/')), test.ResultLeft); - UNIT_ASSERT_EQUAL( + UNIT_ASSERT_EQUAL( StripStringRight(TString(test.Str), EqualsStripAdapter('/')), test.ResultRight); - }; - } - + }; + } + Y_UNIT_TEST(TestNullStringStrip) { TStringBuf nullString(nullptr, nullptr); UNIT_ASSERT_EQUAL( @@ -128,11 +128,11 @@ Y_UNIT_TEST_SUITE(TStripStringTest) { TString abs1("Very long description string written in unknown language."); TString abs2(abs1); TString abs3(abs1); - CollapseText(abs1, 204); - CollapseText(abs2, 54); - CollapseText(abs3, 49); - UNIT_ASSERT_EQUAL(abs1 == "Very long description string written in unknown language.", true); - UNIT_ASSERT_EQUAL(abs2 == "Very long description string written in unknown ...", true); - UNIT_ASSERT_EQUAL(abs3 == "Very long description string written in ...", true); + CollapseText(abs1, 204); + CollapseText(abs2, 54); + CollapseText(abs3, 49); + UNIT_ASSERT_EQUAL(abs1 == "Very long description string written in unknown language.", true); + UNIT_ASSERT_EQUAL(abs2 == "Very long description string written in unknown ...", true); + UNIT_ASSERT_EQUAL(abs3 == "Very long description string written in ...", true); } } diff --git a/util/string/subst.h b/util/string/subst.h index ab8ea56a56..45b622fbef 100644 --- a/util/string/subst.h +++ b/util/string/subst.h @@ -3,7 +3,7 @@ #include <util/generic/fwd.h> #include <stlfwd> - + /* Replace all occurences of substring `what` with string `with` starting from position `from`. * * @param text String to modify. @@ -18,7 +18,7 @@ size_t SubstGlobal(std::string& text, TStringBuf what, TStringBuf with, size_t f size_t SubstGlobal(TUtf16String& text, TWtringBuf what, TWtringBuf with, size_t from = 0); size_t SubstGlobal(std::u16string& text, TWtringBuf what, TWtringBuf with, size_t from = 0); size_t SubstGlobal(TUtf32String& text, TUtf32StringBuf what, TUtf32StringBuf with, size_t from = 0); - + /* Replace all occurences of character `what` with character `with` starting from position `from`. * * @param text String to modify. diff --git a/util/string/subst_ut.cpp b/util/string/subst_ut.cpp index 04ca5cdf60..21eccef779 100644 --- a/util/string/subst_ut.cpp +++ b/util/string/subst_ut.cpp @@ -1,6 +1,6 @@ #include "join.h" #include "subst.h" -#include <string> +#include <string> #include <library/cpp/testing/unittest/registar.h> @@ -169,7 +169,7 @@ Y_UNIT_TEST_SUITE(TStringSubst) { SubstGlobal(s, 'a', 'b', 1); UNIT_ASSERT_EQUAL(s, TString("abb")); } - + Y_UNIT_TEST(TestSubstCharGlobalRet) { const TUtf16String w1 = u"abcdabcd"; const TUtf16String w2 = SubstGlobalCopy(w1, wchar16('b'), wchar16('B'), 3); @@ -181,10 +181,10 @@ Y_UNIT_TEST_SUITE(TStringSubst) { } Y_UNIT_TEST(TestSubstStdString) { - std::string s = "aaa"; - SubstGlobal(s, "a", "b", 1); - UNIT_ASSERT_EQUAL(s, "abb"); - } + std::string s = "aaa"; + SubstGlobal(s, "a", "b", 1); + UNIT_ASSERT_EQUAL(s, "abb"); + } Y_UNIT_TEST(TestSubstStdStringRet) { const std::string s1 = "aaa"; diff --git a/util/string/type_ut.cpp b/util/string/type_ut.cpp index 3916914e23..03e7af62bd 100644 --- a/util/string/type_ut.cpp +++ b/util/string/type_ut.cpp @@ -13,31 +13,31 @@ Y_UNIT_TEST_SUITE(TStringClassify) { } Y_UNIT_TEST(TestIsTrue) { - UNIT_ASSERT(IsTrue("1")); - UNIT_ASSERT(IsTrue("yes")); - UNIT_ASSERT(IsTrue("YeS")); - UNIT_ASSERT(IsTrue("on")); - UNIT_ASSERT(IsTrue("true")); + UNIT_ASSERT(IsTrue("1")); + UNIT_ASSERT(IsTrue("yes")); + UNIT_ASSERT(IsTrue("YeS")); + UNIT_ASSERT(IsTrue("on")); + UNIT_ASSERT(IsTrue("true")); UNIT_ASSERT(IsTrue("t")); - UNIT_ASSERT(IsTrue("da")); + UNIT_ASSERT(IsTrue("da")); UNIT_ASSERT(!IsTrue("")); UNIT_ASSERT(!IsTrue("tr")); - UNIT_ASSERT(!IsTrue("foobar")); + UNIT_ASSERT(!IsTrue("foobar")); } - + Y_UNIT_TEST(TestIsFalse) { - UNIT_ASSERT(IsFalse("0")); - UNIT_ASSERT(IsFalse("no")); - UNIT_ASSERT(IsFalse("off")); - UNIT_ASSERT(IsFalse("false")); + UNIT_ASSERT(IsFalse("0")); + UNIT_ASSERT(IsFalse("no")); + UNIT_ASSERT(IsFalse("off")); + UNIT_ASSERT(IsFalse("false")); UNIT_ASSERT(IsFalse("f")); - UNIT_ASSERT(IsFalse("net")); - + UNIT_ASSERT(IsFalse("net")); + UNIT_ASSERT(!IsFalse("")); UNIT_ASSERT(!IsFalse("fa")); - UNIT_ASSERT(!IsFalse("foobar")); - } + UNIT_ASSERT(!IsFalse("foobar")); + } Y_UNIT_TEST(TestIsNumber) { UNIT_ASSERT(IsNumber("0")); diff --git a/util/system/compiler.h b/util/system/compiler.h index 95a67945d7..b373edcc46 100644 --- a/util/system/compiler.h +++ b/util/system/compiler.h @@ -287,7 +287,7 @@ _YandexAbort(); #endif #else - + #if defined(thread_sanitizer_enabled) || defined(__SANITIZE_THREAD__) #define _tsan_enabled_ #endif diff --git a/util/system/datetime.h b/util/system/datetime.h index d3982a047c..aa009974e0 100644 --- a/util/system/datetime.h +++ b/util/system/datetime.h @@ -17,14 +17,14 @@ /// Current time in microseconds since epoch ui64 MicroSeconds() noexcept; -/// Current time in milliseconds since epoch -inline ui64 MilliSeconds() { - return MicroSeconds() / ui64(1000); -} -/// Current time in milliseconds since epoch (deprecated, use MilliSeconds instead) -inline ui64 millisec() { - return MilliSeconds(); -} +/// Current time in milliseconds since epoch +inline ui64 MilliSeconds() { + return MicroSeconds() / ui64(1000); +} +/// Current time in milliseconds since epoch (deprecated, use MilliSeconds instead) +inline ui64 millisec() { + return MilliSeconds(); +} /// Current time in seconds since epoch ui32 Seconds() noexcept; ///Current thread time in microseconds diff --git a/util/system/direct_io_ut.cpp b/util/system/direct_io_ut.cpp index a3c56fbd96..839c3de7ca 100644 --- a/util/system/direct_io_ut.cpp +++ b/util/system/direct_io_ut.cpp @@ -23,19 +23,19 @@ Y_UNIT_TEST_SUITE(TDirectIoTestSuite) { writePos += writeCount; size_t readPos = RandomNumber(writePos); size_t readCount = RandomNumber(writePos - readPos); - UNIT_ASSERT_VALUES_EQUAL( + UNIT_ASSERT_VALUES_EQUAL( file.Pread(&readResult[0], readCount * sizeof(ui64), readPos * sizeof(ui64)), readCount * sizeof(ui64)); - for (size_t i = 0; i < readCount; ++i) { + for (size_t i = 0; i < readCount; ++i) { UNIT_ASSERT_VALUES_EQUAL(readResult[i], data[i + readPos]); - } + } } file.Finish(); TDirectIOBufferedFile fileNew(FileName_, RdOnly | Direct | Seq | OpenAlways, 1 << 15); for (int i = 0; i < 1000; ++i) { size_t readPos = RandomNumber(data.size()); size_t readCount = RandomNumber(data.size() - readPos); - UNIT_ASSERT_VALUES_EQUAL( + UNIT_ASSERT_VALUES_EQUAL( fileNew.Pread(&readResult[0], readCount * sizeof(ui64), readPos * sizeof(ui64)), readCount * sizeof(ui64)); for (size_t j = 0; j < readCount; ++j) { @@ -43,12 +43,12 @@ Y_UNIT_TEST_SUITE(TDirectIoTestSuite) { } } size_t readCount = data.size(); - UNIT_ASSERT_VALUES_EQUAL( + UNIT_ASSERT_VALUES_EQUAL( fileNew.Pread(&readResult[0], readCount * sizeof(ui64), 0), readCount * sizeof(ui64)); - for (size_t i = 0; i < readCount; ++i) { + for (size_t i = 0; i < readCount; ++i) { UNIT_ASSERT_VALUES_EQUAL(readResult[i], data[i]); - } + } NFs::Remove(FileName_); } diff --git a/util/system/env.cpp b/util/system/env.cpp index edc539a702..ead9b566a5 100644 --- a/util/system/env.cpp +++ b/util/system/env.cpp @@ -1,8 +1,8 @@ -#include "env.h" - +#include "env.h" + #include <util/generic/string.h> #include <util/generic/yexception.h> - + #ifdef _win_ #include <util/generic/vector.h> #include "winint.h" @@ -10,7 +10,7 @@ #include <cerrno> #include <cstdlib> #endif - + /** * On Windows there may be many copies of enviroment variables, there at least two known, one is * manipulated by Win32 API, another by C runtime, so we must be consistent in the choice of @@ -22,7 +22,7 @@ */ TString GetEnv(const TString& key, const TString& def) { -#ifdef _win_ +#ifdef _win_ size_t len = GetEnvironmentVariableA(key.data(), nullptr, 0); if (len == 0) { @@ -43,25 +43,25 @@ TString GetEnv(const TString& key, const TString& def) { } while (len > bufferSize); return TString(buffer.data(), len); -#else +#else const char* env = getenv(key.data()); return env ? TString(env) : def; -#endif -} - +#endif +} + void SetEnv(const TString& key, const TString& value) { bool isOk = false; int errorCode = 0; -#ifdef _win_ +#ifdef _win_ isOk = SetEnvironmentVariable(key.data(), value.data()); if (!isOk) { errorCode = GetLastError(); } -#else +#else isOk = (0 == setenv(key.data(), value.data(), true /*replace*/)); if (!isOk) { errorCode = errno; } -#endif +#endif Y_ENSURE_EX(isOk, TSystemError() << "failed to SetEnv with error-code " << errorCode); -} +} diff --git a/util/system/env.h b/util/system/env.h index 6af09425be..e2ccdd1e95 100644 --- a/util/system/env.h +++ b/util/system/env.h @@ -1,7 +1,7 @@ -#pragma once - +#pragma once + #include <util/generic/string.h> - + /** * Search the environment list provided by the host environment for associated variable. * diff --git a/util/system/env_ut.cpp b/util/system/env_ut.cpp index 32e3a39956..e03cc01658 100644 --- a/util/system/env_ut.cpp +++ b/util/system/env_ut.cpp @@ -1,8 +1,8 @@ #include <library/cpp/testing/unittest/registar.h> - + #include <util/generic/string.h> #include "env.h" - + Y_UNIT_TEST_SUITE(EnvTest) { Y_UNIT_TEST(GetSetEnvTest) { TString key = "util_GETENV_TestVar"; @@ -28,4 +28,4 @@ Y_UNIT_TEST_SUITE(EnvTest) { SetEnv(longKey, TString()); UNIT_ASSERT_VALUES_EQUAL(GetEnv(longKey), TString()); } -} +} diff --git a/util/system/execpath.h b/util/system/execpath.h index 5c476042c7..4b914b8e85 100644 --- a/util/system/execpath.h +++ b/util/system/execpath.h @@ -2,7 +2,7 @@ #include <util/generic/fwd.h> -// NOTE: This function has rare sporadic failures (throws exceptions) on FreeBSD. See REVIEW:54297 +// NOTE: This function has rare sporadic failures (throws exceptions) on FreeBSD. See REVIEW:54297 const TString& GetExecPath(); /** diff --git a/util/system/file_lock.cpp b/util/system/file_lock.cpp index 55160d287f..45d91282c5 100644 --- a/util/system/file_lock.cpp +++ b/util/system/file_lock.cpp @@ -1,8 +1,8 @@ -#include "file_lock.h" +#include "file_lock.h" #include "flock.h" - + #include <util/generic/yexception.h> - + #include <cerrno> namespace { @@ -22,13 +22,13 @@ namespace { TFileLock::TFileLock(const TString& filename, const EFileLockType type) : TFile(filename, OpenAlways | RdOnly) , Type(type) -{ -} - -void TFileLock::Acquire() { +{ +} + +void TFileLock::Acquire() { Flock(GetMode(Type)); -} - +} + bool TFileLock::TryAcquire() { try { Flock(GetMode(Type) | LOCK_NB); @@ -41,6 +41,6 @@ bool TFileLock::TryAcquire() { } } -void TFileLock::Release() { - Flock(LOCK_UN); -} +void TFileLock::Release() { + Flock(LOCK_UN); +} diff --git a/util/system/file_lock.h b/util/system/file_lock.h index ac3f95306f..b2aaff5baf 100644 --- a/util/system/file_lock.h +++ b/util/system/file_lock.h @@ -1,9 +1,9 @@ -#pragma once - +#pragma once + #include <util/generic/fwd.h> -#include <util/generic/noncopyable.h> +#include <util/generic/noncopyable.h> #include <util/system/file.h> - + enum class EFileLockType { Exclusive, Shared @@ -13,9 +13,9 @@ class TFileLock: public TFile { public: TFileLock(const TString& filename, const EFileLockType type = EFileLockType::Exclusive); - void Acquire(); + void Acquire(); bool TryAcquire(); - void Release(); + void Release(); inline void lock() { Acquire(); @@ -31,4 +31,4 @@ public: private: EFileLockType Type; -}; +}; diff --git a/util/system/filemap.cpp b/util/system/filemap.cpp index cfab1b6aca..7454a4cb94 100644 --- a/util/system/filemap.cpp +++ b/util/system/filemap.cpp @@ -74,7 +74,7 @@ namespace { TString TMemoryMapCommon::UnknownFileName() { return "Unknown_file_name"; } - + static inline i64 DownToGranularity(i64 offset) noexcept { return offset & ~((i64)(GRANULARITY - 1)); } diff --git a/util/system/filemap.h b/util/system/filemap.h index a6e97dabaf..11be64bff4 100644 --- a/util/system/filemap.h +++ b/util/system/filemap.h @@ -59,8 +59,8 @@ struct TMemoryMapCommon { oPopulate = 32, // Populate page table entries (see mmap's MAP_POPULATE) }; Y_DECLARE_FLAGS(EOpenMode, EOpenModeFlag) - - /** + + /** * Name that will be printed in exceptions if not specified. * Overridden by name obtained from `TFile` if it's not empty. */ @@ -184,16 +184,16 @@ private: }; template <class T> -class TFileMappedArray { -private: - const T* Ptr_; - const T* End_; +class TFileMappedArray { +private: + const T* Ptr_; + const T* End_; size_t Size_; char DummyData_[sizeof(T) + PLATFORM_DATA_ALIGN]; mutable THolder<T, TDestructor> Dummy_; - THolder<TFileMap> DataHolder_; + THolder<TFileMap> DataHolder_; -public: +public: TFileMappedArray() : Ptr_(nullptr) , End_(nullptr) @@ -204,34 +204,34 @@ public: Ptr_ = nullptr; End_ = nullptr; } - void Init(const char* name) { - DataHolder_.Reset(new TFileMap(name)); - DoInit(name); + void Init(const char* name) { + DataHolder_.Reset(new TFileMap(name)); + DoInit(name); + } + void Init(const TFileMap& fileMap) { + DataHolder_.Reset(new TFileMap(fileMap)); + DoInit(fileMap.GetFile().GetName()); } - void Init(const TFileMap& fileMap) { - DataHolder_.Reset(new TFileMap(fileMap)); - DoInit(fileMap.GetFile().GetName()); - } - void Term() { - DataHolder_.Destroy(); + void Term() { + DataHolder_.Destroy(); Ptr_ = nullptr; Size_ = 0; End_ = nullptr; } - void Precharge() { - DataHolder_->Precharge(); - } + void Precharge() { + DataHolder_->Precharge(); + } const T& operator[](size_t pos) const { Y_ASSERT(pos < size()); return Ptr_[pos]; } - /// for STL compatibility only, Size() usage is recommended + /// for STL compatibility only, Size() usage is recommended size_t size() const { return Size_; } - size_t Size() const { - return Size_; - } + size_t Size() const { + return Size_; + } const T& GetAt(size_t pos) const { if (pos < Size_) return Ptr_[pos]; @@ -251,40 +251,40 @@ public: return *Dummy_; } - /// for STL compatibility only, Empty() usage is recommended + /// for STL compatibility only, Empty() usage is recommended Y_PURE_FUNCTION bool empty() const noexcept { - return Empty(); - } + return Empty(); + } Y_PURE_FUNCTION bool Empty() const noexcept { return 0 == Size_; } - /// for STL compatibility only, Begin() usage is recommended + /// for STL compatibility only, Begin() usage is recommended const T* begin() const noexcept { - return Begin(); - } + return Begin(); + } const T* Begin() const noexcept { return Ptr_; } - /// for STL compatibility only, End() usage is recommended + /// for STL compatibility only, End() usage is recommended const T* end() const noexcept { return End_; } const T* End() const noexcept { - return End_; - } + return End_; + } -private: +private: void DoInit(const TString& fileName) { - DataHolder_->Map(0, DataHolder_->Length()); - if (DataHolder_->Length() % sizeof(T)) { - Term(); - ythrow yexception() << "Incorrect size of file " << fileName.Quote(); - } - Ptr_ = (const T*)DataHolder_->Ptr(); - Size_ = DataHolder_->Length() / sizeof(T); - End_ = Ptr_ + Size_; - } + DataHolder_->Map(0, DataHolder_->Length()); + if (DataHolder_->Length() % sizeof(T)) { + Term(); + ythrow yexception() << "Incorrect size of file " << fileName.Quote(); + } + Ptr_ = (const T*)DataHolder_->Ptr(); + Size_ = DataHolder_->Length() / sizeof(T); + End_ = Ptr_ + Size_; + } }; class TMappedAllocation: TMoveOnly { diff --git a/util/system/filemap_ut.cpp b/util/system/filemap_ut.cpp index 62755f7547..73f109dc88 100644 --- a/util/system/filemap_ut.cpp +++ b/util/system/filemap_ut.cpp @@ -12,7 +12,7 @@ #include <cstdio> Y_UNIT_TEST_SUITE(TFileMapTest) { - static const char* FileName_("./mappped_file"); + static const char* FileName_("./mappped_file"); void BasicTest(TMemoryMapCommon::EOpenMode mode) { char data[] = "abcdefgh"; @@ -132,7 +132,7 @@ Y_UNIT_TEST_SUITE(TFileMapTest) { //cygwin is not real unix :( #else Y_UNIT_TEST(TestNotGreedy) { - unsigned page[4096 / sizeof(unsigned)]; + unsigned page[4096 / sizeof(unsigned)]; #if defined(_unix_) // Temporary limit allowed virtual memory size to 1Gb @@ -221,49 +221,49 @@ Y_UNIT_TEST_SUITE(TFileMapTest) { file.Write(static_cast<void*>(data), sizeof(data)); file.Close(); - mappedArray.Init(FileName_); - // actual test begin - UNIT_ASSERT(mappedArray.Size() == sz); + mappedArray.Init(FileName_); + // actual test begin + UNIT_ASSERT(mappedArray.Size() == sz); for (size_t i = 0; i < sz; ++i) { UNIT_ASSERT(mappedArray[i] == data[i]); } - - UNIT_ASSERT(mappedArray.GetAt(mappedArray.Size()) == 0); - UNIT_ASSERT(*mappedArray.Begin() == data[0]); - UNIT_ASSERT(size_t(mappedArray.End() - mappedArray.Begin()) == sz); - UNIT_ASSERT(!mappedArray.Empty()); - // actual test end - mappedArray.Term(); - - // Init array via file mapping - TFileMap fileMap(FileName_); - fileMap.Map(0, fileMap.Length()); - mappedArray.Init(fileMap); - - // actual test begin - UNIT_ASSERT(mappedArray.Size() == sz); + + UNIT_ASSERT(mappedArray.GetAt(mappedArray.Size()) == 0); + UNIT_ASSERT(*mappedArray.Begin() == data[0]); + UNIT_ASSERT(size_t(mappedArray.End() - mappedArray.Begin()) == sz); + UNIT_ASSERT(!mappedArray.Empty()); + // actual test end + mappedArray.Term(); + + // Init array via file mapping + TFileMap fileMap(FileName_); + fileMap.Map(0, fileMap.Length()); + mappedArray.Init(fileMap); + + // actual test begin + UNIT_ASSERT(mappedArray.Size() == sz); for (size_t i = 0; i < sz; ++i) { - UNIT_ASSERT(mappedArray[i] == data[i]); + UNIT_ASSERT(mappedArray[i] == data[i]); } - - UNIT_ASSERT(mappedArray.GetAt(mappedArray.Size()) == 0); - UNIT_ASSERT(*mappedArray.Begin() == data[0]); - UNIT_ASSERT(size_t(mappedArray.End() - mappedArray.Begin()) == sz); - UNIT_ASSERT(!mappedArray.Empty()); - // actual test end - + + UNIT_ASSERT(mappedArray.GetAt(mappedArray.Size()) == 0); + UNIT_ASSERT(*mappedArray.Begin() == data[0]); + UNIT_ASSERT(size_t(mappedArray.End() - mappedArray.Begin()) == sz); + UNIT_ASSERT(!mappedArray.Empty()); + // actual test end + file = TFile(FileName_, WrOnly); file.Seek(0, sEnd); file.Write("x", 1); file.Close(); - bool caught = false; + bool caught = false; try { - mappedArray.Init(FileName_); + mappedArray.Init(FileName_); } catch (const yexception&) { - caught = true; + caught = true; } - UNIT_ASSERT(caught); + UNIT_ASSERT(caught); } NFs::Remove(FileName_); } @@ -291,32 +291,32 @@ Y_UNIT_TEST_SUITE(TFileMapTest) { } Y_UNIT_TEST(TestMemoryMap) { - TFile file(FileName_, CreateAlways | WrOnly); - file.Close(); - - FILE* f = fopen(FileName_, "rb"); + TFile file(FileName_, CreateAlways | WrOnly); + file.Close(); + + FILE* f = fopen(FileName_, "rb"); UNIT_ASSERT(f != nullptr); - try { - TMemoryMap mappedMem(f); - mappedMem.Map(mappedMem.Length() / 2, mappedMem.Length() + 100); // overflow + try { + TMemoryMap mappedMem(f); + mappedMem.Map(mappedMem.Length() / 2, mappedMem.Length() + 100); // overflow UNIT_ASSERT(0); // should not go here } catch (yexception& exc) { TString text = exc.what(); // exception should contain failed file name UNIT_ASSERT(text.find(TMemoryMapCommon::UnknownFileName()) != TString::npos); - fclose(f); - } - - TFile fileForMap(FileName_, OpenExisting); - try { - TMemoryMap mappedMem(fileForMap); - mappedMem.Map(mappedMem.Length() / 2, mappedMem.Length() + 100); // overflow + fclose(f); + } + + TFile fileForMap(FileName_, OpenExisting); + try { + TMemoryMap mappedMem(fileForMap); + mappedMem.Map(mappedMem.Length() / 2, mappedMem.Length() + 100); // overflow UNIT_ASSERT(0); // should not go here } catch (yexception& exc) { TString text = exc.what(); // exception should contain failed file name UNIT_ASSERT(text.find(FileName_) != TString::npos); - } + } NFs::Remove(FileName_); - } + } Y_UNIT_TEST(TestMemoryMapIsWritable) { TFile file(FileName_, CreateAlways | WrOnly); diff --git a/util/system/flock.h b/util/system/flock.h index 210e834825..797b1970a1 100644 --- a/util/system/flock.h +++ b/util/system/flock.h @@ -2,7 +2,7 @@ #include "error.h" #include "defaults.h" -#include "file.h" +#include "file.h" #if defined(_unix_) @@ -13,7 +13,7 @@ static inline int Flock(int fd, int op) { return flock(fd, op); } -#else // not _unix_ +#else // not _unix_ #ifdef __cplusplus extern "C" { @@ -32,4 +32,4 @@ extern "C" { } #endif -#endif // not _unix_ +#endif // not _unix_ diff --git a/util/system/flock_ut.cpp b/util/system/flock_ut.cpp index 2bb705944c..b5f6cb5328 100644 --- a/util/system/flock_ut.cpp +++ b/util/system/flock_ut.cpp @@ -1,6 +1,6 @@ #include "flock.h" -#include "file_lock.h" -#include "guard.h" +#include "file_lock.h" +#include "guard.h" #include "tempfile.h" #include <library/cpp/testing/unittest/registar.h> @@ -14,15 +14,15 @@ Y_UNIT_TEST_SUITE(TFileLockTest) { } Y_UNIT_TEST(TestFileLocker) { - TTempFileHandle tmp("./file.locker"); + TTempFileHandle tmp("./file.locker"); TFileLock fileLockExclusive1("./file.locker"); TFileLock fileLockExclusive2("./file.locker"); TFileLock fileLockShared1("./file.locker", EFileLockType::Shared); TFileLock fileLockShared2("./file.locker", EFileLockType::Shared); TFileLock fileLockShared3("./file.locker", EFileLockType::Shared); - { + { TGuard<TFileLock> guard(fileLockExclusive1); - } + } { TTryGuard<TFileLock> tryGuard(fileLockExclusive1); UNIT_ASSERT(tryGuard.WasAcquired()); @@ -53,5 +53,5 @@ Y_UNIT_TEST_SUITE(TFileLockTest) { UNIT_ASSERT(!guard2.WasAcquired()); UNIT_ASSERT(guard3.WasAcquired()); } - } -} + } +} diff --git a/util/system/fstat.cpp b/util/system/fstat.cpp index 27f0de682b..81e98cbc6b 100644 --- a/util/system/fstat.cpp +++ b/util/system/fstat.cpp @@ -3,7 +3,7 @@ #include <sys/stat.h> -#include <util/folder/path.h> +#include <util/folder/path.h> #include <cerrno> @@ -82,7 +82,7 @@ static bool GetStatByHandle(TSystemFStat& fs, FHANDLE f) { #endif } -static bool GetStatByName(TSystemFStat& fs, const char* fileName, bool nofollow) { +static bool GetStatByName(TSystemFStat& fs, const char* fileName, bool nofollow) { #ifdef _win_ TFileHandle h = NFsPrivate::CreateFileWithUtf8Name(fileName, FILE_READ_ATTRIBUTES | FILE_READ_EA, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, @@ -92,7 +92,7 @@ static bool GetStatByName(TSystemFStat& fs, const char* fileName, bool nofollow) } return GetStatByHandle(fs, h); #else - return !(nofollow ? lstat : stat)(fileName, &fs); + return !(nofollow ? lstat : stat)(fileName, &fs); #endif } @@ -111,27 +111,27 @@ TFileStat::TFileStat(FHANDLE f) { } } -void TFileStat::MakeFromFileName(const char* fileName, bool nofollow) { +void TFileStat::MakeFromFileName(const char* fileName, bool nofollow) { TSystemFStat st; - if (GetStatByName(st, fileName, nofollow)) { + if (GetStatByName(st, fileName, nofollow)) { MakeStat(*this, st); } else { *this = TFileStat(); } } -TFileStat::TFileStat(const TFsPath& fileName, bool nofollow) { +TFileStat::TFileStat(const TFsPath& fileName, bool nofollow) { MakeFromFileName(fileName.GetPath().data(), nofollow); -} - +} + TFileStat::TFileStat(const TString& fileName, bool nofollow) { MakeFromFileName(fileName.data(), nofollow); -} - -TFileStat::TFileStat(const char* fileName, bool nofollow) { - MakeFromFileName(fileName, nofollow); -} - +} + +TFileStat::TFileStat(const char* fileName, bool nofollow) { + MakeFromFileName(fileName, nofollow); +} + bool TFileStat::IsNull() const noexcept { return *this == TFileStat(); } diff --git a/util/system/fstat.h b/util/system/fstat.h index b9ef3f3987..64e79e1b55 100644 --- a/util/system/fstat.h +++ b/util/system/fstat.h @@ -4,7 +4,7 @@ #include <util/system/fhandle.h> class TFile; -class TFsPath; +class TFsPath; struct TFileStat { ui32 Mode = 0; /* protection */ @@ -29,17 +29,17 @@ public: bool IsDir() const noexcept; bool IsSymlink() const noexcept; - explicit TFileStat(const TFile& f); - explicit TFileStat(FHANDLE f); - TFileStat(const TFsPath& fileName, bool nofollow = false); + explicit TFileStat(const TFile& f); + explicit TFileStat(FHANDLE f); + TFileStat(const TFsPath& fileName, bool nofollow = false); TFileStat(const TString& fileName, bool nofollow = false); - TFileStat(const char* fileName, bool nofollow = false); + TFileStat(const char* fileName, bool nofollow = false); friend bool operator==(const TFileStat& l, const TFileStat& r) noexcept; friend bool operator!=(const TFileStat& l, const TFileStat& r) noexcept; -private: - void MakeFromFileName(const char* fileName, bool nofollow); +private: + void MakeFromFileName(const char* fileName, bool nofollow); }; i64 GetFileLength(FHANDLE fd); diff --git a/util/system/info.cpp b/util/system/info.cpp index 0d4ac42885..cf6681e89a 100644 --- a/util/system/info.cpp +++ b/util/system/info.cpp @@ -148,9 +148,9 @@ size_t NSystemInfo::LoadAverage(double* la, size_t len) { #if defined(_win_) || defined(_musl_) || defined(_bionic_) int ret = -1; #else - for (size_t i = 0; i < len; ++i) { - la[i] = 0; - } + for (size_t i = 0; i < len; ++i) { + la[i] = 0; + } int ret = getloadavg(la, len); #endif diff --git a/util/system/platform.h b/util/system/platform.h index c3b2dd33b2..58f310ab34 100644 --- a/util/system/platform.h +++ b/util/system/platform.h @@ -1,84 +1,84 @@ #pragma once -// ya style breaks indentation in ifdef's and code becomes unreadable -// clang-format off - +// ya style breaks indentation in ifdef's and code becomes unreadable +// clang-format off + // What OS ? // our definition has the form _{osname}_ #if defined(_WIN64) - #define _win64_ - #define _win32_ + #define _win64_ + #define _win32_ #elif defined(__WIN32__) || defined(_WIN32) // _WIN32 is also defined by the 64-bit compiler for backward compatibility - #define _win32_ + #define _win32_ #else - #define _unix_ - - #if defined(__sun__) || defined(sun) || defined(sparc) || defined(__sparc) - #define _sun_ - #endif - - #if defined(__hpux__) - #define _hpux_ - #endif - - #if defined(__linux__) - // Stands for "Linux" in the means of Linux kernel (i. e. Android is included) - #define _linux_ - #endif - - #if defined(__FreeBSD__) - #define _freebsd_ - #endif - - #if defined(__CYGWIN__) - #define _cygwin_ - #endif - - #if defined(__APPLE__) - #define _darwin_ - #endif - - #if defined(__ANDROID__) - #define _android_ - #endif + #define _unix_ + + #if defined(__sun__) || defined(sun) || defined(sparc) || defined(__sparc) + #define _sun_ + #endif + + #if defined(__hpux__) + #define _hpux_ + #endif + + #if defined(__linux__) + // Stands for "Linux" in the means of Linux kernel (i. e. Android is included) + #define _linux_ + #endif + + #if defined(__FreeBSD__) + #define _freebsd_ + #endif + + #if defined(__CYGWIN__) + #define _cygwin_ + #endif + + #if defined(__APPLE__) + #define _darwin_ + #endif + + #if defined(__ANDROID__) + #define _android_ + #endif #endif #if defined(__IOS__) - #define _ios_ + #define _ios_ #endif #if defined(_linux_) - #if defined(_musl_) - // nothing to do - #elif defined(_android_) - // Please do not mix with android-based systems. - // This definition describes Standard Library (libc) type. - #define _bionic_ - #else - #define _glibc_ - #endif + #if defined(_musl_) + // nothing to do + #elif defined(_android_) + // Please do not mix with android-based systems. + // This definition describes Standard Library (libc) type. + #define _bionic_ + #else + #define _glibc_ + #endif #endif #if defined(_darwin_) - #define unix - #define __unix__ + #define unix + #define __unix__ #endif #if defined(_win32_) || defined(_win64_) - #define _win_ + #define _win_ #endif #if defined(__arm__) || defined(__ARM__) || defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM) - #if defined(__arm64) || defined(__arm64__) || defined(__aarch64__) - #define _arm64_ - #else - #define _arm32_ - #endif + #if defined(__arm64) || defined(__arm64__) || defined(__aarch64__) + #define _arm64_ + #else + #define _arm32_ + #endif #endif #if defined(_arm64_) || defined(_arm32_) - #define _arm_ + #define _arm_ #endif /* __ia64__ and __x86_64__ - defined by GNU C. @@ -88,105 +88,105 @@ * or _M_X64 (starting in Visual Studio 8). */ #if defined(__x86_64__) || defined(_M_X64) || defined(_M_AMD64) - #define _x86_64_ + #define _x86_64_ #endif #if defined(__i386__) || defined(_M_IX86) - #define _i386_ + #define _i386_ #endif #if defined(__ia64__) || defined(_M_IA64) - #define _ia64_ + #define _ia64_ #endif #if defined(__powerpc__) - #define _ppc_ + #define _ppc_ #endif #if defined(__powerpc64__) - #define _ppc64_ + #define _ppc64_ #endif #if !defined(sparc) && !defined(__sparc) && !defined(__hpux__) && !defined(__alpha__) && !defined(_ia64_) && !defined(_x86_64_) && !defined(_arm_) && !defined(_i386_) && !defined(_ppc_) && !defined(_ppc64_) - #error "platform not defined, please, define one" + #error "platform not defined, please, define one" #endif #if defined(_x86_64_) || defined(_i386_) - #define _x86_ + #define _x86_ #endif #if defined(__MIC__) - #define _mic_ - #define _k1om_ + #define _mic_ + #define _k1om_ #endif // stdio or MessageBox #if defined(__CONSOLE__) || defined(_CONSOLE) - #define _console_ + #define _console_ #endif #if (defined(_win_) && !defined(_console_)) - #define _windows_ + #define _windows_ #elif !defined(_console_) - #define _console_ + #define _console_ #endif #if defined(__SSE__) || defined(SSE_ENABLED) - #define _sse_ + #define _sse_ #endif #if defined(__SSE2__) || defined(SSE2_ENABLED) - #define _sse2_ + #define _sse2_ #endif #if defined(__SSE3__) || defined(SSE3_ENABLED) - #define _sse3_ + #define _sse3_ #endif #if defined(__SSSE3__) || defined(SSSE3_ENABLED) - #define _ssse3_ + #define _ssse3_ #endif #if defined(__SSE4_1__) || defined(SSE41_ENABLED) - #define _sse4_1_ + #define _sse4_1_ #endif #if defined(__SSE4_2__) || defined(SSE42_ENABLED) - #define _sse4_2_ + #define _sse4_2_ #endif #if defined(__POPCNT__) || defined(POPCNT_ENABLED) - #define _popcnt_ + #define _popcnt_ #endif #if defined(__PCLMUL__) || defined(PCLMUL_ENABLED) - #define _pclmul_ + #define _pclmul_ #endif #if defined(__AES__) || defined(AES_ENABLED) - #define _aes_ + #define _aes_ #endif #if defined(__AVX__) || defined(AVX_ENABLED) - #define _avx_ + #define _avx_ #endif #if defined(__AVX2__) || defined(AVX2_ENABLED) - #define _avx2_ + #define _avx2_ #endif #if defined(__FMA__) || defined(FMA_ENABLED) - #define _fma_ + #define _fma_ #endif #if defined(__DLL__) || defined(_DLL) - #define _dll_ + #define _dll_ #endif // 16, 32 or 64 #if defined(__sparc_v9__) || defined(_x86_64_) || defined(_ia64_) || defined(_arm64_) || defined(_ppc64_) - #define _64_ + #define _64_ #else - #define _32_ + #define _32_ #endif /* All modern 64-bit Unix systems use scheme LP64 (long, pointers are 64-bit). @@ -202,15 +202,15 @@ */ #if defined(_32_) - #define SIZEOF_PTR 4 + #define SIZEOF_PTR 4 #elif defined(_64_) - #define SIZEOF_PTR 8 + #define SIZEOF_PTR 8 #endif #define PLATFORM_DATA_ALIGN SIZEOF_PTR #if !defined(SIZEOF_PTR) - #error todo + #error todo #endif #define SIZEOF_CHAR 1 @@ -221,20 +221,20 @@ #define SIZEOF_UNSIGNED_INT 4 #if defined(_32_) - #define SIZEOF_LONG 4 - #define SIZEOF_UNSIGNED_LONG 4 + #define SIZEOF_LONG 4 + #define SIZEOF_UNSIGNED_LONG 4 #elif defined(_64_) - #if defined(_win_) - #define SIZEOF_LONG 4 - #define SIZEOF_UNSIGNED_LONG 4 - #else - #define SIZEOF_LONG 8 - #define SIZEOF_UNSIGNED_LONG 8 - #endif // _win_ + #if defined(_win_) + #define SIZEOF_LONG 4 + #define SIZEOF_UNSIGNED_LONG 4 + #else + #define SIZEOF_LONG 8 + #define SIZEOF_UNSIGNED_LONG 8 + #endif // _win_ #endif // _32_ #if !defined(SIZEOF_LONG) - #error todo + #error todo #endif #define SIZEOF_LONG_LONG 8 @@ -243,4 +243,4 @@ #undef SIZEOF_SIZE_T // in case we include <Python.h> which defines it, too #define SIZEOF_SIZE_T SIZEOF_PTR -// clang-format on +// clang-format on diff --git a/util/system/protect.cpp b/util/system/protect.cpp index 615a8231bb..bbb8d410df 100644 --- a/util/system/protect.cpp +++ b/util/system/protect.cpp @@ -1,66 +1,66 @@ -#include "protect.h" - -#include <util/generic/yexception.h> +#include "protect.h" + +#include <util/generic/yexception.h> #include <util/generic/string.h> -#include <util/stream/output.h> - -#include "yassert.h" - +#include <util/stream/output.h> + +#include "yassert.h" + #if defined(_unix_) || defined(_darwin_) #include <sys/mman.h> -#endif - -#ifdef _win_ +#endif + +#ifdef _win_ #include <Windows.h> -#endif - +#endif + static TString ModeToString(const EProtectMemory mode) { TString strMode; if (mode == PM_NONE) { - return "PM_NONE"; + return "PM_NONE"; } - + if (mode & PM_READ) { - strMode += "PM_READ|"; + strMode += "PM_READ|"; } if (mode & PM_WRITE) { - strMode += "PM_WRITE|"; + strMode += "PM_WRITE|"; } if (mode & PM_EXEC) { - strMode += "PM_EXEC|"; + strMode += "PM_EXEC|"; } return strMode.substr(0, strMode.size() - 1); -} - +} + void ProtectMemory(void* addr, const size_t length, const EProtectMemory mode) { Y_VERIFY(!(mode & ~(PM_READ | PM_WRITE | PM_EXEC)), "Invalid memory protection flag combination. "); - -#if defined(_unix_) || defined(_darwin_) - int mpMode = PROT_NONE; + +#if defined(_unix_) || defined(_darwin_) + int mpMode = PROT_NONE; if (mode & PM_READ) { - mpMode |= PROT_READ; + mpMode |= PROT_READ; } if (mode & PM_WRITE) { - mpMode |= PROT_WRITE; + mpMode |= PROT_WRITE; } if (mode & PM_EXEC) { - mpMode |= PROT_EXEC; + mpMode |= PROT_EXEC; } - // some old manpages for mprotect say 'const void* addr', but that's wrong + // some old manpages for mprotect say 'const void* addr', but that's wrong if (mprotect(addr, length, mpMode) == -1) { - ythrow TSystemError() << "Memory protection failed for mode " << ModeToString(mode) << ". "; + ythrow TSystemError() << "Memory protection failed for mode " << ModeToString(mode) << ". "; } -#endif - -#ifdef _win_ - DWORD mpMode = PAGE_NOACCESS; +#endif + +#ifdef _win_ + DWORD mpMode = PAGE_NOACCESS; // windows developers are not aware of bit flags :( - - /* - * It's unclear that we should NOT fail on Windows that does not support write-only - * memory protection. As we don't know, what behavior is more correct, we choose - * one of them. A discussion was here: REVIEW: 39725 - */ + + /* + * It's unclear that we should NOT fail on Windows that does not support write-only + * memory protection. As we don't know, what behavior is more correct, we choose + * one of them. A discussion was here: REVIEW: 39725 + */ switch (mode.ToBaseType()) { case PM_READ: mpMode = PAGE_READONLY; @@ -68,8 +68,8 @@ void ProtectMemory(void* addr, const size_t length, const EProtectMemory mode) { case PM_WRITE: mpMode = PAGE_READWRITE; break; // BUG: no write-only support - /*case PM_WRITE: - ythrow TSystemError() << "Write-only protection mode is not supported under Windows. ";*/ + /*case PM_WRITE: + ythrow TSystemError() << "Write-only protection mode is not supported under Windows. ";*/ case PM_READ | PM_WRITE: mpMode = PAGE_READWRITE; break; @@ -82,14 +82,14 @@ void ProtectMemory(void* addr, const size_t length, const EProtectMemory mode) { case PM_WRITE | PM_EXEC: mpMode = PAGE_EXECUTE_READWRITE; break; // BUG: no write-only support - /*case PM_WRITE | PM_EXEC: - ythrow TSystemError() << "Write-execute-only protection mode is not supported under Windows. ";*/ + /*case PM_WRITE | PM_EXEC: + ythrow TSystemError() << "Write-execute-only protection mode is not supported under Windows. ";*/ case PM_READ | PM_WRITE | PM_EXEC: mpMode = PAGE_EXECUTE_READWRITE; break; - } - DWORD oldMode = 0; - if (!VirtualProtect(addr, length, mpMode, &oldMode)) - ythrow TSystemError() << "Memory protection failed for mode " << ModeToString(mode) << ". "; -#endif -} + } + DWORD oldMode = 0; + if (!VirtualProtect(addr, length, mpMode, &oldMode)) + ythrow TSystemError() << "Memory protection failed for mode " << ModeToString(mode) << ". "; +#endif +} diff --git a/util/system/protect.h b/util/system/protect.h index da024548de..26714f3e92 100644 --- a/util/system/protect.h +++ b/util/system/protect.h @@ -1,25 +1,25 @@ -#pragma once - +#pragma once + #include "defaults.h" - + #include <util/generic/flags.h> -enum EProtectMemoryMode { +enum EProtectMemoryMode { PM_NONE = 0x00, // no access allowed PM_READ = 0x01, // read access allowed - PM_WRITE = 0x02, // write access allowed + PM_WRITE = 0x02, // write access allowed PM_EXEC = 0x04 // execute access allowed -}; - +}; + Y_DECLARE_FLAGS(EProtectMemory, EProtectMemoryMode) Y_DECLARE_OPERATORS_FOR_FLAGS(EProtectMemory) -/** - * Set protection mode on memory block - * @param addr Block address to be protected - * @param length Block size in bytes - * @param mode A bitwise combination of @c EProtectMemoryMode flags - * @note On Windows there is no write-only protection mode, - * so PM_WRITE will be translated to (PM_READ | PM_WRITE) on Windows. - **/ +/** + * Set protection mode on memory block + * @param addr Block address to be protected + * @param length Block size in bytes + * @param mode A bitwise combination of @c EProtectMemoryMode flags + * @note On Windows there is no write-only protection mode, + * so PM_WRITE will be translated to (PM_READ | PM_WRITE) on Windows. + **/ void ProtectMemory(void* addr, const size_t length, const EProtectMemory mode); diff --git a/util/system/shellcommand.cpp b/util/system/shellcommand.cpp index 45588154ad..b1989b5c8c 100644 --- a/util/system/shellcommand.cpp +++ b/util/system/shellcommand.cpp @@ -508,8 +508,8 @@ public: } return nullptr; } - - TString GetQuotedCommand() const; + + TString GetQuotedCommand() const; }; #if defined(_win_) @@ -1194,7 +1194,7 @@ TShellCommand& TShellCommand::CloseInput() { Impl->CloseInput(); return *this; } - -TString TShellCommand::GetQuotedCommand() const { - return Impl->GetQuotedCommand(); -} + +TString TShellCommand::GetQuotedCommand() const { + return Impl->GetQuotedCommand(); +} diff --git a/util/system/shellcommand.h b/util/system/shellcommand.h index 0e2a232538..8730627fe5 100644 --- a/util/system/shellcommand.h +++ b/util/system/shellcommand.h @@ -464,11 +464,11 @@ public: */ TShellCommand& CloseInput(); - /** - * @brief Get quoted command (for debug/view purposes only!) - **/ - TString GetQuotedCommand() const; - + /** + * @brief Get quoted command (for debug/view purposes only!) + **/ + TString GetQuotedCommand() const; + private: class TImpl; using TImplRef = TSimpleIntrusivePtr<TImpl>; diff --git a/util/system/shellcommand_ut.cpp b/util/system/shellcommand_ut.cpp index 412ba161e6..9d849279d2 100644 --- a/util/system/shellcommand_ut.cpp +++ b/util/system/shellcommand_ut.cpp @@ -80,8 +80,8 @@ Y_UNIT_TEST_SUITE(TShellCommandTest) { UNIT_ASSERT_VALUES_EQUAL(cmd.GetOutput(), "hello" NL); UNIT_ASSERT(TShellCommand::SHELL_FINISHED == cmd.GetStatus()); UNIT_ASSERT(cmd.GetExitCode().Defined() && 0 == cmd.GetExitCode()); - - UNIT_ASSERT_VALUES_EQUAL(cmd.GetQuotedCommand(), "echo hello"); + + UNIT_ASSERT_VALUES_EQUAL(cmd.GetQuotedCommand(), "echo hello"); } Y_UNIT_TEST(TestOnlyNecessaryQuotes) { diff --git a/util/thread/lfqueue_ut.cpp b/util/thread/lfqueue_ut.cpp index d266848f22..83bca100cf 100644 --- a/util/thread/lfqueue_ut.cpp +++ b/util/thread/lfqueue_ut.cpp @@ -2,8 +2,8 @@ #include <library/cpp/testing/unittest/registar.h> #include <util/generic/algorithm.h> -#include <util/generic/vector.h> -#include <util/generic/ptr.h> +#include <util/generic/vector.h> +#include <util/generic/ptr.h> #include <util/system/atomic.h> #include <util/thread/pool.h> @@ -124,10 +124,10 @@ Y_UNIT_TEST_SUITE(TLockFreeQueueTests) { Y_UNIT_TEST(TestSimpleEnqueueDequeue) { TLockFreeQueue<int> queue; - int i = -1; + int i = -1; UNIT_ASSERT(!queue.Dequeue(&i)); - UNIT_ASSERT_VALUES_EQUAL(i, -1); + UNIT_ASSERT_VALUES_EQUAL(i, -1); queue.Enqueue(10); queue.Enqueue(11); @@ -156,10 +156,10 @@ Y_UNIT_TEST_SUITE(TLockFreeQueueTests) { Y_UNIT_TEST(TestSimpleEnqueueAllDequeue) { TLockFreeQueue<int> queue; - int i = -1; + int i = -1; UNIT_ASSERT(!queue.Dequeue(&i)); - UNIT_ASSERT_VALUES_EQUAL(i, -1); + UNIT_ASSERT_VALUES_EQUAL(i, -1); TVector<int> v; v.push_back(20); diff --git a/util/thread/pool.h b/util/thread/pool.h index 364530e68b..d1ea3a67cb 100644 --- a/util/thread/pool.h +++ b/util/thread/pool.h @@ -175,7 +175,7 @@ public: bool AddAndOwn(THolder<IObjectInQueue> obj) Y_WARN_UNUSED_RESULT; virtual void Start(size_t threadCount, size_t queueSizeLimit = 0) = 0; - /** Wait for completion of all scheduled objects, and then exit */ + /** Wait for completion of all scheduled objects, and then exit */ virtual void Stop() noexcept = 0; /** Number of tasks currently in queue */ virtual size_t Size() const noexcept = 0; diff --git a/util/thread/pool_ut.cpp b/util/thread/pool_ut.cpp index b273dcf3c7..893770d0c4 100644 --- a/util/thread/pool_ut.cpp +++ b/util/thread/pool_ut.cpp @@ -10,12 +10,12 @@ #include <util/system/condvar.h> struct TThreadPoolTest { - TSpinLock Lock; - long R = -1; + TSpinLock Lock; + long R = -1; struct TTask: public IObjectInQueue { TThreadPoolTest* Test = nullptr; - long Value = 0; + long Value = 0; TTask(TThreadPoolTest* test, int value) : Test(test) @@ -26,8 +26,8 @@ struct TThreadPoolTest { void Process(void*) override { THolder<TTask> This(this); - TGuard<TSpinLock> guard(Test->Lock); - Test->R ^= Value; + TGuard<TSpinLock> guard(Test->Lock); + Test->R ^= Value; } }; @@ -54,7 +54,7 @@ struct TThreadPoolTest { TReallyFastRng32 rand(17); const size_t cnt = 1000; - R = 0; + R = 0; for (size_t i = 0; i < cnt; ++i) { R ^= (long)rand.GenRand(); @@ -69,48 +69,48 @@ struct TThreadPoolTest { queue->Stop(); - UNIT_ASSERT_EQUAL(0, R); + UNIT_ASSERT_EQUAL(0, R); } -}; +}; class TFailAddQueue: public IThreadPool { -public: +public: bool Add(IObjectInQueue* /*obj*/) override Y_WARN_UNUSED_RESULT { - return false; + return false; } void Start(size_t, size_t) override { - } + } void Stop() noexcept override { } size_t Size() const noexcept override { - return 0; - } -}; - + return 0; + } +}; + Y_UNIT_TEST_SUITE(TThreadPoolTest) { Y_UNIT_TEST(TestTThreadPool) { TThreadPoolTest t; TThreadPool q; - t.TestAnyQueue(&q); - } - + t.TestAnyQueue(&q); + } + Y_UNIT_TEST(TestTThreadPoolBlocking) { TThreadPoolTest t; TThreadPool q(TThreadPool::TParams().SetBlocking(true)); - t.TestAnyQueue(&q, 100); - } - - // disabled by pg@ long time ago due to test flaps - // Tried to enable: REVIEW:78772 + t.TestAnyQueue(&q, 100); + } + + // disabled by pg@ long time ago due to test flaps + // Tried to enable: REVIEW:78772 Y_UNIT_TEST(TestTAdaptiveThreadPool) { - if (false) { + if (false) { TThreadPoolTest t; TAdaptiveThreadPool q; - t.TestAnyQueue(&q); - } + t.TestAnyQueue(&q); + } } Y_UNIT_TEST(TestAddAndOwn) { @@ -126,12 +126,12 @@ Y_UNIT_TEST_SUITE(TThreadPoolTest) { } Y_UNIT_TEST(TestAddFunc) { - TFailAddQueue queue; - bool added = queue.AddFunc( + TFailAddQueue queue; + bool added = queue.AddFunc( []() {} // Lambda, I call him 'Lambda'! ); - UNIT_ASSERT_VALUES_EQUAL(added, false); - } + UNIT_ASSERT_VALUES_EQUAL(added, false); + } Y_UNIT_TEST(TestSafeAddFuncThrows) { TFailAddQueue queue; @@ -254,4 +254,4 @@ Y_UNIT_TEST_SUITE(TThreadPoolTest) { TestEnumeratedThreadName(pool, expectedNames); } } -} +} |