diff options
author | nga <nga@yandex-team.ru> | 2022-02-10 16:48:09 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:48:09 +0300 |
commit | c2a1af049e9deca890e9923abe64fe6c59060348 (patch) | |
tree | b222e5ac2e2e98872661c51ccceee5da0d291e13 /util | |
parent | 1f553f46fb4f3c5eec631352cdd900a0709016af (diff) | |
download | ydb-c2a1af049e9deca890e9923abe64fe6c59060348.tar.gz |
Restoring authorship annotation for <nga@yandex-team.ru>. Commit 2 of 2.
Diffstat (limited to 'util')
109 files changed, 2608 insertions, 2608 deletions
diff --git a/util/charset/wide.h b/util/charset/wide.h index 4c681679ee..04e6928aab 100644 --- a/util/charset/wide.h +++ b/util/charset/wide.h @@ -312,7 +312,7 @@ inline size_t UTF8ToWideImpl(const char* text, size_t len, TCharType* dest, size ::NDetail::UTF8ToWideImplScalar<robust>(cur, last, p); written = p - dest; - return cur - reinterpret_cast<const unsigned char*>(text); + return cur - reinterpret_cast<const unsigned char*>(text); } template <typename TCharType> @@ -337,15 +337,15 @@ inline bool UTF8ToWide(const char* text, size_t len, TCharType* dest, size_t& wr return UTF8ToWideImpl<robust>(text, len, dest, written) == len; } -//! converts text from UTF8 to unicode, stops immediately it UTF8 byte sequence is wrong -//! @attention destination buffer must be long enough to fit all characters of the text, -//! conversion stops if a broken symbol is met -//! @return @c true if all the text converted successfully, @c false - a broken symbol was found +//! converts text from UTF8 to unicode, stops immediately it UTF8 byte sequence is wrong +//! @attention destination buffer must be long enough to fit all characters of the text, +//! conversion stops if a broken symbol is met +//! @return @c true if all the text converted successfully, @c false - a broken symbol was found template <typename TCharType> inline bool UTF8ToWide(const char* text, size_t len, TCharType* dest, size_t& written) noexcept { return UTF8ToWide<false>(text, len, dest, written); -} - +} + template <bool robust> inline TWtringBuf UTF8ToWide(const TStringBuf src, TUtf16String& dst) { dst.ReserveAndResize(src.size()); diff --git a/util/datetime/base.cpp b/util/datetime/base.cpp index f61b7b889f..38ecc3ab96 100644 --- a/util/datetime/base.cpp +++ b/util/datetime/base.cpp @@ -1,26 +1,26 @@ #include "base.h" - -#include <util/string/cast.h> + +#include <util/string/cast.h> #include <util/stream/output.h> #include <util/stream/mem.h> -#include <util/system/compat.h> +#include <util/system/compat.h> #include <util/memory/tempbuf.h> #include <util/generic/string.h> #include <util/generic/strbuf.h> #include <util/generic/yexception.h> - + TString Strftime(const char* format, const struct tm* tm) { size_t size = Max<size_t>(strlen(format) * 2 + 1, 107); - for (;;) { + for (;;) { TTempBuf buf(size); - int r = strftime(buf.Data(), buf.Size(), format, tm); + int r = strftime(buf.Data(), buf.Size(), format, tm); if (r != 0) { return TString(buf.Data(), r); } - size *= 2; - } -} - + size *= 2; + } +} + template <> TDuration FromStringImpl<TDuration, char>(const char* s, size_t len) { return TDuration::Parse(TStringBuf(s, len)); diff --git a/util/datetime/base.h b/util/datetime/base.h index 152fa983bb..5e902b8f63 100644 --- a/util/datetime/base.h +++ b/util/datetime/base.h @@ -3,14 +3,14 @@ #include "systime.h" #include <util/str_stl.h> -#include <util/system/platform.h> -#include <util/system/datetime.h> +#include <util/system/platform.h> +#include <util/system/datetime.h> #include <util/generic/string.h> #include <util/generic/strbuf.h> -#include <util/generic/ylimits.h> +#include <util/generic/ylimits.h> #include <util/generic/utility.h> #include <util/generic/typetraits.h> -#include <util/generic/yexception.h> +#include <util/generic/yexception.h> #include <chrono> @@ -29,20 +29,20 @@ #pragma warning(disable : 4244) // conversion from 'time_t' to 'long', possible loss of data #endif // _MSC_VER -// Microseconds since epoch -class TInstant; +// Microseconds since epoch +class TInstant; -// Duration is microseconds. Could be used to store timeouts, for example. -class TDuration; - -/// Current time +// Duration is microseconds. Could be used to store timeouts, for example. +class TDuration; + +/// Current time static inline TInstant Now() noexcept; - -/// Use Now() method to obtain current time instead of *Seconds() unless you understand what are you doing. - -class TDateTimeParseException: public yexception { -}; - + +/// Use Now() method to obtain current time instead of *Seconds() unless you understand what are you doing. + +class TDateTimeParseException: public yexception { +}; + const int DATE_BUF_LEN = 4 + 2 + 2 + 1; // [YYYYMMDD*] constexpr long seconds(const struct tm& theTm) { @@ -73,8 +73,8 @@ bool ParseISO8601DateTime(const char* date, time_t& utcTime); bool ParseISO8601DateTime(const char* date, size_t dateLen, time_t& utcTime); bool ParseRFC822DateTime(const char* date, time_t& utcTime); bool ParseRFC822DateTime(const char* date, size_t dateLen, time_t& utcTime); -bool ParseHTTPDateTime(const char* date, time_t& utcTime); -bool ParseHTTPDateTime(const char* date, size_t dateLen, time_t& utcTime); +bool ParseHTTPDateTime(const char* date, time_t& utcTime); +bool ParseHTTPDateTime(const char* date, size_t dateLen, time_t& utcTime); bool ParseX509ValidityDateTime(const char* date, time_t& utcTime); bool ParseX509ValidityDateTime(const char* date, size_t dateLen, time_t& utcTime); @@ -83,7 +83,7 @@ constexpr long TVdiff(timeval r1, timeval r2) { } TString Strftime(const char* format, const struct tm* tm); - + // Use functions below instead of sprint_date (check IGNIETFERRO-892 for details) void DateToString(char* buf, const struct tm& theTm); void DateToString(char* buf, time_t when, long* sec = nullptr); @@ -93,17 +93,17 @@ TString DateToString(time_t when, long* sec = nullptr); TString YearToString(const struct tm& theTm); TString YearToString(time_t when); -template <class S> -class TTimeBase { -public: +template <class S> +class TTimeBase { +public: using TValue = ui64; - + protected: constexpr TTimeBase(const TValue& value) noexcept : Value_(value) - { - } - + { + } + public: constexpr TTimeBase() noexcept : Value_(0) @@ -112,40 +112,40 @@ public: constexpr TTimeBase(const struct timeval& tv) noexcept : Value_(tv.tv_sec * (ui64)1000000 + tv.tv_usec) - { - } - + { + } + constexpr TValue GetValue() const noexcept { return Value_; - } - + } + constexpr double SecondsFloat() const noexcept { return Value_ * (1 / 1000000.0); - } - + } + constexpr double MillisecondsFloat() const noexcept { return Value_ * (1 / 1000.0); } constexpr TValue MicroSeconds() const noexcept { return Value_; - } + } constexpr TValue MilliSeconds() const noexcept { - return MicroSeconds() / 1000; - } + return MicroSeconds() / 1000; + } constexpr TValue Seconds() const noexcept { - return MilliSeconds() / 1000; - } + return MilliSeconds() / 1000; + } constexpr TValue Minutes() const noexcept { - return Seconds() / 60; - } + return Seconds() / 60; + } constexpr TValue Hours() const noexcept { - return Minutes() / 60; - } + return Minutes() / 60; + } constexpr TValue Days() const noexcept { return Hours() / 24; @@ -153,16 +153,16 @@ public: constexpr TValue NanoSeconds() const noexcept { return MicroSeconds() >= (Max<TValue>() / (TValue)1000) ? Max<TValue>() : MicroSeconds() * (TValue)1000; - } + } constexpr ui32 MicroSecondsOfSecond() const noexcept { return MicroSeconds() % (TValue)1000000; - } + } constexpr ui32 MilliSecondsOfSecond() const noexcept { return MicroSecondsOfSecond() / (TValue)1000; - } - + } + constexpr ui32 NanoSecondsOfSecond() const noexcept { return MicroSecondsOfSecond() * (TValue)1000; } @@ -173,26 +173,26 @@ public: protected: TValue Value_; // microseconds count -}; - -namespace NDateTimeHelpers { - template <typename T> - struct TPrecisionHelper { +}; + +namespace NDateTimeHelpers { + template <typename T> + struct TPrecisionHelper { using THighPrecision = ui64; - }; - - template <> - struct TPrecisionHelper<float> { + }; + + template <> + struct TPrecisionHelper<float> { using THighPrecision = double; - }; - - template <> - struct TPrecisionHelper<double> { + }; + + template <> + struct TPrecisionHelper<double> { using THighPrecision = double; - }; + }; } - -class TDuration: public TTimeBase<TDuration> { + +class TDuration: public TTimeBase<TDuration> { using TBase = TTimeBase<TDuration>; private: @@ -201,18 +201,18 @@ private: */ constexpr explicit TDuration(TValue value) noexcept : TBase(value) - { - } - + { + } + public: constexpr TDuration() noexcept { } constexpr TDuration(const struct timeval& tv) noexcept - : TBase(tv) - { - } - + : TBase(tv) + { + } + /** * TDuration is compatible with std::chrono::duration: * it can be constructed and compared with std::chrono::duration. @@ -261,52 +261,52 @@ public: } static constexpr TDuration MicroSeconds(ui64 us) noexcept { - return TDuration(us); - } - + return TDuration(us); + } + /* noexcept(false) as conversion from T might throw, for example FromString("abc") */ - template <typename T> + template <typename T> static constexpr TDuration MilliSeconds(T ms) noexcept(false) { return MicroSeconds((ui64)(typename NDateTimeHelpers::TPrecisionHelper<T>::THighPrecision(ms) * 1000)); - } - + } + using TBase::Days; - using TBase::Hours; + using TBase::Hours; using TBase::MicroSeconds; using TBase::MilliSeconds; - using TBase::Minutes; - using TBase::Seconds; - - /// DeadLineFromTimeOut - inline TInstant ToDeadLine() const; + using TBase::Minutes; + using TBase::Seconds; + + /// DeadLineFromTimeOut + inline TInstant ToDeadLine() const; constexpr TInstant ToDeadLine(TInstant now) const; - + static constexpr TDuration Max() noexcept { return TDuration(::Max<TValue>()); - } - + } + static constexpr TDuration Zero() noexcept { return TDuration(); - } - + } + /* noexcept(false) as conversion from T might throw, for example FromString("abc") */ - template <typename T> + template <typename T> static constexpr TDuration Seconds(T s) noexcept(false) { - return MilliSeconds(typename NDateTimeHelpers::TPrecisionHelper<T>::THighPrecision(s) * 1000); - } - + return MilliSeconds(typename NDateTimeHelpers::TPrecisionHelper<T>::THighPrecision(s) * 1000); + } + static constexpr TDuration Minutes(ui64 m) noexcept { - return Seconds(m * 60); - } + return Seconds(m * 60); + } static constexpr TDuration Hours(ui64 h) noexcept { - return Minutes(h * 60); - } + return Minutes(h * 60); + } static constexpr TDuration Days(ui64 d) noexcept { - return Hours(d * 24); - } - + return Hours(d * 24); + } + /// parses strings like 10s, 15ms, 15.05s, 20us, or just 25 (s). See parser_ut.cpp for details static TDuration Parse(const TStringBuf input); @@ -333,10 +333,10 @@ public: inline TDuration& operator/=(const T& t) noexcept { return (*this = (*this / t)); } - + TString ToString() const; -}; - +}; + Y_DECLARE_PODTYPE(TDuration); template <> @@ -346,8 +346,8 @@ struct THash<TDuration> { } }; -/// TInstant and TDuration are guaranteed to have same precision -class TInstant: public TTimeBase<TInstant> { +/// TInstant and TDuration are guaranteed to have same precision +class TInstant: public TTimeBase<TInstant> { using TBase = TTimeBase<TInstant>; private: @@ -356,61 +356,61 @@ private: */ constexpr explicit TInstant(TValue value) noexcept : TBase(value) - { - } - + { + } + public: constexpr TInstant() noexcept { } constexpr TInstant(const struct timeval& tv) noexcept - : TBase(tv) - { - } - + : TBase(tv) + { + } + static constexpr TInstant FromValue(TValue value) noexcept { return TInstant(value); } - static inline TInstant Now() { + static inline TInstant Now() { return TInstant::MicroSeconds(::MicroSeconds()); - } - + } + using TBase::Days; - using TBase::Hours; + using TBase::Hours; using TBase::MicroSeconds; using TBase::MilliSeconds; - using TBase::Minutes; - using TBase::Seconds; - + using TBase::Minutes; + using TBase::Seconds; + static constexpr TInstant Max() noexcept { return TInstant(::Max<TValue>()); - } - + } + static constexpr TInstant Zero() noexcept { return TInstant(); - } - - /// us since epoch + } + + /// us since epoch static constexpr TInstant MicroSeconds(ui64 us) noexcept { - return TInstant(us); - } + return TInstant(us); + } - /// ms since epoch + /// ms since epoch static constexpr TInstant MilliSeconds(ui64 ms) noexcept { - return MicroSeconds(ms * 1000); - } + return MicroSeconds(ms * 1000); + } - /// seconds since epoch + /// seconds since epoch static constexpr TInstant Seconds(ui64 s) noexcept { - return MilliSeconds(s * 1000); - } + return MilliSeconds(s * 1000); + } - /// minutes since epoch + /// minutes since epoch static constexpr TInstant Minutes(ui64 m) noexcept { - return Seconds(m * 60); - } - + return Seconds(m * 60); + } + /// hours since epoch static constexpr TInstant Hours(ui64 h) noexcept { return Minutes(h * 60); @@ -423,26 +423,26 @@ public: constexpr time_t TimeT() const noexcept { return (time_t)Seconds(); - } - + } + inline struct timeval TimeVal() const noexcept { - struct timeval tv; - ::Zero(tv); - tv.tv_sec = TimeT(); - tv.tv_usec = MicroSecondsOfSecond(); - return tv; - } - + struct timeval tv; + ::Zero(tv); + tv.tv_sec = TimeT(); + tv.tv_usec = MicroSecondsOfSecond(); + return tv; + } + inline struct tm* LocalTime(struct tm* tm) const noexcept { - time_t clock = Seconds(); - return localtime_r(&clock, tm); - } + time_t clock = Seconds(); + return localtime_r(&clock, tm); + } inline struct tm* GmTime(struct tm* tm) const noexcept { - time_t clock = Seconds(); + time_t clock = Seconds(); return GmTimeR(&clock, tm); - } - + } + /** * Formats the instant using the UTC time zone, with microsecond precision. * @@ -464,7 +464,7 @@ public: * @returns An ISO 8601 formatted string, e.g. '2015-11-21T23:30:27Z'. */ TString ToStringUpToSeconds() const; - + /** * Formats the instant using the system time zone, with microsecond precision. * @@ -555,8 +555,8 @@ public: inline TInstant& operator-=(const T& t) noexcept { return (*this = (*this - t)); } -}; - +}; + Y_DECLARE_PODTYPE(TInstant); template <> @@ -631,22 +631,22 @@ static constexpr bool operator>=(const TTimeBase<S>& l, const TTimeBase<S>& r) n return l.GetValue() >= r.GetValue(); } -namespace NDateTimeHelpers { - template <typename T> +namespace NDateTimeHelpers { + template <typename T> static constexpr T SumWithSaturation(T a, T b) { static_assert(!std::numeric_limits<T>::is_signed, "expect !std::numeric_limits<T>::is_signed"); return Max<T>() - a < b ? Max<T>() : a + b; - } - - template <typename T> + } + + template <typename T> static constexpr T DiffWithSaturation(T a, T b) { static_assert(!std::numeric_limits<T>::is_signed, "expect !std::numeric_limits<T>::is_signed"); return a < b ? 0 : a - b; - } -} - + } +} + constexpr TDuration operator-(const TInstant& l, const TInstant& r) noexcept { return TDuration::FromValue(::NDateTimeHelpers::DiffWithSaturation(l.GetValue(), r.GetValue())); } @@ -804,20 +804,20 @@ constexpr double operator/(const TDuration& x, const TDuration& y) noexcept { } inline TInstant TDuration::ToDeadLine() const { - return ToDeadLine(TInstant::Now()); -} - + return ToDeadLine(TInstant::Now()); +} + constexpr TInstant TDuration::ToDeadLine(TInstant now) const { return now + *this; -} - -void Sleep(TDuration duration); +} + +void Sleep(TDuration duration); void SleepUntil(TInstant instant); - + static inline TInstant Now() noexcept { - return TInstant::Now(); -} - + return TInstant::Now(); +} + #ifdef _MSC_VER #pragma warning(pop) #endif // _MSC_VER diff --git a/util/datetime/base_ut.cpp b/util/datetime/base_ut.cpp index 18a7d41efe..afc3f802eb 100644 --- a/util/datetime/base_ut.cpp +++ b/util/datetime/base_ut.cpp @@ -1,15 +1,15 @@ #include "base.h" #include <library/cpp/testing/unittest/registar.h> - + #include <util/generic/utility.h> #include <util/generic/ylimits.h> #include <util/generic/ymath.h> #include <util/string/cast.h> #include <util/stream/output.h> -#include <util/system/compat.h> +#include <util/system/compat.h> #include <util/random/random.h> - + #include <limits.h> using namespace std::chrono_literals; @@ -220,18 +220,18 @@ Y_UNIT_TEST_SUITE(TDateTimeTest) { UNIT_ASSERT(CompareTM(e.Tm_, t)); /* - * strptime seems to be broken on Mac OS X: - * - * struct tm t; - * char *ret = strptime("Jul", "%b ", &t); - * printf("-%s-\n", ret); - * - * yields "- -": ret contains a pointer to a substring of the format string, - * that should never occur: function returns either NULL or pointer to buf substring. - * - * So this test fails on Mac OS X. - */ - + * strptime seems to be broken on Mac OS X: + * + * struct tm t; + * char *ret = strptime("Jul", "%b ", &t); + * printf("-%s-\n", ret); + * + * yields "- -": ret contains a pointer to a substring of the format string, + * that should never occur: function returns either NULL or pointer to buf substring. + * + * So this test fails on Mac OS X. + */ + struct tm t2; Zero(t2); char* ret = strptime(e.Date_, "%a %b %d %H:%M:%S %Y\n ", &t2); @@ -272,7 +272,7 @@ Y_UNIT_TEST_SUITE(TDateTimeTest) { UNIT_ASSERT(Abs(milliseconds - microseconds / 1000) < 100); UNIT_ASSERT(seconds > 1243008607); // > time when test was written } - + Y_UNIT_TEST(TestStrftime) { struct tm tm; Zero(tm); @@ -281,14 +281,14 @@ Y_UNIT_TEST_SUITE(TDateTimeTest) { tm.tm_mday = 29; UNIT_ASSERT_STRINGS_EQUAL("2009-05-29", Strftime("%Y-%m-%d", &tm)); } - + Y_UNIT_TEST(TestNanoSleep) { NanoSleep(0); NanoSleep(1); NanoSleep(1000); NanoSleep(1000000); } - + static bool TimeZoneEq(const char* zone0, const char* zone1) { if (strcmp(zone0, "GMT") == 0) { zone0 = "UTC"; @@ -340,37 +340,37 @@ Y_UNIT_TEST_SUITE(TDateTimeTest) { Y_UNIT_TEST_SUITE(DateTimeTest) { Y_UNIT_TEST(TestDurationFromFloat) { - UNIT_ASSERT_EQUAL(TDuration::MilliSeconds(500), TDuration::Seconds(0.5)); - UNIT_ASSERT_EQUAL(TDuration::MilliSeconds(500), TDuration::Seconds(0.5f)); - } - + UNIT_ASSERT_EQUAL(TDuration::MilliSeconds(500), TDuration::Seconds(0.5)); + UNIT_ASSERT_EQUAL(TDuration::MilliSeconds(500), TDuration::Seconds(0.5f)); + } + Y_UNIT_TEST(TestSecondsLargeValue) { - unsigned int seconds = UINT_MAX; + unsigned int seconds = UINT_MAX; UNIT_ASSERT_VALUES_EQUAL(((ui64)seconds) * 1000000, TDuration::Seconds(seconds).MicroSeconds()); - } - + } + Y_UNIT_TEST(TestToString) { #define CHECK_CONVERTIBLE(v) \ do { \ UNIT_ASSERT_VALUES_EQUAL(v, ToString(TDuration::Parse(v))); \ UNIT_ASSERT_VALUES_EQUAL(v, TDuration::Parse(v).ToString()); \ } while (0) -#if 0 - - CHECK_CONVERTIBLE("10s"); - CHECK_CONVERTIBLE("1234s"); - CHECK_CONVERTIBLE("1234ms"); - CHECK_CONVERTIBLE("12ms"); - CHECK_CONVERTIBLE("12us"); - CHECK_CONVERTIBLE("1234us"); -#endif - - CHECK_CONVERTIBLE("1.000000s"); - CHECK_CONVERTIBLE("11234.000000s"); - CHECK_CONVERTIBLE("0.011122s"); - CHECK_CONVERTIBLE("33.011122s"); - } - +#if 0 + + CHECK_CONVERTIBLE("10s"); + CHECK_CONVERTIBLE("1234s"); + CHECK_CONVERTIBLE("1234ms"); + CHECK_CONVERTIBLE("12ms"); + CHECK_CONVERTIBLE("12us"); + CHECK_CONVERTIBLE("1234us"); +#endif + + CHECK_CONVERTIBLE("1.000000s"); + CHECK_CONVERTIBLE("11234.000000s"); + CHECK_CONVERTIBLE("0.011122s"); + CHECK_CONVERTIBLE("33.011122s"); + } + Y_UNIT_TEST(TestFromString) { static const struct T { const char* const Str; @@ -404,31 +404,31 @@ Y_UNIT_TEST_SUITE(DateTimeTest) { } Y_UNIT_TEST(TestSleep) { - // check does not throw - Sleep(TDuration::Seconds(0)); - Sleep(TDuration::MicroSeconds(1)); - Sleep(TDuration::MilliSeconds(1)); - } - + // check does not throw + Sleep(TDuration::Seconds(0)); + Sleep(TDuration::MicroSeconds(1)); + Sleep(TDuration::MilliSeconds(1)); + } + Y_UNIT_TEST(TestInstantToString) { UNIT_ASSERT_VALUES_EQUAL(TString("2009-08-06T15:19:06.023455Z"), ToString(TInstant::Seconds(1249571946) + TDuration::MicroSeconds(23455))); UNIT_ASSERT_VALUES_EQUAL(TString("2009-08-06T15:19:06.023455Z"), (TInstant::Seconds(1249571946) + TDuration::MicroSeconds(23455)).ToString()); UNIT_ASSERT_VALUES_EQUAL(TString("2009-08-06T15:19:06Z"), (TInstant::Seconds(1249571946) + TDuration::MicroSeconds(23455)).ToStringUpToSeconds()); - } - + } + Y_UNIT_TEST(TestInstantToRfc822String) { UNIT_ASSERT_VALUES_EQUAL(TString("Thu, 06 Aug 2009 15:19:06 GMT"), (TInstant::Seconds(1249571946) + TDuration::MicroSeconds(23455)).ToRfc822String()); } Y_UNIT_TEST(TestInstantMath) { - UNIT_ASSERT_VALUES_EQUAL(TInstant::Seconds(1719), TInstant::Seconds(1700) + TDuration::Seconds(19)); - // overflow - UNIT_ASSERT_VALUES_EQUAL(TInstant::Max(), TInstant::Max() - TDuration::Seconds(10) + TDuration::Seconds(19)); - // underflow - UNIT_ASSERT_VALUES_EQUAL(TInstant::Zero(), TInstant::Seconds(1000) - TDuration::Seconds(2000)); - UNIT_ASSERT_VALUES_EQUAL(TDuration::Zero(), TInstant::Seconds(1000) - TInstant::Seconds(2000)); - } - + UNIT_ASSERT_VALUES_EQUAL(TInstant::Seconds(1719), TInstant::Seconds(1700) + TDuration::Seconds(19)); + // overflow + UNIT_ASSERT_VALUES_EQUAL(TInstant::Max(), TInstant::Max() - TDuration::Seconds(10) + TDuration::Seconds(19)); + // underflow + UNIT_ASSERT_VALUES_EQUAL(TInstant::Zero(), TInstant::Seconds(1000) - TDuration::Seconds(2000)); + UNIT_ASSERT_VALUES_EQUAL(TDuration::Zero(), TInstant::Seconds(1000) - TInstant::Seconds(2000)); + } + Y_UNIT_TEST(TestDurationMath) { TDuration empty; UNIT_ASSERT(!empty); @@ -439,14 +439,14 @@ Y_UNIT_TEST_SUITE(DateTimeTest) { 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)); + 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); - } + } Y_UNIT_TEST(TestDurationGetters) { const TDuration value = TDuration::MicroSeconds(1234567); @@ -651,4 +651,4 @@ Y_UNIT_TEST_SUITE(DateTimeTest) { static_assert(TDuration::Zero() + 1s == 1s); static_assert(TInstant::Seconds(1) + 1s == TInstant::Seconds(2)); } -} +} diff --git a/util/datetime/cputimer.cpp b/util/datetime/cputimer.cpp index 0d60296836..516d372c37 100644 --- a/util/datetime/cputimer.cpp +++ b/util/datetime/cputimer.cpp @@ -30,32 +30,32 @@ TTimer::~TTimer() { Cerr << Message_.Str(); } -static ui64 ManuallySetCyclesPerSecond = 0; - -static ui64 GetCyclesPerSecond() { +static ui64 ManuallySetCyclesPerSecond = 0; + +static ui64 GetCyclesPerSecond() { if (ManuallySetCyclesPerSecond != 0) { - return ManuallySetCyclesPerSecond; + return ManuallySetCyclesPerSecond; } else { return NHPTimer::GetCyclesPerSecond(); } } -void SetCyclesPerSecond(ui64 cycles) { - ManuallySetCyclesPerSecond = cycles; -} - -ui64 GetCyclesPerMillisecond() { - return GetCyclesPerSecond() / 1000; -} - -TDuration CyclesToDuration(ui64 cycles) { - return TDuration::MicroSeconds(cycles * 1000000 / GetCyclesPerSecond()); -} - -ui64 DurationToCycles(TDuration duration) { - return duration.MicroSeconds() * GetCyclesPerSecond() / 1000000; -} - +void SetCyclesPerSecond(ui64 cycles) { + ManuallySetCyclesPerSecond = cycles; +} + +ui64 GetCyclesPerMillisecond() { + return GetCyclesPerSecond() / 1000; +} + +TDuration CyclesToDuration(ui64 cycles) { + return TDuration::MicroSeconds(cycles * 1000000 / GetCyclesPerSecond()); +} + +ui64 DurationToCycles(TDuration duration) { + return duration.MicroSeconds() * GetCyclesPerSecond() / 1000000; +} + TPrecisionTimer::TPrecisionTimer() : Start(::GetCycleCount()) { diff --git a/util/datetime/cputimer.h b/util/datetime/cputimer.h index 1704b55dcc..7d38d5bdb3 100644 --- a/util/datetime/cputimer.h +++ b/util/datetime/cputimer.h @@ -2,13 +2,13 @@ #include "base.h" -#include <util/system/rusage.h> +#include <util/system/rusage.h> #include <util/generic/string.h> #include <util/stream/str.h> class TTimer { private: - TInstant Start_; + TInstant Start_; TStringStream Message_; public: @@ -17,51 +17,51 @@ public: }; class TSimpleTimer { - TInstant T; + TInstant T; public: TSimpleTimer() { Reset(); } TDuration Get() const { - return TInstant::Now() - T; + return TInstant::Now() - T; } void Reset() { - T = TInstant::Now(); + T = TInstant::Now(); } }; class TProfileTimer { - TDuration T; + TDuration T; public: TProfileTimer() { Reset(); } TDuration Get() const { - return TRusage::Get().Utime - T; + return TRusage::Get().Utime - T; } TDuration Step() { - TRusage r; - r.Fill(); - TDuration d = r.Utime - T; - T = r.Utime; + TRusage r; + r.Fill(); + TDuration d = r.Utime - T; + T = r.Utime; return d; } void Reset() { - T = TRusage::Get().Utime; + T = TRusage::Get().Utime; } }; -/// Return cached processor cycle count per second. Method takes 1 second at first invocation. -/// Note, on older systems cycle rate may change during program lifetime, -/// so returned value may be incorrect. Modern Intel and AMD processors keep constant TSC rate. +/// Return cached processor cycle count per second. Method takes 1 second at first invocation. +/// Note, on older systems cycle rate may change during program lifetime, +/// so returned value may be incorrect. Modern Intel and AMD processors keep constant TSC rate. ui64 GetCyclesPerMillisecond(); -void SetCyclesPerSecond(ui64 cycles); +void SetCyclesPerSecond(ui64 cycles); + +TDuration CyclesToDuration(ui64 cycles); +ui64 DurationToCycles(TDuration duration); -TDuration CyclesToDuration(ui64 cycles); -ui64 DurationToCycles(TDuration duration); - class TPrecisionTimer { private: ui64 Start = 0; @@ -91,7 +91,7 @@ public: ~TFuncTimer(); private: - const TInstant Start_; + const TInstant Start_; const char* Func_; }; diff --git a/util/datetime/parser.h b/util/datetime/parser.h index 7816bfd349..f0c1b4a0c7 100644 --- a/util/datetime/parser.h +++ b/util/datetime/parser.h @@ -1,160 +1,160 @@ #pragma once - -// probably you do not need to include this file directly, use "util/datetime/base.h" - -#include "base.h" - -struct TDateTimeFields { - TDateTimeFields() { - Zero(*this); + +// probably you do not need to include this file directly, use "util/datetime/base.h" + +#include "base.h" + +struct TDateTimeFields { + TDateTimeFields() { + Zero(*this); ZoneOffsetMinutes = 0; Hour = 0; - } - - ui32 Year; - ui32 Month; // 1..12 - ui32 Day; // 1 .. 31 - ui32 Hour; // 0 .. 23 - ui32 Minute; // 0 .. 59 - ui32 Second; // 0 .. 60 - ui32 MicroSecond; // 0 .. 999999 - i32 ZoneOffsetMinutes; - - void SetLooseYear(ui32 year) { - if (year < 60) - year += 100; - if (year < 160) - year += 1900; - Year = year; - } - + } + + ui32 Year; + ui32 Month; // 1..12 + ui32 Day; // 1 .. 31 + ui32 Hour; // 0 .. 23 + ui32 Minute; // 0 .. 59 + ui32 Second; // 0 .. 60 + ui32 MicroSecond; // 0 .. 999999 + i32 ZoneOffsetMinutes; + + void SetLooseYear(ui32 year) { + if (year < 60) + year += 100; + if (year < 160) + year += 1900; + Year = year; + } + bool IsOk() const noexcept { - if (Year < 1970) - return false; - if (Month < 1 || Month > 12) - return false; - - unsigned int maxMonthDay = 31; - if (Month == 4 || Month == 6 || Month == 9 || Month == 11) { - maxMonthDay = 30; - } else if (Month == 2) { - if (Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0)) - // leap year - maxMonthDay = 29; - else - maxMonthDay = 28; - } - if (Day > maxMonthDay) - return false; - - if (Hour > 23) - return false; - - if (Minute > 59) - return false; - + if (Year < 1970) + return false; + if (Month < 1 || Month > 12) + return false; + + unsigned int maxMonthDay = 31; + if (Month == 4 || Month == 6 || Month == 9 || Month == 11) { + maxMonthDay = 30; + } else if (Month == 2) { + if (Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0)) + // leap year + maxMonthDay = 29; + else + maxMonthDay = 28; + } + if (Day > maxMonthDay) + return false; + + if (Hour > 23) + return false; + + if (Minute > 59) + return false; + // handle leap second which is explicitly allowed by ISO 8601:2004(E) $2.2.2 // https://datatracker.ietf.org/doc/html/rfc3339#section-5.6 - if (Second > 60) - return false; - - if (MicroSecond > 999999) - return false; - + if (Second > 60) + return false; + + if (MicroSecond > 999999) + return false; + if (Year == 1970 && Month == 1 && Day == 1) { if ((i64)(3600 * Hour + 60 * Minute + Second) < (60 * ZoneOffsetMinutes)) return false; } - return true; - } - + return true; + } + TInstant ToInstant(TInstant defaultValue) const { - time_t tt = ToTimeT(-1); - if (tt == -1) - return defaultValue; - return TInstant::Seconds(tt) + TDuration::MicroSeconds(MicroSecond); - } - + time_t tt = ToTimeT(-1); + if (tt == -1) + return defaultValue; + return TInstant::Seconds(tt) + TDuration::MicroSeconds(MicroSecond); + } + time_t ToTimeT(time_t defaultValue) const { - if (!IsOk()) - return defaultValue; - struct tm tm; - Zero(tm); - tm.tm_year = Year - 1900; - tm.tm_mon = Month - 1; - tm.tm_mday = Day; - tm.tm_hour = Hour; - tm.tm_min = Minute; - tm.tm_sec = Second; + if (!IsOk()) + return defaultValue; + struct tm tm; + Zero(tm); + tm.tm_year = Year - 1900; + tm.tm_mon = Month - 1; + tm.tm_mday = Day; + tm.tm_hour = Hour; + tm.tm_min = Minute; + tm.tm_sec = Second; time_t tt = TimeGM(&tm); - if (tt == -1) - return defaultValue; - return tt - ZoneOffsetMinutes * 60; - } -}; - -class TDateTimeParserBase { + if (tt == -1) + return defaultValue; + return tt - ZoneOffsetMinutes * 60; + } +}; + +class TDateTimeParserBase { public: const TDateTimeFields& GetDateTimeFields() const { return DateTimeFields; } -protected: - TDateTimeFields DateTimeFields; +protected: + TDateTimeFields DateTimeFields; int cs; //for ragel - int Sign; - int I; - int Dc; - + int Sign; + int I; + int Dc; + protected: - TDateTimeParserBase() + TDateTimeParserBase() : DateTimeFields() , cs(0) , Sign(0) , I(0xDEADBEEF) // to guarantee unittest break if ragel code is incorrect , Dc(0xDEADBEEF) - { - } + { + } inline TInstant GetResult(int firstFinalState, TInstant defaultValue) const { if (cs < firstFinalState) return defaultValue; return DateTimeFields.ToInstant(defaultValue); } -}; - +}; + #define DECLARE_PARSER(CLASS) \ struct CLASS: public TDateTimeParserBase { \ CLASS(); \ bool ParsePart(const char* input, size_t len); \ TInstant GetResult(TInstant defaultValue) const; \ - }; - -DECLARE_PARSER(TIso8601DateTimeParser) -DECLARE_PARSER(TRfc822DateTimeParser) -DECLARE_PARSER(THttpDateTimeParser) + }; + +DECLARE_PARSER(TIso8601DateTimeParser) +DECLARE_PARSER(TRfc822DateTimeParser) +DECLARE_PARSER(THttpDateTimeParser) DECLARE_PARSER(TX509ValidityDateTimeParser) DECLARE_PARSER(TX509Validity4yDateTimeParser) - -#undef DECLARE_PARSER - -struct TDurationParser { - int cs; - - ui64 I; - ui32 Dc; - - i32 MultiplierPower; // 6 for seconds, 0 for microseconds, -3 for nanoseconds + +#undef DECLARE_PARSER + +struct TDurationParser { + int cs; + + ui64 I; + ui32 Dc; + + i32 MultiplierPower; // 6 for seconds, 0 for microseconds, -3 for nanoseconds i32 Multiplier; - ui64 IntegerPart; - ui32 FractionPart; - ui32 FractionDigits; - - TDurationParser(); - bool ParsePart(const char* input, size_t len); - TDuration GetResult(TDuration defaultValue) const; -}; + ui64 IntegerPart; + ui32 FractionPart; + ui32 FractionDigits; + + TDurationParser(); + bool ParsePart(const char* input, size_t len); + TDuration GetResult(TDuration defaultValue) const; +}; /** Depcrecated cause of default hour offset (+4 hours) diff --git a/util/datetime/parser.rl6 b/util/datetime/parser.rl6 index 5a8e3f48ad..931f09eae1 100644 --- a/util/datetime/parser.rl6 +++ b/util/datetime/parser.rl6 @@ -11,23 +11,23 @@ %%{ -machine DateTimeParserCommon; +machine DateTimeParserCommon; + +sp = ' '; -sp = ' '; - action clear_int { - I = 0; - Dc = 0; + I = 0; + Dc = 0; } action update_int { - I = I * 10 + (fc - '0'); - ++Dc; + I = I * 10 + (fc - '0'); + ++Dc; } -int = (digit+) - >clear_int - $update_int; +int = (digit+) + >clear_int + $update_int; int1 = digit >clear_int @@ -37,10 +37,10 @@ int2 = (digit digit) >clear_int $update_int; -int3 = (digit digit digit) - >clear_int - $update_int; - +int3 = (digit digit digit) + >clear_int + $update_int; + int4 = (digit digit digit digit) >clear_int $update_int; @@ -53,60 +53,60 @@ int24 = ( digit digit ( digit digit )? ) >clear_int $update_int; -# According to both RFC2822 and RFC2616 dates MUST be case-sensitive, -# but Andrey fomichev@ wants relaxed parser - -month3 = - 'Jan'i %{ DateTimeFields.Month = 1; } - | 'Feb'i %{ DateTimeFields.Month = 2; } - | 'Mar'i %{ DateTimeFields.Month = 3; } - | 'Apr'i %{ DateTimeFields.Month = 4; } - | 'May'i %{ DateTimeFields.Month = 5; } - | 'Jun'i %{ DateTimeFields.Month = 6; } - | 'Jul'i %{ DateTimeFields.Month = 7; } - | 'Aug'i %{ DateTimeFields.Month = 8; } - | 'Sep'i %{ DateTimeFields.Month = 9; } - | 'Oct'i %{ DateTimeFields.Month = 10; } - | 'Nov'i %{ DateTimeFields.Month = 11; } - | 'Dec'i %{ DateTimeFields.Month = 12; }; - -wkday = 'Mon'i | 'Tue'i | 'Wed'i | 'Thu'i | 'Fri'i | 'Sat'i | 'Sun'i; -weekday = 'Monday'i | 'Tuesday'i | 'Wednesday'i | 'Thursday'i - | 'Friday'i | 'Saturday'i | 'Sunday'i; - -action set_second { DateTimeFields.Second = I; } -action set_minute { DateTimeFields.Minute = I; } -action set_hour { DateTimeFields.Hour = I; } -action set_day { DateTimeFields.Day = I; } -action set_month { DateTimeFields.Month = I; } -action set_year { DateTimeFields.SetLooseYear(I); } -action set_zone_utc { DateTimeFields.ZoneOffsetMinutes = 0; } - -}%% - -%%{ - -machine RFC822DateParser; - -################# RFC 2822 3.3 Full Date ################### - -include DateTimeParserCommon; - -ws1 = (space+); -ws0 = (space*); -dow_spec = ( wkday ',' )?; - -day = int12 %set_day; +# According to both RFC2822 and RFC2616 dates MUST be case-sensitive, +# but Andrey fomichev@ wants relaxed parser + +month3 = + 'Jan'i %{ DateTimeFields.Month = 1; } + | 'Feb'i %{ DateTimeFields.Month = 2; } + | 'Mar'i %{ DateTimeFields.Month = 3; } + | 'Apr'i %{ DateTimeFields.Month = 4; } + | 'May'i %{ DateTimeFields.Month = 5; } + | 'Jun'i %{ DateTimeFields.Month = 6; } + | 'Jul'i %{ DateTimeFields.Month = 7; } + | 'Aug'i %{ DateTimeFields.Month = 8; } + | 'Sep'i %{ DateTimeFields.Month = 9; } + | 'Oct'i %{ DateTimeFields.Month = 10; } + | 'Nov'i %{ DateTimeFields.Month = 11; } + | 'Dec'i %{ DateTimeFields.Month = 12; }; + +wkday = 'Mon'i | 'Tue'i | 'Wed'i | 'Thu'i | 'Fri'i | 'Sat'i | 'Sun'i; +weekday = 'Monday'i | 'Tuesday'i | 'Wednesday'i | 'Thursday'i + | 'Friday'i | 'Saturday'i | 'Sunday'i; + +action set_second { DateTimeFields.Second = I; } +action set_minute { DateTimeFields.Minute = I; } +action set_hour { DateTimeFields.Hour = I; } +action set_day { DateTimeFields.Day = I; } +action set_month { DateTimeFields.Month = I; } +action set_year { DateTimeFields.SetLooseYear(I); } +action set_zone_utc { DateTimeFields.ZoneOffsetMinutes = 0; } + +}%% + +%%{ + +machine RFC822DateParser; + +################# RFC 2822 3.3 Full Date ################### + +include DateTimeParserCommon; + +ws1 = (space+); +ws0 = (space*); +dow_spec = ( wkday ',' )?; + +day = int12 %set_day; year = int24 %set_year; # actually it must be from 0 to 23 -hour = int2 %set_hour; +hour = int2 %set_hour; # actually it must be from 0 to 59 -min = int2 %set_minute; +min = int2 %set_minute; # actually it must be from 0 to 59 -sec = int2 %set_second; +sec = int2 %set_second; sec_spec = ( ':' . sec )?; @@ -114,7 +114,7 @@ sec_spec = ( ':' . sec )?; action set_mil_offset { char c = (char)toupper(fc); if (c == 'Z') - DateTimeFields.ZoneOffsetMinutes = 0; + DateTimeFields.ZoneOffsetMinutes = 0; else { if (c <= 'M') { // ['A'..'M'] \ 'J' @@ -140,8 +140,8 @@ mil_zone = /[A-IK-Za-ik-z]/ $set_mil_offset; # it is a bug in ragel 5 because ragel 6.2 works correctly with % at the end of string. # see http://www.complang.org/ragel/ChangeLog. -zone = 'UT' @{ DateTimeFields.ZoneOffsetMinutes = 0; } - | 'GMT' @{ DateTimeFields.ZoneOffsetMinutes = 0; } +zone = 'UT' @{ DateTimeFields.ZoneOffsetMinutes = 0; } + | 'GMT' @{ DateTimeFields.ZoneOffsetMinutes = 0; } | 'EST' @{ DateTimeFields.ZoneOffsetMinutes = -(i32)TDuration::Hours(5).Minutes();} | 'EDT' @{ DateTimeFields.ZoneOffsetMinutes = -(i32)TDuration::Hours(4).Minutes(); } | 'CST' @{ DateTimeFields.ZoneOffsetMinutes = -(i32)TDuration::Hours(6).Minutes();} @@ -151,29 +151,29 @@ zone = 'UT' @{ DateTimeFields.ZoneOffsetMinutes = 0; } | 'PST' @{ DateTimeFields.ZoneOffsetMinutes = -(i32)TDuration::Hours(8).Minutes();} | 'PDT' @{ DateTimeFields.ZoneOffsetMinutes = -(i32)TDuration::Hours(7).Minutes(); }; -digit_offset = ('+' | '-') > { Sign = fc == '+' ? 1 : -1; } . int4 @set_digit_offset; +digit_offset = ('+' | '-') > { Sign = fc == '+' ? 1 : -1; } . int4 @set_digit_offset; offset = ( zone | mil_zone | digit_offset ); -rfc822datetime = ws0 . dow_spec . ws0 . day . ws1 . month3 . ws1 . year . ws1 . hour . ':' . min . sec_spec . ws1 . offset . ws0; +rfc822datetime = ws0 . dow_spec . ws0 . day . ws1 . month3 . ws1 . year . ws1 . hour . ':' . min . sec_spec . ws1 . offset . ws0; -main := rfc822datetime; +main := rfc822datetime; write data noerror; }%% TRfc822DateTimeParserDeprecated::TRfc822DateTimeParserDeprecated() { - %% write init; -} + %% write init; +} bool TRfc822DateTimeParserDeprecated::ParsePart(const char* input, size_t len) { - const char* p = input; - const char* pe = input + len; + const char* p = input; + const char* pe = input + len; - %% write exec; - return cs != %%{ write error; }%%; -} + %% write exec; + return cs != %%{ write error; }%%; +} TRfc822DateTimeParser::TRfc822DateTimeParser() { %% write init; @@ -187,53 +187,53 @@ bool TRfc822DateTimeParser::ParsePart(const char* input, size_t len) { return cs != %%{ write error; }%%; } -%%{ - -machine ISO8601DateTimeParser; - -include DateTimeParserCommon; - -year = int4 @set_year; -month = int2 @set_month; -day = int2 @set_day; -hour = int2 @set_hour; -minute = int2 @set_minute; -second = int2 @set_second; +%%{ + +machine ISO8601DateTimeParser; + +include DateTimeParserCommon; + +year = int4 @set_year; +month = int2 @set_month; +day = int2 @set_day; +hour = int2 @set_hour; +minute = int2 @set_minute; +second = int2 @set_second; secondFrac = digit {1,6} >clear_int $update_int @{ - ui32 us = I; - for (int k = Dc; k < 6; ++k) { - us *= 10; - } - DateTimeFields.MicroSecond = us; -}; + ui32 us = I; + for (int k = Dc; k < 6; ++k) { + us *= 10; + } + DateTimeFields.MicroSecond = us; +}; secondFracTail = (digit*); - -zoneZ = [Zz] @set_zone_utc; + +zoneZ = [Zz] @set_zone_utc; zoneOffset = space? . ('+' | '-') >{ Sign = fc == '+' ? 1 : -1; } . int2 @{ DateTimeFields.ZoneOffsetMinutes = Sign * (i32)TDuration::Hours(I).Minutes(); } . (':')? . (int2 @{ DateTimeFields.ZoneOffsetMinutes += I * Sign; })?; -zone = zoneZ | zoneOffset; - -iso8601date = (year . '-' . month . '-' . day) | (year . month . day); +zone = zoneZ | zoneOffset; + +iso8601date = (year . '-' . month . '-' . day) | (year . month . day); iso8601time = (hour . ':' . minute . (':' . second ('.' secondFrac secondFracTail)?)?) | (hour . minute . second?); - -iso8601datetime = iso8601date . ([Tt ] . iso8601time . zone?)?; - -main := iso8601datetime; - -write data noerror; - -}%% - + +iso8601datetime = iso8601date . ([Tt ] . iso8601time . zone?)?; + +main := iso8601datetime; + +write data noerror; + +}%% + TIso8601DateTimeParserDeprecated::TIso8601DateTimeParserDeprecated() { %% write init; -} - +} + bool TIso8601DateTimeParserDeprecated::ParsePart(const char* input, size_t len) { - const char* p = input; - const char* pe = input + len; - + const char* p = input; + const char* pe = input + len; + %% write exec; - return cs != %%{ write error; }%%; -} + return cs != %%{ write error; }%%; +} TIso8601DateTimeParser::TIso8601DateTimeParser() { %% write init; @@ -247,50 +247,50 @@ bool TIso8601DateTimeParser::ParsePart(const char* input, size_t len) { return cs != %%{ write error; }%%; } -%%{ - -machine HttpDateTimeParser; - -include DateTimeParserCommon; - -################# RFC 2616 3.3.1 Full Date ################# - -time = int2 %set_hour ':' int2 %set_minute ':' int2 %set_second; -date1 = int2 %set_day ' ' month3 ' ' int4 %set_year; -date2 = int2 %set_day '-' month3 '-' int2 %set_year; -date3 = month3 sp (int2 | sp int1) %set_day; - -rfc1123_date = wkday ',' sp date1 sp time sp 'GMT'i; -rfc850_date = weekday ',' sp date2 sp time sp 'GMT'i; -asctime_date = wkday sp date3 sp time sp int4 @set_year; -http_date = (rfc1123_date | rfc850_date | asctime_date) @set_zone_utc; - -}%% - -%%{ - -machine HttpDateTimeParserStandalone; - -include HttpDateTimeParser; - -main := http_date; - -write data noerror; - -}%% - +%%{ + +machine HttpDateTimeParser; + +include DateTimeParserCommon; + +################# RFC 2616 3.3.1 Full Date ################# + +time = int2 %set_hour ':' int2 %set_minute ':' int2 %set_second; +date1 = int2 %set_day ' ' month3 ' ' int4 %set_year; +date2 = int2 %set_day '-' month3 '-' int2 %set_year; +date3 = month3 sp (int2 | sp int1) %set_day; + +rfc1123_date = wkday ',' sp date1 sp time sp 'GMT'i; +rfc850_date = weekday ',' sp date2 sp time sp 'GMT'i; +asctime_date = wkday sp date3 sp time sp int4 @set_year; +http_date = (rfc1123_date | rfc850_date | asctime_date) @set_zone_utc; + +}%% + +%%{ + +machine HttpDateTimeParserStandalone; + +include HttpDateTimeParser; + +main := http_date; + +write data noerror; + +}%% + THttpDateTimeParserDeprecated::THttpDateTimeParserDeprecated() { - %% write init; -} - + %% write init; +} + bool THttpDateTimeParserDeprecated::ParsePart(const char* input, size_t len) { - const char* p = input; - const char* pe = input + len; - - %% write exec; - return cs != %%{ write error; }%%; -} - + const char* p = input; + const char* pe = input + len; + + %% write exec; + return cs != %%{ write error; }%%; +} + THttpDateTimeParser::THttpDateTimeParser() { %% write init; } @@ -334,7 +334,7 @@ bool TX509ValidityDateTimeParserDeprecated::ParsePart(const char *input, size_t const char *pe = input + len; %% write exec; - return cs != %%{ write error; }%%; + return cs != %%{ write error; }%%; } TX509ValidityDateTimeParser::TX509ValidityDateTimeParser() { @@ -379,7 +379,7 @@ bool TX509Validity4yDateTimeParserDeprecated::ParsePart(const char *input, size_ const char *pe = input + len; %% write exec; - return cs != %%{ write error; }%%; + return cs != %%{ write error; }%%; } TX509Validity4yDateTimeParser::TX509Validity4yDateTimeParser() { @@ -397,23 +397,23 @@ bool TX509Validity4yDateTimeParser::ParsePart(const char *input, size_t len) { TInstant TIso8601DateTimeParserDeprecated::GetResult(TInstant defaultValue) const { Y_UNUSED(ISO8601DateTimeParser_en_main); return TDateTimeParserBaseDeprecated::GetResult(ISO8601DateTimeParser_first_final, defaultValue); -} - +} + TInstant TRfc822DateTimeParserDeprecated::GetResult(TInstant defaultValue) const { Y_UNUSED(RFC822DateParser_en_main); return TDateTimeParserBaseDeprecated::GetResult(RFC822DateParser_first_final, defaultValue); -} - +} + TInstant THttpDateTimeParserDeprecated::GetResult(TInstant defaultValue) const { Y_UNUSED(HttpDateTimeParserStandalone_en_main); return TDateTimeParserBaseDeprecated::GetResult(HttpDateTimeParserStandalone_first_final, defaultValue); -} - +} + TInstant TX509ValidityDateTimeParserDeprecated::GetResult(TInstant defaultValue) const { Y_UNUSED(X509ValidityDateTimeParser_en_main); return TDateTimeParserBaseDeprecated::GetResult(X509ValidityDateTimeParser_first_final, defaultValue); } - + TInstant TX509Validity4yDateTimeParserDeprecated::GetResult(TInstant defaultValue) const { Y_UNUSED(X509Validity4yDateTimeParser_en_main); return TDateTimeParserBaseDeprecated::GetResult(X509Validity4yDateTimeParser_first_final, defaultValue); @@ -444,34 +444,34 @@ TInstant TX509Validity4yDateTimeParser::GetResult(TInstant defaultValue) const { return TDateTimeParserBase::GetResult(X509Validity4yDateTimeParser_first_final, defaultValue); } -template<class TParser, class TResult> -static inline TResult Parse(const char* input, size_t len, TResult defaultValue) { - TParser parser; - if (!parser.ParsePart(input, len)) - return defaultValue; - return parser.GetResult(defaultValue); -} - +template<class TParser, class TResult> +static inline TResult Parse(const char* input, size_t len, TResult defaultValue) { + TParser parser; + if (!parser.ParsePart(input, len)) + return defaultValue; + return parser.GetResult(defaultValue); +} + template<class TParser, class TResult, bool ThrowExceptionOnFailure = true> -static inline TResult ParseUnsafe(const char* input, size_t len) { - TResult r = Parse<TParser, TResult>(input, len, TResult::Max()); +static inline TResult ParseUnsafe(const char* input, size_t len) { + TResult r = Parse<TParser, TResult>(input, len, TResult::Max()); if (ThrowExceptionOnFailure && r == TResult::Max()) ythrow TDateTimeParseException() << "error in datetime parsing. Input data: " << TStringBuf(input, len); - return r; -} - + return r; +} + TInstant TInstant::ParseIso8601Deprecated(const TStringBuf input) { return ParseUnsafe<TIso8601DateTimeParserDeprecated, TInstant>(input.data(), input.size()); -} - +} + TInstant TInstant::ParseRfc822Deprecated(const TStringBuf input) { return ParseUnsafe<TRfc822DateTimeParserDeprecated, TInstant>(input.data(), input.size()); -} - +} + TInstant TInstant::ParseHttpDeprecated(const TStringBuf input) { return ParseUnsafe<THttpDateTimeParserDeprecated, TInstant>(input.data(), input.size()); -} - +} + TInstant TInstant::ParseX509ValidityDeprecated(const TStringBuf input) { switch (input.size()) { case 13: @@ -482,7 +482,7 @@ TInstant TInstant::ParseX509ValidityDeprecated(const TStringBuf input) { ythrow TDateTimeParseException(); } } - + bool TInstant::TryParseIso8601Deprecated(const TStringBuf input, TInstant& instant) { const auto parsed = ParseUnsafe<TIso8601DateTimeParserDeprecated, TInstant, false>(input.data(), input.size()); if (TInstant::Max() == parsed) { @@ -663,44 +663,44 @@ bool ParseRFC822DateTime(const char* input, time_t& utcTime) { return ParseRFC822DateTime(input, strlen(input), utcTime); } -bool ParseISO8601DateTime(const char* input, time_t& utcTime) { - return ParseISO8601DateTime(input, strlen(input), utcTime); -} - -bool ParseHTTPDateTime(const char* input, time_t& utcTime) { - return ParseHTTPDateTime(input, strlen(input), utcTime); -} - +bool ParseISO8601DateTime(const char* input, time_t& utcTime) { + return ParseISO8601DateTime(input, strlen(input), utcTime); +} + +bool ParseHTTPDateTime(const char* input, time_t& utcTime) { + return ParseHTTPDateTime(input, strlen(input), utcTime); +} + bool ParseX509ValidityDateTime(const char* input, time_t& utcTime) { return ParseX509ValidityDateTime(input, strlen(input), utcTime); } - + bool ParseRFC822DateTime(const char* input, size_t inputLen, time_t& utcTime) { - try { + try { utcTime = ParseUnsafe<TRfc822DateTimeParser, TInstant>(input, inputLen).TimeT(); - return true; - } catch (const TDateTimeParseException&) { + return true; + } catch (const TDateTimeParseException&) { return false; - } -} - + } +} + bool ParseISO8601DateTime(const char* input, size_t inputLen, time_t& utcTime) { - try { + try { utcTime = ParseUnsafe<TIso8601DateTimeParser, TInstant>(input, inputLen).TimeT(); return true; - } catch (const TDateTimeParseException&) { - return false; + } catch (const TDateTimeParseException&) { + return false; } } - -bool ParseHTTPDateTime(const char* input, size_t inputLen, time_t& utcTime) { - try { + +bool ParseHTTPDateTime(const char* input, size_t inputLen, time_t& utcTime) { + try { utcTime = ParseUnsafe<THttpDateTimeParser, TInstant>(input, inputLen).TimeT(); - return true; - } catch (const TDateTimeParseException&) { - return false; - } -} + return true; + } catch (const TDateTimeParseException&) { + return false; + } +} bool ParseX509ValidityDateTime(const char* input, size_t inputLen, time_t& utcTime) { TInstant r; @@ -720,15 +720,15 @@ bool ParseX509ValidityDateTime(const char* input, size_t inputLen, time_t& utcTi return true; } -%%{ - -machine TDurationParser; - -include DateTimeParserCommon; - - -multiplier - = '' # >{ MultiplierPower = 6; } # work around Ragel bugs +%%{ + +machine TDurationParser; + +include DateTimeParserCommon; + + +multiplier + = '' # >{ MultiplierPower = 6; } # work around Ragel bugs | 'w' @{ MultiplierPower = 6; Multiplier = 604800; } | 'd' @{ MultiplierPower = 6; Multiplier = 86400; } | 'h' @{ MultiplierPower = 6; Multiplier = 3600; } @@ -737,57 +737,57 @@ multiplier | 'ms' @{ MultiplierPower = 3; Multiplier = 1; } | 'us' @{ MultiplierPower = 0; Multiplier = 1; } | 'ns' @{ MultiplierPower = -3; Multiplier = 1; } - ; - -integer = int @{ IntegerPart = I; }; - -fraction = '.' digit {1,6} >clear_int $update_int @{ FractionPart = I; FractionDigits = Dc; } digit*; - -duration = integer fraction? multiplier; - -main := duration; - -write data noerror; - -}%% - -TDurationParser::TDurationParser() - : cs(0) - , I(0) - , Dc(0) - , MultiplierPower(6) + ; + +integer = int @{ IntegerPart = I; }; + +fraction = '.' digit {1,6} >clear_int $update_int @{ FractionPart = I; FractionDigits = Dc; } digit*; + +duration = integer fraction? multiplier; + +main := duration; + +write data noerror; + +}%% + +TDurationParser::TDurationParser() + : cs(0) + , I(0) + , Dc(0) + , MultiplierPower(6) , Multiplier(1) - , IntegerPart(0) - , FractionPart(0) - , FractionDigits(0) -{ + , IntegerPart(0) + , FractionPart(0) + , FractionDigits(0) +{ Y_UNUSED(TDurationParser_en_main); - %% write init; -} - -bool TDurationParser::ParsePart(const char* input, size_t len) { - const char* p = input; - const char* pe = input + len; - - %% write exec; - return cs != %%{ write error; }%%; -} - + %% write init; +} + +bool TDurationParser::ParsePart(const char* input, size_t len) { + const char* p = input; + const char* pe = input + len; + + %% write exec; + return cs != %%{ write error; }%%; +} + static inline ui64 DecPower(ui64 part, i32 power) { if (power >= 0) return part * Power(10, power); return part / Power(10, -power); -} - -TDuration TDurationParser::GetResult(TDuration defaultValue) const { - if (cs < TDurationParser_first_final) - return defaultValue; - ui64 us = 0; +} + +TDuration TDurationParser::GetResult(TDuration defaultValue) const { + if (cs < TDurationParser_first_final) + return defaultValue; + ui64 us = 0; us += Multiplier * DecPower(IntegerPart, MultiplierPower); us += Multiplier * DecPower(FractionPart, MultiplierPower - FractionDigits); - return TDuration::MicroSeconds(us); -} - + return TDuration::MicroSeconds(us); +} + bool TDuration::TryParse(const TStringBuf input, TDuration& result) { TDuration r = ::Parse<TDurationParser, TDuration>(input.data(), input.size(), TDuration::Max()); if (r == TDuration::Max()) @@ -795,7 +795,7 @@ bool TDuration::TryParse(const TStringBuf input, TDuration& result) { result = r; return true; } - + TDuration TDuration::Parse(const TStringBuf input) { return ParseUnsafe<TDurationParser, TDuration>(input.data(), input.size()); -} +} diff --git a/util/datetime/parser_ut.cpp b/util/datetime/parser_ut.cpp index 0fc4d4993a..61364af997 100644 --- a/util/datetime/parser_ut.cpp +++ b/util/datetime/parser_ut.cpp @@ -22,31 +22,31 @@ Y_UNIT_TEST_SUITE(TDateTimeParseTest) { r = ParseRFC822DateTime("Fri, 4 Mar 2005 19:34:45 EST", t); UNIT_ASSERT(r); - UNIT_ASSERT_VALUES_EQUAL(t, (time_t)1109964885 + 5 * SECONDS_PER_HOUR); + UNIT_ASSERT_VALUES_EQUAL(t, (time_t)1109964885 + 5 * SECONDS_PER_HOUR); r = ParseRFC822DateTime("Fri, 4 Mar 2005 19:34:45 EDT", t); UNIT_ASSERT(r); - UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 4 * SECONDS_PER_HOUR); + UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 4 * SECONDS_PER_HOUR); r = ParseRFC822DateTime("Fri, 4 Mar 2005 19:34:45 CST", t); UNIT_ASSERT(r); - UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 6 * SECONDS_PER_HOUR); + UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 6 * SECONDS_PER_HOUR); r = ParseRFC822DateTime("Fri, 4 Mar 2005 19:34:45 CDT", t); UNIT_ASSERT(r); - UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 5 * SECONDS_PER_HOUR); + UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 5 * SECONDS_PER_HOUR); r = ParseRFC822DateTime("Fri, 4 Mar 2005 19:34:45 MST", t); UNIT_ASSERT(r); - UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 7 * SECONDS_PER_HOUR); + UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 7 * SECONDS_PER_HOUR); r = ParseRFC822DateTime("Fri, 4 Mar 2005 19:34:45 MDT", t); UNIT_ASSERT(r); - UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 6 * SECONDS_PER_HOUR); + UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 6 * SECONDS_PER_HOUR); r = ParseRFC822DateTime("Fri, 4 Mar 2005 19:34:45 PST", t); UNIT_ASSERT(r); - UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 8 * SECONDS_PER_HOUR); + UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 8 * SECONDS_PER_HOUR); r = ParseRFC822DateTime("Fri, 4 Mar 2005 19:34:45 PDT", t); UNIT_ASSERT(r); - UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 7 * SECONDS_PER_HOUR); + UNIT_ASSERT_EQUAL(t, (time_t)1109964885 + 7 * SECONDS_PER_HOUR); // optinal century r = ParseRFC822DateTime("Fri, 4 Mar 05 19:34:45 UT", t); @@ -118,14 +118,14 @@ Y_UNIT_TEST_SUITE(TDateTimeParseTest) { r = ParseRFC822DateTime(" \t Fri, \t 4 \t Mar \t 2005 \t 19:34:45 \t UT \t ", t); // spaces with tabs UNIT_ASSERT(r); UNIT_ASSERT_EQUAL(t, (time_t)1109964885); - + r = ParseRFC822DateTime("Thu, 01 Jan 1970 03:00:00 +0300", t); // spaces with tabs - UNIT_ASSERT(r); - UNIT_ASSERT_EQUAL(t, (time_t)0); - + UNIT_ASSERT(r); + UNIT_ASSERT_EQUAL(t, (time_t)0); + r = ParseRFC822DateTime("Sat, 14 Feb 2009 02:31:30 +0300", t); // spaces with tabs - UNIT_ASSERT(r); - UNIT_ASSERT_EQUAL(t, (time_t)1234567890); + UNIT_ASSERT(r); + UNIT_ASSERT_EQUAL(t, (time_t)1234567890); } time_t GetOffset(char militaryZone) { @@ -143,7 +143,7 @@ Y_UNIT_TEST_SUITE(TDateTimeParseTest) { } } - void DoTestMilitaryZones(char firstChar, char lastChar) { + void DoTestMilitaryZones(char firstChar, char lastChar) { const time_t utcTime = 1109964885; // Fri, 4 Mar 2005 19:34:45 UT char text[] = "Fri, 4 Mar 2005 19:34:45 A"; const size_t zoneCharIndex = strlen(text) - 1; @@ -155,17 +155,17 @@ Y_UNIT_TEST_SUITE(TDateTimeParseTest) { text[zoneCharIndex] = militaryZone; UNIT_ASSERT(ParseRFC822DateTime(text, t)); - UNIT_ASSERT_EQUAL(t, utcTime - offset); + UNIT_ASSERT_EQUAL(t, utcTime - offset); } } Y_UNIT_TEST(TestRfc822MilitaryZones) { - DoTestMilitaryZones('A', 'I'); - DoTestMilitaryZones('K', 'Z'); - DoTestMilitaryZones('a', 'i'); - DoTestMilitaryZones('k', 'z'); - } - + DoTestMilitaryZones('A', 'I'); + DoTestMilitaryZones('K', 'Z'); + DoTestMilitaryZones('a', 'i'); + DoTestMilitaryZones('k', 'z'); + } + Y_UNIT_TEST(TestRfc822IncorrectDates) { bool r = true; time_t t = 0; @@ -219,7 +219,7 @@ Y_UNIT_TEST_SUITE(TDateTimeParseTest) { r = ParseRFC822DateTime("17 Nov 2008 19:34:123 UT", t); UNIT_ASSERT(!r); r = ParseRFC822DateTime("17 Nov 2008 19:34:12.12 UT", t); // fractions of second are now allowed - UNIT_ASSERT(!r); + UNIT_ASSERT(!r); r = ParseRFC822DateTime("Mon , 17 Nov 2005 19:34:45 UT", t); // space after day before the comma UNIT_ASSERT(!r); @@ -254,113 +254,113 @@ Y_UNIT_TEST_SUITE(TDateTimeParseTest) { r = ParseRFC822DateTime("Mon, 17 Nov 2008 19:34:45 -03030", t); UNIT_ASSERT(!r); } - + Y_UNIT_TEST(TestRfc822Partial) { TRfc822DateTimeParser p; - const char* part1 = "Fri, 4 Mar 05 1"; - const char* part2 = "9:34:45 +0300"; - UNIT_ASSERT(p.ParsePart(part1, strlen(part1))); - UNIT_ASSERT(p.ParsePart(part2, strlen(part2))); - UNIT_ASSERT_VALUES_EQUAL(TInstant::Seconds(1109954085), p.GetResult(TInstant::Max())); + const char* part1 = "Fri, 4 Mar 05 1"; + const char* part2 = "9:34:45 +0300"; + UNIT_ASSERT(p.ParsePart(part1, strlen(part1))); + UNIT_ASSERT(p.ParsePart(part2, strlen(part2))); + UNIT_ASSERT_VALUES_EQUAL(TInstant::Seconds(1109954085), p.GetResult(TInstant::Max())); p = TRfc822DateTimeParser(); const char* part3 = "Fri, 4 Mar 05 19:34:46 +0300"; UNIT_ASSERT(p.ParsePart(part3, strlen(part3))); UNIT_ASSERT_VALUES_EQUAL(TInstant::Seconds(1109954086), p.GetResult(TInstant::Zero())); - } + } Y_UNIT_TEST(TestIso8601Partial) { TIso8601DateTimeParser p; - const char* part1 = "1990-03-15T15:1"; - const char* part2 = "6:17+0732"; - UNIT_ASSERT(p.ParsePart(part1, strlen(part1))); - UNIT_ASSERT(p.ParsePart(part2, strlen(part2))); - UNIT_ASSERT_VALUES_EQUAL(TInstant::Seconds(637487057), p.GetResult(TInstant::Max())); + const char* part1 = "1990-03-15T15:1"; + const char* part2 = "6:17+0732"; + UNIT_ASSERT(p.ParsePart(part1, strlen(part1))); + UNIT_ASSERT(p.ParsePart(part2, strlen(part2))); + UNIT_ASSERT_VALUES_EQUAL(TInstant::Seconds(637487057), p.GetResult(TInstant::Max())); p = TIso8601DateTimeParser(); const char* part3 = "1990-03-15T15:16:18+0732"; UNIT_ASSERT(p.ParsePart(part3, strlen(part3))); UNIT_ASSERT_VALUES_EQUAL(TInstant::Seconds(637487058), p.GetResult(TInstant::Zero())); - } - + } + Y_UNIT_TEST(TestIso8601Correct) { - bool ret; - time_t t; - - // ISO 8601 actually does not allow time without time zone + bool ret; + time_t t; + + // ISO 8601 actually does not allow time without time zone ret = ParseISO8601DateTime("1990-03-15", t); - UNIT_ASSERT(ret); + UNIT_ASSERT(ret); UNIT_ASSERT_VALUES_EQUAL(t, 637459200); - - // some normal dates + + // some normal dates ret = ParseISO8601DateTime("1990-03-15T15:16:17Z", t); - UNIT_ASSERT(ret); - UNIT_ASSERT_VALUES_EQUAL(t, 637514177); - + UNIT_ASSERT(ret); + UNIT_ASSERT_VALUES_EQUAL(t, 637514177); + ret = ParseISO8601DateTime("1990-03-15t15:16:17z", t); // lower-case must be allowed too - UNIT_ASSERT(ret); - UNIT_ASSERT_VALUES_EQUAL(t, 637514177); - + UNIT_ASSERT(ret); + UNIT_ASSERT_VALUES_EQUAL(t, 637514177); + ret = ParseISO8601DateTime("1990-03-15 15:16:17Z", t); // space as separator should be allowed - UNIT_ASSERT(ret); - UNIT_ASSERT_VALUES_EQUAL(t, 637514177); - + UNIT_ASSERT(ret); + UNIT_ASSERT_VALUES_EQUAL(t, 637514177); + ret = ParseISO8601DateTime("1990-03-15T15:16:17.18Z", t); - UNIT_ASSERT(ret); - UNIT_ASSERT_VALUES_EQUAL(t, 637514177); - + UNIT_ASSERT(ret); + UNIT_ASSERT_VALUES_EQUAL(t, 637514177); + ret = ParseISO8601DateTime("1990-03-15T15:16:17.18+07:32", t); - UNIT_ASSERT(ret); - UNIT_ASSERT_VALUES_EQUAL(t, 637487057); - + UNIT_ASSERT(ret); + UNIT_ASSERT_VALUES_EQUAL(t, 637487057); + ret = ParseISO8601DateTime("1990-03-15T15:16:17.18+0732", t); - UNIT_ASSERT(ret); - UNIT_ASSERT_VALUES_EQUAL(t, 637487057); - + UNIT_ASSERT(ret); + UNIT_ASSERT_VALUES_EQUAL(t, 637487057); + ret = ParseISO8601DateTime("1970-01-01T00:00:00Z", t); - UNIT_ASSERT(ret); - UNIT_ASSERT_VALUES_EQUAL(t, 0); - + UNIT_ASSERT(ret); + UNIT_ASSERT_VALUES_EQUAL(t, 0); + ret = ParseISO8601DateTime("1970-01-01T00:01:02Z", t); - UNIT_ASSERT(ret); - UNIT_ASSERT_VALUES_EQUAL(t, 62); - -#if 0 - // these tests are disabled, because time zones are handled differently - // in old util/ parser and agalakhov@ parser + UNIT_ASSERT(ret); + UNIT_ASSERT_VALUES_EQUAL(t, 62); + +#if 0 + // these tests are disabled, because time zones are handled differently + // in old util/ parser and agalakhov@ parser ret = ParseISO8601DateTime("1970-01-01", t); - UNIT_ASSERT(ret); - UNIT_ASSERT_VALUES_EQUAL(t, -4 * 3600); - + UNIT_ASSERT(ret); + UNIT_ASSERT_VALUES_EQUAL(t, -4 * 3600); + ret = ParseISO8601DateTime("1970-01-02", t); - UNIT_ASSERT(ret); - UNIT_ASSERT_VALUES_EQUAL(t, 86400 - 3 * 3600); -#endif - - // this is wrong because of timezone + UNIT_ASSERT(ret); + UNIT_ASSERT_VALUES_EQUAL(t, 86400 - 3 * 3600); +#endif + + // this is wrong because of timezone ret = ParseISO8601DateTime("2009-02-14T03:31:30", t); - UNIT_ASSERT(ret); + UNIT_ASSERT(ret); UNIT_ASSERT_VALUES_EQUAL(t, 1234582290); - + ret = ParseISO8601DateTime("2009-02-14t03:31:30", t); - UNIT_ASSERT(ret); + UNIT_ASSERT(ret); UNIT_ASSERT_VALUES_EQUAL(t, 1234582290); - + ret = ParseISO8601DateTime("2009-02-14T02:31:30+0300", t); - UNIT_ASSERT(ret); - UNIT_ASSERT_VALUES_EQUAL(t, 1234567890); - + UNIT_ASSERT(ret); + UNIT_ASSERT_VALUES_EQUAL(t, 1234567890); + ret = ParseISO8601DateTime("2009-02-14T02:31:30+03:00", t); - UNIT_ASSERT(ret); - UNIT_ASSERT_VALUES_EQUAL(t, 1234567890); - + UNIT_ASSERT(ret); + UNIT_ASSERT_VALUES_EQUAL(t, 1234567890); + ret = ParseISO8601DateTime("2009-02-14 02:31:30+03:00", t); - UNIT_ASSERT(ret); - UNIT_ASSERT_VALUES_EQUAL(t, 1234567890); + UNIT_ASSERT(ret); + UNIT_ASSERT_VALUES_EQUAL(t, 1234567890); ret = ParseISO8601DateTime("2010-03-28T04:27:00.000-07:00", t); UNIT_ASSERT(ret); UNIT_ASSERT_VALUES_EQUAL(t, 1269775620); - } - + } + Y_UNIT_TEST(TestIso8601TimeZone) { time_t t1, t2, t3, t4; UNIT_ASSERT(ParseISO8601DateTime("2010-03-28T04:27:00.000+07:00", t1)); @@ -373,54 +373,54 @@ Y_UNIT_TEST_SUITE(TDateTimeParseTest) { } Y_UNIT_TEST(TestIso8601Incorrect) { - bool ret; - time_t t; - + bool ret; + time_t t; + t = 12345; ret = ParseISO8601DateTime("", t); UNIT_ASSERT(!ret); UNIT_ASSERT_EQUAL(t, (time_t)12345); - // some bad dates + // some bad dates t = 54321; ret = ParseISO8601DateTime("a990-01-15", t); - UNIT_ASSERT(!ret); + UNIT_ASSERT(!ret); UNIT_ASSERT_EQUAL(t, (time_t)54321); - + ret = ParseISO8601DateTime("1970-01-01T03:00:00+04:00", t); // this is 1969 GMT UNIT_ASSERT(!ret); ret = ParseISO8601DateTime("1987-13-16", t); - UNIT_ASSERT(!ret); - + UNIT_ASSERT(!ret); + ret = ParseISO8601DateTime("1987-02-29", t); - UNIT_ASSERT(!ret); - + UNIT_ASSERT(!ret); + ret = ParseISO8601DateTime("1990-03-151Y15:16:17.18", t); - UNIT_ASSERT(!ret); - + UNIT_ASSERT(!ret); + ret = ParseISO8601DateTime("1990-03-151T15:16:17:43.18", t); - UNIT_ASSERT(!ret); - + UNIT_ASSERT(!ret); + ret = ParseISO8601DateTime("1990-03-151T15:16:17.18Z+21:32", t); - UNIT_ASSERT(!ret); - } - + UNIT_ASSERT(!ret); + } + Y_UNIT_TEST(TestIso8601Fractions) { - UNIT_ASSERT_VALUES_EQUAL( + UNIT_ASSERT_VALUES_EQUAL( TInstant::ParseIso8601("2009-09-19 03:37:08.1+04:00"), TInstant::Seconds(1253317028) + TDuration::MilliSeconds(100)); - UNIT_ASSERT_VALUES_EQUAL( + UNIT_ASSERT_VALUES_EQUAL( TInstant::ParseIso8601("2009-09-19 03:37:03.926+04:00"), TInstant::Seconds(1253317023) + TDuration::MilliSeconds(926)); - UNIT_ASSERT_VALUES_EQUAL( + UNIT_ASSERT_VALUES_EQUAL( TInstant::ParseIso8601("2009-09-19 03:37:03.92622+04:00"), TInstant::Seconds(1253317023) + TDuration::MicroSeconds(926220)); - UNIT_ASSERT_VALUES_EQUAL( + UNIT_ASSERT_VALUES_EQUAL( TInstant::ParseIso8601("2009-09-19 03:37:03.012331+04:00"), TInstant::Seconds(1253317023) + TDuration::MicroSeconds(12331)); - } - + } + Y_UNIT_TEST(TestIso8601FractionsBelowMicro) { UNIT_ASSERT_VALUES_EQUAL( TInstant::ParseIso8601("1970-01-01 00:00:00.0000000+00:00"), @@ -472,26 +472,26 @@ Y_UNIT_TEST_SUITE(TDateTimeParseTest) { } Y_UNIT_TEST(TestHttpDate) { - UNIT_ASSERT_VALUES_EQUAL( + UNIT_ASSERT_VALUES_EQUAL( TInstant::ParseHttp("Sun, 06 Nov 1994 08:49:37 GMT"), TInstant::ParseIso8601("1994-11-06T08:49:37Z")); - UNIT_ASSERT_VALUES_EQUAL( + UNIT_ASSERT_VALUES_EQUAL( TInstant::ParseHttp("Sunday, 06-Nov-94 08:49:37 GMT"), TInstant::ParseIso8601("1994-11-06T08:49:37Z")); - UNIT_ASSERT_VALUES_EQUAL( + UNIT_ASSERT_VALUES_EQUAL( TInstant::ParseHttp("Sun Nov 6 08:49:37 1994"), TInstant::ParseIso8601("1994-11-06T08:49:37Z")); UNIT_ASSERT_VALUES_EQUAL( TInstant::ParseHttp("Mon, 19 Jan 2037 08:49:37 GMT"), TInstant::ParseIso8601("2037-01-19T08:49:37Z")); - } - + } + Y_UNIT_TEST(TestHttpDateIncorrect) { - bool ret; - time_t t = 0; + bool ret; + time_t t = 0; ret = ParseHTTPDateTime("1990-03-15T15:16:17Z", t); - UNIT_ASSERT(!ret); - } + UNIT_ASSERT(!ret); + } Y_UNIT_TEST(TestX509ValidityTime) { UNIT_ASSERT_VALUES_EQUAL( @@ -568,8 +568,8 @@ Y_UNIT_TEST_SUITE(TDateTimeParseTest) { UNIT_ASSERT(!TInstant::TryParseX509(s, iTry)); } } -} - +} + Y_UNIT_TEST_SUITE(TDurationParseTest) { Y_UNIT_TEST(TestParse) { UNIT_ASSERT_VALUES_EQUAL(TDuration::Seconds(60 * 60 * 24 * 7), TDuration::Parse("1w")); @@ -605,23 +605,23 @@ Y_UNIT_TEST_SUITE(TDurationParseTest) { UNIT_ASSERT_VALUES_EQUAL(TDuration::Hours(36), TDuration::Parse("1d12h")); #endif - UNIT_ASSERT_VALUES_EQUAL(TDuration::Seconds(10), TDuration::Parse("10s")); - UNIT_ASSERT_VALUES_EQUAL(TDuration::Seconds(10), TDuration::Parse("10.000s")); - UNIT_ASSERT_VALUES_EQUAL(TDuration::MicroSeconds(4), TDuration::Parse("0.000004s")); - UNIT_ASSERT_VALUES_EQUAL(TDuration::MilliSeconds(3456), TDuration::Parse("3.456s")); - UNIT_ASSERT_VALUES_EQUAL(TDuration::MilliSeconds(3450), TDuration::Parse("3.450s")); - UNIT_ASSERT_VALUES_EQUAL(TDuration::MilliSeconds(3450), TDuration::Parse("3.45000000s")); - UNIT_ASSERT_VALUES_EQUAL(TDuration::MilliSeconds(3450), TDuration::Parse("3.45s")); - - UNIT_ASSERT_VALUES_EQUAL(TDuration::MilliSeconds(1), TDuration::Parse("1ms")); - UNIT_ASSERT_VALUES_EQUAL(TDuration::MicroSeconds(1100), TDuration::Parse("1.1ms")); - - UNIT_ASSERT_VALUES_EQUAL(TDuration::Seconds(112), TDuration::Parse("112")); - UNIT_ASSERT_VALUES_EQUAL(TDuration::MicroSeconds(14456), TDuration::Parse("14456us")); + UNIT_ASSERT_VALUES_EQUAL(TDuration::Seconds(10), TDuration::Parse("10s")); + UNIT_ASSERT_VALUES_EQUAL(TDuration::Seconds(10), TDuration::Parse("10.000s")); + UNIT_ASSERT_VALUES_EQUAL(TDuration::MicroSeconds(4), TDuration::Parse("0.000004s")); + UNIT_ASSERT_VALUES_EQUAL(TDuration::MilliSeconds(3456), TDuration::Parse("3.456s")); + UNIT_ASSERT_VALUES_EQUAL(TDuration::MilliSeconds(3450), TDuration::Parse("3.450s")); + UNIT_ASSERT_VALUES_EQUAL(TDuration::MilliSeconds(3450), TDuration::Parse("3.45000000s")); + UNIT_ASSERT_VALUES_EQUAL(TDuration::MilliSeconds(3450), TDuration::Parse("3.45s")); + + UNIT_ASSERT_VALUES_EQUAL(TDuration::MilliSeconds(1), TDuration::Parse("1ms")); + UNIT_ASSERT_VALUES_EQUAL(TDuration::MicroSeconds(1100), TDuration::Parse("1.1ms")); + + UNIT_ASSERT_VALUES_EQUAL(TDuration::Seconds(112), TDuration::Parse("112")); + UNIT_ASSERT_VALUES_EQUAL(TDuration::MicroSeconds(14456), TDuration::Parse("14456us")); UNIT_ASSERT_VALUES_EQUAL(TDuration::MicroSeconds(1), TDuration::Parse("1000ns")); UNIT_ASSERT_VALUES_EQUAL(TDuration::MicroSeconds(1), TDuration::Parse("0.000001s")); UNIT_ASSERT_EQUAL(TDuration(), TDuration::Parse("10ns")); // TDuration has 1us precision. - } -} + } +} diff --git a/util/datetime/systime.cpp b/util/datetime/systime.cpp index 21f106e9da..6ee7e8fc6e 100644 --- a/util/datetime/systime.cpp +++ b/util/datetime/systime.cpp @@ -1,10 +1,10 @@ #include "systime.h" - + #include <util/system/yassert.h> #include <util/system/defaults.h> -#ifdef _win_ - +#ifdef _win_ + void FileTimeToTimeval(const FILETIME* ft, timeval* tv) { const i64 NANOINTERVAL = LL(116444736000000000); // Number of 100 nanosecond units from 1/1/1601 to 1/1/1970 union { @@ -34,7 +34,7 @@ tm* localtime_r(const time_t* clock, tm* result) { } tm* gmtime_r(const time_t* clock, tm* result) { - return gmtime_s(result, clock) == 0 ? result : 0; + return gmtime_s(result, clock) == 0 ? result : 0; } char* ctime_r(const time_t* clock, char* buf) { diff --git a/util/draft/date.cpp b/util/draft/date.cpp index 11b080820f..a290c46050 100644 --- a/util/draft/date.cpp +++ b/util/draft/date.cpp @@ -2,7 +2,7 @@ #include <util/string/cast.h> #include <util/generic/yexception.h> -#include <util/datetime/base.h> +#include <util/datetime/base.h> time_t GetDateStart(time_t ts) { tm dateTm; diff --git a/util/draft/date.h b/util/draft/date.h index 01c9ae308f..e3eb616fe5 100644 --- a/util/draft/date.h +++ b/util/draft/date.h @@ -11,9 +11,9 @@ time_t GetDateStart(time_t ts); -// Local date (without time zone) +// Local date (without time zone) class TDate { - // XXX: wrong: must store number of days since epoch + // XXX: wrong: must store number of days since epoch time_t Timestamp; public: @@ -22,7 +22,7 @@ public: { } - // XXX: wrong. Should be replace with two methods: TodayGmt() and TodayLocal() + // XXX: wrong. Should be replace with two methods: TodayGmt() and TodayLocal() static TDate Today() { return TDate(time(nullptr)); } diff --git a/util/draft/holder_vector.h b/util/draft/holder_vector.h index c03422584c..1c62055bd9 100644 --- a/util/draft/holder_vector.h +++ b/util/draft/holder_vector.h @@ -15,15 +15,15 @@ public: } ~THolderVector() { - Clear(); - } - - void Clear() { + Clear(); + } + + void Clear() { for (typename TBase::iterator it = TBase::begin(); it != TBase::end(); ++it) { if (*it) D::Destroy(*it); } - TBase::clear(); + TBase::clear(); } size_t Size() const { @@ -46,9 +46,9 @@ public: } void PushBack(THolder<T> t) { - PushBack(t.Release()); - } - + PushBack(t.Release()); + } + void Reset(size_t i, THolder<T> t) { T* current = (*this)[i]; if (current) { @@ -88,9 +88,9 @@ public: using TBase::back; using TBase::begin; using TBase::capacity; - using TBase::empty; + using TBase::empty; using TBase::end; - using TBase::front; + using TBase::front; using TBase::reserve; using TBase::size; diff --git a/util/draft/ya.make b/util/draft/ya.make index 815b771ced..e00674b682 100644 --- a/util/draft/ya.make +++ b/util/draft/ya.make @@ -10,7 +10,7 @@ IF (TSTRING_IS_STD_STRING) ENDIF() SRCS( - date.cpp + date.cpp datetime.cpp enum.cpp holder_vector.cpp diff --git a/util/folder/dirut.cpp b/util/folder/dirut.cpp index 1f22c0e261..ffc9b09f96 100644 --- a/util/folder/dirut.cpp +++ b/util/folder/dirut.cpp @@ -403,17 +403,17 @@ int mkpath(char* path, int mode) { // did not require last component of the file name to exist (other implementations will fail // if it does not). Use RealLocation if that behaviour is required. TString RealPath(const TString& path) { - TTempBuf result; + TTempBuf result; Y_ASSERT(result.Size() > MAX_PATH); //TMP_BUF_LEN > MAX_PATH -#ifdef _win_ +#ifdef _win_ if (GetFullPathName(path.data(), result.Size(), result.Data(), nullptr) == 0) -#else +#else if (realpath(path.data(), result.Data()) == nullptr) -#endif +#endif ythrow TFileError() << "RealPath failed \"" << path << "\""; - return result.Data(); -} - + return result.Data(); +} + TString RealLocation(const TString& path) { if (NFs::Exists(path)) return RealPath(path); @@ -451,37 +451,37 @@ int MakeTempDir(char path[/*FILENAME_MAX*/], const char* prefix) { bool IsDir(const TString& path) { return TFileStat(path).IsDir(); -} - +} + TString GetHomeDir() { TString s(getenv("HOME")); - if (!s) { -#ifndef _win32_ + if (!s) { +#ifndef _win32_ passwd* pw = nullptr; - s = getenv("USER"); + s = getenv("USER"); if (s) pw = getpwnam(s.data()); - else - pw = getpwuid(getuid()); - if (pw) - s = pw->pw_dir; - else -#endif - { + else + pw = getpwuid(getuid()); + if (pw) + s = pw->pw_dir; + else +#endif + { char* cur_dir = getcwd(nullptr, 0); - s = cur_dir; - free(cur_dir); - } - } - return s; -} - + s = cur_dir; + free(cur_dir); + } + } + return s; +} + void MakeDirIfNotExist(const char* path, int mode) { if (!NFs::MakeDirectory(path, NFs::EFilePermission(mode)) && !NFs::Exists(path)) { ythrow TSystemError() << "failed to create directory " << path; - } -} - + } +} + void MakePathIfNotExist(const char* path, int mode) { NFs::MakeDirectoryRecursive(path, NFs::EFilePermission(mode)); if (!NFs::Exists(path) || !TFileStat(path).IsDir()) { @@ -489,22 +489,22 @@ void MakePathIfNotExist(const char* path, int mode) { } } -const char* GetFileNameComponent(const char* f) { - const char* p = strrchr(f, LOCSLASH_C); +const char* GetFileNameComponent(const char* f) { + const char* p = strrchr(f, LOCSLASH_C); #ifdef _win_ // "/" is also valid char separator on Windows const char* p2 = strrchr(f, '/'); if (p2 > p) p = p2; #endif - - if (p) { - return p + 1; - } - - return f; -} - + + if (p) { + return p + 1; + } + + return f; +} + TString GetSystemTempDir() { #ifdef _win_ char buffer[1024]; @@ -513,19 +513,19 @@ TString GetSystemTempDir() { ythrow TSystemError() << "failed to get system temporary directory"; } return TString(buffer, size); -#else - const char* var = "TMPDIR"; - const char* def = "/tmp"; - const char* r = getenv(var); +#else + const char* var = "TMPDIR"; + const char* def = "/tmp"; + const char* r = getenv(var); const char* result = r ? r : def; return result[0] == '/' ? result : ResolveDir(result); #endif -} - +} + TString ResolveDir(const char* path) { - return ResolvePath(path, true); -} - + return ResolvePath(path, true); +} + bool SafeResolveDir(const char* path, TString& result) { try { result = ResolvePath(path, true); @@ -537,10 +537,10 @@ bool SafeResolveDir(const char* path, TString& result) { TString GetDirName(const TString& path) { return TFsPath(path).Dirname(); -} - -#ifdef _win32_ - +} + +#ifdef _win32_ + char* realpath(const char* pathname, char resolved_path[MAXPATHLEN]) { // partial implementation: no path existence check return _fullpath(resolved_path, pathname, MAXPATHLEN - 1); @@ -607,7 +607,7 @@ TString ResolvePath(const char* rel, const char* abs, bool isdir) { ythrow yexception() << "cannot resolve path: \"" << rel << "\""; return buf; } - + TString ResolvePath(const char* path, bool isDir) { return ResolvePath(path, nullptr, isDir); } diff --git a/util/folder/dirut.h b/util/folder/dirut.h index b2794d337a..2537027b12 100644 --- a/util/folder/dirut.h +++ b/util/folder/dirut.h @@ -61,7 +61,7 @@ const char* GetDirectorySeparatorS(); void RemoveDirWithContents(TString dirName); -const char* GetFileNameComponent(const char* f); +const char* GetFileNameComponent(const char* f); inline TString GetFileNameComponent(const TString& f) { return GetFileNameComponent(f.data()); @@ -70,7 +70,7 @@ inline TString GetFileNameComponent(const TString& f) { /// RealPath doesn't guarantee trailing separator to be stripped or left in place for directories. TString RealPath(const TString& path); // throws TString RealLocation(const TString& path); /// throws; last file name component doesn't need to exist - + TString GetSystemTempDir(); int MakeTempDir(char path[/*FILENAME_MAX*/], const char* prefix); diff --git a/util/folder/dirut_ut.cpp b/util/folder/dirut_ut.cpp index 2353e7a6e2..45ebfc842c 100644 --- a/util/folder/dirut_ut.cpp +++ b/util/folder/dirut_ut.cpp @@ -1,18 +1,18 @@ #include "dirut.h" #include "tempdir.h" - + #include <library/cpp/testing/unittest/registar.h> - + #include <util/generic/string.h> #include <util/memory/tempbuf.h> #include <util/stream/file.h> #include <util/system/platform.h> - + Y_UNIT_TEST_SUITE(TDirutTest) { Y_UNIT_TEST(TestRealPath) { - UNIT_ASSERT(IsDir(RealPath("."))); + UNIT_ASSERT(IsDir(RealPath("."))); } - + Y_UNIT_TEST(TestRealLocation) { UNIT_ASSERT(IsDir(RealLocation("."))); diff --git a/util/folder/fts.cpp b/util/folder/fts.cpp index 0a658d9916..0e6a6f86eb 100644 --- a/util/folder/fts.cpp +++ b/util/folder/fts.cpp @@ -39,7 +39,7 @@ #include <util/system/defaults.h> #include <util/system/error.h> -#include <stdlib.h> +#include <stdlib.h> #ifndef _win_ #include <inttypes.h> #include <sys/param.h> diff --git a/util/folder/iterator.h b/util/folder/iterator.h index cf8a621b9b..69e025b9c4 100644 --- a/util/folder/iterator.h +++ b/util/folder/iterator.h @@ -7,8 +7,8 @@ #include <util/generic/iterator.h> #include <util/generic/yexception.h> -/// Note this magic API traverses directory hierarchy - +/// Note this magic API traverses directory hierarchy + class TDirIterator: public TInputRangeAdaptor<TDirIterator> { struct TFtsDestroy { static inline void Destroy(FTS* f) noexcept { diff --git a/util/folder/iterator_ut.cpp b/util/folder/iterator_ut.cpp index 15fdda8713..936becd139 100644 --- a/util/folder/iterator_ut.cpp +++ b/util/folder/iterator_ut.cpp @@ -10,13 +10,13 @@ #include <util/random/mersenne.h> static TString JoinWithNewline(const TVector<TString>& strings) { - TStringStream ss; + TStringStream ss; for (const auto& string : strings) { ss << string << "\n"; - } - return ss.Str(); -} - + } + return ss.Str(); +} + class TDirIteratorTest: public TTestBase { UNIT_TEST_SUITE(TDirIteratorTest); UNIT_TEST(TestIt) diff --git a/util/folder/path.cpp b/util/folder/path.cpp index 60a14b3fe7..bfe0c67d68 100644 --- a/util/folder/path.cpp +++ b/util/folder/path.cpp @@ -7,14 +7,14 @@ #include <util/system/compiler.h> #include <util/system/file.h> #include <util/system/fs.h> - + struct TFsPath::TSplit: public TAtomicRefCount<TSplit>, public TPathSplit { inline TSplit(const TStringBuf path) : TPathSplit(path) { } -}; - +}; + void TFsPath::CheckDefined() const { if (!IsDefined()) { ythrow TIoException() << TStringBuf("must be defined"); @@ -143,62 +143,62 @@ TString TFsPath::GetName() const { if (!IsDefined()) { return TString(); } - + const TSplit& split = GetSplit(); if (split.size() > 0) { if (split.back() != "..") { return TString(split.back()); - } else { - // cannot just drop last component, because path itself may be a symlink - return RealPath().GetName(); - } - } else { + } else { + // cannot just drop last component, because path itself may be a symlink + return RealPath().GetName(); + } + } else { if (split.IsAbsolute) { - return split.Reconstruct(); - } else { - return Cwd().GetName(); - } - } -} - + return split.Reconstruct(); + } else { + return Cwd().GetName(); + } + } +} + TString TFsPath::GetExtension() const { return TString(GetSplit().Extension()); } -bool TFsPath::IsAbsolute() const { +bool TFsPath::IsAbsolute() const { return GetSplit().IsAbsolute; -} - -bool TFsPath::IsRelative() const { - return !IsAbsolute(); -} - -void TFsPath::InitSplit() const { +} + +bool TFsPath::IsRelative() const { + return !IsAbsolute(); +} + +void TFsPath::InitSplit() const { Split_ = new TSplit(Path_); -} - -TFsPath::TSplit& TFsPath::GetSplit() const { - // XXX: race condition here +} + +TFsPath::TSplit& TFsPath::GetSplit() const { + // XXX: race condition here if (!Split_) { - InitSplit(); + InitSplit(); } return *Split_; -} - +} + static Y_FORCE_INLINE void VerifyPath(const TStringBuf path) { Y_VERIFY(!path.Contains('\0'), "wrong format of TFsPath"); } -TFsPath::TFsPath() { -} - +TFsPath::TFsPath() { +} + TFsPath::TFsPath(const TString& path) : Path_(path) { VerifyPath(Path_); -} - +} + TFsPath::TFsPath(const TStringBuf path) : Path_(ToString(path)) { @@ -208,56 +208,56 @@ TFsPath::TFsPath(const TStringBuf path) TFsPath::TFsPath(const char* path) : Path_(path) { -} - +} + TFsPath TFsPath::Child(const TString& name) const { if (!name) { ythrow TIoException() << "child name must not be empty"; } return *this / name; -} - -struct TClosedir { - static void Destroy(DIR* dir) { +} + +struct TClosedir { + static void Destroy(DIR* dir) { if (dir) { if (0 != closedir(dir)) { ythrow TIoSystemError() << "failed to closedir"; } } - } -}; - + } +}; + void TFsPath::ListNames(TVector<TString>& children) const { - CheckDefined(); + CheckDefined(); THolder<DIR, TClosedir> dir(opendir(this->c_str())); if (!dir) { ythrow TIoSystemError() << "failed to opendir " << Path_; } - for (;;) { - struct dirent de; - struct dirent* ok; + for (;;) { + struct dirent de; + struct dirent* ok; // TODO(yazevnul|IGNIETFERRO-1070): remove these macroses by replacing `readdir_r` with proper // alternative Y_PRAGMA_DIAGNOSTIC_PUSH Y_PRAGMA_NO_DEPRECATED - int r = readdir_r(dir.Get(), &de, &ok); + int r = readdir_r(dir.Get(), &de, &ok); Y_PRAGMA_DIAGNOSTIC_POP if (r != 0) { ythrow TIoSystemError() << "failed to readdir " << Path_; } if (ok == nullptr) { - return; + return; } TString name(de.d_name); if (name == "." || name == "..") { - continue; + continue; } - children.push_back(name); - } -} - + children.push_back(name); + } +} + bool TFsPath::Contains(const TString& component) const { if (!IsDefined()) { return false; @@ -277,43 +277,43 @@ bool TFsPath::Contains(const TString& component) const { void TFsPath::List(TVector<TFsPath>& files) const { TVector<TString> names; - ListNames(names); + ListNames(names); for (auto& name : names) { files.push_back(Child(name)); - } -} - + } +} + void TFsPath::RenameTo(const TString& newPath) const { - CheckDefined(); + CheckDefined(); if (!newPath) { - ythrow TIoException() << "bad new file name"; + ythrow TIoException() << "bad new file name"; } if (!NFs::Rename(Path_, newPath)) { ythrow TIoSystemError() << "failed to rename " << Path_ << " to " << newPath; } -} - -void TFsPath::RenameTo(const char* newPath) const { +} + +void TFsPath::RenameTo(const char* newPath) const { RenameTo(TString(newPath)); -} - -void TFsPath::RenameTo(const TFsPath& newPath) const { - RenameTo(newPath.GetPath()); -} - -void TFsPath::Touch() const { - CheckDefined(); - if (!TFile(*this, OpenAlways).IsOpen()) { - ythrow TIoException() << "failed to touch " << *this; - } -} - -// XXX: move implementation to util/somewhere. -TFsPath TFsPath::RealPath() const { - CheckDefined(); +} + +void TFsPath::RenameTo(const TFsPath& newPath) const { + RenameTo(newPath.GetPath()); +} + +void TFsPath::Touch() const { + CheckDefined(); + if (!TFile(*this, OpenAlways).IsOpen()) { + ythrow TIoException() << "failed to touch " << *this; + } +} + +// XXX: move implementation to util/somewhere. +TFsPath TFsPath::RealPath() const { + CheckDefined(); return ::RealPath(*this); -} - +} + TFsPath TFsPath::RealLocation() const { CheckDefined(); return ::RealLocation(*this); @@ -329,20 +329,20 @@ TFsPath TFsPath::ReadLink() const { return NFs::ReadLink(*this); } -bool TFsPath::Exists() const { +bool TFsPath::Exists() const { return IsDefined() && NFs::Exists(*this); -} - +} + void TFsPath::CheckExists() const { if (!Exists()) { ythrow TIoException() << "path does not exist " << Path_; } } -bool TFsPath::IsDirectory() const { +bool TFsPath::IsDirectory() const { return IsDefined() && TFileStat(GetPath().data()).IsDir(); -} - +} + bool TFsPath::IsFile() const { return IsDefined() && TFileStat(GetPath().data()).IsFile(); } @@ -351,20 +351,20 @@ bool TFsPath::IsSymlink() const { return IsDefined() && TFileStat(GetPath().data(), true).IsSymlink(); } -void TFsPath::DeleteIfExists() const { +void TFsPath::DeleteIfExists() const { if (!IsDefined()) { return; } ::unlink(this->c_str()); ::rmdir(this->c_str()); - if (Exists()) { + if (Exists()) { ythrow TIoException() << "failed to delete " << Path_; - } -} - + } +} + void TFsPath::MkDir(const int mode) const { - CheckDefined(); + CheckDefined(); if (!Exists()) { int r = Mkdir(this->c_str(), mode); if (r != 0) { @@ -376,8 +376,8 @@ void TFsPath::MkDir(const int mode) const { } } } -} - +} + void TFsPath::MkDirs(const int mode) const { CheckDefined(); if (!Exists()) { @@ -386,7 +386,7 @@ void TFsPath::MkDirs(const int mode) const { } } -void TFsPath::ForceDelete() const { +void TFsPath::ForceDelete() const { if (!IsDefined()) { return; } @@ -408,20 +408,20 @@ void TFsPath::ForceDelete() const { ClearLastSystemError(); if (stat.IsDir()) { TVector<TFsPath> children; - List(children); + List(children); for (auto& i : children) { i.ForceDelete(); - } + } ::rmdir(this->c_str()); } else { ::unlink(this->c_str()); - } + } if (LastSystemError()) { ythrow TIoException() << "failed to delete " << Path_; } -} - +} + void TFsPath::CopyTo(const TString& newPath, bool force) const { if (IsDirectory()) { if (force) { @@ -458,18 +458,18 @@ void TFsPath::ForceRenameTo(const TString& newPath) const { } } -TFsPath TFsPath::Cwd() { +TFsPath TFsPath::Cwd() { return TFsPath(::NFs::CurrentWorkingDirectory()); -} - +} + const TPathSplit& TFsPath::PathSplit() const { return GetSplit(); } template <> void Out<TFsPath>(IOutputStream& os, const TFsPath& f) { - os << f.GetPath(); -} + os << f.GetPath(); +} template <> TFsPath FromStringImpl<TFsPath>(const char* s, size_t len) { diff --git a/util/folder/path.h b/util/folder/path.h index 01d41df1d2..2fb4d6b4ef 100644 --- a/util/folder/path.h +++ b/util/folder/path.h @@ -1,5 +1,5 @@ #pragma once - + #include "fwd.h" #include "pathsplit.h" @@ -9,7 +9,7 @@ #include <util/generic/vector.h> #include <util/string/cast.h> #include <util/system/fstat.h> -#include <util/system/platform.h> +#include <util/system/platform.h> #include <util/system/sysstat.h> #include <util/system/yassert.h> @@ -19,26 +19,26 @@ * Class behaviour is platform-dependent. * It uses platform-dependent separators for path-reconstructing operations. */ -class TFsPath { +class TFsPath { private: - struct TSplit; - -public: - TFsPath(); + struct TSplit; + +public: + TFsPath(); TFsPath(const TString& path); TFsPath(const TStringBuf path); - TFsPath(const char* path); - + TFsPath(const char* path); + TFsPath(const std::string& path) : TFsPath(TStringBuf(path)) { } void CheckDefined() const; - - inline bool IsDefined() const { + + inline bool IsDefined() const { return Path_.length() > 0; - } + } inline explicit operator bool() const { return IsDefined(); @@ -50,16 +50,16 @@ public: inline operator const TString&() const { return Path_; - } + } - inline bool operator==(const TFsPath& that) const { + inline bool operator==(const TFsPath& that) const { return Path_ == that.Path_; - } + } inline bool operator!=(const TFsPath& that) const { return Path_ != that.Path_; } - + TFsPath& operator/=(const TFsPath& that); friend TFsPath operator/(const TFsPath& s, const TFsPath& p) { @@ -73,11 +73,11 @@ public: inline const TString& GetPath() const { return Path_; - } - - /// last component of path, or "/" if root + } + + /// last component of path, or "/" if root TString GetName() const; - + /** * "a.b.tmp" -> "tmp" * "a.tmp" -> "tmp" @@ -85,8 +85,8 @@ public: */ TString GetExtension() const; - bool IsAbsolute() const; - bool IsRelative() const; + bool IsAbsolute() const; + bool IsRelative() const; /** * TFsPath("/a/b").IsSubpathOf("/a") -> true @@ -113,7 +113,7 @@ public: bool IsContainerOf(const TFsPath& that) const { return that.IsSubpathOf(*this); } - + TFsPath RelativeTo(const TFsPath& root) const; //must be subpath of root /** @@ -121,10 +121,10 @@ public: */ TFsPath RelativePath(const TFsPath& root) const; //..; for relative paths 1st component must be the same - /** - * Never fails. Returns this if already a root. - */ - TFsPath Parent() const; + /** + * Never fails. Returns this if already a root. + */ + TFsPath Parent() const; TString Basename() const { return GetName(); @@ -132,9 +132,9 @@ public: TString Dirname() const { return Parent(); } - + TFsPath Child(const TString& name) const; - + /** * @brief create this directory * @@ -143,7 +143,7 @@ public: * Nothing to do if dir exists. */ void MkDir(const int mode = MODE0777) const; - + /** * @brief create this directory and all parent directories as needed * @@ -151,66 +151,66 @@ public: */ void MkDirs(const int mode = MODE0777) const; - // XXX: rewrite to return iterator + // XXX: rewrite to return iterator void List(TVector<TFsPath>& children) const; void ListNames(TVector<TString>& children) const; - + // Check, if path contains at least one component with a specific name. bool Contains(const TString& component) const; - // fails to delete non-empty directory - void DeleteIfExists() const; - // delete recursively. Does nothing if not exists - void ForceDelete() const; - - // XXX: ino - + // fails to delete non-empty directory + void DeleteIfExists() const; + // delete recursively. Does nothing if not exists + void ForceDelete() const; + + // XXX: ino + inline bool Stat(TFileStat& stat) const { stat = TFileStat(Path_.data()); return stat.Mode; } - bool Exists() const; - /// false if not exists - bool IsDirectory() const; + bool Exists() const; + /// false if not exists + bool IsDirectory() const; /// false if not exists bool IsFile() const; /// false if not exists - bool IsSymlink() const; - /// throw TIoException if not exists - void CheckExists() const; - + bool IsSymlink() const; + /// throw TIoException if not exists + void CheckExists() const; + void RenameTo(const TString& newPath) const; - void RenameTo(const char* newPath) const; - void RenameTo(const TFsPath& newFile) const; + void RenameTo(const char* newPath) const; + void RenameTo(const TFsPath& newFile) const; void ForceRenameTo(const TString& newPath) const; - + void CopyTo(const TString& newPath, bool force) const; - void Touch() const; - - TFsPath RealPath() const; + void Touch() const; + + TFsPath RealPath() const; TFsPath RealLocation() const; TFsPath ReadLink() const; - - /// always absolute - static TFsPath Cwd(); - + + /// always absolute + static TFsPath Cwd(); + inline void Swap(TFsPath& p) noexcept { DoSwap(Path_, p.Path_); Split_.Swap(p.Split_); } -private: - void InitSplit() const; - TSplit& GetSplit() const; +private: + void InitSplit() const; + TSplit& GetSplit() const; private: TString Path_; /// cache mutable TSimpleIntrusivePtr<TSplit> Split_; -}; +}; namespace NPrivate { inline void AppendToFsPath(TFsPath&) { diff --git a/util/folder/path_ut.cpp b/util/folder/path_ut.cpp index 81ecf0e034..e6a3451016 100644 --- a/util/folder/path_ut.cpp +++ b/util/folder/path_ut.cpp @@ -6,12 +6,12 @@ #include <library/cpp/testing/unittest/registar.h> #include <util/generic/scope.h> -#include <util/system/platform.h> +#include <util/system/platform.h> #include <util/system/yassert.h> -#include <util/stream/output.h> +#include <util/stream/output.h> #include <util/stream/file.h> #include <util/system/fs.h> - + #include <algorithm> #ifdef _win_ @@ -116,19 +116,19 @@ Y_UNIT_TEST_SUITE(TFsPathTests) { UNIT_ASSERT_VALUES_EQUAL(TFsPath("..").Parent(), TFsPath("../..")); #endif } - + Y_UNIT_TEST(GetName) { TTestDirectory d("GetName"); UNIT_ASSERT_VALUES_EQUAL(TString("dfgh"), d.Child("dfgh").GetName()); - + // check does not fail TFsPath(".").GetName(); - -#ifdef _unix_ + +#ifdef _unix_ UNIT_ASSERT_VALUES_EQUAL(TString("/"), TFsPath("/").GetName()); -#endif +#endif } - + Y_UNIT_TEST(GetExtension) { TTestDirectory d("GetExtension"); UNIT_ASSERT_VALUES_EQUAL("", d.Child("a").GetExtension()); @@ -147,7 +147,7 @@ Y_UNIT_TEST_SUITE(TFsPathTests) { UNIT_ASSERT(!f1.Exists()); UNIT_ASSERT(f2.Exists()); } - + Y_UNIT_TEST(TestForceRename) { TTestDirectory xx("TestForceRename"); TFsPath fMain = xx.Child("main"); @@ -171,7 +171,7 @@ Y_UNIT_TEST_SUITE(TFsPathTests) { Y_UNIT_TEST(TestRenameFail) { UNIT_ASSERT_EXCEPTION(TFsPath("sfsfsfsdfsfsdfdf").RenameTo("sdfsdf"), TIoException); } - + #ifndef _win_ Y_UNIT_TEST(TestRealPath) { UNIT_ASSERT(TFsPath(".").RealPath().IsDirectory()); @@ -189,7 +189,7 @@ Y_UNIT_TEST_SUITE(TFsPathTests) { UNIT_ASSERT_VALUES_EQUAL(link.RealPath(), target2.RealPath()); // must not cache old value } #endif - + Y_UNIT_TEST(TestSlashesAndBasename) { TFsPath p("/db/BASE/primus121-025-1380131338//"); UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("primus121-025-1380131338")); @@ -227,27 +227,27 @@ Y_UNIT_TEST_SUITE(TFsPathTests) { Y_UNIT_TEST(TestList) { TTestDirectory td("TestList-dir"); - + TFsPath dir = td.GetFsPath(); dir.Child("a").Touch(); dir.Child("b").MkDir(); dir.Child("b").Child("b-1").Touch(); dir.Child("c").MkDir(); dir.Child("d").Touch(); - + TVector<TString> children; dir.ListNames(children); std::sort(children.begin(), children.end()); - + TVector<TString> expected; expected.push_back("a"); expected.push_back("b"); expected.push_back("c"); expected.push_back("d"); - + UNIT_ASSERT_VALUES_EQUAL(expected, children); } - + #ifdef _unix_ Y_UNIT_TEST(MkDirMode) { TTestDirectory td("MkDirMode"); @@ -809,4 +809,4 @@ Y_UNIT_TEST_SUITE(TFsPathTests) { UNIT_ASSERT_EXCEPTION_CONTAINS(testSymlink.ForceDelete(), TIoException, "failed to delete"); } #endif -} +} diff --git a/util/generic/bitops.h b/util/generic/bitops.h index fb12548d12..2db15fc59b 100644 --- a/util/generic/bitops.h +++ b/util/generic/bitops.h @@ -62,7 +62,7 @@ namespace NBitOps { Y_ASSERT(value); // because __builtin_clz* have undefined result for zero. return std::numeric_limits<unsigned int>::digits - __builtin_clz(value); } - + inline unsigned GetValueBitCountImpl(unsigned long value) noexcept { Y_ASSERT(value); // because __builtin_clz* have undefined result for zero. return std::numeric_limits<unsigned long>::digits - __builtin_clzl(value); diff --git a/util/generic/buffer.h b/util/generic/buffer.h index d3cbf95a01..9576467404 100644 --- a/util/generic/buffer.h +++ b/util/generic/buffer.h @@ -87,7 +87,7 @@ public: inline explicit operator bool() const noexcept { return Size(); } - + inline size_t Avail() const noexcept { return Len_ - Pos_; } @@ -123,9 +123,9 @@ public: } else { memmove(Data_ + pos, Data_ + end, Pos_ - end); Pos_ -= count; - } + } } - + inline void ChopHead(size_t count) { Chop(0U, count); } @@ -136,7 +136,7 @@ public: } inline void Advance(size_t len) { - Resize(Pos_ + len); + Resize(Pos_ + len); } inline void Reserve(size_t len) { diff --git a/util/generic/cast.h b/util/generic/cast.h index 1868a7a36b..0d4a41f385 100644 --- a/util/generic/cast.h +++ b/util/generic/cast.h @@ -10,37 +10,37 @@ #include <cstdlib> -template <class T, class F> -static inline T VerifyDynamicCast(F f) { - if (!f) { +template <class T, class F> +static inline T VerifyDynamicCast(F f) { + if (!f) { return nullptr; - } - - T ret = dynamic_cast<T>(f); - + } + + T ret = dynamic_cast<T>(f); + Y_VERIFY(ret, "verify cast failed"); - - return ret; -} - + + return ret; +} + #if !defined(NDEBUG) #define USE_DEBUG_CHECKED_CAST #endif -namespace NPrivate { - template <typename T, typename F> - static T DynamicCast(F f) { - return dynamic_cast<T>(f); - } -} - +namespace NPrivate { + template <typename T, typename F> + static T DynamicCast(F f) { + return dynamic_cast<T>(f); + } +} + /* * replacement for dynamic_cast(dynamic_cast in debug mode, else static_cast) */ template <class T, class F> static inline T CheckedCast(F f) { #if defined(USE_DEBUG_CHECKED_CAST) - return VerifyDynamicCast<T>(f); + return VerifyDynamicCast<T>(f); #else /* Make sure F is polymorphic. * Without this cast, CheckedCast with non-polymorphic F diff --git a/util/generic/maybe.h b/util/generic/maybe.h index b07de3b3b5..34d21aebcd 100644 --- a/util/generic/maybe.h +++ b/util/generic/maybe.h @@ -222,7 +222,7 @@ public: } ~TMaybe() = default; - + constexpr TMaybe& operator=(const TMaybe&) = default; constexpr TMaybe& operator=(TMaybe&&) = default; @@ -238,9 +238,9 @@ public: } else { Init(std::forward<U>(right)); } - return *this; - } - + return *this; + } + template <class U> std::enable_if_t<TCopyAssignable<U>::value, TMaybe&> @@ -289,16 +289,16 @@ public: this->Defined_ = false; Data()->~T(); } - } - + } + constexpr bool Defined() const noexcept { return this->Defined_; } - + Y_PURE_FUNCTION constexpr bool Empty() const noexcept { return !Defined(); - } - + } + void CheckDefined() const { if (Y_UNLIKELY(!Defined())) { Policy::OnEmpty(typeid(TValueType)); @@ -314,17 +314,17 @@ public: } constexpr const T& GetRef() const& { - CheckDefined(); + CheckDefined(); return *Data(); - } - + } + constexpr T& GetRef() & { - CheckDefined(); + CheckDefined(); return *Data(); - } - + } + constexpr const T&& GetRef() const&& { CheckDefined(); @@ -340,11 +340,11 @@ public: constexpr const T& operator*() const& { return GetRef(); } - + constexpr T& operator*() & { return GetRef(); - } - + } + constexpr const T&& operator*() const&& { return std::move(GetRef()); } @@ -355,8 +355,8 @@ public: constexpr const T* operator->() const { return &GetRef(); - } - + } + constexpr T* operator->() { return &GetRef(); } @@ -384,8 +384,8 @@ public: constexpr explicit operator bool() const noexcept { return Defined(); - } - + } + void Save(IOutputStream* out) const { const bool defined = Defined(); diff --git a/util/generic/maybe_ut.cpp b/util/generic/maybe_ut.cpp index a9afc4661a..2c1a425c5e 100644 --- a/util/generic/maybe_ut.cpp +++ b/util/generic/maybe_ut.cpp @@ -2,24 +2,24 @@ #include <util/generic/vector.h> #include <util/stream/str.h> #include <library/cpp/testing/unittest/registar.h> - -#include "maybe.h" - -class TIncrementOnDestroy { -private: + +#include "maybe.h" + +class TIncrementOnDestroy { +private: int* Ptr_; -public: +public: TIncrementOnDestroy(int* ptr) noexcept : Ptr_(ptr) { - } + } ~TIncrementOnDestroy() { ++*Ptr_; } -}; - +}; + Y_UNIT_TEST_SUITE(TMaybeTest) { Y_UNIT_TEST(TestStatic) { using T1 = TMaybe<int>; @@ -56,35 +56,35 @@ Y_UNIT_TEST_SUITE(TMaybeTest) { Y_UNIT_TEST(TTestConstructorDestructor) { int a = 0; int b = 0; - - TMaybe<TIncrementOnDestroy>(); + + TMaybe<TIncrementOnDestroy>(); UNIT_ASSERT_VALUES_EQUAL(a, b); - + TMaybe<TIncrementOnDestroy>(TIncrementOnDestroy(&a)); b += 2; UNIT_ASSERT_VALUES_EQUAL(a, b); - - { + + { TMaybe<TIncrementOnDestroy> m1 = TIncrementOnDestroy(&a); b += 1; UNIT_ASSERT_VALUES_EQUAL(a, b); - + TMaybe<TIncrementOnDestroy> m2 = m1; UNIT_ASSERT_VALUES_EQUAL(a, b); - + TMaybe<TIncrementOnDestroy> m3; m3 = m1; UNIT_ASSERT_VALUES_EQUAL(a, b); - } - + } + b += 3; UNIT_ASSERT_VALUES_EQUAL(a, b); - - { + + { TMaybe<TIncrementOnDestroy> m4 = TIncrementOnDestroy(&a); b += 1; UNIT_ASSERT_VALUES_EQUAL(a, b); - + m4 = TIncrementOnDestroy(&a); b += 1; UNIT_ASSERT_VALUES_EQUAL(a, b); @@ -95,9 +95,9 @@ Y_UNIT_TEST_SUITE(TMaybeTest) { m4.Clear(); UNIT_ASSERT_VALUES_EQUAL(a, b); - } - } - + } + } + Y_UNIT_TEST(TestAssignmentClear) { TMaybe<int> m5; UNIT_ASSERT(!m5.Defined()); @@ -105,24 +105,24 @@ Y_UNIT_TEST_SUITE(TMaybeTest) { UNIT_ASSERT(m5 == TMaybe<int>()); UNIT_ASSERT(m5 == Nothing()); UNIT_ASSERT(m5 != TMaybe<int>(4)); - + m5 = 4; - + UNIT_ASSERT(m5.Defined()); UNIT_ASSERT(!m5.Empty()); - + UNIT_ASSERT_VALUES_EQUAL(4, m5.GetRef()); UNIT_ASSERT(m5 == TMaybe<int>(4)); UNIT_ASSERT(m5 != TMaybe<int>(3)); UNIT_ASSERT(m5 != TMaybe<int>()); UNIT_ASSERT(m5 != Nothing()); - + m5 = TMaybe<int>(5); UNIT_ASSERT(m5.Defined()); UNIT_ASSERT_VALUES_EQUAL(5, m5.GetRef()); UNIT_ASSERT(m5 == TMaybe<int>(5)); UNIT_ASSERT(m5 != TMaybe<int>(4)); - + m5 = TMaybe<int>(); UNIT_ASSERT(m5.Empty()); UNIT_ASSERT(m5 == TMaybe<int>()); @@ -139,7 +139,7 @@ Y_UNIT_TEST_SUITE(TMaybeTest) { m5 = {}; UNIT_ASSERT(m5.Empty()); - } + } Y_UNIT_TEST(TestInPlace) { TMaybe<int> m; @@ -1003,4 +1003,4 @@ Y_UNIT_TEST_SUITE(TMaybeTest) { TMaybe<TStringBuf> v; UNIT_ASSERT_EXCEPTION_CONTAINS(v.GetRef(), yexception, "StringBuf"); } -} +} diff --git a/util/generic/object_counter.h b/util/generic/object_counter.h index 71ec5d57c4..5257afa2e6 100644 --- a/util/generic/object_counter.h +++ b/util/generic/object_counter.h @@ -1,7 +1,7 @@ -#pragma once - -#include <util/system/atomic.h> - +#pragma once + +#include <util/system/atomic.h> + /** * Simple thread-safe per-class counter that can be used to make sure you don't * have any leaks in your code, or for statistical purposes. @@ -16,13 +16,13 @@ * Cerr << "TMyClass instances in use: " << TMyClass::ObjectCount() << Endl; * \endcode */ -template <class T> -class TObjectCounter { +template <class T> +class TObjectCounter { public: inline TObjectCounter() noexcept { AtomicIncrement(Count_); } - + inline TObjectCounter(const TObjectCounter& /*item*/) noexcept { AtomicIncrement(Count_); } @@ -30,11 +30,11 @@ public: inline ~TObjectCounter() { AtomicDecrement(Count_); } - + static inline long ObjectCount() noexcept { return AtomicGet(Count_); } - + /** * Resets object count. Mainly for tests, as you don't want to do this in * your code and then end up with negative counts. @@ -44,10 +44,10 @@ public: static inline long ResetObjectCount() noexcept { return AtomicSwap(&Count_, 0); } - + private: static TAtomic Count_; -}; - -template <class T> -TAtomic TObjectCounter<T>::Count_ = 0; +}; + +template <class T> +TAtomic TObjectCounter<T>::Count_ = 0; diff --git a/util/generic/ptr.h b/util/generic/ptr.h index 3b02d9c19f..19db0e3ec5 100644 --- a/util/generic/ptr.h +++ b/util/generic/ptr.h @@ -370,7 +370,7 @@ public: Y_ASSERT(resultCount >= d); (void)resultCount; } - + inline void Ref() noexcept { auto resultCount = Counter_.Inc(); Y_ASSERT(resultCount != 0); @@ -388,7 +388,7 @@ public: inline void UnRef() noexcept { UnRef(1); } - + inline TAtomicBase RefCount() const noexcept { return Counter_.Val(); } @@ -876,7 +876,7 @@ public: inline void Drop() noexcept { TSharedPtr().Swap(*this); } - + inline T* Get() const noexcept { return T_; } diff --git a/util/generic/refcount.h b/util/generic/refcount.h index c567cdfa3a..966e853b77 100644 --- a/util/generic/refcount.h +++ b/util/generic/refcount.h @@ -23,11 +23,11 @@ public: Check(); return Counter_ += d; } - + inline TAtomicBase Inc() noexcept { return Add(1); } - + inline TAtomicBase Sub(TAtomicBase d) noexcept { Check(); return Counter_ -= d; @@ -112,7 +112,7 @@ public: inline TAtomicBase Add(TAtomicBase d) noexcept { return AtomicAdd(Counter_, d); } - + inline TAtomicBase Inc() noexcept { return Add(1); } @@ -120,7 +120,7 @@ public: inline TAtomicBase Sub(TAtomicBase d) noexcept { return AtomicSub(Counter_, d); } - + inline TAtomicBase Dec() noexcept { return Sub(1); } diff --git a/util/generic/string.h b/util/generic/string.h index f3e28037e6..8cd8aa6917 100644 --- a/util/generic/string.h +++ b/util/generic/string.h @@ -1133,7 +1133,7 @@ public: extern TBasicString EscapeC(const TBasicString&); return TBasicString() + '"' + EscapeC(*this) + '"'; - } + } /** * Modifies the case of the string, depending on the operation. diff --git a/util/generic/typetraits_ut.cpp b/util/generic/typetraits_ut.cpp index 59b6f2a9cf..e7571c75ec 100644 --- a/util/generic/typetraits_ut.cpp +++ b/util/generic/typetraits_ut.cpp @@ -5,17 +5,17 @@ #include <vector> #include <tuple> -namespace { - enum ETestEnum { - }; - +namespace { + enum ETestEnum { + }; + class TPodClass { - }; - + }; + class TNonPodClass { TNonPodClass() { } - }; + }; class TEmptyClass { void operator()() const { @@ -70,8 +70,8 @@ namespace { public: TEmptyClass Base; }; -} - +} + #define ASSERT_SAME_TYPE(x, y) \ { \ const bool x_ = std::is_same<x, y>::value; \ @@ -259,82 +259,82 @@ Y_UNIT_TEST_SUITE(TTypeTraitsTest) { } }; -namespace { - template <typename T> - struct TTypeTraitsExpected; - - template <> - struct TTypeTraitsExpected<void> { - enum { IsIntegral = false }; - enum { IsArithmetic = false }; - enum { IsPod = true }; - enum { IsVolatile = false }; - enum { IsConstant = false }; - enum { IsPointer = false }; - enum { IsReference = false }; +namespace { + template <typename T> + struct TTypeTraitsExpected; + + template <> + struct TTypeTraitsExpected<void> { + enum { IsIntegral = false }; + enum { IsArithmetic = false }; + enum { IsPod = true }; + enum { IsVolatile = false }; + enum { IsConstant = false }; + enum { IsPointer = false }; + enum { IsReference = false }; enum { IsLvalueReference = false }; enum { IsRvalueReference = false }; - enum { IsArray = false }; - enum { IsClassType = false }; - enum { IsVoid = true }; - enum { IsEnum = false }; - }; - - template <> - struct TTypeTraitsExpected<int>: public TTypeTraitsExpected<void> { - enum { IsIntegral = true }; - enum { IsArithmetic = true }; - enum { IsVoid = false }; - }; - - template <> + enum { IsArray = false }; + enum { IsClassType = false }; + enum { IsVoid = true }; + enum { IsEnum = false }; + }; + + template <> + struct TTypeTraitsExpected<int>: public TTypeTraitsExpected<void> { + enum { IsIntegral = true }; + enum { IsArithmetic = true }; + enum { IsVoid = false }; + }; + + template <> struct TTypeTraitsExpected<size_t>: public TTypeTraitsExpected<int> { - }; - - template <> + }; + + template <> struct TTypeTraitsExpected<float>: public TTypeTraitsExpected<int> { - enum { IsIntegral = false }; - }; - - template <> + enum { IsIntegral = false }; + }; + + template <> struct TTypeTraitsExpected<long double>: public TTypeTraitsExpected<float> { - }; - - template <> + }; + + template <> struct TTypeTraitsExpected<const int>: public TTypeTraitsExpected<int> { - enum { IsConstant = true }; - }; - - template <> + enum { IsConstant = true }; + }; + + template <> struct TTypeTraitsExpected<volatile int>: public TTypeTraitsExpected<int> { - enum { IsVolatile = true }; - }; - - template <> + enum { IsVolatile = true }; + }; + + template <> struct TTypeTraitsExpected<ETestEnum>: public TTypeTraitsExpected<int> { - enum { IsIntegral = false }; - enum { IsArithmetic = false }; - enum { IsEnum = true }; - }; - - template <> + enum { IsIntegral = false }; + enum { IsArithmetic = false }; + enum { IsEnum = true }; + }; + + template <> struct TTypeTraitsExpected<TPodClass>: public TTypeTraitsExpected<void> { - enum { IsClassType = true }; - enum { IsVoid = false }; - }; - - template <> + enum { IsClassType = true }; + enum { IsVoid = false }; + }; + + template <> struct TTypeTraitsExpected<TNonPodClass>: public TTypeTraitsExpected<TPodClass> { - enum { IsPod = false }; - }; - - template <> + enum { IsPod = false }; + }; + + template <> struct TTypeTraitsExpected<TNonPodClass&>: public TTypeTraitsExpected<TNonPodClass> { - enum { IsClassType = false }; - enum { IsReference = true }; + enum { IsClassType = false }; + enum { IsReference = true }; enum { IsLvalueReference = true }; - }; - + }; + template <> struct TTypeTraitsExpected<TNonPodClass&&>: public TTypeTraitsExpected<TNonPodClass> { enum { IsClassType = false }; @@ -342,25 +342,25 @@ namespace { enum { IsRvalueReference = true }; }; - template <> + template <> struct TTypeTraitsExpected<const TNonPodClass&>: public TTypeTraitsExpected<TNonPodClass&> { - }; - - template <> + }; + + template <> struct TTypeTraitsExpected<float*>: public TTypeTraitsExpected<int> { - enum { IsIntegral = false }; - enum { IsArithmetic = false }; - enum { IsPointer = true }; - }; - - template <> + enum { IsIntegral = false }; + enum { IsArithmetic = false }; + enum { IsPointer = true }; + }; + + template <> struct TTypeTraitsExpected<float&>: public TTypeTraitsExpected<float*> { - enum { IsPointer = false }; - enum { IsReference = true }; + enum { IsPointer = false }; + enum { IsReference = true }; enum { IsLvalueReference = true }; - }; - - template <> + }; + + template <> struct TTypeTraitsExpected<float&&>: public TTypeTraitsExpected<float*> { enum { IsPointer = false }; enum { IsReference = true }; @@ -369,22 +369,22 @@ namespace { template <> struct TTypeTraitsExpected<const float&>: public TTypeTraitsExpected<float&> { - }; - - template <> + }; + + template <> struct TTypeTraitsExpected<float[17]>: public TTypeTraitsExpected<int> { - enum { IsIntegral = false }; - enum { IsArithmetic = false }; - enum { IsArray = true }; - }; -} - + enum { IsIntegral = false }; + enum { IsArithmetic = false }; + enum { IsArray = true }; + }; +} + #define UNIT_ASSERT_EQUAL_ENUM(expected, actual) UNIT_ASSERT_VALUES_EQUAL((bool)(expected), (bool)(actual)) - + Y_UNIT_TEST_SUITE(TTypeTraitsTestNg) { - template <typename T> - void TestImpl() { - //UNIT_ASSERT_EQUAL_ENUM(TTypeTraitsExpected<T>::IsPod, TTypeTraits<T>::IsPod); + template <typename T> + void TestImpl() { + //UNIT_ASSERT_EQUAL_ENUM(TTypeTraitsExpected<T>::IsPod, TTypeTraits<T>::IsPod); UNIT_ASSERT_EQUAL_ENUM(TTypeTraitsExpected<T>::IsVoid, std::is_void<T>::value); UNIT_ASSERT_EQUAL_ENUM(TTypeTraitsExpected<T>::IsEnum, std::is_enum<T>::value); UNIT_ASSERT_EQUAL_ENUM(TTypeTraitsExpected<T>::IsIntegral, std::is_integral<T>::value); @@ -397,30 +397,30 @@ Y_UNIT_TEST_SUITE(TTypeTraitsTestNg) { UNIT_ASSERT_EQUAL_ENUM(TTypeTraitsExpected<T>::IsRvalueReference, std::is_rvalue_reference<T>::value); UNIT_ASSERT_EQUAL_ENUM(TTypeTraitsExpected<T>::IsArray, std::is_array<T>::value); UNIT_ASSERT_EQUAL_ENUM(TTypeTraitsExpected<T>::IsClassType, std::is_class<T>::value); - } - + } + #define TYPE_TEST(name, type) \ Y_UNIT_TEST(name) { \ TestImpl<type>(); \ } - - TYPE_TEST(Void, void) - TYPE_TEST(Int, int) - TYPE_TEST(Float, float) - TYPE_TEST(LongDouble, long double) - TYPE_TEST(SizeT, size_t) - TYPE_TEST(VolatileInt, volatile int) - TYPE_TEST(ConstInt, const int) - TYPE_TEST(Enum, ETestEnum) - TYPE_TEST(FloatPointer, float*) - TYPE_TEST(FloatReference, float&) - TYPE_TEST(FloatConstReference, const float&) - TYPE_TEST(FloatArray, float[17]) + + TYPE_TEST(Void, void) + TYPE_TEST(Int, int) + TYPE_TEST(Float, float) + TYPE_TEST(LongDouble, long double) + TYPE_TEST(SizeT, size_t) + TYPE_TEST(VolatileInt, volatile int) + TYPE_TEST(ConstInt, const int) + TYPE_TEST(Enum, ETestEnum) + TYPE_TEST(FloatPointer, float*) + TYPE_TEST(FloatReference, float&) + TYPE_TEST(FloatConstReference, const float&) + TYPE_TEST(FloatArray, float[17]) TYPE_TEST(PodClass, TPodClass) TYPE_TEST(NonPodClass, TNonPodClass) TYPE_TEST(NonPodClassReference, TNonPodClass&) TYPE_TEST(NonPodClassConstReference, const TNonPodClass&) -} +} enum E4 { X diff --git a/util/generic/vector_ut.cpp b/util/generic/vector_ut.cpp index be27286038..0f6b4037a0 100644 --- a/util/generic/vector_ut.cpp +++ b/util/generic/vector_ut.cpp @@ -1,13 +1,13 @@ #include "vector.h" - + #include <library/cpp/testing/unittest/registar.h> #include <utility> #include "yexception.h" - + #include <stdexcept> -class TYVectorTest: public TTestBase { +class TYVectorTest: public TTestBase { UNIT_TEST_SUITE(TYVectorTest); UNIT_TEST(TestConstructorsAndAssignments) UNIT_TEST(TestTildeEmptyToNull) @@ -92,23 +92,23 @@ private: } // Copy-paste of STLPort tests - + void Test1() { TVector<int> v1; // Empty vector of integers. - + UNIT_ASSERT(v1.empty() == true); UNIT_ASSERT(v1.size() == 0); UNIT_ASSERT(!v1); - + // UNIT_ASSERT(v1.max_size() == INT_MAX / sizeof(int)); // cout << "max_size = " << v1.max_size() << endl; v1.push_back(42); // Add an integer to the vector. - + UNIT_ASSERT(v1.size() == 1); UNIT_ASSERT(v1); - + UNIT_ASSERT(v1[0] == 42); - + { TVector<TVector<int>> vect(10); TVector<TVector<int>>::iterator it(vect.begin()), end(vect.end()); @@ -117,102 +117,102 @@ private: UNIT_ASSERT((*it).size() == 0); UNIT_ASSERT((*it).capacity() == 0); UNIT_ASSERT((*it).begin() == (*it).end()); - } - } + } + } } - + void Test2() { TVector<double> v1; // Empty vector of doubles. v1.push_back(32.1); v1.push_back(40.5); TVector<double> v2; // Another empty vector of doubles. v2.push_back(3.56); - + UNIT_ASSERT(v1.size() == 2); UNIT_ASSERT(v1[0] == 32.1); UNIT_ASSERT(v1[1] == 40.5); - + UNIT_ASSERT(v2.size() == 1); UNIT_ASSERT(v2[0] == 3.56); v1.swap(v2); // Swap the vector's contents. - + UNIT_ASSERT(v1.size() == 1); UNIT_ASSERT(v1[0] == 3.56); - + UNIT_ASSERT(v2.size() == 2); UNIT_ASSERT(v2[0] == 32.1); UNIT_ASSERT(v2[1] == 40.5); - + v2 = v1; // Assign one vector to another. - + UNIT_ASSERT(v2.size() == 1); UNIT_ASSERT(v2[0] == 3.56); } - + void Test3() { using vec_type = TVector<char>; - + vec_type v1; // Empty vector of characters. v1.push_back('h'); v1.push_back('i'); - + UNIT_ASSERT(v1.size() == 2); UNIT_ASSERT(v1[0] == 'h'); UNIT_ASSERT(v1[1] == 'i'); - + vec_type v2(v1.begin(), v1.end()); v2[1] = 'o'; // Replace second character. - + UNIT_ASSERT(v2.size() == 2); UNIT_ASSERT(v2[0] == 'h'); UNIT_ASSERT(v2[1] == 'o'); - + UNIT_ASSERT((v1 == v2) == false); - + UNIT_ASSERT((v1 < v2) == true); } - + void Test4() { TVector<int> v(4); - + v[0] = 1; v[1] = 4; v[2] = 9; v[3] = 16; - + UNIT_ASSERT(v.front() == 1); UNIT_ASSERT(v.back() == 16); - + v.push_back(25); - + UNIT_ASSERT(v.back() == 25); UNIT_ASSERT(v.size() == 5); - + v.pop_back(); - + UNIT_ASSERT(v.back() == 16); UNIT_ASSERT(v.size() == 4); } - + void Test5() { int array[] = {1, 4, 9, 16}; - + TVector<int> v(array, array + 4); - + UNIT_ASSERT(v.size() == 4); - + UNIT_ASSERT(v[0] == 1); UNIT_ASSERT(v[1] == 4); UNIT_ASSERT(v[2] == 9); UNIT_ASSERT(v[3] == 16); } - + void Test6() { int array[] = {1, 4, 9, 16, 25, 36}; - + TVector<int> v(array, array + 6); TVector<int>::iterator vit; - + UNIT_ASSERT(v.size() == 6); UNIT_ASSERT(v[0] == 1); UNIT_ASSERT(v[1] == 4); @@ -220,57 +220,57 @@ private: UNIT_ASSERT(v[3] == 16); UNIT_ASSERT(v[4] == 25); UNIT_ASSERT(v[5] == 36); - + vit = v.erase(v.begin()); // Erase first element. UNIT_ASSERT(*vit == 4); - + UNIT_ASSERT(v.size() == 5); UNIT_ASSERT(v[0] == 4); UNIT_ASSERT(v[1] == 9); UNIT_ASSERT(v[2] == 16); UNIT_ASSERT(v[3] == 25); UNIT_ASSERT(v[4] == 36); - + vit = v.erase(v.end() - 1); // Erase last element. UNIT_ASSERT(vit == v.end()); - + UNIT_ASSERT(v.size() == 4); UNIT_ASSERT(v[0] == 4); UNIT_ASSERT(v[1] == 9); UNIT_ASSERT(v[2] == 16); UNIT_ASSERT(v[3] == 25); - + v.erase(v.begin() + 1, v.end() - 1); // Erase all but first and last. - + UNIT_ASSERT(v.size() == 2); UNIT_ASSERT(v[0] == 4); UNIT_ASSERT(v[1] == 25); } - + void Test7() { int array1[] = {1, 4, 25}; int array2[] = {9, 16}; - + TVector<int> v(array1, array1 + 3); TVector<int>::iterator vit; vit = v.insert(v.begin(), 0); // Insert before first element. UNIT_ASSERT(*vit == 0); - + vit = v.insert(v.end(), 36); // Insert after last element. UNIT_ASSERT(*vit == 36); - + UNIT_ASSERT(v.size() == 5); UNIT_ASSERT(v[0] == 0); UNIT_ASSERT(v[1] == 1); UNIT_ASSERT(v[2] == 4); UNIT_ASSERT(v[3] == 25); UNIT_ASSERT(v[4] == 36); - + // Insert contents of array2 before fourth element. v.insert(v.begin() + 3, array2, array2 + 2); - + UNIT_ASSERT(v.size() == 7); - + UNIT_ASSERT(v[0] == 0); UNIT_ASSERT(v[1] == 1); UNIT_ASSERT(v[2] == 4); @@ -278,11 +278,11 @@ private: UNIT_ASSERT(v[4] == 16); UNIT_ASSERT(v[5] == 25); UNIT_ASSERT(v[6] == 36); - + size_t curCapacity = v.capacity(); v.clear(); UNIT_ASSERT(v.empty()); - + //check that clear save reserved data UNIT_ASSERT_EQUAL(curCapacity, v.capacity()); @@ -294,22 +294,22 @@ private: UNIT_ASSERT(v[3] == 10); UNIT_ASSERT(v[4] == 10); } - + struct TestStruct { unsigned int a[3]; }; - + void TestCapacity() { { TVector<int> v; - + UNIT_ASSERT(v.capacity() == 0); v.push_back(42); UNIT_ASSERT(v.capacity() >= 1); v.reserve(5000); UNIT_ASSERT(v.capacity() >= 5000); } - + { TVector<int> v(Reserve(100)); @@ -322,18 +322,18 @@ private: TVector<TestStruct> va; va.reserve(1); va.reserve(2); - } + } } - + void TestAt() { TVector<int> v; TVector<int> const& cv = v; - + v.push_back(10); UNIT_ASSERT(v.at(0) == 10); v.at(0) = 20; UNIT_ASSERT(cv.at(0) == 20); - + for (;;) { try { v.at(1) = 20; @@ -342,15 +342,15 @@ private: return; } catch (...) { UNIT_ASSERT(false); - } - } + } + } } - + void TestPointer() { TVector<int*> v1; TVector<int*> v2 = v1; TVector<int*> v3; - + v3.insert(v3.end(), v1.begin(), v1.end()); } @@ -358,25 +358,25 @@ private: TVector<int> ref; for (int i = 0; i < 5; ++i) { ref.push_back(i); - } - + } + TVector<TVector<int>> v_v_int(1, ref); v_v_int.push_back(v_v_int[0]); v_v_int.push_back(ref); v_v_int.push_back(v_v_int[0]); v_v_int.push_back(v_v_int[0]); v_v_int.push_back(ref); - + TVector<TVector<int>>::iterator vvit(v_v_int.begin()), vvitEnd(v_v_int.end()); for (; vvit != vvitEnd; ++vvit) { UNIT_ASSERT(*vvit == ref); - } + } } - + struct Point { int x, y; }; - + struct PointEx: public Point { PointEx() : builtFromBase(false) @@ -386,37 +386,37 @@ private: : builtFromBase(true) { } - + bool builtFromBase; }; - + void TestIterators() { TVector<int> vint(10, 0); TVector<int> const& crvint = vint; - + UNIT_ASSERT(vint.begin() == vint.begin()); UNIT_ASSERT(crvint.begin() == vint.begin()); UNIT_ASSERT(vint.begin() == crvint.begin()); UNIT_ASSERT(crvint.begin() == crvint.begin()); - + UNIT_ASSERT(vint.begin() != vint.end()); UNIT_ASSERT(crvint.begin() != vint.end()); UNIT_ASSERT(vint.begin() != crvint.end()); UNIT_ASSERT(crvint.begin() != crvint.end()); - + UNIT_ASSERT(vint.rbegin() == vint.rbegin()); // Not Standard: //UNIT_ASSERT(vint.rbegin() == crvint.rbegin()); //UNIT_ASSERT(crvint.rbegin() == vint.rbegin()); UNIT_ASSERT(crvint.rbegin() == crvint.rbegin()); - + UNIT_ASSERT(vint.rbegin() != vint.rend()); // Not Standard: //UNIT_ASSERT(vint.rbegin() != crvint.rend()); //UNIT_ASSERT(crvint.rbegin() != vint.rend()); UNIT_ASSERT(crvint.rbegin() != crvint.rend()); } - + void TestShrink() { TVector<int> v; v.resize(1000); @@ -429,8 +429,8 @@ private: } /* This test check a potential issue with empty base class - * optimization. Some compilers (VC6) do not implement it - * correctly resulting ina wrong behavior. */ + * optimization. Some compilers (VC6) do not implement it + * correctly resulting ina wrong behavior. */ void TestEbo() { // We use heap memory as test failure can corrupt vector internal // representation making executable crash on vector destructor invocation. @@ -439,36 +439,36 @@ private: using V = TVector<int>; V* pv1 = new V(1, 1); V* pv2 = new V(10, 2); - + size_t v1Capacity = pv1->capacity(); size_t v2Capacity = pv2->capacity(); - + pv1->swap(*pv2); - + UNIT_ASSERT(pv1->size() == 10); UNIT_ASSERT(pv1->capacity() == v2Capacity); UNIT_ASSERT((*pv1)[5] == 2); - + UNIT_ASSERT(pv2->size() == 1); UNIT_ASSERT(pv2->capacity() == v1Capacity); UNIT_ASSERT((*pv2)[0] == 1); - + delete pv2; delete pv1; } - + void TestFillInConstructor() { for (int k = 0; k < 3; ++k) { TVector<int> v(100); UNIT_ASSERT_VALUES_EQUAL(100u, v.size()); for (size_t i = 0; i < v.size(); ++i) { UNIT_ASSERT_VALUES_EQUAL(0, v[i]); - } + } // fill with garbage for the next iteration for (size_t i = 0; i < v.size(); ++i) { v[i] = 10; } - } + } } struct TPod { @@ -591,6 +591,6 @@ private: CheckInitializeList(v); } } -}; - -UNIT_TEST_SUITE_REGISTRATION(TYVectorTest); +}; + +UNIT_TEST_SUITE_REGISTRATION(TYVectorTest); diff --git a/util/generic/ylimits.h b/util/generic/ylimits.h index e6a52a340f..fe42b4dfc0 100644 --- a/util/generic/ylimits.h +++ b/util/generic/ylimits.h @@ -2,10 +2,10 @@ #include <limits> -#if defined(max) || defined(min) +#if defined(max) || defined(min) #error "stop defining 'min' and 'max' macros, evil people" -#endif - +#endif + template <class T> static constexpr T Max() noexcept { return std::numeric_limits<T>::max(); diff --git a/util/generic/ymath_ut.cpp b/util/generic/ymath_ut.cpp index 18103fa3c9..29190b55eb 100644 --- a/util/generic/ymath_ut.cpp +++ b/util/generic/ymath_ut.cpp @@ -12,13 +12,13 @@ template <class T> static inline T SlowClp2(T t) noexcept { Y_ASSERT(t > 0); - T ret = 1; + T ret = 1; - while (ret < t) { - ret *= 2; + while (ret < t) { + ret *= 2; } - return ret; + return ret; } class TMathTest: public TTestBase { @@ -50,7 +50,7 @@ private: inline void TestIsValidFloat() { UNIT_ASSERT(IsValidFloat(-Max<double>() / 2.)); } - + inline void TestClpSimple() { UNIT_ASSERT_EQUAL(FastClp2<ui32>(12), 16); UNIT_ASSERT_EQUAL(FastClp2<ui16>(11), 16); @@ -83,19 +83,19 @@ void TMathTest::TestSqr() { } void TMathTest::TestClp2() { - for (ui8 i = 1; i < 127; ++i) { + for (ui8 i = 1; i < 127; ++i) { UNIT_ASSERT_EQUAL(SlowClp2(i), FastClp2(i)); } - for (ui16 i = 1; i < 255; ++i) { + for (ui16 i = 1; i < 255; ++i) { UNIT_ASSERT_EQUAL(SlowClp2(i), FastClp2(i)); } - for (ui32 i = 1; i < 255; ++i) { + for (ui32 i = 1; i < 255; ++i) { UNIT_ASSERT_EQUAL(SlowClp2(i), FastClp2(i)); } - for (ui64 i = 1; i < 255; ++i) { + for (ui64 i = 1; i < 255; ++i) { UNIT_ASSERT_EQUAL(SlowClp2(i), FastClp2(i)); } diff --git a/util/memory/blob.cpp b/util/memory/blob.cpp index 9610cf82ac..91da5cadca 100644 --- a/util/memory/blob.cpp +++ b/util/memory/blob.cpp @@ -159,7 +159,7 @@ TBlob TBlob::SubBlob(size_t len) const { TBlob TBlob::SubBlob(size_t begin, size_t end) const { if (begin > Length() || end > Length() || begin > end) { - ythrow yexception() << "incorrect subblob (" << begin << ", " << end << ", outer length = " << Length() << ")"; + ythrow yexception() << "incorrect subblob (" << begin << ", " << end << ", outer length = " << Length() << ")"; } return TBlob(Begin() + begin, end - begin, S_.Base); diff --git a/util/network/address.cpp b/util/network/address.cpp index 5e13cdca81..a81a9e6994 100644 --- a/util/network/address.cpp +++ b/util/network/address.cpp @@ -37,8 +37,8 @@ static inline void PrintAddr(IOutputStream& out, const IRemoteAddr& addr) { if (printPort) { out << "[" << buf << "]" << ":" << InetToHost(sa->sin6_port); - } else { - out << buf; + } else { + out << buf; } break; @@ -55,33 +55,33 @@ static inline void PrintAddr(IOutputStream& out, const IRemoteAddr& addr) { #endif default: { - size_t len = addr.Len(); - + size_t len = addr.Len(); + const char* b = (const char*)a; - const char* e = b + len; - - bool allZeros = true; - for (size_t i = 0; i < len; ++i) { - if (b[i] != 0) { - allZeros = false; - break; - } - } - - if (allZeros) { - out << "(raw all zeros)"; - } else { + const char* e = b + len; + + bool allZeros = true; + for (size_t i = 0; i < len; ++i) { + if (b[i] != 0) { + allZeros = false; + break; + } + } + + if (allZeros) { + out << "(raw all zeros)"; + } else { out << "(raw " << (int)a->sa_family << " "; - - while (b != e) { - //just print raw bytes - out << (int)*b++; - if (b != e) { - out << " "; - } - } - - out << ")"; + + while (b != e) { + //just print raw bytes + out << (int)*b++; + if (b != e) { + out << " "; + } + } + + out << ")"; } break; diff --git a/util/network/address_ut.cpp b/util/network/address_ut.cpp index 2a18cad9df..28f45172ff 100644 --- a/util/network/address_ut.cpp +++ b/util/network/address_ut.cpp @@ -1,33 +1,33 @@ #include <library/cpp/testing/unittest/registar.h> - -#include "address.h" - -using namespace NAddr; - + +#include "address.h" + +using namespace NAddr; + Y_UNIT_TEST_SUITE(IRemoteAddr_ToString) { Y_UNIT_TEST(Raw) { - THolder<TOpaqueAddr> opaque(new TOpaqueAddr); - IRemoteAddr* addr = opaque.Get(); - + THolder<TOpaqueAddr> opaque(new TOpaqueAddr); + IRemoteAddr* addr = opaque.Get(); + TString s = ToString(*addr); - UNIT_ASSERT_VALUES_EQUAL("(raw all zeros)", s); - - opaque->MutableAddr()->sa_data[10] = 17; - + UNIT_ASSERT_VALUES_EQUAL("(raw all zeros)", s); + + opaque->MutableAddr()->sa_data[10] = 17; + TString t = ToString(*addr); - + UNIT_ASSERT_C(t.StartsWith("(raw 0 0"), t); UNIT_ASSERT_C(t.EndsWith(')'), t); - } - + } + Y_UNIT_TEST(Ipv6) { - TNetworkAddress address("::1", 22); - TNetworkAddress::TIterator it = address.Begin(); - UNIT_ASSERT(it != address.End()); - UNIT_ASSERT(it->ai_family == AF_INET6); + TNetworkAddress address("::1", 22); + TNetworkAddress::TIterator it = address.Begin(); + UNIT_ASSERT(it != address.End()); + UNIT_ASSERT(it->ai_family == AF_INET6); TString toString = ToString((const IRemoteAddr&)TAddrInfo(&*it)); UNIT_ASSERT_VALUES_EQUAL(TString("[::1]:22"), toString); - } + } Y_UNIT_TEST(Loopback) { TNetworkAddress localAddress("127.70.0.1", 22); @@ -36,4 +36,4 @@ Y_UNIT_TEST_SUITE(IRemoteAddr_ToString) { TNetworkAddress localAddress2("127.0.0.1", 22); UNIT_ASSERT_VALUES_EQUAL(NAddr::IsLoopback(TAddrInfo(&*localAddress2.Begin())), true); } -} +} diff --git a/util/network/ip.h b/util/network/ip.h index 0e944248a5..dc7c2d24a0 100644 --- a/util/network/ip.h +++ b/util/network/ip.h @@ -8,10 +8,10 @@ #include <util/generic/string.h> #include <util/generic/yexception.h> -/// IPv4 address in network format +/// IPv4 address in network format using TIpHost = ui32; - -/// Port number in host format + +/// Port number in host format using TIpPort = ui16; /* @@ -53,7 +53,7 @@ static inline TIpHost ResolveHost(const char* data, size_t len) { return HostToInet(ret); } -/// socket address +/// socket address struct TIpAddress: public sockaddr_in { inline TIpAddress() noexcept { Clear(); diff --git a/util/network/poller.cpp b/util/network/poller.cpp index 36a007b5c6..7954d0e8b5 100644 --- a/util/network/poller.cpp +++ b/util/network/poller.cpp @@ -57,18 +57,18 @@ void TSocketPoller::WaitRdhup(SOCKET sock, void* cookie) { Impl_->Set(cookie, sock, CONT_POLL_RDHUP); } -void TSocketPoller::WaitReadOneShot(SOCKET sock, void* cookie) { - Impl_->Set(cookie, sock, CONT_POLL_READ | CONT_POLL_ONE_SHOT); -} - -void TSocketPoller::WaitWriteOneShot(SOCKET sock, void* cookie) { - Impl_->Set(cookie, sock, CONT_POLL_WRITE | CONT_POLL_ONE_SHOT); -} - -void TSocketPoller::WaitReadWriteOneShot(SOCKET sock, void* cookie) { - Impl_->Set(cookie, sock, CONT_POLL_READ | CONT_POLL_WRITE | CONT_POLL_ONE_SHOT); -} - +void TSocketPoller::WaitReadOneShot(SOCKET sock, void* cookie) { + Impl_->Set(cookie, sock, CONT_POLL_READ | CONT_POLL_ONE_SHOT); +} + +void TSocketPoller::WaitWriteOneShot(SOCKET sock, void* cookie) { + Impl_->Set(cookie, sock, CONT_POLL_WRITE | CONT_POLL_ONE_SHOT); +} + +void TSocketPoller::WaitReadWriteOneShot(SOCKET sock, void* cookie) { + Impl_->Set(cookie, sock, CONT_POLL_READ | CONT_POLL_WRITE | CONT_POLL_ONE_SHOT); +} + void TSocketPoller::WaitReadWriteEdgeTriggered(SOCKET sock, void* cookie) { Impl_->Set(cookie, sock, CONT_POLL_READ | CONT_POLL_WRITE | CONT_POLL_EDGE_TRIGGERED); } diff --git a/util/network/poller.h b/util/network/poller.h index d687fb0463..8dccd73140 100644 --- a/util/network/poller.h +++ b/util/network/poller.h @@ -18,7 +18,7 @@ public: void WaitReadOneShot(SOCKET sock, void* cookie); void WaitWriteOneShot(SOCKET sock, void* cookie); void WaitReadWriteOneShot(SOCKET sock, void* cookie); - + void WaitReadWriteEdgeTriggered(SOCKET sock, void* cookie); void RestartReadWriteEdgeTriggered(SOCKET sock, void* cookie, bool empty = true); diff --git a/util/network/poller_ut.cpp b/util/network/poller_ut.cpp index 1d542f8c67..6df0dda8ec 100644 --- a/util/network/poller_ut.cpp +++ b/util/network/poller_ut.cpp @@ -1,105 +1,105 @@ #include <library/cpp/testing/unittest/registar.h> #include <util/system/error.h> - + #include "pair.h" -#include "poller.h" +#include "poller.h" #include "pollerimpl.h" - + Y_UNIT_TEST_SUITE(TSocketPollerTest) { Y_UNIT_TEST(TestSimple) { - SOCKET sockets[2]; - UNIT_ASSERT(SocketPair(sockets) == 0); - - TSocketHolder s1(sockets[0]); - TSocketHolder s2(sockets[1]); - - TSocketPoller poller; + SOCKET sockets[2]; + UNIT_ASSERT(SocketPair(sockets) == 0); + + TSocketHolder s1(sockets[0]); + TSocketHolder s2(sockets[1]); + + TSocketPoller poller; poller.WaitRead(sockets[1], (void*)17); - + UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); - - for (ui32 i = 0; i < 3; ++i) { + + for (ui32 i = 0; i < 3; ++i) { char buf[] = {18}; - UNIT_ASSERT_VALUES_EQUAL(1, send(sockets[0], buf, 1, 0)); - + UNIT_ASSERT_VALUES_EQUAL(1, send(sockets[0], buf, 1, 0)); + UNIT_ASSERT_VALUES_EQUAL((void*)17, poller.WaitT(TDuration::Zero())); - - UNIT_ASSERT_VALUES_EQUAL(1, recv(sockets[1], buf, 1, 0)); - UNIT_ASSERT_VALUES_EQUAL(18, buf[0]); - + + UNIT_ASSERT_VALUES_EQUAL(1, recv(sockets[1], buf, 1, 0)); + UNIT_ASSERT_VALUES_EQUAL(18, buf[0]); + UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); - } - } - + } + } + Y_UNIT_TEST(TestSimpleOneShot) { - SOCKET sockets[2]; - UNIT_ASSERT(SocketPair(sockets) == 0); - - TSocketHolder s1(sockets[0]); - TSocketHolder s2(sockets[1]); - - TSocketPoller poller; - + SOCKET sockets[2]; + UNIT_ASSERT(SocketPair(sockets) == 0); + + TSocketHolder s1(sockets[0]); + TSocketHolder s2(sockets[1]); + + TSocketPoller poller; + UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); - - for (ui32 i = 0; i < 3; ++i) { + + for (ui32 i = 0; i < 3; ++i) { poller.WaitReadOneShot(sockets[1], (void*)17); - - char buf[1]; - - buf[0] = i + 20; - - UNIT_ASSERT_VALUES_EQUAL(1, send(sockets[0], buf, 1, 0)); - + + char buf[1]; + + buf[0] = i + 20; + + UNIT_ASSERT_VALUES_EQUAL(1, send(sockets[0], buf, 1, 0)); + UNIT_ASSERT_VALUES_EQUAL((void*)17, poller.WaitT(TDuration::Zero())); - - UNIT_ASSERT_VALUES_EQUAL(1, recv(sockets[1], buf, 1, 0)); - UNIT_ASSERT_VALUES_EQUAL(char(i + 20), buf[0]); - - UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); - UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); - - buf[0] = i + 21; - - UNIT_ASSERT_VALUES_EQUAL(1, send(sockets[0], buf, 1, 0)); - - // this fails if socket is not oneshot - UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); - UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); - - UNIT_ASSERT_VALUES_EQUAL(1, recv(sockets[1], buf, 1, 0)); - UNIT_ASSERT_VALUES_EQUAL(char(i + 21), buf[0]); - } - } - + + UNIT_ASSERT_VALUES_EQUAL(1, recv(sockets[1], buf, 1, 0)); + UNIT_ASSERT_VALUES_EQUAL(char(i + 20), buf[0]); + + UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); + UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); + + buf[0] = i + 21; + + UNIT_ASSERT_VALUES_EQUAL(1, send(sockets[0], buf, 1, 0)); + + // this fails if socket is not oneshot + UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); + UNIT_ASSERT_VALUES_EQUAL(nullptr, poller.WaitT(TDuration::Zero())); + + UNIT_ASSERT_VALUES_EQUAL(1, recv(sockets[1], buf, 1, 0)); + UNIT_ASSERT_VALUES_EQUAL(char(i + 21), buf[0]); + } + } + Y_UNIT_TEST(TestItIsSafeToUnregisterUnregisteredDescriptor) { - SOCKET sockets[2]; - UNIT_ASSERT(SocketPair(sockets) == 0); - - TSocketHolder s1(sockets[0]); - TSocketHolder s2(sockets[1]); - - TSocketPoller poller; - - poller.Unwait(s1); - } - + SOCKET sockets[2]; + UNIT_ASSERT(SocketPair(sockets) == 0); + + TSocketHolder s1(sockets[0]); + TSocketHolder s2(sockets[1]); + + TSocketPoller poller; + + poller.Unwait(s1); + } + Y_UNIT_TEST(TestItIsSafeToReregisterDescriptor) { - SOCKET sockets[2]; - UNIT_ASSERT(SocketPair(sockets) == 0); - - TSocketHolder s1(sockets[0]); - TSocketHolder s2(sockets[1]); - - TSocketPoller poller; - + SOCKET sockets[2]; + UNIT_ASSERT(SocketPair(sockets) == 0); + + TSocketHolder s1(sockets[0]); + TSocketHolder s2(sockets[1]); + + TSocketPoller poller; + poller.WaitRead(s1, nullptr); poller.WaitRead(s1, nullptr); poller.WaitWrite(s1, nullptr); - } + } Y_UNIT_TEST(TestSimpleEdgeTriggered) { SOCKET sockets[2]; @@ -233,4 +233,4 @@ Y_UNIT_TEST_SUITE(TSocketPollerTest) { UNIT_ASSERT_EQUAL(TPoller::ExtractEvent(&e), (void*)17); } #endif -} +} diff --git a/util/network/pollerimpl.h b/util/network/pollerimpl.h index 35a981ea7d..e8c7e40fba 100644 --- a/util/network/pollerimpl.h +++ b/util/network/pollerimpl.h @@ -9,7 +9,7 @@ #include <util/generic/utility.h> #include <util/generic/vector.h> #include <util/generic/yexception.h> -#include <util/datetime/base.h> +#include <util/datetime/base.h> #if defined(_freebsd_) || defined(_darwin_) #define HAVE_KQUEUE_POLLER @@ -426,7 +426,7 @@ public: inline void SetImpl(void* data, SOCKET fd, int what) { with_lock (CommandLock_) { - Commands_.push_back(TCommand(fd, what, data)); + Commands_.push_back(TCommand(fd, what, data)); } Signal(); @@ -434,7 +434,7 @@ public: inline void Remove(SOCKET fd) noexcept { with_lock (CommandLock_) { - Commands_.push_back(TCommand(fd, 0)); + Commands_.push_back(TCommand(fd, 0)); } Signal(); @@ -442,7 +442,7 @@ public: inline size_t Wait(TEvent* events, size_t len, int timeout) noexcept { auto guard = Guard(Lock_); - + do { if (Begin_ != End_) { const size_t ret = Min<size_t>(End_ - Begin_, len); @@ -475,25 +475,25 @@ public: inline size_t WaitBase(TEvent* events, size_t len, int timeout) noexcept { with_lock (CommandLock_) { for (auto command = Commands_.begin(); command != Commands_.end(); ++command) { - if (command->Filter_ != 0) { - Fds_.Set(command->Fd_, command->Cookie_, command->Filter_); - } else { - Fds_.Remove(command->Fd_); - } - } - - Commands_.clear(); - } - - TTempBuf tmpBuf(3 * sizeof(fd_set) + Fds_.size() * sizeof(SOCKET)); + if (command->Filter_ != 0) { + Fds_.Set(command->Fd_, command->Cookie_, command->Filter_); + } else { + Fds_.Remove(command->Fd_); + } + } + + Commands_.clear(); + } + + TTempBuf tmpBuf(3 * sizeof(fd_set) + Fds_.size() * sizeof(SOCKET)); fd_set* in = (fd_set*)tmpBuf.Data(); fd_set* out = &in[1]; fd_set* errFds = &in[2]; SOCKET* keysToDeleteBegin = (SOCKET*)&in[3]; - SOCKET* keysToDeleteEnd = keysToDeleteBegin; - + SOCKET* keysToDeleteEnd = keysToDeleteBegin; + #if defined(_msan_enabled_) // msan doesn't handle FD_ZERO and cause false positive BALANCER-1347 memset(in, 0, sizeof(*in)); memset(out, 0, sizeof(*out)); @@ -529,12 +529,12 @@ public: if (FD_ISSET(fd, errFds)) { (events++)->Error(handle.Data(), EIO); - - if (handle.Filter() & CONT_POLL_ONE_SHOT) { - *keysToDeleteEnd = fd; - ++keysToDeleteEnd; - } - + + if (handle.Filter() & CONT_POLL_ONE_SHOT) { + *keysToDeleteEnd = fd; + ++keysToDeleteEnd; + } + } else { int what = 0; @@ -548,11 +548,11 @@ public: if (what) { (events++)->Success(handle.Data(), what); - - if (handle.Filter() & CONT_POLL_ONE_SHOT) { - *keysToDeleteEnd = fd; - ++keysToDeleteEnd; - } + + if (handle.Filter() & CONT_POLL_ONE_SHOT) { + *keysToDeleteEnd = fd; + ++keysToDeleteEnd; + } if (handle.Filter() & CONT_POLL_EDGE_TRIGGERED) { // Emulate edge-triggered for level-triggered select(). @@ -563,11 +563,11 @@ public: } } - while (keysToDeleteBegin != keysToDeleteEnd) { - Fds_.erase(*keysToDeleteBegin); - ++keysToDeleteBegin; - } - + while (keysToDeleteBegin != keysToDeleteEnd) { + Fds_.erase(*keysToDeleteBegin); + ++keysToDeleteBegin; + } + return events - eventsStart; } @@ -611,25 +611,25 @@ private: } private: - struct TCommand { - SOCKET Fd_; - int Filter_; // 0 to remove - void* Cookie_; - - TCommand(SOCKET fd, int filter, void* cookie) + struct TCommand { + SOCKET Fd_; + int Filter_; // 0 to remove + void* Cookie_; + + TCommand(SOCKET fd, int filter, void* cookie) : Fd_(fd) , Filter_(filter) , Cookie_(cookie) { } - - TCommand(SOCKET fd, int filter) + + TCommand(SOCKET fd, int filter) : Fd_(fd) , Filter_(filter) { } - }; - + }; + TFds Fds_; TMyMutex Lock_; @@ -637,9 +637,9 @@ private: TEvent* Begin_; TEvent* End_; - TMyMutex CommandLock_; + TMyMutex CommandLock_; TVector<TCommand> Commands_; - + SOCKET Signal_[2]; }; #endif diff --git a/util/network/socket.cpp b/util/network/socket.cpp index f3ea77929a..4f6e804346 100644 --- a/util/network/socket.cpp +++ b/util/network/socket.cpp @@ -554,25 +554,25 @@ static ssize_t DoSendMsg(SOCKET sock, const struct iovec* iov, int iovcnt) { #endif void TSocketHolder::Close() noexcept { - if (Fd_ != INVALID_SOCKET) { - bool ok = (closesocket(Fd_) == 0); - if (!ok) { + if (Fd_ != INVALID_SOCKET) { + bool ok = (closesocket(Fd_) == 0); + if (!ok) { // Do not quietly close bad descriptor, // because often it means double close // that is disasterous -#ifdef _win_ +#ifdef _win_ Y_VERIFY(WSAGetLastError() != WSAENOTSOCK, "must not quietly close bad socket descriptor"); -#elif defined(_unix_) +#elif defined(_unix_) Y_VERIFY(errno != EBADF, "must not quietly close bad descriptor: fd=%d", int(Fd_)); -#else +#else #error unsupported platform -#endif - } - - Fd_ = INVALID_SOCKET; - } -} - +#endif + } + + Fd_ = INVALID_SOCKET; + } +} + class TSocket::TImpl: public TAtomicRefCount<TImpl> { using TOps = TSocket::TOps; diff --git a/util/random/random.cpp b/util/random/random.cpp index a2191076b8..71f9323856 100644 --- a/util/random/random.cpp +++ b/util/random/random.cpp @@ -79,7 +79,7 @@ namespace { return GetRndGen<TToRealType<TY>::TResult>()->Uniform(n); \ } -DEF_RND(char) +DEF_RND(char) DEF_RND(unsigned char) DEF_RND(unsigned int) DEF_RND(unsigned long) @@ -89,11 +89,11 @@ DEF_RND(unsigned long long) #undef DEF_RND template <> -bool RandomNumber<bool>() { - return RandomNumber<ui8>() % 2 == 0; -} - -template <> +bool RandomNumber<bool>() { + return RandomNumber<ui8>() % 2 == 0; +} + +template <> float RandomNumber<float>() { float ret; diff --git a/util/random/random.h b/util/random/random.h index 8e7e23bf87..16b52d3995 100644 --- a/util/random/random.h +++ b/util/random/random.h @@ -5,7 +5,7 @@ * * specialized for: * all unsigned types (return value in range [0, MAX_VALUE_FOR_TYPE]) - * bool + * bool * long double (return value in range [0, 1)) * double (return value in range [0, 1)) * float (return value in range [0, 1)) @@ -16,8 +16,8 @@ T RandomNumber(); /* * returns value in range [0, max) */ -template <class T> -T RandomNumber(T max); +template <class T> +T RandomNumber(T max); /* * Re-initialize random state - useful after forking in multi-process programs. diff --git a/util/random/random_ut.cpp b/util/random/random_ut.cpp index c2ffc6ab27..30427676f3 100644 --- a/util/random/random_ut.cpp +++ b/util/random/random_ut.cpp @@ -1,9 +1,9 @@ #include "random.h" #include <library/cpp/testing/unittest/registar.h> - -#include <util/generic/ylimits.h> - + +#include <util/generic/ylimits.h> + template <class T> static inline void AssertRange(T v, T r1, T r2) { UNIT_ASSERT(v >= r1); @@ -11,50 +11,50 @@ static inline void AssertRange(T v, T r1, T r2) { } Y_UNIT_TEST_SUITE(TRandomNumberTest) { - template <typename T> - void TestAll(T n) { - for (T i = 0; i < n; ++i) { - while (RandomNumber<T>(n) != i) { - } - } - } - - template <typename T> - void TestSome(T n) { - for (int i = 0; i < 100; ++i) { - UNIT_ASSERT(RandomNumber<T>(n) < n); - } - } - - template <typename T> - void TestType() { - TestAll<T>(1); - TestAll<T>(2); - TestAll<T>(3); - TestAll<T>(4); - TestAll<T>(5); - TestAll<T>(6); - TestAll<T>(9); - TestAll<T>(15); - TestAll<T>(16); - TestSome<T>(Max<T>()); - TestSome<T>(Max<T>() - 1); - TestSome<T>(Max<T>() - 2); - TestSome<T>(Max<T>() - 3); - TestSome<T>(Max<T>() - 4); - TestSome<T>(Max<T>() - 5); - TestSome<T>(Max<T>() - 7); - TestSome<T>(Max<T>() - 8); - TestSome<T>(Max<T>() - 2222); - TestSome<T>(Max<T>() - 22222); - } - + template <typename T> + void TestAll(T n) { + for (T i = 0; i < n; ++i) { + while (RandomNumber<T>(n) != i) { + } + } + } + + template <typename T> + void TestSome(T n) { + for (int i = 0; i < 100; ++i) { + UNIT_ASSERT(RandomNumber<T>(n) < n); + } + } + + template <typename T> + void TestType() { + TestAll<T>(1); + TestAll<T>(2); + TestAll<T>(3); + TestAll<T>(4); + TestAll<T>(5); + TestAll<T>(6); + TestAll<T>(9); + TestAll<T>(15); + TestAll<T>(16); + TestSome<T>(Max<T>()); + TestSome<T>(Max<T>() - 1); + TestSome<T>(Max<T>() - 2); + TestSome<T>(Max<T>() - 3); + TestSome<T>(Max<T>() - 4); + TestSome<T>(Max<T>() - 5); + TestSome<T>(Max<T>() - 7); + TestSome<T>(Max<T>() - 8); + TestSome<T>(Max<T>() - 2222); + TestSome<T>(Max<T>() - 22222); + } + Y_UNIT_TEST(TestWithLimit) { - TestType<unsigned short>(); - TestType<unsigned int>(); - TestType<unsigned long>(); - TestType<unsigned long long>(); - } + TestType<unsigned short>(); + TestType<unsigned int>(); + TestType<unsigned long>(); + TestType<unsigned long long>(); + } Y_UNIT_TEST(TestRandomNumberFloat) { for (size_t i = 0; i < 1000; ++i) { @@ -73,13 +73,13 @@ Y_UNIT_TEST_SUITE(TRandomNumberTest) { AssertRange<long double>(RandomNumber<long double>(), 0.0, 1.0); } } - + Y_UNIT_TEST(TestBoolean) { - while (RandomNumber<bool>()) { - } - while (!RandomNumber<bool>()) { - } - } + while (RandomNumber<bool>()) { + } + while (!RandomNumber<bool>()) { + } + } Y_UNIT_TEST(TestResetSeed) { SetRandomSeed(42); @@ -152,4 +152,4 @@ Y_UNIT_TEST_SUITE(TRandomNumberTest) { UNIT_ASSERT_EQUAL(RandomNumber<ui32>(1 << 8), el); } } -} +} diff --git a/util/stream/format.h b/util/stream/format.h index 30e321d377..b033208a1b 100644 --- a/util/stream/format.h +++ b/util/stream/format.h @@ -1,5 +1,5 @@ #pragma once - + #include "mem.h" #include "output.h" @@ -8,7 +8,7 @@ #include <util/generic/flags.h> #include <util/memory/tempbuf.h> #include <util/string/cast.h> - + enum ENumberFormatFlag { HF_FULL = 0x01, /**< Output number with leading zeros. */ HF_ADDX = 0x02, /**< Output '0x' or '0b' before hex/bin digits. */ @@ -21,7 +21,7 @@ enum ESizeFormat { SF_BYTES, /**< Base 1024, byte suffix. 1100 gets turned into "1.07KiB". */ }; -namespace NFormatPrivate { +namespace NFormatPrivate { template <size_t Value> struct TLog2: std::integral_constant<size_t, TLog2<Value / 2>::value + 1> {}; @@ -29,66 +29,66 @@ namespace NFormatPrivate { struct TLog2<1>: std::integral_constant<size_t, 0> {}; static inline void WriteChars(IOutputStream& os, char c, size_t count) { - if (count == 0) - return; - TTempBuf buf(count); - memset(buf.Data(), c, count); - os.Write(buf.Data(), count); - } - - template <typename T> - struct TLeftPad { + if (count == 0) + return; + TTempBuf buf(count); + memset(buf.Data(), c, count); + os.Write(buf.Data(), count); + } + + template <typename T> + struct TLeftPad { T Value; - size_t Width; - char Padc; - + size_t Width; + char Padc; + inline TLeftPad(const T& value, size_t width, char padc) - : Value(value) - , Width(width) - , Padc(padc) - { - } - }; - - template <typename T> + : Value(value) + , Width(width) + , Padc(padc) + { + } + }; + + template <typename T> IOutputStream& operator<<(IOutputStream& o, const TLeftPad<T>& lp) { - TTempBuf buf; - TMemoryOutput ss(buf.Data(), buf.Size()); + TTempBuf buf; + TMemoryOutput ss(buf.Data(), buf.Size()); ss << lp.Value; - size_t written = buf.Size() - ss.Avail(); - if (lp.Width > written) { - WriteChars(o, lp.Padc, lp.Width - written); - } - o.Write(buf.Data(), written); - return o; - } - - template <typename T> - struct TRightPad { + size_t written = buf.Size() - ss.Avail(); + if (lp.Width > written) { + WriteChars(o, lp.Padc, lp.Width - written); + } + o.Write(buf.Data(), written); + return o; + } + + template <typename T> + struct TRightPad { T Value; - size_t Width; - char Padc; - + size_t Width; + char Padc; + inline TRightPad(const T& value, size_t width, char padc) - : Value(value) - , Width(width) - , Padc(padc) - { - } - }; - - template <typename T> + : Value(value) + , Width(width) + , Padc(padc) + { + } + }; + + template <typename T> IOutputStream& operator<<(IOutputStream& o, const TRightPad<T>& lp) { - TTempBuf buf; - TMemoryOutput ss(buf.Data(), buf.Size()); + TTempBuf buf; + TMemoryOutput ss(buf.Data(), buf.Size()); ss << lp.Value; - size_t written = buf.Size() - ss.Avail(); - o.Write(buf.Data(), written); - if (lp.Width > written) { - WriteChars(o, lp.Padc, lp.Width - written); - } - return o; - } + size_t written = buf.Size() - ss.Avail(); + o.Write(buf.Data(), written); + if (lp.Width > written) { + WriteChars(o, lp.Padc, lp.Width - written); + } + return o; + } template <typename T, size_t Base> struct TBaseNumber { @@ -184,8 +184,8 @@ namespace NFormatPrivate { double Value; ESizeFormat Format; }; -} - +} + /** * Output manipulator basically equivalent to `std::setw` and `std::setfill` * combined. @@ -203,11 +203,11 @@ namespace NFormatPrivate { * @param padc Character to use for padding. * @see RightPad */ -template <typename T> +template <typename T> static constexpr ::NFormatPrivate::TLeftPad<T> LeftPad(const T& value, const size_t width, const char padc = ' ') noexcept { return ::NFormatPrivate::TLeftPad<T>(value, width, padc); -} - +} + template <typename T, int N> static constexpr ::NFormatPrivate::TLeftPad<const T*> LeftPad(const T (&value)[N], const size_t width, const char padc = ' ') noexcept { return ::NFormatPrivate::TLeftPad<const T*>(value, width, padc); @@ -229,11 +229,11 @@ static constexpr ::NFormatPrivate::TLeftPad<const T*> LeftPad(const T (&value)[N * @param padc Character to use for padding. * @see LeftPad */ -template <typename T> +template <typename T> static constexpr ::NFormatPrivate::TRightPad<T> RightPad(const T& value, const size_t width, const char padc = ' ') noexcept { return ::NFormatPrivate::TRightPad<T>(value, width, padc); -} - +} + template <typename T, int N> static constexpr ::NFormatPrivate::TRightPad<const T*> RightPad(const T (&value)[N], const size_t width, const char padc = ' ') noexcept { return ::NFormatPrivate::TRightPad<const T*>(value, width, padc); diff --git a/util/stream/format_ut.cpp b/util/stream/format_ut.cpp index 2e50f0f9c5..43245aeb48 100644 --- a/util/stream/format_ut.cpp +++ b/util/stream/format_ut.cpp @@ -2,28 +2,28 @@ #include <library/cpp/testing/unittest/registar.h> #include <util/charset/wide.h> - + Y_UNIT_TEST_SUITE(TOutputStreamFormattingTest) { Y_UNIT_TEST(TestLeftPad) { - TStringStream ss; - ss << LeftPad(10, 4, '0'); - UNIT_ASSERT_VALUES_EQUAL("0010", ss.Str()); - + TStringStream ss; + ss << LeftPad(10, 4, '0'); + UNIT_ASSERT_VALUES_EQUAL("0010", ss.Str()); + ss.Clear(); - ss << LeftPad(222, 1); - UNIT_ASSERT_VALUES_EQUAL("222", ss.Str()); - } - + ss << LeftPad(222, 1); + UNIT_ASSERT_VALUES_EQUAL("222", ss.Str()); + } + Y_UNIT_TEST(TestRightPad) { - TStringStream ss; - ss << RightPad("aa", 4); - UNIT_ASSERT_VALUES_EQUAL("aa ", ss.Str()); - + TStringStream ss; + ss << RightPad("aa", 4); + UNIT_ASSERT_VALUES_EQUAL("aa ", ss.Str()); + ss.Clear(); - ss << RightPad("aa", 1); - UNIT_ASSERT_VALUES_EQUAL("aa", ss.Str()); - } - + ss << RightPad("aa", 1); + UNIT_ASSERT_VALUES_EQUAL("aa", ss.Str()); + } + Y_UNIT_TEST(TestTime) { TStringStream ss; @@ -179,4 +179,4 @@ Y_UNIT_TEST_SUITE(TOutputStreamFormattingTest) { UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadable(TDuration::Seconds(3672))), "1h 1m 12s"); UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadable(TDuration::Seconds(4220))), "1h 10m 20s"); } -} +} diff --git a/util/stream/output.cpp b/util/stream/output.cpp index c193889e7f..db81b81b70 100644 --- a/util/stream/output.cpp +++ b/util/stream/output.cpp @@ -99,7 +99,7 @@ void Out<std::string>(IOutputStream& o, const std::string& p) { o.Write(p.data(), p.length()); } -template <> +template <> void Out<std::string_view>(IOutputStream& o, const std::string_view& p) { o.Write(p.data(), p.length()); } diff --git a/util/stream/output.h b/util/stream/output.h index 8d904b5ecf..00eef50b95 100644 --- a/util/stream/output.h +++ b/util/stream/output.h @@ -296,7 +296,7 @@ static inline void Flush(IOutputStream& o) { /* * Also see format.h for additional manipulators. */ - + #include "debug.h" void RedirectStdioToAndroidLog(bool redirect); diff --git a/util/string/escape.cpp b/util/string/escape.cpp index afec4780e7..cd09a7dbd0 100644 --- a/util/string/escape.cpp +++ b/util/string/escape.cpp @@ -1,10 +1,10 @@ #include "escape.h" #include "cast.h" -#include <util/system/defaults.h> +#include <util/system/defaults.h> #include <util/charset/utf8.h> #include <util/charset/wide.h> - + /// @todo: escape trigraphs (eg "??/" is "\") /* REFEREBCES FOR ESCAPE SEQUENCE INTERPRETATION: @@ -54,31 +54,31 @@ namespace { template <typename TChar> static inline char OctDigit(TChar value) { Y_ASSERT(value < 8); - return '0' + value; + return '0' + value; } - + template <typename TChar> static inline bool IsPrintable(TChar c) { return c >= 32 && c <= 126; } - + template <typename TChar> static inline bool IsHexDigit(TChar c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } - + template <typename TChar> static inline bool IsOctDigit(TChar c) { return c >= '0' && c <= '7'; } - + template <typename TChar> struct TEscapeUtil; - + template <> struct TEscapeUtil<char> { static const size_t ESCAPE_C_BUFFER_SIZE = 4; - + template <typename TNextChar, typename TBufferChar> static inline size_t EscapeC(unsigned char c, TNextChar next, TBufferChar r[ESCAPE_C_BUFFER_SIZE]) { // (1) Printable characters go as-is, except backslash and double quote. @@ -124,13 +124,13 @@ namespace { r[3] = OctDigit((c & 0007) >> 0); return 4; } - } + } }; - + template <> struct TEscapeUtil<wchar16> { static const size_t ESCAPE_C_BUFFER_SIZE = 6; - + template <typename TNextChar, typename TBufferChar> static inline size_t EscapeC(wchar16 c, TNextChar next, TBufferChar r[ESCAPE_C_BUFFER_SIZE]) { if (c < 0x100) { @@ -144,26 +144,26 @@ namespace { r[5] = HexDigit((c & 0x000F) >> 0); return 6; } - } + } }; } - -template <class TChar> + +template <class TChar> TBasicString<TChar>& EscapeCImpl(const TChar* str, size_t len, TBasicString<TChar>& r) { using TEscapeUtil = ::TEscapeUtil<TChar>; - + TChar buffer[TEscapeUtil::ESCAPE_C_BUFFER_SIZE]; - + size_t i, j; for (i = 0, j = 0; i < len; ++i) { size_t rlen = TEscapeUtil::EscapeC(str[i], (i + 1 < len ? str[i + 1] : 0), buffer); - + if (rlen > 1) { r.append(str + j, i - j); j = i + 1; r.append(buffer, rlen); } - } + } if (j > 0) { r.append(str + j, len - j); @@ -172,8 +172,8 @@ TBasicString<TChar>& EscapeCImpl(const TChar* str, size_t len, TBasicString<TCha } return r; -} - +} + template TString& EscapeCImpl<TString::TChar>(const TString::TChar* str, size_t len, TString& r); template TUtf16String& EscapeCImpl<TUtf16String::TChar>(const TUtf16String::TChar* str, size_t len, TUtf16String& r); @@ -410,11 +410,11 @@ TUtf16String& EscapeC(const TWtringBuf str, TUtf16String& w) { TString EscapeC(const TString& str) { return EscapeC(str.data(), str.size()); -} - +} + TUtf16String EscapeC(const TUtf16String& str) { return EscapeC(str.data(), str.size()); -} +} TString& UnescapeC(const TStringBuf str, TString& s) { return UnescapeC(str.data(), str.size(), s); diff --git a/util/string/escape.h b/util/string/escape.h index ec72f71573..b01be65b0e 100644 --- a/util/string/escape.h +++ b/util/string/escape.h @@ -1,18 +1,18 @@ #pragma once - + #include <util/generic/string.h> #include <util/generic/strbuf.h> - -template <class TChar> + +template <class TChar> TBasicString<TChar>& EscapeCImpl(const TChar* str, size_t len, TBasicString<TChar>&); - + template <class TChar> TBasicString<TChar>& UnescapeCImpl(const TChar* str, size_t len, TBasicString<TChar>&); template <class TChar> TChar* UnescapeC(const TChar* str, size_t len, TChar* buf); -template <typename TChar> +template <typename TChar> static inline TBasicString<TChar>& EscapeC(const TChar* str, size_t len, TBasicString<TChar>& s) { return EscapeCImpl(str, len, s); } @@ -23,7 +23,7 @@ static inline TBasicString<TChar> EscapeC(const TChar* str, size_t len) { return EscapeC(str, len, s); } -template <typename TChar> +template <typename TChar> static inline TBasicString<TChar> EscapeC(const TBasicStringBuf<TChar>& str) { return EscapeC(str.data(), str.size()); } diff --git a/util/string/escape_ut.cpp b/util/string/escape_ut.cpp index 51836a64ed..cd38ecffd3 100644 --- a/util/string/escape_ut.cpp +++ b/util/string/escape_ut.cpp @@ -1,10 +1,10 @@ #include "escape.h" #include <library/cpp/testing/unittest/registar.h> - + #include <util/generic/string.h> -#include <util/charset/wide.h> - +#include <util/charset/wide.h> + using namespace std::string_view_literals; namespace { @@ -24,7 +24,7 @@ static const TExample CommonTestData[] = { // Should be valid UTF-8. {"http://ya.ru/", "http://ya.ru/"}, {"http://ya.ru/\\x17\\n", "http://ya.ru/\x17\n"}, - + {"http://ya.ru/\\0", "http://ya.ru/\0"sv}, {"http://ya.ru/\\0\\0", "http://ya.ru/\0\0"sv}, {"http://ya.ru/\\0\\0000", "http://ya.ru/\0\0" @@ -60,9 +60,9 @@ Y_UNIT_TEST_SUITE(TEscapeCTest) { UNIT_ASSERT_VALUES_EQUAL("http://ya.ru/\\x17\\n\\xAB", EscapeC(TString("http://ya.ru/\x17\n\xab"))); UNIT_ASSERT_VALUES_EQUAL("http://ya.ru/\x17\n\xab", UnescapeC(TString("http://ya.ru/\\x17\\n\\xAB"))); - UNIT_ASSERT_VALUES_EQUAL("h", EscapeC('h')); + UNIT_ASSERT_VALUES_EQUAL("h", EscapeC('h')); UNIT_ASSERT_VALUES_EQUAL("h", UnescapeC(TString("h"))); - UNIT_ASSERT_VALUES_EQUAL("\\xFF", EscapeC('\xFF')); + UNIT_ASSERT_VALUES_EQUAL("\\xFF", EscapeC('\xFF')); UNIT_ASSERT_VALUES_EQUAL("\xFF", UnescapeC(TString("\\xFF"))); UNIT_ASSERT_VALUES_EQUAL("\\377f", EscapeC(TString("\xff" @@ -77,8 +77,8 @@ Y_UNIT_TEST_SUITE(TEscapeCTest) { UnescapeC(TString("\\xFFg"))); UNIT_ASSERT_VALUES_EQUAL("\xEA\x9A\x96", UnescapeC(TString("\\uA696"))); UNIT_ASSERT_VALUES_EQUAL("Странный компроматтест", UnescapeC(TString("\\u0421\\u0442\\u0440\\u0430\\u043d\\u043d\\u044b\\u0439 \\u043a\\u043e\\u043c\\u043f\\u0440\\u043e\\u043c\\u0430\\u0442тест"))); - } - + } + Y_UNIT_TEST(TestWtrokaEscapeC) { for (const auto& e : CommonTestData) { TUtf16String expected(UTF8ToWide(e.Expected)); @@ -93,7 +93,7 @@ Y_UNIT_TEST_SUITE(TEscapeCTest) { UNIT_ASSERT_VALUES_EQUAL(u"http://ya.ru/\\x17\\n\\u1234", EscapeC(u"http://ya.ru/\x17\n\u1234")); UNIT_ASSERT_VALUES_EQUAL(u"h", EscapeC(u'h')); UNIT_ASSERT_VALUES_EQUAL(u"\\xFF", EscapeC(wchar16(255))); - } + } Y_UNIT_TEST(TestEscapeTrigraphs) { UNIT_ASSERT_VALUES_EQUAL("?", EscapeC(TString("?"))); @@ -145,4 +145,4 @@ Y_UNIT_TEST_SUITE(TEscapeCTest) { UNIT_ASSERT_VALUES_EQUAL(UnescapeC("\\U00000020"), " "); UNIT_ASSERT_VALUES_EQUAL(UnescapeC("\\Uxxx"), "Uxxx"); } -} +} diff --git a/util/string/split.cpp b/util/string/split.cpp index 7438c07525..7d26857cc7 100644 --- a/util/string/split.cpp +++ b/util/string/split.cpp @@ -1,24 +1,24 @@ -#include "split.h" - +#include "split.h" + template <class TValue> inline size_t Split(const char* ptr, const char* delim, TVector<TValue>& values) { - values.erase(values.begin(), values.end()); - while (ptr && *ptr) { - ptr += strspn(ptr, delim); - if (ptr && *ptr) { - size_t epos = strcspn(ptr, delim); - assert(epos); + values.erase(values.begin(), values.end()); + while (ptr && *ptr) { + ptr += strspn(ptr, delim); + if (ptr && *ptr) { + size_t epos = strcspn(ptr, delim); + assert(epos); values.push_back(TValue(ptr, epos)); - ptr += epos; - } - } - return values.size(); -} - + ptr += epos; + } + } + return values.size(); +} + size_t Split(const char* ptr, const char* delim, TVector<TString>& values) { return Split<TString>(ptr, delim, values); } size_t Split(const TString& in, const TString& delim, TVector<TString>& res) { return Split(in.data(), delim.data(), res); -} +} diff --git a/util/string/split.h b/util/string/split.h index 166ee10660..bc46d9e64c 100644 --- a/util/string/split.h +++ b/util/string/split.h @@ -407,10 +407,10 @@ static inline void Split(char* buf, char ch, T* res) { SplitString(buf, delim, pusher); } -/// Split string into res vector. Res vector is cleared before split. +/// Split string into res vector. Res vector is cleared before split. /// Old good slow split function. /// Field delimter is any number of symbols specified in delim (no empty strings in res vector) -/// @return number of elements created +/// @return number of elements created size_t Split(const char* in, const char* delim, TVector<TString>& res); size_t Split(const TString& in, const TString& delim, TVector<TString>& res); diff --git a/util/system/backtrace.cpp b/util/system/backtrace.cpp index 1bc57de75d..b77fe58fb1 100644 --- a/util/system/backtrace.cpp +++ b/util/system/backtrace.cpp @@ -236,15 +236,15 @@ TResolvedSymbol ResolveSymbol(void* sym, char*, size_t) { void FormatBackTrace(IOutputStream* out, void* const* backtrace, size_t backtraceSize) { char tmpBuf[1024]; - for (size_t i = 0; i < backtraceSize; ++i) { - TResolvedSymbol rs = ResolveSymbol(backtrace[i], tmpBuf, sizeof(tmpBuf)); + for (size_t i = 0; i < backtraceSize; ++i) { + TResolvedSymbol rs = ResolveSymbol(backtrace[i], tmpBuf, sizeof(tmpBuf)); *out << rs.Name << "+" << ((ptrdiff_t)backtrace[i] - (ptrdiff_t)rs.NearestSymbol) << " (" << Hex((ptrdiff_t)backtrace[i], HF_ADDX) << ')' << '\n'; } } TFormatBackTraceFn FormatBackTraceFn = FormatBackTrace; - + TFormatBackTraceFn SetFormatBackTraceFn(TFormatBackTraceFn f) { TFormatBackTraceFn prevFn = FormatBackTraceFn; FormatBackTraceFn = f; @@ -264,25 +264,25 @@ TFormatBackTraceFn GetFormatBackTraceFn() { void PrintBackTrace() { FormatBackTrace(&Cerr); } - -TBackTrace::TBackTrace() - : Size(0) + +TBackTrace::TBackTrace() + : Size(0) { } - -void TBackTrace::Capture() { - Size = BackTrace(Data, CAPACITY); -} - + +void TBackTrace::Capture() { + Size = BackTrace(Data, CAPACITY); +} + void TBackTrace::PrintTo(IOutputStream& out) const { FormatBackTraceFn(&out, Data, Size); -} - +} + TString TBackTrace::PrintToString() const { - TStringStream ss; - PrintTo(ss); + TStringStream ss; + PrintTo(ss); return ss.Str(); -} +} size_t TBackTrace::size() const { return Size; diff --git a/util/system/backtrace.h b/util/system/backtrace.h index 71b3c8f528..2fce7585c3 100644 --- a/util/system/backtrace.h +++ b/util/system/backtrace.h @@ -17,7 +17,7 @@ TResolvedSymbol ResolveSymbol(void* sym, char* buf, size_t len); void FormatBackTrace(IOutputStream* out, void* const* backtrace, size_t backtraceSize); void FormatBackTrace(IOutputStream* out); void PrintBackTrace(); - + using TFormatBackTraceFn = void (*)(IOutputStream*, void* const* backtrace, size_t backtraceSize); TFormatBackTraceFn SetFormatBackTraceFn(TFormatBackTraceFn f); @@ -25,15 +25,15 @@ TFormatBackTraceFn GetFormatBackTraceFn(); using TBackTraceView = TArrayRef<void* const>; -class TBackTrace { -private: +class TBackTrace { +private: static constexpr size_t CAPACITY = 300; - void* Data[CAPACITY]; - size_t Size; + void* Data[CAPACITY]; + size_t Size; -public: - TBackTrace(); - void Capture(); +public: + TBackTrace(); + void Capture(); void PrintTo(IOutputStream&) const; TString PrintToString() const; size_t size() const; @@ -41,4 +41,4 @@ public: operator TBackTraceView() const; static TBackTrace FromCurrentException(); -}; +}; diff --git a/util/system/byteorder_ut.cpp b/util/system/byteorder_ut.cpp index b728f86915..39b8603d3f 100644 --- a/util/system/byteorder_ut.cpp +++ b/util/system/byteorder_ut.cpp @@ -1,8 +1,8 @@ #include "byteorder.h" #include <library/cpp/testing/unittest/registar.h> - -class TByteOrderTest: public TTestBase { + +class TByteOrderTest: public TTestBase { UNIT_TEST_SUITE(TByteOrderTest); UNIT_TEST(TestSwap16) UNIT_TEST(TestSwap32) @@ -21,6 +21,6 @@ private: inline void TestSwap64() { UNIT_ASSERT_EQUAL(0x1234567890abcdefULL, SwapBytes((ui64)ULL(0xefcdab9078563412))); } -}; - -UNIT_TEST_SUITE_REGISTRATION(TByteOrderTest); +}; + +UNIT_TEST_SUITE_REGISTRATION(TByteOrderTest); diff --git a/util/system/compat.cpp b/util/system/compat.cpp index edeb78e8e3..18fbfa296a 100644 --- a/util/system/compat.cpp +++ b/util/system/compat.cpp @@ -16,7 +16,7 @@ #include <io.h> #endif -#ifndef HAVE_NATIVE_GETPROGNAME +#ifndef HAVE_NATIVE_GETPROGNAME const char* getprogname() { return GetProgramName().data(); } diff --git a/util/system/compat.h b/util/system/compat.h index 6aef2761f9..c53dbcca17 100644 --- a/util/system/compat.h +++ b/util/system/compat.h @@ -30,9 +30,9 @@ extern "C" { #if defined(__FreeBSD__) || defined(_darwin_) #define HAVE_NATIVE_GETPROGNAME -#endif - -#ifndef HAVE_NATIVE_GETPROGNAME +#endif + +#ifndef HAVE_NATIVE_GETPROGNAME const char* getprogname(); #endif diff --git a/util/system/compat_ut.cpp b/util/system/compat_ut.cpp index a46b41a4ce..dbd9289c17 100644 --- a/util/system/compat_ut.cpp +++ b/util/system/compat_ut.cpp @@ -1,12 +1,12 @@ #include "compat.h" #include <library/cpp/testing/unittest/registar.h> - -#include <util/folder/dirut.h> -#include <util/stream/output.h> - + +#include <util/folder/dirut.h> +#include <util/stream/output.h> + Y_UNIT_TEST_SUITE(TCompatTest) { Y_UNIT_TEST(TestGetprogname) { - getprogname(); // just check it links - } -} + getprogname(); // just check it links + } +} diff --git a/util/system/condvar.cpp b/util/system/condvar.cpp index 48addfb210..62f3d22356 100644 --- a/util/system/condvar.cpp +++ b/util/system/condvar.cpp @@ -112,7 +112,7 @@ public: int ret = pthread_cond_timedwait(&Cond_, (pthread_mutex_t*)lock.Handle(), &spec); Y_VERIFY(ret == 0 || ret == ETIMEDOUT, "pthread_cond_timedwait failed: %s", LastSystemErrorText(ret)); - + return ret == 0; } } diff --git a/util/system/condvar.h b/util/system/condvar.h index 2fa33a1107..569162717c 100644 --- a/util/system/condvar.h +++ b/util/system/condvar.h @@ -4,7 +4,7 @@ #include <util/generic/ptr.h> #include <util/generic/noncopyable.h> -#include <util/datetime/base.h> +#include <util/datetime/base.h> #include <utility> diff --git a/util/system/context.cpp b/util/system/context.cpp index 0c8f3069ff..ad99309088 100644 --- a/util/system/context.cpp +++ b/util/system/context.cpp @@ -24,7 +24,7 @@ namespace __cxxabiv1 { #endif #endif -#include <util/stream/output.h> +#include <util/stream/output.h> #include <util/generic/yexception.h> #define FROM_CONTEXT_IMPL @@ -37,7 +37,7 @@ void ITrampoLine::DoRunNaked() { try { DoRun(); } catch (...) { - Cerr << "Uncaught exception in coroutine: " << CurrentExceptionMessage() << "\n"; + Cerr << "Uncaught exception in coroutine: " << CurrentExceptionMessage() << "\n"; } abort(); diff --git a/util/system/datetime.cpp b/util/system/datetime.cpp index 4c5488a24c..b07b50679a 100644 --- a/util/system/datetime.cpp +++ b/util/system/datetime.cpp @@ -7,7 +7,7 @@ #include <ctime> #include <cerrno> - + #ifdef _darwin_ #include <AvailabilityMacros.h> #if defined(MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_12 @@ -19,8 +19,8 @@ static ui64 ToMicroSeconds(const struct timeval& tv) { return (ui64)tv.tv_sec * 1000000 + (ui64)tv.tv_usec; -} - +} + #if defined(_win_) static ui64 ToMicroSeconds(const FILETIME& ft) { return (((ui64)ft.dwHighDateTime << 32) + (ui64)ft.dwLowDateTime) / (ui64)10; @@ -32,12 +32,12 @@ static ui64 ToMicroSeconds(const struct timespec& ts) { #endif ui64 MicroSeconds() noexcept { - struct timeval tv; + struct timeval tv; gettimeofday(&tv, nullptr); - + return ToMicroSeconds(tv); -} - +} + ui64 ThreadCPUUserTime() noexcept { #if defined(_win_) FILETIME creationTime, exitTime, kernelTime, userTime; @@ -73,26 +73,26 @@ ui64 ThreadCPUTime() noexcept { } ui32 Seconds() noexcept { - struct timeval tv; + struct timeval tv; gettimeofday(&tv, nullptr); - return tv.tv_sec; -} - + return tv.tv_sec; +} + void NanoSleep(ui64 ns) noexcept { #if defined(_win_) - Sleep(ns / 1000000); -#else - const ui64 NS = 1000 * 1000 * 1000; - struct timespec req; - req.tv_sec = ns / NS; - req.tv_nsec = ns % NS; - struct timespec left; - while (nanosleep(&req, &left) < 0) { + Sleep(ns / 1000000); +#else + const ui64 NS = 1000 * 1000 * 1000; + struct timespec req; + req.tv_sec = ns / NS; + req.tv_nsec = ns % NS; + struct timespec left; + while (nanosleep(&req, &left) < 0) { Y_ASSERT(errno == EINTR); - req = left; - } -#endif -} + req = left; + } +#endif +} #if defined(_x86_) extern const bool HaveRdtscp = NX86::HaveRDTSCP(); diff --git a/util/system/datetime.h b/util/system/datetime.h index 92aacdc31f..aa009974e0 100644 --- a/util/system/datetime.h +++ b/util/system/datetime.h @@ -1,21 +1,21 @@ #pragma once - + #include "defaults.h" #include "platform.h" - + #if defined(_win_) #include <intrin.h> #pragma intrinsic(__rdtsc) #endif // _win_ - + #if defined(_darwin_) && !defined(_x86_) #include <mach/mach_time.h> #endif -/// util/system/datetime.h contains only system time providers -/// for handy datetime utilities include util/datetime/base.h - -/// Current time in microseconds since epoch +/// util/system/datetime.h contains only system time providers +/// for handy datetime utilities include util/datetime/base.h + +/// Current time in microseconds since epoch ui64 MicroSeconds() noexcept; /// Current time in milliseconds since epoch inline ui64 MilliSeconds() { @@ -25,17 +25,17 @@ inline ui64 MilliSeconds() { inline ui64 millisec() { return MilliSeconds(); } -/// Current time in seconds since epoch +/// Current time in seconds since epoch ui32 Seconds() noexcept; ///Current thread time in microseconds ui64 ThreadCPUUserTime() noexcept; ui64 ThreadCPUSystemTime() noexcept; ui64 ThreadCPUTime() noexcept; - + void NanoSleep(ui64 ns) noexcept; - -// GetCycleCount guarantees to return synchronous values on different cores -// and provide constant rate only on modern Intel and AMD processors + +// GetCycleCount guarantees to return synchronous values on different cores +// and provide constant rate only on modern Intel and AMD processors // NOTE: rdtscp is used to prevent out of order execution // rdtsc can be reordered, while rdtscp cannot be reordered // with preceding instructions @@ -95,4 +95,4 @@ Y_FORCE_INLINE ui64 GetCycleCount() noexcept { #else #error "unsupported arch" #endif -} +} diff --git a/util/system/datetime_ut.cpp b/util/system/datetime_ut.cpp index bddf9df35d..a865a888ca 100644 --- a/util/system/datetime_ut.cpp +++ b/util/system/datetime_ut.cpp @@ -1 +1 @@ -#include "datetime.h" +#include "datetime.h" diff --git a/util/system/defaults.h b/util/system/defaults.h index 2d95db149b..dcd7abea38 100644 --- a/util/system/defaults.h +++ b/util/system/defaults.h @@ -142,7 +142,7 @@ constexpr bool Y_IS_DEBUG_BUILD = true; #define Y_CAT_II(X, Y) X##Y #define Y_STRINGIZE(X) UTIL_PRIVATE_STRINGIZE_AUX(X) -#define UTIL_PRIVATE_STRINGIZE_AUX(X) #X +#define UTIL_PRIVATE_STRINGIZE_AUX(X) #X #if defined(__COUNTER__) #define Y_GENERATE_UNIQUE_ID(N) Y_CAT(N, __COUNTER__) diff --git a/util/system/error_ut.cpp b/util/system/error_ut.cpp index 8403dfa180..763b0dddb7 100644 --- a/util/system/error_ut.cpp +++ b/util/system/error_ut.cpp @@ -6,7 +6,7 @@ #ifdef _win_ #include "winint.h" -#else +#else #include <fcntl.h> #endif diff --git a/util/system/event.h b/util/system/event.h index a63498a72e..cab2fc478a 100644 --- a/util/system/event.h +++ b/util/system/event.h @@ -1,7 +1,7 @@ #pragma once #include <util/generic/ptr.h> -#include <util/datetime/base.h> +#include <util/datetime/base.h> struct TEventResetType { enum ResetMode { diff --git a/util/system/execpath.cpp b/util/system/execpath.cpp index 836edeb76d..33198af58b 100644 --- a/util/system/execpath.cpp +++ b/util/system/execpath.cpp @@ -2,11 +2,11 @@ #include <stdlib.h> -#if defined(_solaris_) +#if defined(_solaris_) #include <stdlib.h> -#elif defined(_darwin_) +#elif defined(_darwin_) #include <mach-o/dyld.h> -#elif defined(_win_) +#elif defined(_win_) #include "winint.h" #include <io.h> #elif defined(_linux_) @@ -16,13 +16,13 @@ #include <sys/types.h> // for u_int not defined in sysctl.h #include <sys/sysctl.h> #include <unistd.h> -#endif - +#endif + #include <util/folder/dirut.h> #include <util/generic/singleton.h> #include <util/generic/function.h> #include <util/generic/yexception.h> -#include <util/memory/tempbuf.h> +#include <util/memory/tempbuf.h> #include <util/stream/file.h> #include <util/stream/pipe.h> #include <util/string/cast.h> @@ -30,7 +30,7 @@ #include "filemap.h" #include "execpath.h" #include "fs.h" - + #if defined(_freebsd_) static inline bool GoodPath(const TString& path) { return path.find('/') != TString::npos; @@ -101,9 +101,9 @@ static inline bool FreeBSDGuessExecBasePath(const TString& guessBasePath, TStrin #endif static TString GetExecPathImpl() { -#if defined(_solaris_) +#if defined(_solaris_) return execname(); -#elif defined(_darwin_) +#elif defined(_darwin_) TTempBuf execNameBuf; for (size_t i = 0; i < 2; ++i) { std::remove_pointer_t<TFunctionArg<decltype(_NSGetExecutablePath), 1>> bufsize = execNameBuf.Size(); @@ -112,10 +112,10 @@ static TString GetExecPathImpl() { return execNameBuf.Data(); } else if (r == -1) { execNameBuf = TTempBuf(bufsize); - } + } } ythrow yexception() << "GetExecPathImpl() failed"; -#elif defined(_win_) +#elif defined(_win_) TTempBuf execNameBuf; for (;;) { DWORD r = GetModuleFileName(nullptr, execNameBuf.Data(), execNameBuf.Size()); @@ -125,13 +125,13 @@ static TString GetExecPathImpl() { ythrow yexception() << "GetExecPathImpl() failed: " << LastSystemErrorText(); } else { return execNameBuf.Data(); - } + } } #elif defined(_linux_) || defined(_cygwin_) TString path("/proc/self/exe"); return NFs::ReadLink(path); // TODO(yoda): check if the filename ends with " (deleted)" -#elif defined(_freebsd_) +#elif defined(_freebsd_) TString execPath = FreeBSDGetExecPath(); if (GoodPath(execPath)) { return execPath; @@ -150,9 +150,9 @@ static TString GetExecPathImpl() { } ythrow yexception() << "can not resolve exec path"; -#else +#else #error dont know how to implement GetExecPath on this platform -#endif +#endif } static bool GetPersistentExecPathImpl(TString& to) { @@ -189,10 +189,10 @@ namespace { TString PersistentExecPath; }; } - + const TString& GetExecPath() { return TExecPathsHolder::Instance()->ExecPath; -} +} const TString& GetPersistentExecPath() { return TExecPathsHolder::Instance()->PersistentExecPath; diff --git a/util/system/execpath.h b/util/system/execpath.h index 7f1cd5a14b..4b914b8e85 100644 --- a/util/system/execpath.h +++ b/util/system/execpath.h @@ -1,7 +1,7 @@ #pragma once - + #include <util/generic/fwd.h> - + // NOTE: This function has rare sporadic failures (throws exceptions) on FreeBSD. See REVIEW:54297 const TString& GetExecPath(); diff --git a/util/system/execpath_ut.cpp b/util/system/execpath_ut.cpp index ebccec6791..16b01466f5 100644 --- a/util/system/execpath_ut.cpp +++ b/util/system/execpath_ut.cpp @@ -3,8 +3,8 @@ #include <library/cpp/testing/unittest/registar.h> #include "platform.h" -#include <util/folder/dirut.h> - +#include <util/folder/dirut.h> + Y_UNIT_TEST_SUITE(TExecPathTest) { Y_UNIT_TEST(TestIt) { TString execPath = GetExecPath(); @@ -18,5 +18,5 @@ Y_UNIT_TEST_SUITE(TExecPathTest) { throw; } - } -} + } +} diff --git a/util/system/fasttime.cpp b/util/system/fasttime.cpp index 3a32bd4019..057a814f0a 100644 --- a/util/system/fasttime.cpp +++ b/util/system/fasttime.cpp @@ -5,7 +5,7 @@ #include <util/generic/yexception.h> #include <utility> -#include <util/thread/singleton.h> +#include <util/thread/singleton.h> #if defined(_win_) || defined(_arm32_) || defined(_cygwin_) ui64 InterpolatedMicroSeconds() { @@ -236,7 +236,7 @@ namespace { } ui64 InterpolatedMicroSeconds() { - return FastTlsSingleton<TTimePredictor>()->Get(); + return FastTlsSingleton<TTimePredictor>()->Get(); } #endif diff --git a/util/system/file.cpp b/util/system/file.cpp index 5fd4ae8d2f..4a261d020c 100644 --- a/util/system/file.cpp +++ b/util/system/file.cpp @@ -22,7 +22,7 @@ #include <util/generic/yexception.h> #include <util/datetime/base.h> - + #include <errno.h> #if defined(_unix_) @@ -140,7 +140,7 @@ TFileHandle::TFileHandle(const TString& fName, EOpenMode oMode) noexcept { ::SetFilePointer(Fd_, 0, 0, FILE_END); } -#elif defined(_unix_) +#elif defined(_unix_) switch (createMode) { case OpenExisting: @@ -262,7 +262,7 @@ TFileHandle::TFileHandle(const TString& fName, EOpenMode oMode) noexcept { if (Fd_ >= 0 && (oMode & Transient)) { unlink(fName.data()); } -#else +#else #error unsupported platform #endif } @@ -277,9 +277,9 @@ bool TFileHandle::Close() noexcept { Y_VERIFY(GetLastError() != ERROR_INVALID_HANDLE, "must not quietly close invalid handle"); } -#elif defined(_unix_) +#elif defined(_unix_) if (Fd_ != INVALID_FHANDLE) { - isOk = (::close(Fd_) == 0 || errno == EINTR); + isOk = (::close(Fd_) == 0 || errno == EINTR); } if (!isOk) { // Do not quietly close bad descriptor, @@ -307,7 +307,7 @@ static inline i64 DoSeek(FHANDLE h, i64 offset, SeekDir origin) noexcept { pos.QuadPart = -1; } return pos.QuadPart; -#elif defined(_unix_) +#elif defined(_unix_) static int dir[] = {SEEK_SET, SEEK_CUR, SEEK_END}; #if defined(_sun_) return ::llseek(h, (offset_t)offset, dir[origin]); @@ -328,9 +328,9 @@ i64 TFileHandle::Seek(i64 offset, SeekDir origin) noexcept { } i64 TFileHandle::GetLength() const noexcept { - // XXX: returns error code, but does not set errno + // XXX: returns error code, but does not set errno if (!IsOpen()) { - return -1L; + return -1L; } return GetFileLength(Fd_); } @@ -424,7 +424,7 @@ bool TFileHandle::Flush() noexcept { * The function returns FALSE, and GetLastError returns ERROR_INVALID_HANDLE. */ return ok || GetLastError() == ERROR_INVALID_HANDLE; -#elif defined(_unix_) +#elif defined(_unix_) int ret = ::fsync(Fd_); /* @@ -469,13 +469,13 @@ i32 TFileHandle::Read(void* buffer, ui32 byteCount) noexcept { return bytesRead; } return -1; -#elif defined(_unix_) +#elif defined(_unix_) i32 ret; do { ret = ::read(Fd_, buffer, byteCount); } while (ret == -1 && errno == EINTR); return ret; -#else +#else #error unsupported platform #endif } @@ -490,13 +490,13 @@ i32 TFileHandle::Write(const void* buffer, ui32 byteCount) noexcept { return bytesWritten; } return -1; -#elif defined(_unix_) +#elif defined(_unix_) i32 ret; do { ret = ::write(Fd_, buffer, byteCount); } while (ret == -1 && errno == EINTR); return ret; -#else +#else #error unsupported platform #endif } @@ -515,13 +515,13 @@ i32 TFileHandle::Pread(void* buffer, ui32 byteCount, i64 offset) const noexcept return 0; } return -1; -#elif defined(_unix_) +#elif defined(_unix_) i32 ret; do { ret = ::pread(Fd_, buffer, byteCount, offset); } while (ret == -1 && errno == EINTR); return ret; -#else +#else #error unsupported platform #endif } @@ -537,13 +537,13 @@ i32 TFileHandle::Pwrite(const void* buffer, ui32 byteCount, i64 offset) const no return bytesWritten; } return -1; -#elif defined(_unix_) +#elif defined(_unix_) i32 ret; do { ret = ::pwrite(Fd_, buffer, byteCount, offset); } while (ret == -1 && errno == EINTR); return ret; -#else +#else #error unsupported platform #endif } @@ -558,9 +558,9 @@ FHANDLE TFileHandle::Duplicate() const noexcept { return INVALID_FHANDLE; } return dupHandle; -#elif defined(_unix_) +#elif defined(_unix_) return ::dup(Fd_); -#else +#else #error unsupported platform #endif } @@ -776,10 +776,10 @@ bool TFileHandle::FlushCache(i64 offset, i64 length, bool wait) noexcept { } TString DecodeOpenMode(ui32 mode0) { - ui32 mode = mode0; - + ui32 mode = mode0; + TStringBuilder r; - + #define F(flag) \ if ((mode & flag) == flag) { \ mode &= ~flag; \ @@ -787,14 +787,14 @@ TString DecodeOpenMode(ui32 mode0) { r << TStringBuf("|"); \ } \ r << TStringBuf(#flag); \ - } - - F(RdWr) + } + + F(RdWr) F(RdOnly) F(WrOnly) F(CreateAlways) - F(CreateNew) + F(CreateNew) F(OpenAlways) F(TruncExisting) F(ForAppend) @@ -809,38 +809,38 @@ TString DecodeOpenMode(ui32 mode0) { F(NoReuse) F(NoReadAhead) - F(AX) - F(AR) - F(AW) - F(ARW) - - F(AXOther) - F(AWOther) - F(AROther) - F(AXGroup) - F(AWGroup) - F(ARGroup) - F(AXUser) - F(AWUser) - F(ARUser) - -#undef F - - if (mode != 0) { + F(AX) + F(AR) + F(AW) + F(ARW) + + F(AXOther) + F(AWOther) + F(AROther) + F(AXGroup) + F(AWGroup) + F(ARGroup) + F(AXUser) + F(AWUser) + F(ARUser) + +#undef F + + if (mode != 0) { if (r) { r << TStringBuf("|"); } r << Hex(mode); - } - + } + if (!r) { return "0"; } - - return r; + + return r; } - + class TFile::TImpl: public TAtomicRefCount<TImpl> { public: inline TImpl(FHANDLE fd, const TString& fname = TString()) @@ -1277,7 +1277,7 @@ TFile Duplicate(int fd) { return TFile(dupHandle); #elif defined(_unix_) - return TFile(::dup(fd)); + return TFile(::dup(fd)); #else #error unsupported platform #endif diff --git a/util/system/file.h b/util/system/file.h index 27f711aff6..9502e159b6 100644 --- a/util/system/file.h +++ b/util/system/file.h @@ -53,7 +53,7 @@ Y_DECLARE_FLAGS(EOpenMode, EOpenModeFlag) Y_DECLARE_OPERATORS_FOR_FLAGS(EOpenMode) TString DecodeOpenMode(ui32 openMode); - + enum SeekDir { sSet = 0, sCur = 1, @@ -64,7 +64,7 @@ class TFileHandle: public TNonCopyable { public: constexpr TFileHandle() = default; - /// Warning: takes ownership of fd, so closes it in destructor. + /// Warning: takes ownership of fd, so closes it in destructor. inline TFileHandle(FHANDLE fd) noexcept : Fd_(fd) { @@ -147,7 +147,7 @@ private: class TFile { public: TFile(); - /// Takes ownership of handle, so closes it when the last holder of descriptor dies. + /// Takes ownership of handle, so closes it when the last holder of descriptor dies. explicit TFile(FHANDLE fd); TFile(FHANDLE fd, const TString& fname); TFile(const TString& fName, EOpenMode oMode); diff --git a/util/system/file_ut.cpp b/util/system/file_ut.cpp index bb97a6e5d4..941e6a50f3 100644 --- a/util/system/file_ut.cpp +++ b/util/system/file_ut.cpp @@ -408,9 +408,9 @@ UNIT_ASSERT_VALUES_EQUAL(file.CountCache(0, 12345), -1); Y_UNIT_TEST_SUITE(TTestDecodeOpenMode) { Y_UNIT_TEST(It) { UNIT_ASSERT_VALUES_EQUAL("0", DecodeOpenMode(0)); - UNIT_ASSERT_VALUES_EQUAL("RdOnly", DecodeOpenMode(RdOnly)); - UNIT_ASSERT_VALUES_EQUAL("RdWr", DecodeOpenMode(RdWr)); - UNIT_ASSERT_VALUES_EQUAL("WrOnly|ForAppend", DecodeOpenMode(WrOnly | ForAppend)); + UNIT_ASSERT_VALUES_EQUAL("RdOnly", DecodeOpenMode(RdOnly)); + UNIT_ASSERT_VALUES_EQUAL("RdWr", DecodeOpenMode(RdWr)); + UNIT_ASSERT_VALUES_EQUAL("WrOnly|ForAppend", DecodeOpenMode(WrOnly | ForAppend)); UNIT_ASSERT_VALUES_EQUAL("RdWr|CreateAlways|CreateNew|ForAppend|Transient|CloseOnExec|Temp|Sync|Direct|DirectAligned|Seq|NoReuse|NoReadAhead|AX|AR|AW|AWOther|0xF8888000", DecodeOpenMode(0xFFFFFFFF)); - } -} + } +} diff --git a/util/system/filemap.cpp b/util/system/filemap.cpp index 992acdf724..7454a4cb94 100644 --- a/util/system/filemap.cpp +++ b/util/system/filemap.cpp @@ -2,7 +2,7 @@ #include "madvise.h" #include "defaults.h" #include "hi_lo.h" - + #include <util/generic/buffer.h> #include <util/generic/yexception.h> #include <util/generic/singleton.h> diff --git a/util/system/info.cpp b/util/system/info.cpp index 9175c664b3..cf6681e89a 100644 --- a/util/system/info.cpp +++ b/util/system/info.cpp @@ -12,7 +12,7 @@ #if defined(_win_) #include "winint.h" #include <stdio.h> -#else +#else #include <unistd.h> #endif @@ -175,17 +175,17 @@ size_t NSystemInfo::CachedNumberOfCpus() { return NCpus; } - + size_t NSystemInfo::GetPageSize() noexcept { #if defined(_win_) SYSTEM_INFO sysInfo; GetSystemInfo(&sysInfo); - + return sysInfo.dwPageSize; #else return sysconf(_SC_PAGESIZE); #endif -} +} size_t NSystemInfo::TotalMemorySize() { #if defined(_linux_) && defined(_64_) diff --git a/util/system/info_ut.cpp b/util/system/info_ut.cpp index 6923c63005..ad7449f8f4 100644 --- a/util/system/info_ut.cpp +++ b/util/system/info_ut.cpp @@ -7,7 +7,7 @@ class TSysInfoTest: public TTestBase { UNIT_TEST(TestNumberOfCpus) UNIT_TEST(TestGetPageSize) UNIT_TEST_SUITE_END(); - + private: inline void TestNumberOfCpus() { UNIT_ASSERT(NSystemInfo::NumberOfCpus() > 0); diff --git a/util/system/pipe.cpp b/util/system/pipe.cpp index f1d80a363b..a543bd7472 100644 --- a/util/system/pipe.cpp +++ b/util/system/pipe.cpp @@ -2,36 +2,36 @@ #include <util/stream/output.h> #include <util/generic/yexception.h> - + ssize_t TPipeHandle::Read(void* buffer, size_t byteCount) const noexcept { -#ifdef _win_ +#ifdef _win_ return recv(Fd_, (char*)buffer, byteCount, 0); -#else +#else return read(Fd_, buffer, byteCount); -#endif -} - +#endif +} + ssize_t TPipeHandle::Write(const void* buffer, size_t byteCount) const noexcept { -#ifdef _win_ +#ifdef _win_ return send(Fd_, (const char*)buffer, byteCount, 0); -#else +#else return write(Fd_, buffer, byteCount); -#endif -} - +#endif +} + bool TPipeHandle::Close() noexcept { - bool ok = true; + bool ok = true; if (Fd_ != INVALID_PIPEHANDLE) { -#ifdef _win_ +#ifdef _win_ ok = closesocket(Fd_) == 0; -#else +#else ok = close(Fd_) == 0; -#endif - } +#endif + } Fd_ = INVALID_PIPEHANDLE; - return ok; -} - + return ok; +} + void TPipeHandle::Pipe(TPipeHandle& reader, TPipeHandle& writer, EOpenMode mode) { PIPEHANDLE fds[2]; #ifdef _win_ @@ -66,90 +66,90 @@ void TPipeHandle::Pipe(TPipeHandle& reader, TPipeHandle& writer, EOpenMode mode) } class TPipe::TImpl: public TAtomicRefCount<TImpl> { -public: - TImpl() +public: + TImpl() : Handle_(INVALID_PIPEHANDLE) - { - } + { + } - TImpl(PIPEHANDLE fd) + TImpl(PIPEHANDLE fd) : Handle_(fd) - { - } - - inline ~TImpl() { - Close(); - } - - bool IsOpen() { + { + } + + inline ~TImpl() { + Close(); + } + + bool IsOpen() { return Handle_.IsOpen(); - } - - inline void Close() { + } + + inline void Close() { if (!Handle_.IsOpen()) { - return; + return; } if (!Handle_.Close()) { ythrow TFileError() << "failed to close pipe"; } - } - + } + TPipeHandle& GetHandle() noexcept { return Handle_; - } - + } + size_t Read(void* buffer, size_t count) const { ssize_t r = Handle_.Read(buffer, count); if (r < 0) { ythrow TFileError() << "failed to read from pipe"; } - return r; - } - + return r; + } + size_t Write(const void* buffer, size_t count) const { ssize_t r = Handle_.Write(buffer, count); if (r < 0) { ythrow TFileError() << "failed to write to pipe"; } - return r; - } + return r; + } -private: +private: TPipeHandle Handle_; -}; - -TPipe::TPipe() +}; + +TPipe::TPipe() : Impl_(new TImpl) -{ -} - -TPipe::TPipe(PIPEHANDLE fd) +{ +} + +TPipe::TPipe(PIPEHANDLE fd) : Impl_(new TImpl(fd)) -{ -} - +{ +} + TPipe::~TPipe() = default; - -void TPipe::Close() { + +void TPipe::Close() { Impl_->Close(); -} - +} + PIPEHANDLE TPipe::GetHandle() const noexcept { return Impl_->GetHandle(); -} - +} + bool TPipe::IsOpen() const noexcept { return Impl_->IsOpen(); -} - +} + size_t TPipe::Read(void* buf, size_t len) const { return Impl_->Read(buf, len); -} - +} + size_t TPipe::Write(const void* buf, size_t len) const { return Impl_->Write(buf, len); -} - +} + void TPipe::Pipe(TPipe& reader, TPipe& writer, EOpenMode mode) { TImplRef r(new TImpl()); TImplRef w(new TImpl()); @@ -158,4 +158,4 @@ void TPipe::Pipe(TPipe& reader, TPipe& writer, EOpenMode mode) { r.Swap(reader.Impl_); w.Swap(writer.Impl_); -} +} diff --git a/util/system/pipe.h b/util/system/pipe.h index b8cd9bd2ac..75d0360049 100644 --- a/util/system/pipe.h +++ b/util/system/pipe.h @@ -4,19 +4,19 @@ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Warray-bounds" //need because of bug in gcc4.9.2 #endif - + #include "defaults.h" #include "file.h" -#include <util/generic/ptr.h> +#include <util/generic/ptr.h> #include <util/network/pair.h> #include <util/generic/noncopyable.h> - + using PIPEHANDLE = SOCKET; #define INVALID_PIPEHANDLE INVALID_SOCKET -/// Pipe-like object: pipe on POSIX and socket on windows +/// Pipe-like object: pipe on POSIX and socket on windows class TPipeHandle: public TNonCopyable { -public: +public: inline TPipeHandle() noexcept : Fd_(INVALID_PIPEHANDLE) { @@ -24,66 +24,66 @@ public: inline TPipeHandle(PIPEHANDLE fd) noexcept : Fd_(fd) - { - } - + { + } + inline ~TPipeHandle() { - Close(); - } - + Close(); + } + bool Close() noexcept; - + inline PIPEHANDLE Release() noexcept { PIPEHANDLE ret = Fd_; Fd_ = INVALID_PIPEHANDLE; - return ret; - } - + return ret; + } + inline void Swap(TPipeHandle& r) noexcept { DoSwap(Fd_, r.Fd_); - } - + } + inline operator PIPEHANDLE() const noexcept { return Fd_; - } - + } + inline bool IsOpen() const noexcept { return Fd_ != INVALID_PIPEHANDLE; - } - + } + ssize_t Read(void* buffer, size_t byteCount) const noexcept; ssize_t Write(const void* buffer, size_t byteCount) const noexcept; - + // Only CloseOnExec is supported static void Pipe(TPipeHandle& reader, TPipeHandle& writer, EOpenMode mode = 0); -private: +private: PIPEHANDLE Fd_; -}; - -class TPipe { -public: - TPipe(); - /// Takes ownership of handle, so closes it when the last holder of descriptor dies. - explicit TPipe(PIPEHANDLE fd); +}; + +class TPipe { +public: + TPipe(); + /// Takes ownership of handle, so closes it when the last holder of descriptor dies. + explicit TPipe(PIPEHANDLE fd); ~TPipe(); - - void Close(); - + + void Close(); + bool IsOpen() const noexcept; PIPEHANDLE GetHandle() const noexcept; - + size_t Read(void* buf, size_t len) const; size_t Write(const void* buf, size_t len) const; - + // Only CloseOnExec is supported static void Pipe(TPipe& reader, TPipe& writer, EOpenMode mode = 0); - -private: - class TImpl; + +private: + class TImpl; using TImplRef = TSimpleIntrusivePtr<TImpl>; TImplRef Impl_; -}; +}; #ifdef __GNUC__ #pragma GCC diagnostic pop diff --git a/util/system/pipe_ut.cpp b/util/system/pipe_ut.cpp index 67cc0eb5f0..6d53432de8 100644 --- a/util/system/pipe_ut.cpp +++ b/util/system/pipe_ut.cpp @@ -1,15 +1,15 @@ #include "pipe.h" #include <library/cpp/testing/unittest/registar.h> - + Y_UNIT_TEST_SUITE(TPipeTest) { Y_UNIT_TEST(TestPipe) { - TPipe r; - TPipe w; - TPipe::Pipe(r, w); - char c = 'a'; - UNIT_ASSERT(1 == w.Write(&c, 1)); - UNIT_ASSERT(1 == r.Read(&c, 1)); - UNIT_ASSERT_VALUES_EQUAL('a', c); - } -} + TPipe r; + TPipe w; + TPipe::Pipe(r, w); + char c = 'a'; + UNIT_ASSERT(1 == w.Write(&c, 1)); + UNIT_ASSERT(1 == r.Read(&c, 1)); + UNIT_ASSERT_VALUES_EQUAL('a', c); + } +} diff --git a/util/system/rusage.cpp b/util/system/rusage.cpp index 918169ebdf..2befeca875 100644 --- a/util/system/rusage.cpp +++ b/util/system/rusage.cpp @@ -1,40 +1,40 @@ #include "platform.h" - + #if defined(__APPLE__) && defined(__MACH__) #include <mach/mach.h> #endif -#ifdef _win_ - +#ifdef _win_ + #include "winint.h" #include <psapi.h> - -#else - + +#else + #include <sys/time.h> #include <sys/resource.h> - -#endif - -#include <util/generic/yexception.h> - -#include "info.h" - -#include "rusage.h" - -#ifdef _win_ -TDuration FiletimeToDuration(const FILETIME& ft) { + +#endif + +#include <util/generic/yexception.h> + +#include "info.h" + +#include "rusage.h" + +#ifdef _win_ +TDuration FiletimeToDuration(const FILETIME& ft) { union { ui64 ft_scalar; FILETIME ft_struct; } nt_time; - nt_time.ft_struct = ft; - return TDuration::MicroSeconds(nt_time.ft_scalar / 10); -} -#endif - + nt_time.ft_struct = ft; + return TDuration::MicroSeconds(nt_time.ft_scalar / 10); +} +#endif + size_t TRusage::GetCurrentRSS() { /* * Author: David Robert Nadeau @@ -74,40 +74,40 @@ size_t TRusage::GetCurrentRSS() { #endif } -void TRusage::Fill() { - *this = TRusage(); - -#ifdef _win_ - // copy-paste from PostgreSQL getrusage.c - - FILETIME starttime; - FILETIME exittime; - FILETIME kerneltime; - FILETIME usertime; - - if (GetProcessTimes(GetCurrentProcess(), &starttime, &exittime, &kerneltime, &usertime) == 0) { - ythrow TSystemError() << "GetProcessTimes failed"; - } - - Utime = FiletimeToDuration(usertime); - Stime = FiletimeToDuration(kerneltime); - - PROCESS_MEMORY_COUNTERS pmc; - - if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)) == 0) { - ythrow TSystemError() << "GetProcessMemoryInfo failed"; - } - +void TRusage::Fill() { + *this = TRusage(); + +#ifdef _win_ + // copy-paste from PostgreSQL getrusage.c + + FILETIME starttime; + FILETIME exittime; + FILETIME kerneltime; + FILETIME usertime; + + if (GetProcessTimes(GetCurrentProcess(), &starttime, &exittime, &kerneltime, &usertime) == 0) { + ythrow TSystemError() << "GetProcessTimes failed"; + } + + Utime = FiletimeToDuration(usertime); + Stime = FiletimeToDuration(kerneltime); + + PROCESS_MEMORY_COUNTERS pmc; + + if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)) == 0) { + ythrow TSystemError() << "GetProcessMemoryInfo failed"; + } + MaxRss = pmc.PeakWorkingSetSize; MajorPageFaults = pmc.PageFaultCount; - -#else - struct rusage ru; - int r = getrusage(RUSAGE_SELF, &ru); - if (r < 0) { - ythrow TSystemError() << "rusage failed"; - } - + +#else + struct rusage ru; + int r = getrusage(RUSAGE_SELF, &ru); + if (r < 0) { + ythrow TSystemError() << "rusage failed"; + } + #if defined(_darwin_) // see https://lists.apple.com/archives/darwin-kernel/2009/Mar/msg00005.html MaxRss = ru.ru_maxrss; @@ -115,7 +115,7 @@ void TRusage::Fill() { MaxRss = ru.ru_maxrss * 1024LL; #endif MajorPageFaults = ru.ru_majflt; - Utime = ru.ru_utime; - Stime = ru.ru_stime; -#endif -} + Utime = ru.ru_utime; + Stime = ru.ru_stime; +#endif +} diff --git a/util/system/rusage.h b/util/system/rusage.h index 3964df1116..61aeca83f2 100644 --- a/util/system/rusage.h +++ b/util/system/rusage.h @@ -1,26 +1,26 @@ #pragma once - + #include "defaults.h" -#include <util/generic/utility.h> -#include <util/datetime/base.h> - -/// portable getrusage - -struct TRusage { - // some fields may be zero if unsupported - +#include <util/generic/utility.h> +#include <util/datetime/base.h> + +/// portable getrusage + +struct TRusage { + // some fields may be zero if unsupported + ui64 MaxRss = 0; ui64 MajorPageFaults = 0; - TDuration Utime; - TDuration Stime; - - void Fill(); + TDuration Utime; + TDuration Stime; + + void Fill(); static size_t GetCurrentRSS(); - static TRusage Get() { - TRusage r; - r.Fill(); - return r; - } -}; + static TRusage Get() { + TRusage r; + r.Fill(); + return r; + } +}; diff --git a/util/system/rusage_ut.cpp b/util/system/rusage_ut.cpp index a5c6a80e62..0d4e0fe54b 100644 --- a/util/system/rusage_ut.cpp +++ b/util/system/rusage_ut.cpp @@ -1,11 +1,11 @@ #include "rusage.h" #include <library/cpp/testing/unittest/registar.h> - + Y_UNIT_TEST_SUITE(TRusageTest) { Y_UNIT_TEST(TestRusage) { - TRusage r; - // just check it returns something - r.Fill(); - } -} + TRusage r; + // just check it returns something + r.Fill(); + } +} diff --git a/util/system/spin_wait.h b/util/system/spin_wait.h index e52f413e6d..91dd423e33 100644 --- a/util/system/spin_wait.h +++ b/util/system/spin_wait.h @@ -4,7 +4,7 @@ struct TSpinWait { TSpinWait() noexcept; void Sleep() noexcept; - + unsigned T; unsigned C; -}; +}; diff --git a/util/system/spinlock.h b/util/system/spinlock.h index 9d1480130b..af2630890a 100644 --- a/util/system/spinlock.h +++ b/util/system/spinlock.h @@ -3,29 +3,29 @@ #include "atomic.h" #include "spin_wait.h" -class TSpinLockBase { +class TSpinLockBase { protected: inline TSpinLockBase() noexcept { AtomicSet(Val_, 0); } - + public: inline bool IsLocked() const noexcept { return AtomicGet(Val_); } - + inline bool TryAcquire() noexcept { return AtomicTryLock(&Val_); } - + inline bool try_lock() noexcept { return TryAcquire(); } protected: TAtomic Val_; -}; - +}; + static inline void SpinLockPause() { #if defined(__GNUC__) #if defined(_i386_) || defined(_x86_64_) diff --git a/util/system/spinlock_ut.cpp b/util/system/spinlock_ut.cpp index f2793fd95f..e8639a6404 100644 --- a/util/system/spinlock_ut.cpp +++ b/util/system/spinlock_ut.cpp @@ -1,23 +1,23 @@ #include <library/cpp/testing/unittest/registar.h> - -#include "spinlock.h" - + +#include "spinlock.h" + Y_UNIT_TEST_SUITE(TSpinLock) { - template <typename TLock> - void TestLock() { - TLock lock; - UNIT_ASSERT(!lock.IsLocked()); - lock.Acquire(); - UNIT_ASSERT(lock.IsLocked()); - lock.Release(); - UNIT_ASSERT(!lock.IsLocked()); - - UNIT_ASSERT(lock.TryAcquire()); - UNIT_ASSERT(lock.IsLocked()); - UNIT_ASSERT(!lock.TryAcquire()); - UNIT_ASSERT(lock.IsLocked()); - lock.Release(); - UNIT_ASSERT(!lock.IsLocked()); + template <typename TLock> + void TestLock() { + TLock lock; + UNIT_ASSERT(!lock.IsLocked()); + lock.Acquire(); + UNIT_ASSERT(lock.IsLocked()); + lock.Release(); + UNIT_ASSERT(!lock.IsLocked()); + + UNIT_ASSERT(lock.TryAcquire()); + UNIT_ASSERT(lock.IsLocked()); + UNIT_ASSERT(!lock.TryAcquire()); + UNIT_ASSERT(lock.IsLocked()); + lock.Release(); + UNIT_ASSERT(!lock.IsLocked()); // Lockable requirements lock.lock(); @@ -25,13 +25,13 @@ Y_UNIT_TEST_SUITE(TSpinLock) { UNIT_ASSERT(!lock.try_lock()); lock.unlock(); UNIT_ASSERT(!lock.IsLocked()); - } - + } + Y_UNIT_TEST(TSpinLock_IsLocked) { - TestLock<TSpinLock>(); - } - + TestLock<TSpinLock>(); + } + Y_UNIT_TEST(TAdaptiveLock_IsLocked) { - TestLock<TAdaptiveLock>(); - } -} + TestLock<TAdaptiveLock>(); + } +} diff --git a/util/system/thread.cpp b/util/system/thread.cpp index 0aad030bcf..6236746c2d 100644 --- a/util/system/thread.cpp +++ b/util/system/thread.cpp @@ -5,7 +5,7 @@ #include <util/generic/ptr.h> #include <util/generic/ymath.h> #include <util/generic/ylimits.h> -#include <util/generic/yexception.h> +#include <util/generic/yexception.h> #include "yassert.h" #include <utility> @@ -289,7 +289,7 @@ TThread::~TThread() { Join(); } -void TThread::Start() { +void TThread::Start() { Impl(Impl_, "start", false)->Start(); } diff --git a/util/system/thread.h b/util/system/thread.h index 541ecccbef..a6e8abdb5b 100644 --- a/util/system/thread.h +++ b/util/system/thread.h @@ -1,9 +1,9 @@ #pragma once -/// This code should not be used directly unless you really understand what you do. +/// This code should not be used directly unless you really understand what you do. /// If you need threads, use thread pool functionality in <util/thread/factory.h> /// @see SystemThreadFactory() - + #include <util/generic/ptr.h> #include <util/generic/string.h> diff --git a/util/system/type_name.cpp b/util/system/type_name.cpp index 411b98774c..0377da4212 100644 --- a/util/system/type_name.cpp +++ b/util/system/type_name.cpp @@ -1,13 +1,13 @@ #include "platform.h" #include "demangle_impl.h" - + #ifdef __GNUC__ #include <stdexcept> #include <cxxabi.h> -#endif - +#endif + #include "type_name.h" - + namespace { #if defined(_LIBCPP_VERSION) @@ -26,18 +26,18 @@ namespace { const char* NPrivate::TCppDemangler::Demangle(const char* name) { #ifndef __GNUC__ - return name; -#else - int status; + return name; +#else + int status; TmpBuf_.Reset(__cxxabiv1::__cxa_demangle(name, nullptr, nullptr, &status)); if (!TmpBuf_) { - return name; + return name; } return TmpBuf_.Get(); -#endif -} +#endif +} TString CppDemangle(const TString& name) { return NPrivate::TCppDemangler().Demangle(name.data()); diff --git a/util/system/type_name.h b/util/system/type_name.h index 6561519bc1..b6619aba3f 100644 --- a/util/system/type_name.h +++ b/util/system/type_name.h @@ -1,8 +1,8 @@ #pragma once - + #include <util/generic/string.h> #include <util/string/subst.h> - + #include <typeindex> #include <typeinfo> diff --git a/util/system/type_name_ut.cpp b/util/system/type_name_ut.cpp index 7af6838814..86597f4232 100644 --- a/util/system/type_name_ut.cpp +++ b/util/system/type_name_ut.cpp @@ -1,7 +1,7 @@ #include "type_name.h" #include <library/cpp/testing/unittest/registar.h> - + #include <util/generic/yexception.h> #include <util/generic/fwd.h> @@ -10,12 +10,12 @@ Y_UNIT_TEST_SUITE(TDemangleTest) { Y_UNIT_TEST(SimpleTest) { - // just check it does not crash or leak - CppDemangle("hello"); - CppDemangle(""); - CppDemangle("Sfsdf$dfsdfTTSFSDF23234::SDFS:FSDFSDF#$%"); - } -} + // just check it does not crash or leak + CppDemangle("hello"); + CppDemangle(""); + CppDemangle("Sfsdf$dfsdfTTSFSDF23234::SDFS:FSDFSDF#$%"); + } +} namespace NUtil::NTypeNameTest { diff --git a/util/system/yassert.cpp b/util/system/yassert.cpp index d356f11300..0f586648b7 100644 --- a/util/system/yassert.cpp +++ b/util/system/yassert.cpp @@ -12,7 +12,7 @@ #include <util/stream/output.h> #include <util/stream/str.h> #include <util/string/printf.h> - + #include <cstdlib> #include <stdarg.h> #include <stdio.h> @@ -37,20 +37,20 @@ namespace { namespace NPrivate { [[noreturn]] Y_NO_INLINE void InternalPanicImpl(int line, const char* function, const char* expr, int, int, int, const TStringBuf file, const char* errorMessage, size_t errorMessageSize) noexcept; } - + void ::NPrivate::Panic(const TStaticBuf& file, int line, const char* function, const char* expr, const char* format, ...) noexcept { try { // We care of panic of first failed thread only // Otherwise stderr could contain multiple messages and stack traces shuffled auto guard = Guard(*Singleton<TPanicLockHolder>()); - + TString errorMsg; va_list args; va_start(args, format); - // format has " " prefix to mute GCC warning on empty format - vsprintf(errorMsg, format[0] == ' ' ? format + 1 : format, args); + // format has " " prefix to mute GCC warning on empty format + vsprintf(errorMsg, format[0] == ' ' ? format + 1 : format, args); va_end(args); - + constexpr int abiPlaceholder = 0; ::NPrivate::InternalPanicImpl(line, function, expr, abiPlaceholder, abiPlaceholder, abiPlaceholder, file.As<TStringBuf>(), errorMsg.c_str(), errorMsg.size()); } catch (...) { @@ -69,19 +69,19 @@ namespace NPrivate { TStringOutput o(r); if (expr) { o << "VERIFY failed (" << now << "): " << errorMsg << Endl; - } else { + } else { o << "FAIL (" << now << "): " << errorMsg << Endl; - } + } o << " " << file << ":" << line << Endl; if (expr) { - o << " " << function << "(): requirement " << expr << " failed" << Endl; - } else { - o << " " << function << "() failed" << Endl; - } + o << " " << function << "(): requirement " << expr << " failed" << Endl; + } else { + o << " " << function << "() failed" << Endl; + } Cerr << r << Flush; -#ifndef WITH_VALGRIND +#ifndef WITH_VALGRIND PrintBackTrace(); -#endif +#endif #ifdef CLANG_COVERAGE if (__llvm_profile_write_file()) { Cerr << "Failed to dump clang coverage" << Endl; @@ -91,4 +91,4 @@ namespace NPrivate { } catch (...) { abort(); } -} +} diff --git a/util/system/yassert.h b/util/system/yassert.h index a94b47d3f4..529823440c 100644 --- a/util/system/yassert.h +++ b/util/system/yassert.h @@ -3,7 +3,7 @@ #include "defaults.h" #include "src_root.h" #include "backtrace.h" - + #if defined(_MSC_VER) #include <new> #if defined(_DEBUG) @@ -89,12 +89,12 @@ inline void YaDebugBreak() { } while (false) #endif -namespace NPrivate { - /// method should not be used directly +namespace NPrivate { + /// method should not be used directly [[noreturn]] void Panic(const TStaticBuf& file, int line, const char* function, const char* expr, const char* format, ...) noexcept Y_PRINTF_FORMAT(5, 6); -} - -/// Assert that does not depend on NDEBUG macro and outputs message like printf +} + +/// Assert that does not depend on NDEBUG macro and outputs message like printf #define Y_VERIFY(expr, ...) \ do { \ if (Y_UNLIKELY(!(expr))) { \ @@ -106,7 +106,7 @@ namespace NPrivate { do { \ ::NPrivate::Panic(__SOURCE_FILE_IMPL__, __LINE__, __FUNCTION__, nullptr, " " __VA_ARGS__); \ } while (false) - + #ifndef NDEBUG /// Assert that depend on NDEBUG macro and outputs message like printf #define Y_VERIFY_DEBUG(expr, ...) \ diff --git a/util/system/yassert_ut.cpp b/util/system/yassert_ut.cpp index c3f8cce999..ddd392666c 100644 --- a/util/system/yassert_ut.cpp +++ b/util/system/yassert_ut.cpp @@ -1,9 +1,9 @@ -#undef NDEBUG -// yassert.h must be included before all headers -#include "yassert.h" - +#undef NDEBUG +// yassert.h must be included before all headers +#include "yassert.h" + #include <library/cpp/testing/unittest/registar.h> - + Y_UNIT_TEST_SUITE(YassertTest) { Y_UNIT_TEST(TestAcsLikeFunctionCall) { if (true) { @@ -11,25 +11,25 @@ Y_UNIT_TEST_SUITE(YassertTest) { } else { Y_ASSERT(false); } - - bool var = false; + + bool var = false; if (false) { Y_ASSERT(false); } else { var = true; // this is unreachable if Y_ASSERT is "if (!cond) { ... }" } - UNIT_ASSERT(var); - } - + UNIT_ASSERT(var); + } + Y_UNIT_TEST(TestFailCompiles) { - if (false) { + if (false) { Y_FAIL("%d is a lucky number", 7); Y_FAIL(); - } - } - + } + } + Y_UNIT_TEST(TestVerify) { Y_VERIFY(true, "hi %s", "there"); Y_VERIFY(true); - } -} + } +} diff --git a/util/thread/lfqueue.h b/util/thread/lfqueue.h index 2bd4416737..ab523631e4 100644 --- a/util/thread/lfqueue.h +++ b/util/thread/lfqueue.h @@ -173,27 +173,27 @@ class TLockFreeQueue: public TNonCopyable { void EnqueueImpl(TListNode* head, TListNode* tail) { TRootNode* newRoot = new TRootNode; - AsyncRef(); + AsyncRef(); AtomicSet(newRoot->PushQueue, head); - for (;;) { + for (;;) { TRootNode* curRoot = AtomicGet(JobQueue); AtomicSet(tail->Next, AtomicGet(curRoot->PushQueue)); AtomicSet(newRoot->PopQueue, AtomicGet(curRoot->PopQueue)); - newRoot->CopyCounter(curRoot); - + newRoot->CopyCounter(curRoot); + for (TListNode* node = head;; node = AtomicGet(node->Next)) { - newRoot->IncCount(node->Data); - if (node == tail) - break; - } - - if (AtomicCas(&JobQueue, newRoot, curRoot)) { + newRoot->IncCount(node->Data); + if (node == tail) + break; + } + + if (AtomicCas(&JobQueue, newRoot, curRoot)) { AsyncUnref(curRoot, nullptr); - break; - } - } - } - + break; + } + } + } + template <typename TCollection> static void FillCollection(TListNode* lst, TCollection* res) { while (lst) { @@ -242,8 +242,8 @@ public: template <typename U> void Enqueue(U&& data) { TListNode* newNode = new TListNode(std::forward<U>(data)); - EnqueueImpl(newNode, newNode); - } + EnqueueImpl(newNode, newNode); + } void Enqueue(T&& data) { TListNode* newNode = new TListNode(std::move(data)); EnqueueImpl(newNode, newNode); @@ -252,24 +252,24 @@ public: TListNode* newNode = new TListNode(data); EnqueueImpl(newNode, newNode); } - template <typename TCollection> + template <typename TCollection> void EnqueueAll(const TCollection& data) { - EnqueueAll(data.begin(), data.end()); - } - template <typename TIter> + EnqueueAll(data.begin(), data.end()); + } + template <typename TIter> void EnqueueAll(TIter dataBegin, TIter dataEnd) { - if (dataBegin == dataEnd) - return; - - TIter i = dataBegin; + if (dataBegin == dataEnd) + return; + + TIter i = dataBegin; TListNode* volatile node = new TListNode(*i); TListNode* volatile tail = node; - - for (++i; i != dataEnd; ++i) { - TListNode* nextNode = node; + + for (++i; i != dataEnd; ++i) { + TListNode* nextNode = node; node = new TListNode(*i, nextNode); } - EnqueueImpl(node, tail); + EnqueueImpl(node, tail); } bool Dequeue(T* data) { TRootNode* newRoot = nullptr; diff --git a/util/thread/lfqueue_ut.cpp b/util/thread/lfqueue_ut.cpp index d65fbd3769..83bca100cf 100644 --- a/util/thread/lfqueue_ut.cpp +++ b/util/thread/lfqueue_ut.cpp @@ -6,9 +6,9 @@ #include <util/generic/ptr.h> #include <util/system/atomic.h> #include <util/thread/pool.h> - + #include "lfqueue.h" - + class TMoveTest { public: TMoveTest(int marker = 0, int value = 0) @@ -122,74 +122,74 @@ Y_UNIT_TEST_SUITE(TLockFreeQueueTests) { } Y_UNIT_TEST(TestSimpleEnqueueDequeue) { - TLockFreeQueue<int> queue; - + TLockFreeQueue<int> queue; + int i = -1; - - UNIT_ASSERT(!queue.Dequeue(&i)); + + UNIT_ASSERT(!queue.Dequeue(&i)); UNIT_ASSERT_VALUES_EQUAL(i, -1); - - queue.Enqueue(10); - queue.Enqueue(11); - queue.Enqueue(12); - - UNIT_ASSERT(queue.Dequeue(&i)); - UNIT_ASSERT_VALUES_EQUAL(10, i); - UNIT_ASSERT(queue.Dequeue(&i)); - UNIT_ASSERT_VALUES_EQUAL(11, i); - - queue.Enqueue(13); - - UNIT_ASSERT(queue.Dequeue(&i)); - UNIT_ASSERT_VALUES_EQUAL(12, i); - UNIT_ASSERT(queue.Dequeue(&i)); - UNIT_ASSERT_VALUES_EQUAL(13, i); - - UNIT_ASSERT(!queue.Dequeue(&i)); + + queue.Enqueue(10); + queue.Enqueue(11); + queue.Enqueue(12); + + UNIT_ASSERT(queue.Dequeue(&i)); + UNIT_ASSERT_VALUES_EQUAL(10, i); + UNIT_ASSERT(queue.Dequeue(&i)); + UNIT_ASSERT_VALUES_EQUAL(11, i); + + queue.Enqueue(13); + + UNIT_ASSERT(queue.Dequeue(&i)); + UNIT_ASSERT_VALUES_EQUAL(12, i); + UNIT_ASSERT(queue.Dequeue(&i)); + UNIT_ASSERT_VALUES_EQUAL(13, i); + + UNIT_ASSERT(!queue.Dequeue(&i)); const int tmp = 100; queue.Enqueue(tmp); UNIT_ASSERT(queue.Dequeue(&i)); UNIT_ASSERT_VALUES_EQUAL(i, tmp); - } - + } + Y_UNIT_TEST(TestSimpleEnqueueAllDequeue) { - TLockFreeQueue<int> queue; - + TLockFreeQueue<int> queue; + int i = -1; - - UNIT_ASSERT(!queue.Dequeue(&i)); + + UNIT_ASSERT(!queue.Dequeue(&i)); UNIT_ASSERT_VALUES_EQUAL(i, -1); - + TVector<int> v; - v.push_back(20); - v.push_back(21); - - queue.EnqueueAll(v); - - v.clear(); - v.push_back(22); - v.push_back(23); - v.push_back(24); - - queue.EnqueueAll(v); - - v.clear(); - queue.EnqueueAll(v); - - v.clear(); - v.push_back(25); - - queue.EnqueueAll(v); - - for (int j = 20; j <= 25; ++j) { - UNIT_ASSERT(queue.Dequeue(&i)); - UNIT_ASSERT_VALUES_EQUAL(j, i); - } - - UNIT_ASSERT(!queue.Dequeue(&i)); - } - + v.push_back(20); + v.push_back(21); + + queue.EnqueueAll(v); + + v.clear(); + v.push_back(22); + v.push_back(23); + v.push_back(24); + + queue.EnqueueAll(v); + + v.clear(); + queue.EnqueueAll(v); + + v.clear(); + v.push_back(25); + + queue.EnqueueAll(v); + + for (int j = 20; j <= 25; ++j) { + UNIT_ASSERT(queue.Dequeue(&i)); + UNIT_ASSERT_VALUES_EQUAL(j, i); + } + + UNIT_ASSERT(!queue.Dequeue(&i)); + } + void DequeueAllRunner(TLockFreeQueue<int>& queue, bool singleConsumer) { size_t threadsNum = 4; size_t enqueuesPerThread = 10'000; @@ -304,19 +304,19 @@ Y_UNIT_TEST_SUITE(TLockFreeQueueTests) { Y_UNIT_TEST(CleanInDestructor) { TSimpleSharedPtr<bool> p(new bool); - UNIT_ASSERT_VALUES_EQUAL(1u, p.RefCount()); - - { + UNIT_ASSERT_VALUES_EQUAL(1u, p.RefCount()); + + { TLockFreeQueue<TSimpleSharedPtr<bool>> stack; - - stack.Enqueue(p); - stack.Enqueue(p); - - UNIT_ASSERT_VALUES_EQUAL(3u, p.RefCount()); - } - - UNIT_ASSERT_VALUES_EQUAL(1, p.RefCount()); - } + + stack.Enqueue(p); + stack.Enqueue(p); + + UNIT_ASSERT_VALUES_EQUAL(3u, p.RefCount()); + } + + UNIT_ASSERT_VALUES_EQUAL(1, p.RefCount()); + } Y_UNIT_TEST(CheckOperationsCount) { TOperationsChecker o; @@ -330,4 +330,4 @@ Y_UNIT_TEST_SUITE(TLockFreeQueueTests) { queue.Dequeue(&o); o.Check(0, 0, 2, 1, 0); } -} +} diff --git a/util/thread/lfstack.h b/util/thread/lfstack.h index 81534cd1d1..ca3d95f3c3 100644 --- a/util/thread/lfstack.h +++ b/util/thread/lfstack.h @@ -43,12 +43,12 @@ class TLockFreeStack: TNonCopyable { } } void EnqueueImpl(TNode* volatile head, TNode* volatile tail) { - for (;;) { + for (;;) { tail->Next = AtomicGet(Head); - if (AtomicCas(&Head, head, tail->Next)) - break; - } - } + if (AtomicCas(&Head, head, tail->Next)) + break; + } + } template <class U> void EnqueueImpl(U&& u) { TNode* volatile node = new TNode(std::forward<U>(u)); @@ -69,31 +69,31 @@ public: void Enqueue(const T& t) { EnqueueImpl(t); - } + } void Enqueue(T&& t) { EnqueueImpl(std::move(t)); } - template <typename TCollection> + template <typename TCollection> void EnqueueAll(const TCollection& data) { - EnqueueAll(data.begin(), data.end()); - } - template <typename TIter> + EnqueueAll(data.begin(), data.end()); + } + template <typename TIter> void EnqueueAll(TIter dataBegin, TIter dataEnd) { - if (dataBegin == dataEnd) { - return; + if (dataBegin == dataEnd) { + return; } - TIter i = dataBegin; + TIter i = dataBegin; TNode* volatile node = new TNode(*i); TNode* volatile tail = node; - - for (++i; i != dataEnd; ++i) { - TNode* nextNode = node; - node = new TNode(*i); - node->Next = nextNode; - } - EnqueueImpl(node, tail); + + for (++i; i != dataEnd; ++i) { + TNode* nextNode = node; + node = new TNode(*i); + node->Next = nextNode; + } + EnqueueImpl(node, tail); } bool Dequeue(T* res) { AtomicAdd(DequeueCount, 1); @@ -122,8 +122,8 @@ public: return false; } // add all elements to *res - // elements are returned in order of dequeue (top to bottom; see example in unittest) - template <typename TCollection> + // elements are returned in order of dequeue (top to bottom; see example in unittest) + template <typename TCollection> void DequeueAll(TCollection* res) { AtomicAdd(DequeueCount, 1); for (TNode* current = AtomicGet(Head); current; current = AtomicGet(Head)) { @@ -168,7 +168,7 @@ public: } // add all elements to *res // elements are returned in order of dequeue (top to bottom; see example in unittest) - template <typename TCollection> + template <typename TCollection> void DequeueAllSingleConsumer(TCollection* res) { for (TNode* current = AtomicGet(Head); current; current = AtomicGet(Head)) { if (AtomicCas(&Head, (TNode*)nullptr, current)) { diff --git a/util/thread/lfstack_ut.cpp b/util/thread/lfstack_ut.cpp index 824d633a62..e20a838f95 100644 --- a/util/thread/lfstack_ut.cpp +++ b/util/thread/lfstack_ut.cpp @@ -1,194 +1,194 @@ -#include <util/system/atomic.h> -#include <util/system/event.h> +#include <util/system/atomic.h> +#include <util/system/event.h> #include <util/generic/deque.h> #include <library/cpp/threading/future/legacy_future.h> - + #include <library/cpp/testing/unittest/registar.h> - + #include "lfstack.h" - + Y_UNIT_TEST_SUITE(TLockFreeStackTests) { - class TCountDownLatch { - private: + class TCountDownLatch { + private: TAtomic Current_; TSystemEvent EventObject_; - public: - TCountDownLatch(unsigned initial) + public: + TCountDownLatch(unsigned initial) : Current_(initial) { } - - void CountDown() { + + void CountDown() { if (AtomicDecrement(Current_) == 0) { EventObject_.Signal(); - } - } - - void Await() { + } + } + + void Await() { EventObject_.Wait(); - } - - bool Await(TDuration timeout) { + } + + bool Await(TDuration timeout) { return EventObject_.WaitT(timeout); - } - }; - - template <bool SingleConsumer> - struct TDequeueAllTester { - size_t EnqueueThreads; - size_t DequeueThreads; - - size_t EnqueuesPerThread; - TAtomic LeftToDequeue; - - TCountDownLatch StartLatch; - TLockFreeStack<int> Stack; - - TDequeueAllTester() - : EnqueueThreads(4) - , DequeueThreads(SingleConsumer ? 1 : 3) - , EnqueuesPerThread(100000) - , LeftToDequeue(EnqueueThreads * EnqueuesPerThread) - , StartLatch(EnqueueThreads + DequeueThreads) - { - } - - void Enqueuer() { - StartLatch.CountDown(); - StartLatch.Await(); - - for (size_t i = 0; i < EnqueuesPerThread; ++i) { - Stack.Enqueue(i); - } - } - - void DequeuerAll() { - StartLatch.CountDown(); - StartLatch.Await(); - + } + }; + + template <bool SingleConsumer> + struct TDequeueAllTester { + size_t EnqueueThreads; + size_t DequeueThreads; + + size_t EnqueuesPerThread; + TAtomic LeftToDequeue; + + TCountDownLatch StartLatch; + TLockFreeStack<int> Stack; + + TDequeueAllTester() + : EnqueueThreads(4) + , DequeueThreads(SingleConsumer ? 1 : 3) + , EnqueuesPerThread(100000) + , LeftToDequeue(EnqueueThreads * EnqueuesPerThread) + , StartLatch(EnqueueThreads + DequeueThreads) + { + } + + void Enqueuer() { + StartLatch.CountDown(); + StartLatch.Await(); + + for (size_t i = 0; i < EnqueuesPerThread; ++i) { + Stack.Enqueue(i); + } + } + + void DequeuerAll() { + StartLatch.CountDown(); + StartLatch.Await(); + TVector<int> temp; - while (AtomicGet(LeftToDequeue) > 0) { - size_t dequeued = 0; - for (size_t i = 0; i < 100; ++i) { - temp.clear(); - if (SingleConsumer) { - Stack.DequeueAllSingleConsumer(&temp); - } else { - Stack.DequeueAll(&temp); - } - dequeued += temp.size(); - } - AtomicAdd(LeftToDequeue, -dequeued); - } - } - - void Run() { + while (AtomicGet(LeftToDequeue) > 0) { + size_t dequeued = 0; + for (size_t i = 0; i < 100; ++i) { + temp.clear(); + if (SingleConsumer) { + Stack.DequeueAllSingleConsumer(&temp); + } else { + Stack.DequeueAll(&temp); + } + dequeued += temp.size(); + } + AtomicAdd(LeftToDequeue, -dequeued); + } + } + + void Run() { TVector<TSimpleSharedPtr<NThreading::TLegacyFuture<>>> futures; - - for (size_t i = 0; i < EnqueueThreads; ++i) { + + for (size_t i = 0; i < EnqueueThreads; ++i) { futures.push_back(new NThreading::TLegacyFuture<>(std::bind(&TDequeueAllTester<SingleConsumer>::Enqueuer, this))); - } - - for (size_t i = 0; i < DequeueThreads; ++i) { + } + + for (size_t i = 0; i < DequeueThreads; ++i) { futures.push_back(new NThreading::TLegacyFuture<>(std::bind(&TDequeueAllTester<SingleConsumer>::DequeuerAll, this))); - } - - // effectively join - futures.clear(); - - UNIT_ASSERT_VALUES_EQUAL(0, int(AtomicGet(LeftToDequeue))); - + } + + // effectively join + futures.clear(); + + UNIT_ASSERT_VALUES_EQUAL(0, int(AtomicGet(LeftToDequeue))); + TVector<int> left; - Stack.DequeueAll(&left); - UNIT_ASSERT(left.empty()); - } - }; - + Stack.DequeueAll(&left); + UNIT_ASSERT(left.empty()); + } + }; + Y_UNIT_TEST(TestDequeueAll) { - TDequeueAllTester<false>().Run(); - } - + TDequeueAllTester<false>().Run(); + } + Y_UNIT_TEST(TestDequeueAllSingleConsumer) { - TDequeueAllTester<true>().Run(); - } - + TDequeueAllTester<true>().Run(); + } + Y_UNIT_TEST(TestDequeueAllEmptyStack) { - TLockFreeStack<int> stack; - + TLockFreeStack<int> stack; + TVector<int> r; - stack.DequeueAll(&r); - - UNIT_ASSERT(r.empty()); - } - + stack.DequeueAll(&r); + + UNIT_ASSERT(r.empty()); + } + Y_UNIT_TEST(TestDequeueAllReturnsInReverseOrder) { - TLockFreeStack<int> stack; - - stack.Enqueue(17); - stack.Enqueue(19); - stack.Enqueue(23); - + TLockFreeStack<int> stack; + + stack.Enqueue(17); + stack.Enqueue(19); + stack.Enqueue(23); + TVector<int> r; - - stack.DequeueAll(&r); - - UNIT_ASSERT_VALUES_EQUAL(size_t(3), r.size()); - UNIT_ASSERT_VALUES_EQUAL(23, r.at(0)); - UNIT_ASSERT_VALUES_EQUAL(19, r.at(1)); - UNIT_ASSERT_VALUES_EQUAL(17, r.at(2)); - } - + + stack.DequeueAll(&r); + + UNIT_ASSERT_VALUES_EQUAL(size_t(3), r.size()); + UNIT_ASSERT_VALUES_EQUAL(23, r.at(0)); + UNIT_ASSERT_VALUES_EQUAL(19, r.at(1)); + UNIT_ASSERT_VALUES_EQUAL(17, r.at(2)); + } + Y_UNIT_TEST(TestEnqueueAll) { - TLockFreeStack<int> stack; - + TLockFreeStack<int> stack; + TVector<int> v; TVector<int> expected; - - stack.EnqueueAll(v); // add empty - - v.push_back(2); - v.push_back(3); - v.push_back(5); - expected.insert(expected.end(), v.begin(), v.end()); - stack.EnqueueAll(v); - - v.clear(); - - stack.EnqueueAll(v); // add empty - - v.push_back(7); - v.push_back(11); - v.push_back(13); - v.push_back(17); - expected.insert(expected.end(), v.begin(), v.end()); - stack.EnqueueAll(v); - + + stack.EnqueueAll(v); // add empty + + v.push_back(2); + v.push_back(3); + v.push_back(5); + expected.insert(expected.end(), v.begin(), v.end()); + stack.EnqueueAll(v); + + v.clear(); + + stack.EnqueueAll(v); // add empty + + v.push_back(7); + v.push_back(11); + v.push_back(13); + v.push_back(17); + expected.insert(expected.end(), v.begin(), v.end()); + stack.EnqueueAll(v); + TVector<int> actual; - stack.DequeueAll(&actual); - - UNIT_ASSERT_VALUES_EQUAL(expected.size(), actual.size()); - for (size_t i = 0; i < actual.size(); ++i) { - UNIT_ASSERT_VALUES_EQUAL(expected.at(expected.size() - i - 1), actual.at(i)); - } - } - + stack.DequeueAll(&actual); + + UNIT_ASSERT_VALUES_EQUAL(expected.size(), actual.size()); + for (size_t i = 0; i < actual.size(); ++i) { + UNIT_ASSERT_VALUES_EQUAL(expected.at(expected.size() - i - 1), actual.at(i)); + } + } + Y_UNIT_TEST(CleanInDestructor) { TSimpleSharedPtr<bool> p(new bool); - UNIT_ASSERT_VALUES_EQUAL(1u, p.RefCount()); - - { + UNIT_ASSERT_VALUES_EQUAL(1u, p.RefCount()); + + { TLockFreeStack<TSimpleSharedPtr<bool>> stack; - - stack.Enqueue(p); - stack.Enqueue(p); - - UNIT_ASSERT_VALUES_EQUAL(3u, p.RefCount()); - } - - UNIT_ASSERT_VALUES_EQUAL(1, p.RefCount()); - } + + stack.Enqueue(p); + stack.Enqueue(p); + + UNIT_ASSERT_VALUES_EQUAL(3u, p.RefCount()); + } + + UNIT_ASSERT_VALUES_EQUAL(1, p.RefCount()); + } Y_UNIT_TEST(NoCopyTest) { static unsigned copied = 0; @@ -343,4 +343,4 @@ Y_UNIT_TEST_SUITE(TLockFreeStackTests) { Y_UNIT_TEST(TesMultiThreadMove) { TMultiThreadTester<TMoveTest>().Run(); } -} +} diff --git a/util/thread/pool.cpp b/util/thread/pool.cpp index 25018ea95f..05fad02e9b 100644 --- a/util/thread/pool.cpp +++ b/util/thread/pool.cpp @@ -22,8 +22,8 @@ #include <util/system/condvar.h> #include <util/system/thread.h> -#include <util/datetime/base.h> - +#include <util/datetime/base.h> + #include "factory.h" #include "pool.h" diff --git a/util/thread/pool_ut.cpp b/util/thread/pool_ut.cpp index 86f167f423..893770d0c4 100644 --- a/util/thread/pool_ut.cpp +++ b/util/thread/pool_ut.cpp @@ -1,14 +1,14 @@ #include "pool.h" #include <library/cpp/testing/unittest/registar.h> - + #include <util/stream/output.h> #include <util/random/fast.h> #include <util/system/spinlock.h> #include <util/system/thread.h> #include <util/system/mutex.h> #include <util/system/condvar.h> - + struct TThreadPoolTest { TSpinLock Lock; long R = -1; @@ -65,7 +65,7 @@ struct TThreadPoolTest { for (size_t i = 0; i < cnt; ++i) { UNIT_ASSERT(queue->Add(new TTask(this, (long)rand.GenRand()))); - } + } queue->Stop(); @@ -124,7 +124,7 @@ Y_UNIT_TEST_SUITE(TThreadPoolTest) { UNIT_ASSERT_C(processed, "Not processed"); UNIT_ASSERT_C(destructed, "Not destructed"); } - + Y_UNIT_TEST(TestAddFunc) { TFailAddQueue queue; bool added = queue.AddFunc( diff --git a/util/thread/singleton.h b/util/thread/singleton.h index e9d43bcf20..4a1e05aea0 100644 --- a/util/thread/singleton.h +++ b/util/thread/singleton.h @@ -1,20 +1,20 @@ -#pragma once - -#include <util/system/tls.h> -#include <util/generic/singleton.h> -#include <util/generic/ptr.h> - +#pragma once + +#include <util/system/tls.h> +#include <util/generic/singleton.h> +#include <util/generic/ptr.h> + namespace NPrivate { template <class T, size_t Priority> struct TFastThreadSingletonHelper { static inline T* GetSlow() { return SingletonWithPriority<NTls::TValue<T>, Priority>()->GetPtr(); } - + static inline T* Get() { #if defined(Y_HAVE_FAST_POD_TLS) Y_POD_STATIC_THREAD(T*) fast(nullptr); - + if (Y_UNLIKELY(!fast)) { fast = GetSlow(); } @@ -25,16 +25,16 @@ namespace NPrivate { #endif } }; -} - +} + template <class T, size_t Priority> static inline T* FastTlsSingletonWithPriority() { return ::NPrivate::TFastThreadSingletonHelper<T, Priority>::Get(); -} - -// NB: the singleton is the same for all modules that use -// FastTlsSingleton with the same type parameter. If unique singleton -// required, use unique types. +} + +// NB: the singleton is the same for all modules that use +// FastTlsSingleton with the same type parameter. If unique singleton +// required, use unique types. template <class T> static inline T* FastTlsSingleton() { return FastTlsSingletonWithPriority<T, TSingletonTraits<T>::Priority>(); diff --git a/util/thread/singleton_ut.cpp b/util/thread/singleton_ut.cpp index f02316e6ba..164b1cc184 100644 --- a/util/thread/singleton_ut.cpp +++ b/util/thread/singleton_ut.cpp @@ -1,21 +1,21 @@ #include <library/cpp/testing/unittest/registar.h> - -#include "singleton.h" - -namespace { - struct TFoo { - int i; - TFoo() - : i(0) + +#include "singleton.h" + +namespace { + struct TFoo { + int i; + TFoo() + : i(0) { } - }; -} - + }; +} + Y_UNIT_TEST_SUITE(Tls) { Y_UNIT_TEST(FastThread) { - UNIT_ASSERT_VALUES_EQUAL(0, FastTlsSingleton<TFoo>()->i); - FastTlsSingleton<TFoo>()->i += 3; - UNIT_ASSERT_VALUES_EQUAL(3, FastTlsSingleton<TFoo>()->i); - } -} + UNIT_ASSERT_VALUES_EQUAL(0, FastTlsSingleton<TFoo>()->i); + FastTlsSingleton<TFoo>()->i += 3; + UNIT_ASSERT_VALUES_EQUAL(3, FastTlsSingleton<TFoo>()->i); + } +} diff --git a/util/ya.make b/util/ya.make index d031eb0493..6ebe7e40cf 100644 --- a/util/ya.make +++ b/util/ya.make @@ -10,7 +10,7 @@ NO_UTIL() # stream # string PEERDIR( - util/charset + util/charset contrib/libs/zlib contrib/libs/double-conversion ) @@ -54,8 +54,8 @@ JOIN_SRCS( JOIN_SRCS( all_util.cpp - ysafeptr.cpp - ysaveload.cpp + ysafeptr.cpp + ysaveload.cpp str_stl.cpp ) diff --git a/util/ysaveload.h b/util/ysaveload.h index 966ff3ee85..02efb4049b 100644 --- a/util/ysaveload.h +++ b/util/ysaveload.h @@ -25,12 +25,12 @@ public: }; }; -struct TSerializeException: public yexception { +struct TSerializeException: public yexception { +}; + +struct TLoadEOF: public TSerializeException { }; -struct TLoadEOF: public TSerializeException { -}; - template <class T> static inline void Save(IOutputStream* out, const T& t); |