diff --git a/client/draft/ydb_scripting.cpp b/client/draft/ydb_scripting.cpp index 83c158245f8..bf91c476835 100644 --- a/client/draft/ydb_scripting.cpp +++ b/client/draft/ydb_scripting.cpp @@ -15,7 +15,7 @@ namespace NScripting { using namespace NThreading; TExecuteYqlResult::TExecuteYqlResult(TStatus&& status, std::vector&& resultSets, - const TMaybe& queryStats) + const std::optional& queryStats) : TStatus(std::move(status)) , ResultSets_(std::move(resultSets)) , QueryStats_(queryStats) {} @@ -36,7 +36,7 @@ TResultSetParser TExecuteYqlResult::GetResultSetParser(size_t resultIndex) const return TResultSetParser(GetResultSet(resultIndex)); } -const TMaybe& TExecuteYqlResult::GetStats() const { +const std::optional& TExecuteYqlResult::GetStats() const { return QueryStats_; } @@ -77,7 +77,7 @@ class TYqlResultPartIterator::TReaderImpl { EStatus clientStatus = static_cast(self->Response_.status()); TPlainStatus plainStatus{ clientStatus, std::move(issues), self->Endpoint_, {} }; TStatus status{ std::move(plainStatus) }; - TMaybe queryStats; + std::optional queryStats; if (self->Response_.result().has_query_stats()) { queryStats = NTable::TQueryStats(self->Response_.result().query_stats()); @@ -164,12 +164,12 @@ class TScriptingClient::TImpl : public TClientImplCommon res; - TMaybe queryStats; + std::optional queryStats; if (any) { Ydb::Scripting::ExecuteYqlResult result; any->UnpackTo(&result); - for (size_t i = 0; i < result.result_sets_size(); i++) { + for (size_t i = 0; i < static_cast(result.result_sets_size()); i++) { res.push_back(TResultSet(*result.mutable_result_sets(i))); } diff --git a/client/draft/ydb_scripting.h b/client/draft/ydb_scripting.h index e875a1d75b0..8268139e301 100644 --- a/client/draft/ydb_scripting.h +++ b/client/draft/ydb_scripting.h @@ -10,18 +10,18 @@ namespace NScripting { class TExecuteYqlResult : public TStatus { public: TExecuteYqlResult(TStatus&& status, std::vector&& resultSets, - const TMaybe& queryStats); + const std::optional& queryStats); const std::vector& GetResultSets() const; TResultSet GetResultSet(size_t resultIndex) const; TResultSetParser GetResultSetParser(size_t resultIndex) const; - const TMaybe& GetStats() const; + const std::optional& GetStats() const; private: std::vector ResultSets_; - TMaybe QueryStats_; + std::optional QueryStats_; }; class TYqlPartialResult { @@ -41,10 +41,10 @@ class TYqlPartialResult { class TYqlResultPart : public TStreamPartStatus { public: - bool HasPartialResult() const { return PartialResult_.Defined(); } + bool HasPartialResult() const { return PartialResult_.has_value(); } const TYqlPartialResult& GetPartialResult() const { return *PartialResult_; } - bool HasQueryStats() const { return QueryStats_.Defined(); } + bool HasQueryStats() const { return QueryStats_.has_value(); } const NTable::TQueryStats& GetQueryStats() const { return *QueryStats_; } NTable::TQueryStats ExtractQueryStats() { return std::move(*QueryStats_); } @@ -52,20 +52,20 @@ class TYqlResultPart : public TStreamPartStatus { : TStreamPartStatus(std::move(status)) {} - TYqlResultPart(TStatus&& status, const TMaybe &queryStats) + TYqlResultPart(TStatus&& status, const std::optional &queryStats) : TStreamPartStatus(std::move(status)) , QueryStats_(queryStats) {} - TYqlResultPart(TStatus&& status, TYqlPartialResult&& partialResult, const TMaybe &queryStats) + TYqlResultPart(TStatus&& status, TYqlPartialResult&& partialResult, const std::optional &queryStats) : TStreamPartStatus(std::move(status)) , PartialResult_(std::move(partialResult)) , QueryStats_(queryStats) {} private: - TMaybe PartialResult_; - TMaybe QueryStats_; + std::optional PartialResult_; + std::optional QueryStats_; }; using TAsyncYqlResultPart = NThreading::TFuture; diff --git a/client/impl/ydb_internal/grpc_connections/grpc_connections.cpp b/client/impl/ydb_internal/grpc_connections/grpc_connections.cpp index 3d9ff8fc637..d8c1982bc5f 100644 --- a/client/impl/ydb_internal/grpc_connections/grpc_connections.cpp +++ b/client/impl/ydb_internal/grpc_connections/grpc_connections.cpp @@ -265,18 +265,18 @@ void TGRpcConnectionsImpl::ScheduleCallback( } TDbDriverStatePtr TGRpcConnectionsImpl::GetDriverState( - const TMaybe& database, - const TMaybe& discoveryEndpoint, - const TMaybe& discoveryMode, - const TMaybe& sslCredentials, - const TMaybe>& credentialsProviderFactory + const std::optional& database, + const std::optional& discoveryEndpoint, + const std::optional& discoveryMode, + const std::optional& sslCredentials, + const std::optional>& credentialsProviderFactory ) { return StateTracker_.GetDriverState( - database ? database.GetRef() : DefaultDatabase_, - discoveryEndpoint ? discoveryEndpoint.GetRef() : DefaultDiscoveryEndpoint_, - discoveryMode ? discoveryMode.GetRef() : DefaultDiscoveryMode_, - sslCredentials ? sslCredentials.GetRef() : SslCredentials_, - credentialsProviderFactory ? credentialsProviderFactory.GetRef() : DefaultCredentialsProviderFactory_); + database.value_or(DefaultDatabase_), + discoveryEndpoint.value_or(DefaultDiscoveryEndpoint_), + discoveryMode.value_or(DefaultDiscoveryMode_), + sslCredentials.value_or(SslCredentials_), + credentialsProviderFactory.value_or(DefaultCredentialsProviderFactory_)); } IQueueClientContextPtr TGRpcConnectionsImpl::CreateContext() { diff --git a/client/impl/ydb_internal/grpc_connections/grpc_connections.h b/client/impl/ydb_internal/grpc_connections/grpc_connections.h index 6022797cb05..d4f163336ec 100644 --- a/client/impl/ydb_internal/grpc_connections/grpc_connections.h +++ b/client/impl/ydb_internal/grpc_connections/grpc_connections.h @@ -58,11 +58,11 @@ class TGRpcConnectionsImpl // This method returns DbDriverState (or just db state) for given database credentials pair // this state is used to keep data related to particular database. TDbDriverStatePtr GetDriverState( - const TMaybe& database, - const TMaybe& discoveryEndpoint, - const TMaybe& discoveryMode, - const TMaybe& sslCredentials, - const TMaybe>& credentialsProviderFactory + const std::optional& database, + const std::optional& discoveryEndpoint, + const std::optional& discoveryMode, + const std::optional& sslCredentials, + const std::optional>& credentialsProviderFactory ); IQueueClientContextPtr CreateContext() override; bool TryCreateContext(IQueueClientContextPtr& context); diff --git a/client/impl/ydb_internal/retry/retry.h b/client/impl/ydb_internal/retry/retry.h index 524b7b86955..c89ec74e0cb 100644 --- a/client/impl/ydb_internal/retry/retry.h +++ b/client/impl/ydb_internal/retry/retry.h @@ -7,7 +7,6 @@ #include #include #include -#include #include #include diff --git a/client/impl/ydb_internal/retry/retry_async.h b/client/impl/ydb_internal/retry/retry_async.h index 6e261b82805..c939a128356 100644 --- a/client/impl/ydb_internal/retry/retry_async.h +++ b/client/impl/ydb_internal/retry/retry_async.h @@ -122,7 +122,7 @@ class TRetryWithSession : public TRetryContext { private: TOperation Operation_; - TMaybe Session_; + std::optional Session_; public: explicit TRetryWithSession( @@ -158,14 +158,14 @@ class TRetryWithSession : public TRetryContext { private: void Reset() override { - Session_.Clear(); + Session_.reset(); } TAsyncStatusType RunOperation() override { if constexpr (TFunctionArgs::Length == 1) { - return Operation_(this->Session_.GetRef()); + return Operation_(this->Session_.value()); } else { - return Operation_(this->Session_.GetRef(), this->GetRemainingTimeout()); + return Operation_(this->Session_.value(), this->GetRemainingTimeout()); } } }; diff --git a/client/impl/ydb_internal/retry/retry_sync.h b/client/impl/ydb_internal/retry/retry_sync.h index d8846995f32..51094817a95 100644 --- a/client/impl/ydb_internal/retry/retry_sync.h +++ b/client/impl/ydb_internal/retry/retry_sync.h @@ -4,8 +4,6 @@ #include #include -#include - namespace NYdb::NRetry::Sync { template @@ -89,7 +87,7 @@ class TRetryWithSession : public TRetryContext { private: const TOperation& Operation_; - TMaybe Session_; + std::optional Session_; public: TRetryWithSession(TClient& client, const TOperation& operation, const TRetryOperationSettings& settings) @@ -99,7 +97,7 @@ class TRetryWithSession : public TRetryContext { protected: TStatusType Retry() override { - TMaybe status; + std::optional status; if (!Session_) { auto settings = TCreateSessionSettings().ClientTimeout(this->Settings_.GetSessionClientTimeout_); @@ -119,14 +117,14 @@ class TRetryWithSession : public TRetryContext { TStatusType RunOperation() override { if constexpr (TFunctionArgs::Length == 1) { - return Operation_(this->Session_.GetRef()); + return Operation_(this->Session_.value()); } else { - return Operation_(this->Session_.GetRef(), this->GetRemainingTimeout()); + return Operation_(this->Session_.value(), this->GetRemainingTimeout()); } } void Reset() override { - Session_.Clear(); + Session_.reset(); } }; diff --git a/client/impl/ydb_internal/table_helpers/helpers.h b/client/impl/ydb_internal/table_helpers/helpers.h index 8a47f5d0018..be5c45a5fd7 100644 --- a/client/impl/ydb_internal/table_helpers/helpers.h +++ b/client/impl/ydb_internal/table_helpers/helpers.h @@ -7,8 +7,8 @@ namespace NYdb { -inline Ydb::Table::QueryStatsCollection::Mode GetStatsCollectionMode(TMaybe mode) { - if (mode) { +inline Ydb::Table::QueryStatsCollection::Mode GetStatsCollectionMode(std::optional mode) { + if (mode.has_value()) { switch (*mode) { case NTable::ECollectQueryStatsMode::None: return Ydb::Table::QueryStatsCollection::STATS_COLLECTION_NONE; diff --git a/client/ydb_common_client/impl/client.h b/client/ydb_common_client/impl/client.h index c587cab06eb..bcf9f5d6a48 100644 --- a/client/ydb_common_client/impl/client.h +++ b/client/ydb_common_client/impl/client.h @@ -20,11 +20,11 @@ class TClientImplCommon public: TClientImplCommon( std::shared_ptr&& connections, - const TMaybe& database, - const TMaybe& discoveryEndpoint, - const TMaybe& discoveryMode, - const TMaybe& sslCredentials, - const TMaybe>& credentialsProviderFactory) + const std::optional& database, + const std::optional& discoveryEndpoint, + const std::optional& discoveryMode, + const std::optional& sslCredentials, + const std::optional>& credentialsProviderFactory) : Connections_(std::move(connections)) , DbDriverState_(Connections_->GetDriverState( database, discoveryEndpoint, discoveryMode, sslCredentials, credentialsProviderFactory)) diff --git a/client/ydb_common_client/settings.cpp b/client/ydb_common_client/settings.cpp index b8b3bbcb5f0..6489e18cde9 100644 --- a/client/ydb_common_client/settings.cpp +++ b/client/ydb_common_client/settings.cpp @@ -4,8 +4,8 @@ namespace NYdb { -TCommonClientSettings& TCommonClientSettings::AuthToken(const TMaybe& token) { - return CredentialsProviderFactory(CreateOAuthCredentialsProviderFactory(token.GetRef())); +TCommonClientSettings& TCommonClientSettings::AuthToken(const std::optional& token) { + return CredentialsProviderFactory(CreateOAuthCredentialsProviderFactory(token.value())); } TCommonClientSettings GetClientSettingsFromConnectionString(const std::string& connectionString) { diff --git a/client/ydb_common_client/settings.h b/client/ydb_common_client/settings.h index dad24d1036d..d16a8692896 100644 --- a/client/ydb_common_client/settings.h +++ b/client/ydb_common_client/settings.h @@ -26,7 +26,7 @@ struct TCommonClientSettings { //! Allows to override current discovery endpoint FLUENT_SETTING_OPTIONAL(std::string, DiscoveryEndpoint); //! Allows to override current token for client - TSelf& AuthToken(const TMaybe& token); + TSelf& AuthToken(const std::optional& token); //! Allows to override current credentials provider FLUENT_SETTING_OPTIONAL(std::shared_ptr, CredentialsProviderFactory); //! Allows to override discovery mode @@ -46,7 +46,7 @@ struct TCommonClientSettingsBase : public TCommonClientSettings { COMMON_CLIENT_SETTINGS_TO_DERIVED(std::string, Database); COMMON_CLIENT_SETTINGS_TO_DERIVED(std::string, DiscoveryEndpoint); - COMMON_CLIENT_SETTINGS_TO_DERIVED(TMaybe, AuthToken); + COMMON_CLIENT_SETTINGS_TO_DERIVED(std::optional, AuthToken); COMMON_CLIENT_SETTINGS_TO_DERIVED(std::shared_ptr, CredentialsProviderFactory); COMMON_CLIENT_SETTINGS_TO_DERIVED(EDiscoveryMode, DiscoveryMode); COMMON_CLIENT_SETTINGS_TO_DERIVED(TSslCredentials, SslCredentials); diff --git a/client/ydb_coordination/coordination.cpp b/client/ydb_coordination/coordination.cpp index e94393faf43..2232e492453 100644 --- a/client/ydb_coordination/coordination.cpp +++ b/client/ydb_coordination/coordination.cpp @@ -87,8 +87,8 @@ struct TNodeDescription::TImpl { Proto_ = desc; } - TMaybe SelfCheckPeriod_; - TMaybe SessionGracePeriod_; + std::optional SelfCheckPeriod_; + std::optional SessionGracePeriod_; EConsistencyMode ReadConsistencyMode_; EConsistencyMode AttachConsistencyMode_; ERateLimiterCountersMode RateLimiterCountersMode_; @@ -102,11 +102,11 @@ TNodeDescription::TNodeDescription( : Impl_(new TImpl(desc)) { } -const TMaybe& TNodeDescription::GetSelfCheckPeriod() const { +const std::optional& TNodeDescription::GetSelfCheckPeriod() const { return Impl_->SelfCheckPeriod_; } -const TMaybe& TNodeDescription::GetSessionGracePeriod() const { +const std::optional& TNodeDescription::GetSessionGracePeriod() const { return Impl_->SessionGracePeriod_; } @@ -733,7 +733,7 @@ class TSessionContext : public TThrRefBase { Y_ABORT_UNLESS(ConnectionState == EConnectionState::ATTACHING); SessionState = ESessionState::ATTACHED; ConnectionState = EConnectionState::CONNECTED; - SessionExpireDeadline.Clear(); + SessionExpireDeadline.reset(); SessionReconnectDelay = TDuration::Zero(); if (ClosedPromise.Initialized()) { // Send the delayed close request, will fail if cancelled @@ -1777,7 +1777,7 @@ class TSessionContext : public TThrRefBase { // Reconnection uses sleep between attempts IQueueClientContextPtr SleepContext; - TMaybe SessionExpireDeadline; + std::optional SessionExpireDeadline; TDuration SessionReconnectDelay = TDuration::Zero(); IProcessor::TPtr Processor; diff --git a/client/ydb_coordination/coordination.h b/client/ydb_coordination/coordination.h index 2bf677ee3de..2cec5add6de 100644 --- a/client/ydb_coordination/coordination.h +++ b/client/ydb_coordination/coordination.h @@ -2,8 +2,6 @@ #include -#include - namespace Ydb { namespace Coordination { class DescribeNodeResult; @@ -99,8 +97,8 @@ class TNodeDescription { public: TNodeDescription(const Ydb::Coordination::DescribeNodeResult& desc); - const TMaybe& GetSelfCheckPeriod() const; - const TMaybe& GetSessionGracePeriod() const; + const std::optional& GetSelfCheckPeriod() const; + const std::optional& GetSessionGracePeriod() const; EConsistencyMode GetReadConsistencyMode() const; EConsistencyMode GetAttachConsistencyMode() const; ERateLimiterCountersMode GetRateLimiterCountersMode() const; diff --git a/client/ydb_datastreams/datastreams.cpp b/client/ydb_datastreams/datastreams.cpp index 4f8f132f78e..76011206c30 100644 --- a/client/ydb_datastreams/datastreams.cpp +++ b/client/ydb_datastreams/datastreams.cpp @@ -62,7 +62,7 @@ namespace NYdb::NDataStreams::V1 { } TAsyncCreateStreamResult CreateStream(const std::string &path, TCreateStreamSettings settings) { - if (settings.RetentionPeriodHours_.Defined() && settings.RetentionStorageMegabytes_.Defined()) { + if (settings.RetentionPeriodHours_.has_value() && settings.RetentionStorageMegabytes_.has_value()) { return NThreading::MakeFuture(TProtoResultWrapper( NYdb::TPlainStatus(NYdb::EStatus::BAD_REQUEST, "both retention types can not be set"), std::make_unique())); @@ -75,15 +75,15 @@ namespace NYdb::NDataStreams::V1 { [&](Ydb::DataStreams::V1::CreateStreamRequest& req) { req.set_stream_name(path); req.set_shard_count(settings.ShardCount_); - if (settings.RetentionStorageMegabytes_.Defined()) { - req.set_retention_storage_megabytes(*settings.RetentionStorageMegabytes_.Get()); - } else if (settings.RetentionPeriodHours_.Defined()) { - req.set_retention_period_hours(*settings.RetentionPeriodHours_.Get()); + if (settings.RetentionStorageMegabytes_.has_value()) { + req.set_retention_storage_megabytes(*settings.RetentionStorageMegabytes_); + } else if (settings.RetentionPeriodHours_.has_value()) { + req.set_retention_period_hours(*settings.RetentionPeriodHours_); } else { req.set_retention_period_hours(24); } req.set_write_quota_kb_per_sec(settings.WriteQuotaKbPerSec_); - if (settings.StreamMode_.Defined()) { + if (settings.StreamMode_.has_value()) { req.mutable_stream_mode_details()->set_stream_mode( *settings.StreamMode_ == ESM_PROVISIONED ? Ydb::DataStreams::V1::StreamMode::PROVISIONED : Ydb::DataStreams::V1::StreamMode::ON_DEMAND); @@ -347,7 +347,7 @@ namespace NYdb::NDataStreams::V1 { } TAsyncUpdateStreamResult UpdateStream(const std::string& streamName, TUpdateStreamSettings settings) { - if (settings.RetentionPeriodHours_.Defined() && settings.RetentionStorageMegabytes_.Defined()) { + if (settings.RetentionPeriodHours_.has_value() && settings.RetentionStorageMegabytes_.has_value()) { return NThreading::MakeFuture(TProtoResultWrapper( NYdb::TPlainStatus(NYdb::EStatus::BAD_REQUEST, "both retention types can not be set"), std::make_unique())); @@ -360,14 +360,14 @@ namespace NYdb::NDataStreams::V1 { [&](Ydb::DataStreams::V1::UpdateStreamRequest& req) { req.set_stream_name(streamName); req.set_target_shard_count(settings.TargetShardCount_); - if (settings.RetentionPeriodHours_.Defined()) { - req.set_retention_period_hours(*settings.RetentionPeriodHours_.Get()); + if (settings.RetentionPeriodHours_.has_value()) { + req.set_retention_period_hours(*settings.RetentionPeriodHours_); } - if (settings.RetentionStorageMegabytes_.Defined()) { - req.set_retention_storage_megabytes(*settings.RetentionStorageMegabytes_.Get()); + if (settings.RetentionStorageMegabytes_.has_value()) { + req.set_retention_storage_megabytes(*settings.RetentionStorageMegabytes_); } req.set_write_quota_kb_per_sec(settings.WriteQuotaKbPerSec_); - if (settings.StreamMode_.Defined()) { + if (settings.StreamMode_.has_value()) { req.mutable_stream_mode_details()->set_stream_mode( *settings.StreamMode_ == ESM_PROVISIONED ? Ydb::DataStreams::V1::StreamMode::PROVISIONED : Ydb::DataStreams::V1::StreamMode::ON_DEMAND); diff --git a/client/ydb_export/export.cpp b/client/ydb_export/export.cpp index 53f98a515e5..04f41df9048 100644 --- a/client/ydb_export/export.cpp +++ b/client/ydb_export/export.cpp @@ -150,7 +150,7 @@ TFuture TExportClient::ExportToYt(const TExportToYtSettings auto request = MakeOperationRequest(settings); request.mutable_settings()->set_host(settings.Host_); - request.mutable_settings()->set_port(settings.Port_.GetOrElse(80)); + request.mutable_settings()->set_port(settings.Port_.value_or(80)); request.mutable_settings()->set_token(settings.Token_); for (const auto& item : settings.Item_) { @@ -160,11 +160,11 @@ TFuture TExportClient::ExportToYt(const TExportToYtSettings } if (settings.Description_) { - request.mutable_settings()->set_description(settings.Description_.GetRef()); + request.mutable_settings()->set_description(settings.Description_.value()); } if (settings.NumberOfRetries_) { - request.mutable_settings()->set_number_of_retries(settings.NumberOfRetries_.GetRef()); + request.mutable_settings()->set_number_of_retries(settings.NumberOfRetries_.value()); } request.mutable_settings()->set_use_type_v3(settings.UseTypeV3_); @@ -189,11 +189,11 @@ TFuture TExportClient::ExportToS3(const TExportToS3Settings } if (settings.Description_) { - request.mutable_settings()->set_description(settings.Description_.GetRef()); + request.mutable_settings()->set_description(settings.Description_.value()); } if (settings.NumberOfRetries_) { - request.mutable_settings()->set_number_of_retries(settings.NumberOfRetries_.GetRef()); + request.mutable_settings()->set_number_of_retries(settings.NumberOfRetries_.value()); } if (settings.Compression_) { diff --git a/client/ydb_federated_topic/federated_topic.h b/client/ydb_federated_topic/federated_topic.h index 94a648bd20d..350cbcff474 100644 --- a/client/ydb_federated_topic/federated_topic.h +++ b/client/ydb_federated_topic/federated_topic.h @@ -401,11 +401,11 @@ class IFederatedReadSession { //! If maxEventsCount is not specified, //! read session chooses event batch size automatically. virtual std::vector - GetEvents(bool block = false, TMaybe maxEventsCount = Nothing(), + GetEvents(bool block = false, std::optional maxEventsCount = std::nullopt, size_t maxByteSize = std::numeric_limits::max()) = 0; //! Get single event. - virtual TMaybe + virtual std::optional GetEvent(bool block = false, size_t maxByteSize = std::numeric_limits::max()) = 0; //! Close read session. diff --git a/client/ydb_federated_topic/impl/federated_read_session.cpp b/client/ydb_federated_topic/impl/federated_read_session.cpp index 31d674af3de..ca7d5600173 100644 --- a/client/ydb_federated_topic/impl/federated_read_session.cpp +++ b/client/ydb_federated_topic/impl/federated_read_session.cpp @@ -129,7 +129,7 @@ NThreading::TFuture TFederatedReadSessionImpl::WaitEvent() { }); } -std::vector TFederatedReadSessionImpl::GetEvents(bool block, TMaybe maxEventsCount, size_t maxByteSize) { +std::vector TFederatedReadSessionImpl::GetEvents(bool block, std::optional maxEventsCount, size_t maxByteSize) { if (block) { WaitEvent().Wait(); } diff --git a/client/ydb_federated_topic/impl/federated_read_session.h b/client/ydb_federated_topic/impl/federated_read_session.h index 248a2f1df5e..e087621baba 100644 --- a/client/ydb_federated_topic/impl/federated_read_session.h +++ b/client/ydb_federated_topic/impl/federated_read_session.h @@ -33,7 +33,7 @@ class TFederatedReadSessionImpl : public NPersQueue::TEnableSelfContext WaitEvent(); - std::vector GetEvents(bool block, TMaybe maxEventsCount, size_t maxByteSize); + std::vector GetEvents(bool block, std::optional maxEventsCount, size_t maxByteSize); bool Close(TDuration timeout); @@ -104,13 +104,13 @@ class TFederatedReadSession : public IFederatedReadSession, return TryGetImpl()->WaitEvent(); } - std::vector GetEvents(bool block, TMaybe maxEventsCount, size_t maxByteSize) override { + std::vector GetEvents(bool block, std::optional maxEventsCount, size_t maxByteSize) override { return TryGetImpl()->GetEvents(block, maxEventsCount, maxByteSize); } - TMaybe GetEvent(bool block, size_t maxByteSize) override { + std::optional GetEvent(bool block, size_t maxByteSize) override { auto events = GetEvents(block, 1, maxByteSize); - return events.empty() ? Nothing() : TMaybe{std::move(events.front())}; + return events.empty() ? std::nullopt : std::optional{std::move(events.front())}; } bool Close(TDuration timeout) override { diff --git a/client/ydb_federated_topic/impl/federated_write_session.cpp b/client/ydb_federated_topic/impl/federated_write_session.cpp index 8740a673287..62702dfc43a 100644 --- a/client/ydb_federated_topic/impl/federated_write_session.cpp +++ b/client/ydb_federated_topic/impl/federated_write_session.cpp @@ -53,7 +53,7 @@ void TFederatedWriteSession::Start() { void TFederatedWriteSession::OpenSubSessionImpl(std::shared_ptr db) { if (Subsession) { - PendingToken.Clear(); + PendingToken.reset(); Subsession->Close(TDuration::Zero()); } NTopic::TTopicClientSettings clientSettings = SubClientSetttings; @@ -67,7 +67,7 @@ void TFederatedWriteSession::OpenSubSessionImpl(std::shared_ptr db) { .ReadyToAcceptHander([self = shared_from_this()](NTopic::TWriteSessionEvent::TReadyToAcceptEvent& ev){ TDeferredWrite deferred(self->Subsession); with_lock(self->Lock) { - Y_ABORT_UNLESS(self->PendingToken.Empty()); + Y_ABORT_UNLESS(!self->PendingToken.has_value()); self->PendingToken = std::move(ev.ContinuationToken); self->PrepareDeferredWrite(deferred); } @@ -198,25 +198,25 @@ NThreading::TFuture TFederatedWriteSession::WaitEvent() { return ClientEventsQueue->WaitEvent(); } -std::vector TFederatedWriteSession::GetEvents(bool block, TMaybe maxEventsCount) { +std::vector TFederatedWriteSession::GetEvents(bool block, std::optional maxEventsCount) { return ClientEventsQueue->GetEvents(block, maxEventsCount); } -TMaybe TFederatedWriteSession::GetEvent(bool block) { +std::optional TFederatedWriteSession::GetEvent(bool block) { auto events = GetEvents(block, 1); - return events.empty() ? Nothing() : TMaybe{std::move(events.front())}; + return events.empty() ? std::nullopt : std::optional{std::move(events.front())}; } NThreading::TFuture TFederatedWriteSession::GetInitSeqNo() { return NThreading::MakeFuture(0u); } -void TFederatedWriteSession::Write(NTopic::TContinuationToken&& token, std::string_view data, TMaybe seqNo, - TMaybe createTimestamp) { +void TFederatedWriteSession::Write(NTopic::TContinuationToken&& token, std::string_view data, std::optional seqNo, + std::optional createTimestamp) { NTopic::TWriteMessage message{std::move(data)}; - if (seqNo.Defined()) + if (seqNo.has_value()) message.SeqNo(*seqNo); - if (createTimestamp.Defined()) + if (createTimestamp.has_value()) message.CreateTimestamp(*createTimestamp); return WriteInternal(std::move(token), std::move(message)); } @@ -226,11 +226,11 @@ void TFederatedWriteSession::Write(NTopic::TContinuationToken&& token, NTopic::T } void TFederatedWriteSession::WriteEncoded(NTopic::TContinuationToken&& token, std::string_view data, NTopic::ECodec codec, - ui32 originalSize, TMaybe seqNo, TMaybe createTimestamp) { + ui32 originalSize, std::optional seqNo, std::optional createTimestamp) { auto message = NTopic::TWriteMessage::CompressedMessage(std::move(data), codec, originalSize); - if (seqNo.Defined()) + if (seqNo.has_value()) message.SeqNo(*seqNo); - if (createTimestamp.Defined()) + if (createTimestamp.has_value()) message.CreateTimestamp(*createTimestamp); return WriteInternal(std::move(token), std::move(message)); } @@ -241,7 +241,7 @@ void TFederatedWriteSession::WriteEncoded(NTopic::TContinuationToken&& token, NT void TFederatedWriteSession::WriteInternal(NTopic::TContinuationToken&&, NTopic::TWriteMessage&& message) { ClientHasToken = false; - if (!message.CreateTimestamp_.Defined()) { + if (!message.CreateTimestamp_.has_value()) { message.CreateTimestamp_ = TInstant::Now(); } @@ -262,17 +262,17 @@ void TFederatedWriteSession::WriteInternal(NTopic::TContinuationToken&&, NTopic: } bool TFederatedWriteSession::PrepareDeferredWrite(TDeferredWrite& deferred) { - if (PendingToken.Empty()) { + if (!PendingToken.has_value()) { return false; } if (OriginalMessagesToPassDown.empty()) { return false; } OriginalMessagesToGetAck.push_back(OriginalMessagesToPassDown.front()); - deferred.Token.ConstructInPlace(std::move(*PendingToken)); - deferred.Message.ConstructInPlace(std::move(OriginalMessagesToPassDown.front())); + deferred.Token.emplace(std::move(*PendingToken)); + deferred.Message.emplace(std::move(OriginalMessagesToPassDown.front())); OriginalMessagesToPassDown.pop_front(); - PendingToken.Clear(); + PendingToken.reset(); return true; } diff --git a/client/ydb_federated_topic/impl/federated_write_session.h b/client/ydb_federated_topic/impl/federated_write_session.h index f93e180c53e..ffc5b0faf9d 100644 --- a/client/ydb_federated_topic/impl/federated_write_session.h +++ b/client/ydb_federated_topic/impl/federated_write_session.h @@ -22,16 +22,16 @@ class TFederatedWriteSession : public NTopic::IWriteSession, } void DoWrite() { - if (Token.Empty() && Message.Empty()) { + if (!Token.has_value() && !Message.has_value()) { return; } - Y_ABORT_UNLESS(Token.Defined() && Message.Defined()); + Y_ABORT_UNLESS(Token.has_value() && Message.has_value()); return Writer->Write(std::move(*Token), std::move(*Message)); } std::shared_ptr Writer; - TMaybe Token; - TMaybe Message; + std::optional Token; + std::optional Message; }; TFederatedWriteSession(const TFederatedWriteSessionSettings& settings, @@ -42,8 +42,8 @@ class TFederatedWriteSession : public NTopic::IWriteSession, ~TFederatedWriteSession() = default; NThreading::TFuture WaitEvent() override; - TMaybe GetEvent(bool block) override; - std::vector GetEvents(bool block, TMaybe maxEventsCount) override; + std::optional GetEvent(bool block) override; + std::vector GetEvents(bool block, std::optional maxEventsCount) override; virtual NThreading::TFuture GetInitSeqNo() override; @@ -51,11 +51,11 @@ class TFederatedWriteSession : public NTopic::IWriteSession, virtual void WriteEncoded(NTopic::TContinuationToken&& continuationToken, NTopic::TWriteMessage&& params) override; - virtual void Write(NTopic::TContinuationToken&&, std::string_view, TMaybe seqNo = Nothing(), - TMaybe createTimestamp = Nothing()) override; + virtual void Write(NTopic::TContinuationToken&&, std::string_view, std::optional seqNo = std::nullopt, + std::optional createTimestamp = std::nullopt) override; virtual void WriteEncoded(NTopic::TContinuationToken&&, std::string_view, NTopic::ECodec, ui32, - TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing()) override; + std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt) override; bool Close(TDuration timeout) override; @@ -97,7 +97,7 @@ class TFederatedWriteSession : public NTopic::IWriteSession, std::shared_ptr ClientEventsQueue; - TMaybe PendingToken; // from Subsession + std::optional PendingToken; // from Subsession bool ClientHasToken = false; std::deque OriginalMessagesToPassDown; std::deque OriginalMessagesToGetAck; diff --git a/client/ydb_federated_topic/impl/federation_observer.cpp b/client/ydb_federated_topic/impl/federation_observer.cpp index b26e422d12c..f21ccd00c91 100644 --- a/client/ydb_federated_topic/impl/federation_observer.cpp +++ b/client/ydb_federated_topic/impl/federation_observer.cpp @@ -132,7 +132,7 @@ void TFederatedDbObserverImpl::OnFederationDiscovery(TStatus&& status, Ydb::Fede if (status.GetStatus() == EStatus::CLIENT_CALL_UNIMPLEMENTED) { // fall back to single db mode FederatedDbState->Status = TPlainStatus{}; // SUCCESS - auto dbState = Connections_->GetDriverState(Nothing(),Nothing(),Nothing(),Nothing(),Nothing()); + auto dbState = Connections_->GetDriverState(std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt); FederatedDbState->ControlPlaneEndpoint = dbState->DiscoveryEndpoint; // FederatedDbState->SelfLocation = ???; auto db = std::make_shared(); @@ -147,8 +147,8 @@ void TFederatedDbObserverImpl::OnFederationDiscovery(TStatus&& status, Ydb::Fede if (!FederationDiscoveryRetryState) { FederationDiscoveryRetryState = FederationDiscoveryRetryPolicy->CreateRetryState(); } - TMaybe retryDelay = FederationDiscoveryRetryState->GetNextRetryDelay(status.GetStatus()); - if (retryDelay) { + std::optional retryDelay = FederationDiscoveryRetryState->GetNextRetryDelay(status.GetStatus()); + if (retryDelay.has_value()) { ScheduleFederationDiscoveryImpl(*retryDelay); return; } diff --git a/client/ydb_federated_topic/ut/basic_usage_ut.cpp b/client/ydb_federated_topic/ut/basic_usage_ut.cpp index 680da2d5311..77115390441 100644 --- a/client/ydb_federated_topic/ut/basic_usage_ut.cpp +++ b/client/ydb_federated_topic/ut/basic_usage_ut.cpp @@ -56,7 +56,7 @@ Y_UNIT_TEST_SUITE(BasicUsage) { Cerr << "Session was created" << Endl; ReadSession->WaitEvent().Wait(TDuration::Seconds(1)); - TMaybe event = ReadSession->GetEvent(false); + std::optional event = ReadSession->GetEvent(false); Y_ASSERT(!event); auto fdsRequest = fdsMock.GetNextPendingRequest(); @@ -97,7 +97,7 @@ Y_UNIT_TEST_SUITE(BasicUsage) { for (size_t i = 0; i < partitionsCount; ++i) { ReadSession->WaitEvent().Wait(); // Get event - TMaybe event = ReadSession->GetEvent(true/*block - will block if no event received yet*/); + std::optional event = ReadSession->GetEvent(true/*block - will block if no event received yet*/); Cerr << "Got new read session event: " << DebugString(*event) << Endl; auto* startPartitionSessionEvent = std::get_if(&*event); @@ -411,7 +411,7 @@ Y_UNIT_TEST_SUITE(BasicUsage) { Cerr << "Session was created" << Endl; ReadSession->WaitEvent().Wait(TDuration::Seconds(1)); - TMaybe event = ReadSession->GetEvent(false); + std::optional event = ReadSession->GetEvent(false); Y_ASSERT(event); Cerr << "Got new read session event: " << DebugString(*event) << Endl; diff --git a/client/ydb_federated_topic/ut/fds_mock.h b/client/ydb_federated_topic/ut/fds_mock.h index b0746d14b70..1f39ab0c441 100644 --- a/client/ydb_federated_topic/ut/fds_mock.h +++ b/client/ydb_federated_topic/ut/fds_mock.h @@ -8,7 +8,7 @@ namespace NYdb::NFederatedTopic::NTests { -// ctor gets ---list of response--- tmaybe{response} +// ctor gets ---list of response--- optional{response} // ListFederationDatabases gets 1 element under lock and respond. otherwise // create 2 queues, for requests and responses // getrequest() - put request and returns> diff --git a/client/ydb_import/import.cpp b/client/ydb_import/import.cpp index 19b8c9d03ec..ba3466e8f51 100644 --- a/client/ydb_import/import.cpp +++ b/client/ydb_import/import.cpp @@ -153,11 +153,11 @@ TFuture TImportClient::ImportFromS3(const TImportFromS3Se } if (settings.Description_) { - request.mutable_settings()->set_description(settings.Description_.GetRef()); + request.mutable_settings()->set_description(settings.Description_.value()); } if (settings.NumberOfRetries_) { - request.mutable_settings()->set_number_of_retries(settings.NumberOfRetries_.GetRef()); + request.mutable_settings()->set_number_of_retries(settings.NumberOfRetries_.value()); } return Impl_->ImportFromS3(std::move(request), settings); diff --git a/client/ydb_monitoring/monitoring.cpp b/client/ydb_monitoring/monitoring.cpp index c33bdac5600..ece51698e55 100644 --- a/client/ydb_monitoring/monitoring.cpp +++ b/client/ydb_monitoring/monitoring.cpp @@ -37,15 +37,15 @@ class TMonitoringClient::TImpl : public TClientImplCommon(settings); if (settings.ReturnVerboseStatus_) { - request.set_return_verbose_status(settings.ReturnVerboseStatus_.GetRef()); + request.set_return_verbose_status(settings.ReturnVerboseStatus_.value()); } if (settings.MinimumStatus_) { - request.set_minimum_status((::Ydb::Monitoring::StatusFlag_Status)settings.MinimumStatus_.GetRef()); + request.set_minimum_status((::Ydb::Monitoring::StatusFlag_Status)settings.MinimumStatus_.value()); } if (settings.MaximumLevel_) { - request.set_maximum_level(settings.MaximumLevel_.GetRef()); + request.set_maximum_level(settings.MaximumLevel_.value()); } auto promise = NThreading::NewPromise(); diff --git a/client/ydb_params/impl.cpp b/client/ydb_params/impl.cpp index ea1016308c4..22a7aaaa2a7 100644 --- a/client/ydb_params/impl.cpp +++ b/client/ydb_params/impl.cpp @@ -26,14 +26,14 @@ std::map TParams::TImpl::GetValues() const { return valuesMap; } -TMaybe TParams::TImpl::GetValue(const std::string& name) const { +std::optional TParams::TImpl::GetValue(const std::string& name) const { auto it = ParamsMap_.find(name); if (it != ParamsMap_.end()) { auto paramType = TType(it->second.type()); return TValue(paramType, it->second.value()); } - return TMaybe(); + return std::optional(); } ::google::protobuf::Map* TParams::TImpl::GetProtoMapPtr() { diff --git a/client/ydb_params/impl.h b/client/ydb_params/impl.h index 9be96d935c1..b10fd331b48 100644 --- a/client/ydb_params/impl.h +++ b/client/ydb_params/impl.h @@ -10,7 +10,7 @@ class TParams::TImpl { bool Empty() const; std::map GetValues() const; - TMaybe GetValue(const std::string& name) const; + std::optional GetValue(const std::string& name) const; ::google::protobuf::Map* GetProtoMapPtr(); const ::google::protobuf::Map& GetProtoMap() const; diff --git a/client/ydb_params/params.cpp b/client/ydb_params/params.cpp index db8aae0b221..26b8a7522aa 100644 --- a/client/ydb_params/params.cpp +++ b/client/ydb_params/params.cpp @@ -30,7 +30,7 @@ std::map TParams::GetValues() const { return Impl_->GetValues(); } -TMaybe TParams::GetValue(const std::string& name) const { +std::optional TParams::GetValue(const std::string& name) const { return Impl_->GetValue(name); } diff --git a/client/ydb_params/params.h b/client/ydb_params/params.h index 5f626b1cd94..4a526204370 100644 --- a/client/ydb_params/params.h +++ b/client/ydb_params/params.h @@ -45,7 +45,7 @@ class TParams { bool Empty() const; std::map GetValues() const; - TMaybe GetValue(const std::string& name) const; + std::optional GetValue(const std::string& name) const; private: TParams(::google::protobuf::Map&& protoMap); diff --git a/client/ydb_persqueue_core/impl/common.h b/client/ydb_persqueue_core/impl/common.h index bfaa01184da..1d3cf2c6843 100644 --- a/client/ydb_persqueue_core/impl/common.h +++ b/client/ydb_persqueue_core/impl/common.h @@ -417,7 +417,7 @@ class TBaseSessionEventsQueue : public ISignalable { std::queue Events; std::condition_variable CondVar; std::mutex Mutex; - TMaybe CloseEvent; + std::optional CloseEvent; std::atomic Closed = false; }; diff --git a/client/ydb_persqueue_core/impl/counters_logger.h b/client/ydb_persqueue_core/impl/counters_logger.h index b50908bb26c..6c91c2f0c08 100644 --- a/client/ydb_persqueue_core/impl/counters_logger.h +++ b/client/ydb_persqueue_core/impl/counters_logger.h @@ -90,7 +90,7 @@ class TCountersLogger : public std::enable_shared_from_thisCurrentSessionLifetimeMs = (TInstant::Now() - StartSessionTime).MilliSeconds(); { - TMaybe log; + std::optional log; bool dumpHeader = true; for (auto& sessionCtx : SessionsContexts) { @@ -98,7 +98,7 @@ class TCountersLogger : public std::enable_shared_from_thisUpdateMemoryUsageStatistics(); if (dumpSessionsStatistics) { if (dumpHeader) { - log.ConstructInPlace(&Log, TLOG_INFO); + log.emplace(&Log, TLOG_INFO); (*log) << "Read/commit by partition streams (cluster:topic:partition:stream-id:read-offset:committed-offset):"; dumpHeader = false; } diff --git a/client/ydb_persqueue_core/impl/persqueue_impl.cpp b/client/ydb_persqueue_core/impl/persqueue_impl.cpp index 57bf0334a52..bc248efcbe3 100644 --- a/client/ydb_persqueue_core/impl/persqueue_impl.cpp +++ b/client/ydb_persqueue_core/impl/persqueue_impl.cpp @@ -5,7 +5,7 @@ namespace NYdb::NPersQueue { std::shared_ptr TPersQueueClient::TImpl::CreateReadSession(const TReadSessionSettings& settings) { - TMaybe maybeSettings; + std::optional maybeSettings; if (!settings.DecompressionExecutor_ || !settings.EventHandlers_.HandlersExecutor_) { maybeSettings = settings; with_lock (Lock) { @@ -17,7 +17,7 @@ std::shared_ptr TPersQueueClient::TImpl::CreateReadSession(const T } } } - auto session = std::make_shared(maybeSettings.GetOrElse(settings), shared_from_this(), Connections_, DbDriverState_); + auto session = std::make_shared(maybeSettings.value_or(settings), shared_from_this(), Connections_, DbDriverState_); session->Start(); return std::move(session); } @@ -25,7 +25,7 @@ std::shared_ptr TPersQueueClient::TImpl::CreateReadSession(const T std::shared_ptr TPersQueueClient::TImpl::CreateWriteSession( const TWriteSessionSettings& settings ) { - TMaybe maybeSettings; + std::optional maybeSettings; if (!settings.CompressionExecutor_ || !settings.EventHandlers_.HandlersExecutor_) { maybeSettings = settings; with_lock (Lock) { @@ -38,7 +38,7 @@ std::shared_ptr TPersQueueClient::TImpl::CreateWriteSession( } } auto session = std::make_shared( - maybeSettings.GetOrElse(settings), shared_from_this(), Connections_, DbDriverState_ + maybeSettings.value_or(settings), shared_from_this(), Connections_, DbDriverState_ ); session->Start(TDuration::Zero()); return std::move(session); diff --git a/client/ydb_persqueue_core/impl/persqueue_impl.h b/client/ydb_persqueue_core/impl/persqueue_impl.h index a09079a5c19..2fdbd296348 100644 --- a/client/ydb_persqueue_core/impl/persqueue_impl.h +++ b/client/ydb_persqueue_core/impl/persqueue_impl.h @@ -75,11 +75,11 @@ class TPersQueueClient::TImpl : public TClientImplCommonset_endpoint(settings.RemoteMirrorRule_.GetRef().Endpoint_); - rmr->set_topic_path(settings.RemoteMirrorRule_.GetRef().TopicPath_); - rmr->set_consumer_name(settings.RemoteMirrorRule_.GetRef().ConsumerName_); - rmr->set_starting_message_timestamp_ms(settings.RemoteMirrorRule_.GetRef().StartingMessageTimestamp_.MilliSeconds()); - const auto& credentials = settings.RemoteMirrorRule_.GetRef().Credentials_; + rmr->set_endpoint(settings.RemoteMirrorRule_.value().Endpoint_); + rmr->set_topic_path(settings.RemoteMirrorRule_.value().TopicPath_); + rmr->set_consumer_name(settings.RemoteMirrorRule_.value().ConsumerName_); + rmr->set_starting_message_timestamp_ms(settings.RemoteMirrorRule_.value().StartingMessageTimestamp_.MilliSeconds()); + const auto& credentials = settings.RemoteMirrorRule_.value().Credentials_; switch (credentials.GetMode()) { case TCredentials::EMode::OAUTH_TOKEN: { rmr->mutable_credentials()->set_oauth_token(credentials.GetOauthToken()); @@ -101,7 +101,7 @@ class TPersQueueClient::TImpl : public TClientImplCommonset_database(settings.RemoteMirrorRule_.GetRef().Database_); + rmr->set_database(settings.RemoteMirrorRule_.value().Database_); } return request; } diff --git a/client/ydb_persqueue_core/impl/read_session.cpp b/client/ydb_persqueue_core/impl/read_session.cpp index 48c5a772454..8a0ffbfb8fe 100644 --- a/client/ydb_persqueue_core/impl/read_session.cpp +++ b/client/ydb_persqueue_core/impl/read_session.cpp @@ -44,7 +44,7 @@ TReadSession::TReadSession(const TReadSessionSettings& settings, TDbDriverStatePtr dbDriverState) : Settings(settings) , SessionId(CreateGuidAsString()) - , Log(settings.Log_.GetOrElse(dbDriverState->Log)) + , Log(settings.Log_.value_or(dbDriverState->Log)) , Client(std::move(client)) , Connections(std::move(connections)) , DbDriverState(std::move(dbDriverState)) @@ -236,7 +236,7 @@ void TReadSession::OnClusterDiscovery(const TStatus& status, const Ydb::PersQueu if (!ClusterDiscoveryRetryState) { ClusterDiscoveryRetryState = Settings.RetryPolicy_->CreateRetryState(); } - TMaybe retryDelay = ClusterDiscoveryRetryState->GetNextRetryDelay(status.GetStatus()); + std::optional retryDelay = ClusterDiscoveryRetryState->GetNextRetryDelay(status.GetStatus()); if (retryDelay) { LOG_LAZY(Log, TLOG_INFO, @@ -489,7 +489,7 @@ NThreading::TFuture TReadSession::WaitEvent() { return EventsQueue->WaitEvent(); } -std::vector TReadSession::GetEvents(bool block, TMaybe maxEventsCount, size_t maxByteSize) { +std::vector TReadSession::GetEvents(bool block, std::optional maxEventsCount, size_t maxByteSize) { auto res = EventsQueue->GetEvents(block, maxEventsCount, maxByteSize); if (EventsQueue->IsClosed()) { Abort(); @@ -497,7 +497,7 @@ std::vector TReadSession::GetEvents(bool block, TMayb return res; } -TMaybe TReadSession::GetEvent(bool block, size_t maxByteSize) { +std::optional TReadSession::GetEvent(bool block, size_t maxByteSize) { auto res = EventsQueue->GetEvent(block, maxByteSize); if (EventsQueue->IsClosed()) { Abort(); @@ -565,7 +565,7 @@ TReadSessionEvent::TCreatePartitionStreamEvent::TCreatePartitionStreamEvent(TPar { } -void TReadSessionEvent::TCreatePartitionStreamEvent::Confirm(TMaybe readOffset, TMaybe commitOffset) { +void TReadSessionEvent::TCreatePartitionStreamEvent::Confirm(std::optional readOffset, std::optional commitOffset) { if (PartitionStream) { static_cast*>(PartitionStream.Get())->ConfirmCreate(readOffset, commitOffset); } diff --git a/client/ydb_persqueue_core/impl/read_session.h b/client/ydb_persqueue_core/impl/read_session.h index 16f075ef9bc..02aaaf42367 100644 --- a/client/ydb_persqueue_core/impl/read_session.h +++ b/client/ydb_persqueue_core/impl/read_session.h @@ -166,7 +166,7 @@ class TDeferredActions { std::vector::TPtr, typename IAExecutor::TFunction>> ExecutorsTasks; // Abort session. - TMaybe> SessionClosedEvent; + std::optional> SessionClosedEvent; // Waiters. std::vector Waiters; @@ -230,7 +230,7 @@ class TDataDecompressionInfo : public std::enable_shared_from_this> GetReadyThreshold() const { + std::optional> GetReadyThreshold() const { size_t readyCount = 0; std::pair ret; for (auto i = ReadyThresholds.begin(), end = ReadyThresholds.end(); i != end; ++i) { @@ -243,7 +243,7 @@ class TDataDecompressionInfo : public std::enable_shared_from_this> PartitionStream; bool HasDataEvents = false; size_t EventsCount = 0; - TMaybe Event; + std::optional Event; TCallbackContextPtr CbContext; // Close event. @@ -611,7 +611,7 @@ class TPartitionStreamImpl : public TAPartitionStream { void Commit(ui64 startOffset, ui64 endOffset) /*override*/; void RequestStatus() override; - void ConfirmCreate(TMaybe readOffset, TMaybe commitOffset); + void ConfirmCreate(std::optional readOffset, std::optional commitOffset); void ConfirmDestroy(); void StopReading() /*override*/; @@ -766,10 +766,10 @@ class TReadSessionEventsQueue: public TBaseSessionEventsQueue::TEvent> GetEvents(bool block = false, - TMaybe maxEventsCount = Nothing(), + std::optional maxEventsCount = std::nullopt, size_t maxByteSize = std::numeric_limits::max()); - TMaybe::TEvent> + std::optional::TEvent> GetEvent(bool block = false, size_t maxByteSize = std::numeric_limits::max()); @@ -960,7 +960,7 @@ class TSingleClusterReadSessionImpl : public NPersQueue::TEnableSelfContext* partitionStream, TMaybe readOffset, TMaybe commitOffset); + void ConfirmPartitionStreamCreate(const TPartitionStreamImpl* partitionStream, std::optional readOffset, std::optional commitOffset); void ConfirmPartitionStreamDestroy(TPartitionStreamImpl* partitionStream); void RequestPartitionStreamStatus(const TPartitionStreamImpl* partitionStream); void Commit(const TPartitionStreamImpl* partitionStream, ui64 startOffset, ui64 endOffset); @@ -1221,8 +1221,8 @@ class TReadSession : public IReadSession, void Start(); NThreading::TFuture WaitEvent() override; - std::vector GetEvents(bool block, TMaybe maxEventsCount, size_t maxByteSize) override; - TMaybe GetEvent(bool block, size_t maxByteSize) override; + std::vector GetEvents(bool block, std::optional maxEventsCount, size_t maxByteSize) override; + std::optional GetEvent(bool block, size_t maxByteSize) override; bool Close(TDuration timeout) override; diff --git a/client/ydb_persqueue_core/impl/read_session.ipp b/client/ydb_persqueue_core/impl/read_session.ipp index 3938a7f27a1..00eb3ed9200 100644 --- a/client/ydb_persqueue_core/impl/read_session.ipp +++ b/client/ydb_persqueue_core/impl/read_session.ipp @@ -90,7 +90,7 @@ void TPartitionStreamImpl::RequestStatus() { } template -void TPartitionStreamImpl::ConfirmCreate(TMaybe readOffset, TMaybe commitOffset) { +void TPartitionStreamImpl::ConfirmCreate(std::optional readOffset, std::optional commitOffset) { if (auto sessionShared = CbContext->LockShared()) { sessionShared->ConfirmPartitionStreamCreate(this, readOffset, commitOffset); } @@ -295,7 +295,7 @@ bool TSingleClusterReadSessionImpl::Reconnect(const TPlain RetryState = Settings.RetryPolicy_->CreateRetryState(); } if (!status.Ok()) { - TMaybe nextDelay = RetryState->GetNextRetryDelay(status.Status); + std::optional nextDelay = RetryState->GetNextRetryDelay(status.Status); if (!nextDelay) { return false; } @@ -572,7 +572,7 @@ bool TSingleClusterReadSessionImpl::IsActualPartitionStrea } template -void TSingleClusterReadSessionImpl::ConfirmPartitionStreamCreate(const TPartitionStreamImpl* partitionStream, TMaybe readOffset, TMaybe commitOffset) { +void TSingleClusterReadSessionImpl::ConfirmPartitionStreamCreate(const TPartitionStreamImpl* partitionStream, std::optional readOffset, std::optional commitOffset) { NUtils::TYdbStringBuilder commitOffsetLogStr; if (commitOffset) { commitOffsetLogStr << ". Commit offset: " << *commitOffset; @@ -1694,7 +1694,7 @@ void TSingleClusterReadSessionImpl::UpdateMemoryUsageStati template bool TSingleClusterReadSessionImpl::GetRangesMode() const { if constexpr (UseMigrationProtocol) { - return Settings.RangesMode_.GetOrElse(RangesMode); + return Settings.RangesMode_.value_or(RangesMode); } else { return true; } @@ -2012,7 +2012,7 @@ TReadSessionEventsQueue::GetEventImpl(size_t& maxByteSize, Y_ABORT("can't be here - got events in global queue, but nothing in partition queue"); } - TMaybe::TEvent> event; + std::optional::TEvent> event; auto frontCbContext = front.CbContext; if (partitionStream->TopEvent().IsDataEvent()) { event = GetDataEventImpl(partitionStream, maxByteSize, accumulator); @@ -2035,7 +2035,7 @@ TReadSessionEventsQueue::GetEventImpl(size_t& maxByteSize, template std::vector::TEvent> -TReadSessionEventsQueue::GetEvents(bool block, TMaybe maxEventsCount, size_t maxByteSize) +TReadSessionEventsQueue::GetEvents(bool block, std::optional maxEventsCount, size_t maxByteSize) { if (!maxByteSize) { ThrowFatalError("the maxByteSize value must be greater than 0"); @@ -2046,7 +2046,7 @@ TReadSessionEventsQueue::GetEvents(bool block, TMaybe accumulator; std::lock_guard guard(TParent::Mutex); - eventInfos.reserve(Min(TParent::Events.size() + TParent::CloseEvent.Defined(), maxCount)); + eventInfos.reserve(Min(TParent::Events.size() + TParent::CloseEvent.has_value(), maxCount)); do { if (block) { TParent::WaitEventsImpl(); @@ -2073,14 +2073,14 @@ TReadSessionEventsQueue::GetEvents(bool block, TMaybe -TMaybe::TEvent> +std::optional::TEvent> TReadSessionEventsQueue::GetEvent(bool block, size_t maxByteSize) { if (!maxByteSize) { ThrowFatalError("the maxByteSize value must be greater than 0"); } - TMaybe> eventInfo; + std::optional> eventInfo; TUserRetrievedEventsInfoAccumulator accumulator; std::lock_guard guard(TParent::Mutex); @@ -2101,7 +2101,7 @@ TReadSessionEventsQueue::GetEvent(bool block, size_t maxBy return std::move(eventInfo->Event); } - return Nothing(); + return std::nullopt; } template @@ -2480,7 +2480,7 @@ void TDataDecompressionEvent::TakeData(TIntrusivePtr bool TDataDecompressionInfo::HasReadyUnreadData() const { - TMaybe> threshold = GetReadyThreshold(); + std::optional> threshold = GetReadyThreshold(); if (!threshold) { return false; } diff --git a/client/ydb_persqueue_core/impl/write_session.cpp b/client/ydb_persqueue_core/impl/write_session.cpp index 7749cb6a1b4..b8a2cb5387f 100644 --- a/client/ydb_persqueue_core/impl/write_session.cpp +++ b/client/ydb_persqueue_core/impl/write_session.cpp @@ -31,11 +31,11 @@ NThreading::TFuture TWriteSession::GetInitSeqNo() { return TryGetImpl()->GetInitSeqNo(); } -TMaybe TWriteSession::GetEvent(bool block) { +std::optional TWriteSession::GetEvent(bool block) { return TryGetImpl()->EventsQueue->GetEvent(block); } -std::vector TWriteSession::GetEvents(bool block, TMaybe maxEventsCount) { +std::vector TWriteSession::GetEvents(bool block, std::optional maxEventsCount) { return TryGetImpl()->EventsQueue->GetEvents(block, maxEventsCount); } @@ -44,12 +44,12 @@ NThreading::TFuture TWriteSession::WaitEvent() { } void TWriteSession::WriteEncoded(TContinuationToken&& token, std::string_view data, ECodec codec, ui32 originalSize, - TMaybe seqNo, TMaybe createTimestamp) { + std::optional seqNo, std::optional createTimestamp) { TryGetImpl()->WriteInternal(std::move(token), data, codec, originalSize, seqNo, createTimestamp); } -void TWriteSession::Write(TContinuationToken&& token, std::string_view data, TMaybe seqNo, - TMaybe createTimestamp) { +void TWriteSession::Write(TContinuationToken&& token, std::string_view data, std::optional seqNo, + std::optional createTimestamp) { TryGetImpl()->WriteInternal(std::move(token), data, {}, 0, seqNo, createTimestamp); } @@ -96,45 +96,45 @@ ui64 TSimpleBlockingWriteSession::GetInitSeqNo() { } bool TSimpleBlockingWriteSession::Write( - std::string_view data, TMaybe seqNo, TMaybe createTimestamp, const TDuration& blockTimeout + std::string_view data, std::optional seqNo, std::optional createTimestamp, const TDuration& blockTimeout ) { auto continuationToken = WaitForToken(blockTimeout); - if (continuationToken.Defined()) { + if (continuationToken.has_value()) { Writer->Write(std::move(*continuationToken), std::move(data), seqNo, createTimestamp); return true; } return false; } -TMaybe TSimpleBlockingWriteSession::WaitForToken(const TDuration& timeout) { +std::optional TSimpleBlockingWriteSession::WaitForToken(const TDuration& timeout) { TInstant startTime = TInstant::Now(); TDuration remainingTime = timeout; - TMaybe token = Nothing(); + std::optional token = std::nullopt; while (IsAlive() && remainingTime > TDuration::Zero()) { Writer->WaitEvent().Wait(remainingTime); for (auto event : Writer->GetEvents()) { if (auto* readyEvent = std::get_if(&event)) { - Y_ABORT_UNLESS(token.Empty()); + Y_ABORT_UNLESS(!token.has_value()); token = std::move(readyEvent->ContinuationToken); } else if (auto* ackEvent = std::get_if(&event)) { // discard } else if (auto* closeSessionEvent = std::get_if(&event)) { Closed.store(true); - return Nothing(); + return std::nullopt; } } - if (token.Defined()) { + if (token.has_value()) { return token; } remainingTime = timeout - (TInstant::Now() - startTime); } - return Nothing(); + return std::nullopt; } TWriterCounters::TPtr TSimpleBlockingWriteSession::GetCounters() { diff --git a/client/ydb_persqueue_core/impl/write_session.h b/client/ydb_persqueue_core/impl/write_session.h index d3f3b35250a..19a07dfef67 100644 --- a/client/ydb_persqueue_core/impl/write_session.h +++ b/client/ydb_persqueue_core/impl/write_session.h @@ -33,16 +33,16 @@ class TWriteSession : public IWriteSession, std::shared_ptr connections, TDbDriverStatePtr dbDriverState); - TMaybe GetEvent(bool block = false) override; + std::optional GetEvent(bool block = false) override; std::vector GetEvents(bool block = false, - TMaybe maxEventsCount = Nothing()) override; + std::optional maxEventsCount = std::nullopt) override; NThreading::TFuture GetInitSeqNo() override; void Write(TContinuationToken&& continuationToken, std::string_view data, - TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing()) override; + std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt) override; void WriteEncoded(TContinuationToken&& continuationToken, std::string_view data, ECodec codec, ui32 originalSize, - TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing()) override; + std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt) override; NThreading::TFuture WaitEvent() override; @@ -77,7 +77,7 @@ class TSimpleBlockingWriteSession : public ISimpleBlockingWriteSession { std::shared_ptr connections, TDbDriverStatePtr dbDriverState); - bool Write(std::string_view data, TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing(), + bool Write(std::string_view data, std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt, const TDuration& blockTimeout = TDuration::Max()) override; ui64 GetInitSeqNo() override; @@ -91,7 +91,7 @@ class TSimpleBlockingWriteSession : public ISimpleBlockingWriteSession { std::shared_ptr Writer; private: - TMaybe WaitForToken(const TDuration& timeout); + std::optional WaitForToken(const TDuration& timeout); void HandleAck(TWriteSessionEvent::TAcksEvent&); void HandleReady(TWriteSessionEvent::TReadyToAcceptEvent&); void HandleClosed(const TSessionClosedEvent&); diff --git a/client/ydb_persqueue_core/impl/write_session_impl.cpp b/client/ydb_persqueue_core/impl/write_session_impl.cpp index 8eeab93a7b0..92cee33d4cf 100644 --- a/client/ydb_persqueue_core/impl/write_session_impl.cpp +++ b/client/ydb_persqueue_core/impl/write_session_impl.cpp @@ -53,8 +53,8 @@ TWriteSessionImpl::TWriteSessionImpl( , PrevToken(DbDriverState->CredentialsProvider ? DbDriverState->CredentialsProvider->GetAuthInfo() : "") , InitSeqNoPromise(NThreading::NewPromise()) , WakeupInterval( - Settings.BatchFlushInterval_.GetOrElse(TDuration::Zero()) ? - std::min(Settings.BatchFlushInterval_.GetOrElse(TDuration::Seconds(1)) / 5, TDuration::MilliSeconds(100)) + Settings.BatchFlushInterval_.value_or(TDuration::Zero()) ? + std::min(Settings.BatchFlushInterval_.value_or(TDuration::Seconds(1)) / 5, TDuration::MilliSeconds(100)) : TDuration::MilliSeconds(100) ) @@ -66,7 +66,7 @@ TWriteSessionImpl::TWriteSessionImpl( TargetCluster = *Settings.PreferredCluster_; NUtils::ToLower(TargetCluster); } - if (Settings.Counters_.Defined()) { + if (Settings.Counters_.has_value()) { Counters = *Settings.Counters_; } else { Counters = MakeIntrusive(new ::NMonitoring::TDynamicCounters()); @@ -120,7 +120,7 @@ TWriteSessionImpl::THandleResult TWriteSessionImpl::RestartImpl(const TPlainStat << ". Description: " << IssuesSingleLineString(status.Issues) ); SessionEstablished = false; - TMaybe nextDelay = TDuration::Zero(); + std::optional nextDelay = TDuration::Zero(); if (!RetryState) { RetryState = Settings.RetryPolicy_->CreateRetryState(); } @@ -176,9 +176,9 @@ void TWriteSessionImpl::DoCdsRequest(TDuration delay) { auto* params = req.add_write_sessions(); params->set_topic(Settings.Path_); params->set_source_id(Settings.MessageGroupId_); - if (Settings.PartitionGroupId_.Defined()) + if (Settings.PartitionGroupId_.has_value()) params->set_partition_group(*Settings.PartitionGroupId_); - if (Settings.PreferredCluster_.Defined()) + if (Settings.PreferredCluster_.has_value()) params->set_preferred_cluster_name(*Settings.PreferredCluster_); LOG_LAZY(DbDriverState->Log, TLOG_INFO, LogPrefix() << "Do schedule cds request after " << delay.MilliSeconds() << " ms\n"); @@ -291,7 +291,7 @@ void TWriteSessionImpl::InitWriter() { // No Lock, very initial start - no race // Client method NThreading::TFuture TWriteSessionImpl::GetInitSeqNo() { if (Settings.ValidateSeqNo_) { - if (AutoSeqNoMode.Defined() && *AutoSeqNoMode) { + if (AutoSeqNoMode.has_value() && *AutoSeqNoMode) { LOG_LAZY(DbDriverState->Log, TLOG_ERR, LogPrefix() << "Cannot call GetInitSeqNo in Auto SeqNo mode"); ThrowFatalError("Cannot call GetInitSeqNo in Auto SeqNo mode"); } @@ -306,36 +306,36 @@ std::string DebugString(const TWriteSessionEvent::TEvent& event) { } // Client method -TMaybe TWriteSessionImpl::GetEvent(bool block) { +std::optional TWriteSessionImpl::GetEvent(bool block) { return EventsQueue->GetEvent(block); } // Client method -std::vector TWriteSessionImpl::GetEvents(bool block, TMaybe maxEventsCount) { +std::vector TWriteSessionImpl::GetEvents(bool block, std::optional maxEventsCount) { return EventsQueue->GetEvents(block, maxEventsCount); } ui64 TWriteSessionImpl::GetIdImpl(ui64 seqNo) { - Y_ABORT_UNLESS(AutoSeqNoMode.Defined()); + Y_ABORT_UNLESS(AutoSeqNoMode.has_value()); Y_ABORT_UNLESS(!*AutoSeqNoMode || InitSeqNo.contains(CurrentCluster) && seqNo > InitSeqNo[CurrentCluster]); return *AutoSeqNoMode ? seqNo - InitSeqNo[CurrentCluster] : seqNo; } ui64 TWriteSessionImpl::GetSeqNoImpl(ui64 id) { - Y_ABORT_UNLESS(AutoSeqNoMode.Defined()); + Y_ABORT_UNLESS(AutoSeqNoMode.has_value()); return *AutoSeqNoMode ? id + InitSeqNo[CurrentCluster] : id; } -ui64 TWriteSessionImpl::GetNextIdImpl(const TMaybe& seqNo) { +ui64 TWriteSessionImpl::GetNextIdImpl(const std::optional& seqNo) { Y_ABORT_UNLESS(Lock.IsLocked()); ui64 id = ++NextId; - if (!AutoSeqNoMode.Defined()) { - AutoSeqNoMode = !seqNo.Defined(); + if (!AutoSeqNoMode.has_value()) { + AutoSeqNoMode = !seqNo.has_value(); } - if (seqNo.Defined()) { + if (seqNo.has_value()) { if (*AutoSeqNoMode) { LOG_LAZY(DbDriverState->Log, TLOG_ERR, @@ -380,9 +380,9 @@ NThreading::TFuture TWriteSessionImpl::WaitEvent() { // Client method. void TWriteSessionImpl::WriteInternal( - TContinuationToken&&, std::string_view data, TMaybe codec, ui32 originalSize, TMaybe seqNo, TMaybe createTimestamp + TContinuationToken&&, std::string_view data, std::optional codec, ui32 originalSize, std::optional seqNo, std::optional createTimestamp ) { - TInstant createdAtValue = createTimestamp.Defined() ? *createTimestamp : TInstant::Now(); + TInstant createdAtValue = createTimestamp.value_or(TInstant::Now()); bool readyToAccept = false; size_t bufferSize = data.size(); with_lock(Lock) { @@ -398,13 +398,13 @@ void TWriteSessionImpl::WriteInternal( // Client method. void TWriteSessionImpl::WriteEncoded( - TContinuationToken&& token, std::string_view data, ECodec codec, ui32 originalSize, TMaybe seqNo, TMaybe createTimestamp + TContinuationToken&& token, std::string_view data, ECodec codec, ui32 originalSize, std::optional seqNo, std::optional createTimestamp ) { WriteInternal(std::move(token), data, codec, originalSize, seqNo, createTimestamp); } void TWriteSessionImpl::Write( - TContinuationToken&& token, std::string_view data, TMaybe seqNo, TMaybe createTimestamp + TContinuationToken&& token, std::string_view data, std::optional seqNo, std::optional createTimestamp ) { WriteInternal(std::move(token), data, {}, 0, seqNo, createTimestamp); } @@ -670,7 +670,7 @@ void TWriteSessionImpl::OnReadDone(NYdbGrpc::TGrpcStatus&& grpcStatus, size_t co errorStatus = MakeErrorFromProto(*ServerMessage); } else { processResult = ProcessServerMessageImpl(); - needSetValue = !InitSeqNoSetDone && processResult.InitSeqNo.Defined() && (InitSeqNoSetDone = true); + needSetValue = !InitSeqNoSetDone && processResult.InitSeqNo.has_value() && (InitSeqNoSetDone = true); if (errorStatus.Ok() && processResult.Ok) { doRead = true; } @@ -997,8 +997,8 @@ void TWriteSessionImpl::FlushWriteIfRequiredImpl() { if (!CurrentBatch.Empty() && !CurrentBatch.FlushRequested) { MessagesAcquired += static_cast(CurrentBatch.Acquire()); - if (TInstant::Now() - CurrentBatch.StartedAt >= Settings.BatchFlushInterval_.GetOrElse(TDuration::Zero()) - || CurrentBatch.CurrentSize >= Settings.BatchFlushSizeBytes_.GetOrElse(0) + if (TInstant::Now() - CurrentBatch.StartedAt >= Settings.BatchFlushInterval_.value_or(TDuration::Zero()) + || CurrentBatch.CurrentSize >= Settings.BatchFlushSizeBytes_.value_or(0) || CurrentBatch.CurrentSize >= MaxBlockSize || CurrentBatch.Messages.size() >= MaxBlockMessageCount || CurrentBatch.HasCodec() @@ -1041,7 +1041,7 @@ size_t TWriteSessionImpl::WriteBatchImpl() { block.OriginalSize += datum.size(); block.OriginalMemoryUsage = CurrentBatch.Data.size(); block.OriginalDataRefs.emplace_back(datum); - if (CurrentBatch.Messages[i].Codec.Defined()) { + if (CurrentBatch.Messages[i].Codec.has_value()) { Y_ABORT_UNLESS(CurrentBatch.Messages.size() == 1); block.CodecID = GetCodecId(*CurrentBatch.Messages[i].Codec); block.OriginalSize = CurrentBatch.Messages[i].OriginalSize; diff --git a/client/ydb_persqueue_core/impl/write_session_impl.h b/client/ydb_persqueue_core/impl/write_session_impl.h index 5fce7da8596..bf9107183c5 100644 --- a/client/ydb_persqueue_core/impl/write_session_impl.h +++ b/client/ydb_persqueue_core/impl/write_session_impl.h @@ -46,8 +46,8 @@ class TWriteSessionEventsQueue: public TBaseSessionEventsQueue GetEvent(bool block = false) { - TMaybe eventInfo; + std::optional GetEvent(bool block = false) { + std::optional eventInfo; { std::lock_guard guard(Mutex); if (block) { @@ -56,28 +56,28 @@ class TWriteSessionEventsQueue: public TBaseSessionEventsQueueOnUserRetrievedEvent(); return std::move(eventInfo->Event); } - std::vector GetEvents(bool block = false, TMaybe maxEventsCount = Nothing()) { + std::vector GetEvents(bool block = false, std::optional maxEventsCount = std::nullopt) { std::vector eventInfos; { std::lock_guard guard(Mutex); if (block) { WaitEventsImpl(); } - eventInfos.reserve(Min(Events.size() + CloseEvent.Defined(), maxEventsCount ? *maxEventsCount : std::numeric_limits::max())); + eventInfos.reserve(Min(Events.size() + CloseEvent.has_value(), maxEventsCount.value_or(std::numeric_limits::max()))); while (!Events.empty()) { eventInfos.emplace_back(GetEventImpl()); - if (maxEventsCount && eventInfos.size() >= *maxEventsCount) { + if (maxEventsCount.has_value() && eventInfos.size() >= *maxEventsCount) { break; } } - if (CloseEvent && Events.empty() && (!maxEventsCount || eventInfos.size() < *maxEventsCount)) { + if (CloseEvent && Events.empty() && (!maxEventsCount.has_value() || eventInfos.size() < *maxEventsCount)) { eventInfos.push_back({*CloseEvent}); } } @@ -181,9 +181,9 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, ui64 Id; TInstant CreatedAt; std::string_view DataRef; - TMaybe Codec; + std::optional Codec; ui32 OriginalSize; // only for coded messages - TMessage(ui64 id, const TInstant& createdAt, std::string_view data, TMaybe codec = {}, ui32 originalSize = 0) + TMessage(ui64 id, const TInstant& createdAt, std::string_view data, std::optional codec = {}, ui32 originalSize = 0) : Id(id) , CreatedAt(createdAt) , DataRef(data) @@ -199,7 +199,7 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, TInstant StartedAt = TInstant::Zero(); bool Acquired = false; bool FlushRequested = false; - void Add(ui64 id, const TInstant& createdAt, std::string_view data, TMaybe codec, ui32 originalSize) { + void Add(ui64 id, const TInstant& createdAt, std::string_view data, std::optional codec, ui32 originalSize) { if (StartedAt == TInstant::Zero()) StartedAt = TInstant::Now(); CurrentSize += codec ? originalSize : data.size(); @@ -208,7 +208,7 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, } bool HasCodec() const { - return Messages.empty() ? false : Messages.front().Codec.Defined(); + return Messages.empty() ? false : Messages.front().Codec.has_value(); } bool Acquire() { @@ -294,7 +294,7 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, }; struct TProcessSrvMessageResult { THandleResult HandleResult; - TMaybe InitSeqNo; + std::optional InitSeqNo; std::vector Events; bool Ok = true; }; @@ -307,16 +307,16 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, std::shared_ptr connections, TDbDriverStatePtr dbDriverState); - TMaybe GetEvent(bool block = false); + std::optional GetEvent(bool block = false); std::vector GetEvents(bool block = false, - TMaybe maxEventsCount = Nothing()); + std::optional maxEventsCount = std::nullopt); NThreading::TFuture GetInitSeqNo(); void Write(TContinuationToken&& continuationToken, std::string_view data, - TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing()); + std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt); void WriteEncoded(TContinuationToken&& continuationToken, std::string_view data, ECodec codec, ui32 originalSize, - TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing()); + std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt); NThreading::TFuture WaitEvent(); @@ -338,8 +338,8 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, void UpdateTokenIfNeededImpl(); - void WriteInternal(TContinuationToken&& continuationToken, std::string_view data, TMaybe codec, ui32 originalSize, - TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing()); + void WriteInternal(TContinuationToken&& continuationToken, std::string_view data, std::optional codec, ui32 originalSize, + std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt); void FlushWriteIfRequiredImpl(); size_t WriteBatchImpl(); @@ -370,7 +370,7 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, bool CleanupOnAcknowledged(ui64 id); bool IsReadyToSendNextImpl(); void DumpState(); - ui64 GetNextIdImpl(const TMaybe& seqNo); + ui64 GetNextIdImpl(const std::optional& seqNo); ui64 GetSeqNoImpl(ui64 id); ui64 GetIdImpl(ui64 seqNo); void SendImpl(); @@ -436,7 +436,7 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, ui64 NextId = 0; ui64 MinUnsentId = 1; std::map InitSeqNo; - TMaybe AutoSeqNoMode; + std::optional AutoSeqNoMode; bool ValidateSeqNoMode = false; NThreading::TPromise InitSeqNoPromise; diff --git a/client/ydb_persqueue_core/persqueue.h b/client/ydb_persqueue_core/persqueue.h index fdec3ed2c0c..83f4c56ea57 100644 --- a/client/ydb_persqueue_core/persqueue.h +++ b/client/ydb_persqueue_core/persqueue.h @@ -10,7 +10,6 @@ #include #include -#include #include #include #include @@ -123,15 +122,15 @@ struct TDescribeTopicResult : public TStatus { // attributes GETTER(bool, AllowUnauthenticatedWrite); GETTER(bool, AllowUnauthenticatedRead); - GETTER(TMaybe, PartitionsPerTablet); - GETTER(TMaybe, AbcId); - GETTER(TMaybe, AbcSlug); - GETTER(TMaybe, FederationAccount); + GETTER(std::optional, PartitionsPerTablet); + GETTER(std::optional, AbcId); + GETTER(std::optional, AbcSlug); + GETTER(std::optional, FederationAccount); const std::vector& ReadRules() const { return ReadRules_; } - GETTER(TMaybe, RemoteMirrorRule); + GETTER(std::optional, RemoteMirrorRule); #undef GETTER @@ -146,13 +145,13 @@ struct TDescribeTopicResult : public TStatus { ui64 MaxPartitionWriteBurst_; bool ClientWriteDisabled_; std::vector ReadRules_; - TMaybe RemoteMirrorRule_; + std::optional RemoteMirrorRule_; // attributes bool AllowUnauthenticatedRead_; bool AllowUnauthenticatedWrite_; - TMaybe PartitionsPerTablet_; - TMaybe AbcId_; - TMaybe AbcSlug_; + std::optional PartitionsPerTablet_; + std::optional AbcId_; + std::optional AbcSlug_; std::string FederationAccount_; }; @@ -280,7 +279,7 @@ struct TTopicSettings : public TOperationRequestSettings { ReadRules_.back().SetSettings(readRule); } if (settings.RemoteMirrorRule()) { - RemoteMirrorRule_ = TRemoteMirrorRuleSettings().SetSettings(settings.RemoteMirrorRule().GetRef()); + RemoteMirrorRule_ = TRemoteMirrorRuleSettings().SetSettings(settings.RemoteMirrorRule().value()); } return static_cast(*this); } @@ -769,7 +768,7 @@ struct TReadSessionEvent { //! Confirm partition stream creation. //! This signals that user is ready to receive data from this partition stream. //! If maybe is empty then no rewinding - void Confirm(TMaybe readOffset = Nothing(), TMaybe commitOffset = Nothing()); + void Confirm(std::optional readOffset = std::nullopt, std::optional commitOffset = std::nullopt); std::string DebugString() const; @@ -1008,7 +1007,7 @@ struct TWriteSessionEvent { ui64 SeqNo; EEventState State; //! Filled only for EES_WRITTEN. Empty for ALREADY and DISCARDED. - TMaybe Details; + std::optional Details; //! Write stats from server. See TWriteStat. nullptr for DISCARDED event. TWriteStat::TPtr Stat; @@ -1367,7 +1366,7 @@ class ISimpleBlockingWriteSession : public TThrRefBase { //! Write single message. Blocks for up to blockTimeout if inflight is full or memoryUsage is exceeded; //! return - true if write succeeded, false if message was not enqueued for write within blockTimeout. //! no Ack is provided. - virtual bool Write(std::string_view data, TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing(), + virtual bool Write(std::string_view data, std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt, const TDuration& blockTimeout = TDuration::Max()) = 0; //! Blocks till SeqNo is discovered from server. Returns 0 in case of failure on init. @@ -1395,25 +1394,25 @@ class IWriteSession { virtual NThreading::TFuture WaitEvent() = 0; //! Wait and return next event. Use WaitEvent() for non-blocking wait. - virtual TMaybe GetEvent(bool block = false) = 0; + virtual std::optional GetEvent(bool block = false) = 0; //! Get several events in one call. //! If blocking = false, instantly returns up to maxEventsCount available events. //! If blocking = true, blocks till maxEventsCount events are available. //! If maxEventsCount is unset, write session decides the count to return itself. - virtual std::vector GetEvents(bool block = false, TMaybe maxEventsCount = Nothing()) = 0; + virtual std::vector GetEvents(bool block = false, std::optional maxEventsCount = std::nullopt) = 0; //! Future that is set when initial SeqNo is available. virtual NThreading::TFuture GetInitSeqNo() = 0; //! Write single message. //! continuationToken - a token earlier provided to client with ReadyToAccept event. - virtual void Write(TContinuationToken&& continuationToken, std::string_view data, TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing()) = 0; + virtual void Write(TContinuationToken&& continuationToken, std::string_view data, std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt) = 0; //! Write single message that is already coded by codec. Codec from settings does not apply to this message. //! continuationToken - a token earlier provided to client with ReadyToAccept event. //! originalSize - size of unpacked message - virtual void WriteEncoded(TContinuationToken&& continuationToken, std::string_view data, ECodec codec, ui32 originalSize, TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing()) = 0; + virtual void WriteEncoded(TContinuationToken&& continuationToken, std::string_view data, ECodec codec, ui32 originalSize, std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt) = 0; //! Wait for all writes to complete (no more that closeTimeout()), than close. Empty maybe - means infinite timeout. @@ -1443,10 +1442,10 @@ class IReadSession { //! //! If maxEventsCount is not specified, //! read session chooses event batch size automatically. - virtual std::vector GetEvents(bool block = false, TMaybe maxEventsCount = Nothing(), size_t maxByteSize = std::numeric_limits::max()) = 0; + virtual std::vector GetEvents(bool block = false, std::optional maxEventsCount = std::nullopt, size_t maxByteSize = std::numeric_limits::max()) = 0; //! Get single event. - virtual TMaybe GetEvent(bool block = false, size_t maxByteSize = std::numeric_limits::max()) = 0; + virtual std::optional GetEvent(bool block = false, size_t maxByteSize = std::numeric_limits::max()) = 0; //! Add topic to session, in other words, start reading new topic. // virtual void AddTopic(const TTopicReadSettings& topicReadSettings) = 0; // Not implemented yet. diff --git a/client/ydb_persqueue_core/ut/basic_usage_ut.cpp b/client/ydb_persqueue_core/ut/basic_usage_ut.cpp index f6f7d2e1c99..1aab1f1175b 100644 --- a/client/ydb_persqueue_core/ut/basic_usage_ut.cpp +++ b/client/ydb_persqueue_core/ut/basic_usage_ut.cpp @@ -64,7 +64,7 @@ Y_UNIT_TEST_SUITE(BasicUsage) { // AssertStreamingMessageCase(TReadResponse::kInit, isStarted.Response); ui32 readMessageCount = 0; - TMaybe committedOffset; + std::optional committedOffset; ui32 previousOffset = 0; bool closed = false; while ((readMessageCount < messageCount || committedOffset <= previousOffset) && !closed) { @@ -131,7 +131,7 @@ Y_UNIT_TEST_SUITE(BasicUsage) { void SimpleWriteAndValidateData( TPersQueueYdbSdkTestSetup* setup, TWriteSessionSettings& writeSettings, ui64 count, - TMaybe shouldCaptureData = Nothing() + std::optional shouldCaptureData = std::nullopt ) { std::shared_ptr readSession; @@ -148,7 +148,7 @@ Y_UNIT_TEST_SUITE(BasicUsage) { { auto sessionAdapter = TSimpleWriteSessionTestAdapter( dynamic_cast(session.get())); - if (shouldCaptureData.Defined()) { + if (shouldCaptureData.has_value()) { TYdbStringBuilder msg; msg << "Session has captured " << sessionAdapter.GetAcquiredMessagesCount() << " messages, capturing was expected: " << *shouldCaptureData << Endl; diff --git a/client/ydb_persqueue_core/ut/compress_executor_ut.cpp b/client/ydb_persqueue_core/ut/compress_executor_ut.cpp index 76509ac4723..da4bcde9c72 100644 --- a/client/ydb_persqueue_core/ut/compress_executor_ut.cpp +++ b/client/ydb_persqueue_core/ut/compress_executor_ut.cpp @@ -37,7 +37,7 @@ Y_UNIT_TEST_SUITE(CompressExecutor) { auto writer = setup->GetPersQueueClient().CreateWriteSession(config); - TMaybe continueToken; + std::optional continueToken; auto event = *writer->GetEvent(true); UNIT_ASSERT(std::holds_alternative(event)); continueToken = std::move(std::get(event).ContinuationToken); diff --git a/client/ydb_persqueue_core/ut/read_session_ut.cpp b/client/ydb_persqueue_core/ut/read_session_ut.cpp index 9b27f208fdf..8e2add87ccd 100644 --- a/client/ydb_persqueue_core/ut/read_session_ut.cpp +++ b/client/ydb_persqueue_core/ut/read_session_ut.cpp @@ -657,7 +657,7 @@ void TReadSessionImplTestSetup::SuccessfulInit(bool hasInitRequest) { TPartitionStream::TPtr TReadSessionImplTestSetup::CreatePartitionStream(const std::string& topic, const std::string& cluster, ui64 partition, ui64 assignId) { MockProcessor->AddServerResponse(TMockReadSessionProcessor::TServerReadInfo().CreatePartitionStream(topic, cluster, partition, assignId)); // Callback will be called. - TMaybe event = EventsQueue->GetEvent(true); + std::optional event = EventsQueue->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TCreatePartitionStreamEvent); auto& createEvent = std::get(*event); @@ -668,7 +668,7 @@ TPartitionStream::TPtr TReadSessionImplTestSetup::CreatePartitionStream(const st } void TReadSessionImplTestSetup::AssertNoEvents() { - TMaybe event = GetEventsQueue()->GetEvent(false); + std::optional event = GetEventsQueue()->GetEvent(false); UNIT_ASSERT(!event); } @@ -686,7 +686,7 @@ Y_UNIT_TEST_SUITE(PersQueueSdkReadSessionTest) { TDeferredCommit dc; // Event 1: create partition stream. { - TMaybe event = session->GetEvent(true); + std::optional event = session->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TCreatePartitionStreamEvent); std::get(*event).Confirm(); @@ -694,7 +694,7 @@ Y_UNIT_TEST_SUITE(PersQueueSdkReadSessionTest) { } // Event 2: data. { - TMaybe event = session->GetEvent(true); + std::optional event = session->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TDataReceivedEvent); TReadSessionEvent::TDataReceivedEvent& dataEvent = std::get(*event); @@ -710,7 +710,7 @@ Y_UNIT_TEST_SUITE(PersQueueSdkReadSessionTest) { setup.WriteToTopic({"message3"}); // Event 3: data. { - TMaybe event = session->GetEvent(true); + std::optional event = session->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TDataReceivedEvent); TReadSessionEvent::TDataReceivedEvent& dataEvent = std::get(*event); @@ -731,14 +731,14 @@ Y_UNIT_TEST_SUITE(PersQueueSdkReadSessionTest) { // Event 4: commit ack. if (commit) { // (commit && close) branch check is broken with current TReadSession::Close quick fix - TMaybe event = session->GetEvent(!close); // Event is expected to be already in queue if closed. + std::optional event = session->GetEvent(!close); // Event is expected to be already in queue if closed. UNIT_ASSERT(event); Cerr << "commit ack or close event " << DebugString(*event) << Endl; UNIT_ASSERT(std::holds_alternative(*event) || std::holds_alternative(*event)); } if (close && !commit) { - TMaybe event = session->GetEvent(false); + std::optional event = session->GetEvent(false); UNIT_ASSERT(event); Cerr << "close event " << DebugString(*event) << Endl; UNIT_ASSERT(std::holds_alternative(*event)); @@ -770,7 +770,7 @@ Y_UNIT_TEST_SUITE(PersQueueSdkReadSessionTest) { std::shared_ptr session = \ setup.GetPersQueueClient().CreateReadSession(settings); \ session->WaitEvent().Wait(); \ - TMaybe event = \ + std::optional event = \ session->GetEvent(true); \ UNIT_ASSERT(event); \ Cerr << DebugString(*event) << Endl; \ @@ -807,7 +807,7 @@ Y_UNIT_TEST_SUITE(PersQueueSdkReadSessionTest) { // Set policy with max retries == 3. settings.RetryPolicy(NYdb::NPersQueue::IRetryPolicy::GetExponentialBackoffPolicy(TDuration::MilliSeconds(10), TDuration::MilliSeconds(10), TDuration::MilliSeconds(100), 3)); std::shared_ptr session = setup.GetPersQueueClient().CreateReadSession(settings); - TMaybe event = session->GetEvent(true); + std::optional event = session->GetEvent(true); UNIT_ASSERT(event); Cerr << DebugString(*event) << Endl; UNIT_ASSERT_EVENT_TYPE(*event, TSessionClosedEvent); @@ -822,7 +822,7 @@ Y_UNIT_TEST_SUITE(PersQueueSdkReadSessionTest) { // Success. { std::shared_ptr session = setup.GetPersQueueClient().CreateReadSession(settings); - TMaybe event = session->GetEvent(true); + std::optional event = session->GetEvent(true); UNIT_ASSERT(event); Cerr << DebugString(*event) << Endl; UNIT_ASSERT_NOT_EVENT_TYPE(*event, TSessionClosedEvent); @@ -832,7 +832,7 @@ Y_UNIT_TEST_SUITE(PersQueueSdkReadSessionTest) { { settings.AppendClusters("unknown_cluster"); std::shared_ptr session = setup.GetPersQueueClient().CreateReadSession(settings); - TMaybe event = session->GetEvent(true); + std::optional event = session->GetEvent(true); UNIT_ASSERT(event); Cerr << DebugString(*event) << Endl; UNIT_ASSERT_EVENT_TYPE(*event, TSessionClosedEvent); @@ -842,7 +842,7 @@ Y_UNIT_TEST_SUITE(PersQueueSdkReadSessionTest) { { settings.ReadOriginal({"unknown_cluster"}); std::shared_ptr session = setup.GetPersQueueClient().CreateReadSession(settings); - TMaybe event = session->GetEvent(true); + std::optional event = session->GetEvent(true); UNIT_ASSERT(event); Cerr << DebugString(*event) << Endl; UNIT_ASSERT_EVENT_TYPE(*event, TSessionClosedEvent); @@ -856,7 +856,7 @@ Y_UNIT_TEST_SUITE(PersQueueSdkReadSessionTest) { // Event 1: create partition stream. { - TMaybe event = session->GetEvent(true); + std::optional event = session->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TCreatePartitionStreamEvent); std::get(*event).Confirm(); @@ -864,8 +864,8 @@ Y_UNIT_TEST_SUITE(PersQueueSdkReadSessionTest) { } // Event 2: receive data. - auto GetDataEvent = [&](const std::string& content) -> TMaybe { - TMaybe event = session->GetEvent(true); + auto GetDataEvent = [&](const std::string& content) -> std::optional { + std::optional event = session->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TDataReceivedEvent); TReadSessionEvent::TDataReceivedEvent& dataEvent = std::get(*event); @@ -875,7 +875,7 @@ Y_UNIT_TEST_SUITE(PersQueueSdkReadSessionTest) { return event; }; - TMaybe dataEvents[2]; + std::optional dataEvents[2]; dataEvents[0] = GetDataEvent("message1"); @@ -894,7 +894,7 @@ Y_UNIT_TEST_SUITE(PersQueueSdkReadSessionTest) { // Commit and check that other events will come. for (int i = 0; i < 2; ++i) { std::get(*dataEvents[i]).Commit(); - TMaybe event = session->GetEvent(true); + std::optional event = session->GetEvent(true); UNIT_ASSERT(event); Y_ASSERT(std::holds_alternative(*event)); Cerr << DebugString(*event) << Endl; @@ -1038,7 +1038,7 @@ Y_UNIT_TEST_SUITE(ReadSessionImplTest) { class TTestRetryState : public NYdb::NPersQueue::IRetryPolicy::IRetryState { TDuration Delay; - TMaybe GetNextRetryDelay(NYdb::EStatus) override { + std::optional GetNextRetryDelay(NYdb::EStatus) override { Delay += TDuration::Seconds(1); return Delay; } @@ -1141,7 +1141,7 @@ Y_UNIT_TEST_SUITE(ReadSessionImplTest) { // Check destroy event. if (!forceful) { - TMaybe event = setup.EventsQueue->GetEvent(true); + std::optional event = setup.EventsQueue->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TDestroyPartitionStreamEvent); auto& destroyEvent = std::get(*event); @@ -1160,7 +1160,7 @@ Y_UNIT_TEST_SUITE(ReadSessionImplTest) { // Check closed event. { - TMaybe event = setup.EventsQueue->GetEvent(true); + std::optional event = setup.EventsQueue->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TPartitionStreamClosedEvent); auto& closedEvent = std::get(*event); @@ -1195,7 +1195,7 @@ Y_UNIT_TEST_SUITE(ReadSessionImplTest) { } for (ui64 i = 1; i <= 2; ) { - TMaybe event = setup.EventsQueue->GetEvent(true); + std::optional event = setup.EventsQueue->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TDataReceivedEvent); auto& dataEvent = std::get(*event); @@ -1221,7 +1221,7 @@ Y_UNIT_TEST_SUITE(ReadSessionImplTest) { // Exception was passed during decompression. { - TMaybe event = setup.EventsQueue->GetEvent(true); + std::optional event = setup.EventsQueue->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TDataReceivedEvent); auto& dataEvent = std::get(*event); @@ -1249,7 +1249,7 @@ Y_UNIT_TEST_SUITE(ReadSessionImplTest) { .Batch("src_id") .CompressMessage(1, data, codec)); - TMaybe event = setup.EventsQueue->GetEvent(true); + std::optional event = setup.EventsQueue->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TDataReceivedEvent); auto& dataEvent = std::get(*event); @@ -1355,7 +1355,7 @@ Y_UNIT_TEST_SUITE(ReadSessionImplTest) { ui64 prevSeqNo = 41; for (size_t i = 0; i < batches; ++i) { Cerr << "Getting new event" << Endl; - TMaybe event = setup.EventsQueue->GetEvent(true, batchLimit); + std::optional event = setup.EventsQueue->GetEvent(true, batchLimit); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TDataReceivedEvent); Cerr << DebugString(*event) << Endl; @@ -1535,7 +1535,7 @@ Y_UNIT_TEST_SUITE(ReadSessionImplTest) { stream->RequestStatus(); - TMaybe event = setup.EventsQueue->GetEvent(true); + std::optional event = setup.EventsQueue->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TPartitionStreamStatusEvent); auto& statusEvent = std::get(*event); @@ -1586,7 +1586,7 @@ Y_UNIT_TEST_SUITE(ReadSessionImplTest) { })); for (int i = 0; i < 2; ) { - TMaybe event = setup.EventsQueue->GetEvent(true); + std::optional event = setup.EventsQueue->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TDataReceivedEvent); TReadSessionEvent::TDataReceivedEvent& dataEvent = std::get(*event); @@ -1611,7 +1611,7 @@ Y_UNIT_TEST_SUITE(ReadSessionImplTest) { .Batch("src_id") .CompressMessage(1, "message1")); - TMaybe event = setup.EventsQueue->GetEvent(true); + std::optional event = setup.EventsQueue->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TDataReceivedEvent); TReadSessionEvent::TDataReceivedEvent& dataEvent = std::get(*event); @@ -1688,7 +1688,7 @@ Y_UNIT_TEST_SUITE(ReadSessionImplTest) { setup.MockProcessor->AddServerResponse(TMockReadSessionProcessor::TServerReadInfo() .ForcefulReleasePartitionStream()); - TMaybe event = setup.EventsQueue->GetEvent(true); + std::optional event = setup.EventsQueue->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TPartitionStreamClosedEvent); calledPromise.GetFuture().Wait(); @@ -1719,7 +1719,7 @@ Y_UNIT_TEST_SUITE(ReadSessionImplTest) { .Batch("src_id") .CompressMessage(1, "message1")); - TMaybe event = setup.EventsQueue->GetEvent(true); + std::optional event = setup.EventsQueue->GetEvent(true); UNIT_ASSERT(event); UNIT_ASSERT_EVENT_TYPE(*event, TReadSessionEvent::TDataReceivedEvent); @@ -1771,7 +1771,7 @@ Y_UNIT_TEST_SUITE(ReadSessionImplTest) { TReadSessionImplTestSetup setup; auto dataReceived = std::make_shared>(NThreading::NewPromise()); auto dataReceivedFuture = dataReceived->GetFuture(); - std::shared_ptr> dataReceivedEvent = std::make_shared>(); + std::shared_ptr> dataReceivedEvent = std::make_shared>(); setup.Settings.EventHandlers_.SimpleDataHandlers([dataReceivedEvent,dataReceived](TReadSessionEvent::TDataReceivedEvent& event) mutable { *dataReceivedEvent = std::move(event); dataReceived->SetValue(); diff --git a/client/ydb_persqueue_core/ut/ut_utils/data_plane_helpers.cpp b/client/ydb_persqueue_core/ut/ut_utils/data_plane_helpers.cpp index 216dd3004fe..fbd006e928f 100644 --- a/client/ydb_persqueue_core/ut/ut_utils/data_plane_helpers.cpp +++ b/client/ydb_persqueue_core/ut/ut_utils/data_plane_helpers.cpp @@ -79,12 +79,12 @@ namespace NKikimr::NPersQueueTests { return TPersQueueClient(driver, clientSettings).CreateReadSession(TReadSessionSettings(settings).DisableClusterDiscovery(true)); } - TMaybe GetNextMessageSkipAssignment(std::shared_ptr& reader, TDuration timeout) { + std::optional GetNextMessageSkipAssignment(std::shared_ptr& reader, TDuration timeout) { while (true) { auto future = reader->WaitEvent(); future.Wait(timeout); - TMaybe event = reader->GetEvent(false, 1); + std::optional event = reader->GetEvent(false, 1); if (!event) return {}; if (auto dataEvent = std::get_if(&*event)) { diff --git a/client/ydb_persqueue_core/ut/ut_utils/data_plane_helpers.h b/client/ydb_persqueue_core/ut/ut_utils/data_plane_helpers.h index 471e47b5f45..24c4b2b625e 100644 --- a/client/ydb_persqueue_core/ut/ut_utils/data_plane_helpers.h +++ b/client/ydb_persqueue_core/ut/ut_utils/data_plane_helpers.h @@ -44,6 +44,6 @@ namespace NKikimr::NPersQueueTests { ); - TMaybe GetNextMessageSkipAssignment(std::shared_ptr& reader, TDuration timeout = TDuration::Max()); + std::optional GetNextMessageSkipAssignment(std::shared_ptr& reader, TDuration timeout = TDuration::Max()); } diff --git a/client/ydb_persqueue_core/ut/ut_utils/test_server.h b/client/ydb_persqueue_core/ut/ut_utils/test_server.h index edeadae0fa4..f42cfc6945c 100644 --- a/client/ydb_persqueue_core/ut/ut_utils/test_server.h +++ b/client/ydb_persqueue_core/ut/ut_utils/test_server.h @@ -19,7 +19,7 @@ class TTestServer { bool start = true, const std::vector& logServices = TTestServer::LOGGED_SERVICES, NActors::NLog::EPriority logPriority = NActors::NLog::PRI_DEBUG, - TMaybe> portManager = Nothing()) + std::optional> portManager = std::nullopt) : PortManager(portManager.GetOrElse(MakeSimpleShared())) , Port(PortManager->GetPort(2134)) , GrpcPort(PortManager->GetPort(2135)) @@ -44,7 +44,7 @@ class TTestServer { { } - void StartServer(bool doClientInit = true, TMaybe databaseName = Nothing()) { + void StartServer(bool doClientInit = true, std::optional databaseName = std::nullopt) { Log.SetFormatter([](ELogPriority priority, std::string_view message) { return TYdbStringBuilder() << TInstant::Now() << " " << priority << ": " << message << Endl; }); diff --git a/client/ydb_persqueue_core/ut/ut_utils/ut_utils.h b/client/ydb_persqueue_core/ut/ut_utils/ut_utils.h index 691c7d48715..31f33d9dffd 100644 --- a/client/ydb_persqueue_core/ut/ut_utils/ut_utils.h +++ b/client/ydb_persqueue_core/ut/ut_utils/ut_utils.h @@ -106,7 +106,7 @@ struct TYDBClientEventLoop : public ::NPersQueue::IClientEventLoop { writerConfig.PreferredCluster(preferredCluster); auto writer = setup->GetPersQueueClient().CreateWriteSession(writerConfig); - TMaybe continueToken; + std::optional continueToken; NThreading::TFuture waitEventFuture = writer->WaitEvent(); THashMap> ackPromiseBySequenceNumber; TDeque> ackPromiseQueue; @@ -164,7 +164,7 @@ struct TYDBClientEventLoop : public ::NPersQueue::IClientEventLoop { } Y_ABORT_UNLESS(continueToken); - TMaybe seqNo = Nothing(); + std::optional seqNo = std::nullopt; if (!AutoSeqNo) { seqNo = acknowledgeableMessage.SequenceNumber; Log << TLOG_INFO << "[" << sourceId << "] Write messages with sequence numbers " @@ -176,7 +176,7 @@ struct TYDBClientEventLoop : public ::NPersQueue::IClientEventLoop { seqNo, acknowledgeableMessage.CreatedAt ); - continueToken = Nothing(); + continueToken = std::nullopt; } } Log << TLOG_DEBUG << "Close writer (stop)"; @@ -200,7 +200,7 @@ struct TYdbPqTestRetryState : NYdb::NPersQueue::IRetryPolicy::IRetryState { , Delay(delay) {} - TMaybe GetNextRetryDelay(NYdb::EStatus) override { + std::optional GetNextRetryDelay(NYdb::EStatus) override { Cerr << "Test retry state: get retry delay\n"; RetryDone(); return Delay; @@ -215,10 +215,10 @@ struct TYdbPqTestRetryState : NYdb::NPersQueue::IRetryPolicy::IRetryState { }; struct TYdbPqNoRetryState : NYdb::NPersQueue::IRetryPolicy::IRetryState { TAtomic DelayCalled = 0; - TMaybe GetNextRetryDelay(NYdb::EStatus) override { + std::optional GetNextRetryDelay(NYdb::EStatus) override { auto res = AtomicSwap(&DelayCalled, 0); UNIT_ASSERT(!res); - return Nothing(); + return std::nullopt; } }; diff --git a/client/ydb_query/client.cpp b/client/ydb_query/client.cpp index 26b4d414e25..58460253c47 100644 --- a/client/ydb_query/client.cpp +++ b/client/ydb_query/client.cpp @@ -67,15 +67,15 @@ class TQueryClient::TImpl: public TClientImplCommon, public } TAsyncExecuteQueryIterator StreamExecuteQuery(const std::string& query, const TTxControl& txControl, - const TMaybe& params, const TExecuteQuerySettings& settings, const TMaybe& session = {}) + const std::optional& params, const TExecuteQuerySettings& settings, const std::optional& session = {}) { return TExecQueryImpl::StreamExecuteQuery( Connections_, DbDriverState_, query, txControl, params, settings, session); } TAsyncExecuteQueryResult ExecuteQuery(const std::string& query, const TTxControl& txControl, - const TMaybe& params, const TExecuteQuerySettings& settings, - const TMaybe& session = {}) + const std::optional& params, const TExecuteQuerySettings& settings, + const std::optional& session = {}) { return TExecQueryImpl::ExecuteQuery( Connections_, DbDriverState_, query, txControl, params, settings, session); diff --git a/client/ydb_query/client.h b/client/ydb_query/client.h index 2457c2d142e..5e69a44aa93 100644 --- a/client/ydb_query/client.h +++ b/client/ydb_query/client.h @@ -8,7 +8,6 @@ #include #include -#include #include namespace NYdb { @@ -188,22 +187,22 @@ class TBeginTransactionResult : public TStatus { class TExecuteQueryPart : public TStreamPartStatus { public: - bool HasResultSet() const { return ResultSet_.Defined(); } + bool HasResultSet() const { return ResultSet_.has_value(); } ui64 GetResultSetIndex() const { return ResultSetIndex_; } const TResultSet& GetResultSet() const { return *ResultSet_; } TResultSet ExtractResultSet() { return std::move(*ResultSet_); } - const TMaybe& GetStats() const { return Stats_; } - const TMaybe& GetTransaction() const { return Transaction_; } + const std::optional& GetStats() const { return Stats_; } + const std::optional& GetTransaction() const { return Transaction_; } - TExecuteQueryPart(TStatus&& status, TMaybe&& queryStats, TMaybe&& tx) + TExecuteQueryPart(TStatus&& status, std::optional&& queryStats, std::optional&& tx) : TStreamPartStatus(std::move(status)) , Stats_(std::move(queryStats)) , Transaction_(std::move(tx)) {} TExecuteQueryPart(TStatus&& status, TResultSet&& resultSet, i64 resultSetIndex, - TMaybe&& queryStats, TMaybe&& tx) + std::optional&& queryStats, std::optional&& tx) : TStreamPartStatus(std::move(status)) , ResultSet_(std::move(resultSet)) , ResultSetIndex_(resultSetIndex) @@ -212,10 +211,10 @@ class TExecuteQueryPart : public TStreamPartStatus { {} private: - TMaybe ResultSet_; + std::optional ResultSet_; i64 ResultSetIndex_ = 0; - TMaybe Stats_; - TMaybe Transaction_; + std::optional Stats_; + std::optional Transaction_; }; class TExecuteQueryResult : public TStatus { @@ -224,16 +223,16 @@ class TExecuteQueryResult : public TStatus { TResultSet GetResultSet(size_t resultIndex) const; TResultSetParser GetResultSetParser(size_t resultIndex) const; - const TMaybe& GetStats() const { return Stats_; } + const std::optional& GetStats() const { return Stats_; } - TMaybe GetTransaction() const {return Transaction_; } + std::optional GetTransaction() const {return Transaction_; } TExecuteQueryResult(TStatus&& status) : TStatus(std::move(status)) {} TExecuteQueryResult(TStatus&& status, std::vector&& resultSets, - TMaybe&& stats, TMaybe&& tx) + std::optional&& stats, std::optional&& tx) : TStatus(std::move(status)) , ResultSets_(std::move(resultSets)) , Stats_(std::move(stats)) @@ -242,8 +241,8 @@ class TExecuteQueryResult : public TStatus { private: std::vector ResultSets_; - TMaybe Stats_; - TMaybe Transaction_; + std::optional Stats_; + std::optional Transaction_; }; } // namespace NYdb::NQuery diff --git a/client/ydb_query/impl/exec_query.cpp b/client/ydb_query/impl/exec_query.cpp index e2673b9e12a..31a0ee12acc 100644 --- a/client/ydb_query/impl/exec_query.cpp +++ b/client/ydb_query/impl/exec_query.cpp @@ -42,7 +42,7 @@ class TExecuteQueryIterator::TReaderImpl { using TGRpcStatus = NYdbGrpc::TGrpcStatus; using TBatchReadResult = std::pair; - TReaderImpl(TStreamProcessorPtr streamProcessor, const std::string& endpoint, const TMaybe& session) + TReaderImpl(TStreamProcessorPtr streamProcessor, const std::string& endpoint, const std::optional& session) : StreamProcessor_(streamProcessor) , Finished_(false) , Endpoint_(endpoint) @@ -71,14 +71,14 @@ class TExecuteQueryIterator::TReaderImpl { TPlainStatus plainStatus{clientStatus, std::move(issues), self->Endpoint_, {}}; TStatus status{std::move(plainStatus)}; - TMaybe stats; - TMaybe tx; + std::optional stats; + std::optional tx; if (self->Response_.has_exec_stats()) { stats = TExecStats(std::move(*self->Response_.mutable_exec_stats())); } - if (self->Response_.has_tx_meta() && self->Session_.Defined()) { - tx = TTransaction(self->Session_.GetRef(), self->Response_.tx_meta().id()); + if (self->Response_.has_tx_meta() && self->Session_.has_value()) { + tx = TTransaction(self->Session_.value(), self->Response_.tx_meta().id()); } if (self->Response_.has_result_set()) { @@ -103,7 +103,7 @@ class TExecuteQueryIterator::TReaderImpl { TResponse Response_; bool Finished_; std::string Endpoint_; - TMaybe Session_; + std::optional Session_; }; TAsyncExecuteQueryPart TExecuteQueryIterator::ReadNext() { @@ -127,8 +127,8 @@ struct TExecuteQueryBuffer : public TThrRefBase, TNonCopyable { TExecuteQueryIterator Iterator_; std::vector Issues_; std::vector ResultSets_; - TMaybe Stats_; - TMaybe Tx_; + std::optional Stats_; + std::optional Tx_; void Next() { TPtr self(this); @@ -140,8 +140,8 @@ struct TExecuteQueryBuffer : public TThrRefBase, TNonCopyable { if (part.EOS()) { std::vector issues; std::vector resultProtos; - TMaybe stats; - TMaybe tx; + std::optional stats; + std::optional tx; std::swap(self->Issues_, issues); std::swap(self->ResultSets_, resultProtos); @@ -204,16 +204,16 @@ struct TExecuteQueryBuffer : public TThrRefBase, TNonCopyable { TFuture> StreamExecuteQueryImpl( const std::shared_ptr& connections, const TDbDriverStatePtr& driverState, const std::string& query, const TTxControl& txControl, const ::google::protobuf::Map* params, - const TExecuteQuerySettings& settings, const TMaybe& session) + const TExecuteQuerySettings& settings, const std::optional& session) { auto request = MakeRequest(); request.set_exec_mode(::Ydb::Query::ExecMode(settings.ExecMode_)); request.set_stats_mode(::Ydb::Query::StatsMode(settings.StatsMode_)); request.mutable_query_content()->set_text(query); request.mutable_query_content()->set_syntax(::Ydb::Query::Syntax(settings.Syntax_)); - if (session.Defined()) { + if (session.has_value()) { request.set_session_id(session->GetId()); - } else if ((txControl.TxSettings_.Defined() && !txControl.CommitTx_) || txControl.TxId_.Defined()) { + } else if ((txControl.TxSettings_.has_value() && !txControl.CommitTx_) || txControl.TxId_.has_value()) { throw TContractViolation("Interactive tx must use explisit session"); } @@ -241,7 +241,7 @@ TFuture> StreamExecuteQueryIm auto promise = NewPromise>(); auto rpcSettings = TRpcRequestSettings::Make(settings); - if (session.Defined()) { + if (session.has_value()) { rpcSettings.PreferredEndpoint = TEndpointKey(GetNodeIdFromSession(session->GetId())); } @@ -264,7 +264,7 @@ TFuture> StreamExecuteQueryIm TAsyncExecuteQueryIterator TExecQueryImpl::StreamExecuteQuery(const std::shared_ptr& connections, const TDbDriverStatePtr& driverState, const std::string& query, const TTxControl& txControl, - const TMaybe& params, const TExecuteQuerySettings& settings, const TMaybe& session) + const std::optional& params, const TExecuteQuerySettings& settings, const std::optional& session) { auto promise = NewPromise(); @@ -290,7 +290,7 @@ TAsyncExecuteQueryIterator TExecQueryImpl::StreamExecuteQuery(const std::shared_ TAsyncExecuteQueryResult TExecQueryImpl::ExecuteQuery(const std::shared_ptr& connections, const TDbDriverStatePtr& driverState, const std::string& query, const TTxControl& txControl, - const TMaybe& params, const TExecuteQuerySettings& settings, const TMaybe& session) + const std::optional& params, const TExecuteQuerySettings& settings, const std::optional& session) { auto syncSettings = settings; syncSettings.ConcurrentResultSets(true); diff --git a/client/ydb_query/impl/exec_query.h b/client/ydb_query/impl/exec_query.h index 93f8bac84a0..510fcde04d7 100644 --- a/client/ydb_query/impl/exec_query.h +++ b/client/ydb_query/impl/exec_query.h @@ -13,11 +13,11 @@ class TExecQueryImpl { public: static TAsyncExecuteQueryIterator StreamExecuteQuery(const std::shared_ptr& connections, const TDbDriverStatePtr& driverState, const std::string& query, const TTxControl& txControl, - const TMaybe& params, const TExecuteQuerySettings& settings, const TMaybe& session); + const std::optional& params, const TExecuteQuerySettings& settings, const std::optional& session); static TAsyncExecuteQueryResult ExecuteQuery(const std::shared_ptr& connections, const TDbDriverStatePtr& driverState, const std::string& query, const TTxControl& txControl, - const TMaybe& params, const TExecuteQuerySettings& settings, const TMaybe& session); + const std::optional& params, const TExecuteQuerySettings& settings, const std::optional& session); }; } // namespace NYdb::NQuery::NImpl diff --git a/client/ydb_query/query.h b/client/ydb_query/query.h index 29a025cc854..11b1f393473 100644 --- a/client/ydb_query/query.h +++ b/client/ydb_query/query.h @@ -144,7 +144,7 @@ struct TFetchScriptResultsSettings : public TRequestSettings ResultSet_; + std::optional ResultSet_; i64 ResultSetIndex_ = 0; std::string NextFetchToken_; }; diff --git a/client/ydb_query/stats.cpp b/client/ydb_query/stats.cpp index 16fece9534a..1a3892d27f0 100644 --- a/client/ydb_query/stats.cpp +++ b/client/ydb_query/stats.cpp @@ -36,7 +36,7 @@ std::string TExecStats::ToString(bool withPlan) const { return res; } -TMaybe TExecStats::GetPlan() const { +std::optional TExecStats::GetPlan() const { auto proto = Impl_->Proto; if (proto.query_plan().empty()) { diff --git a/client/ydb_query/stats.h b/client/ydb_query/stats.h index 788c2a64fa4..6c4b04209c6 100644 --- a/client/ydb_query/stats.h +++ b/client/ydb_query/stats.h @@ -1,7 +1,6 @@ #pragma once #include -#include #include @@ -28,7 +27,7 @@ class TExecStats { std::string ToString(bool withPlan = false) const; - TMaybe GetPlan() const; + std::optional GetPlan() const; TDuration GetTotalDuration() const; TDuration GetTotalCpuTime() const; diff --git a/client/ydb_query/tx.h b/client/ydb_query/tx.h index e8e42d4d5fd..1dd8d42e466 100644 --- a/client/ydb_query/tx.h +++ b/client/ydb_query/tx.h @@ -4,6 +4,8 @@ #include +#include + namespace NYdb::NQuery { struct TTxOnlineSettings { @@ -86,11 +88,11 @@ struct TTxControl { return TTxControl(); } - const TMaybe TxId_; - const TMaybe TxSettings_; + const std::optional TxId_; + const std::optional TxSettings_; FLUENT_SETTING_FLAG(CommitTx); - bool HasTx() const { return TxId_.Defined() || TxSettings_.Defined(); } + bool HasTx() const { return TxId_.has_value() || TxSettings_.has_value(); } private: TTxControl() {} diff --git a/client/ydb_rate_limiter/rate_limiter.cpp b/client/ydb_rate_limiter/rate_limiter.cpp index 3771c08bf4d..18fce0ca0e0 100644 --- a/client/ydb_rate_limiter/rate_limiter.cpp +++ b/client/ydb_rate_limiter/rate_limiter.cpp @@ -171,9 +171,9 @@ class TRateLimiterClient::TImpl : public TClientImplCommon( diff --git a/client/ydb_rate_limiter/rate_limiter.h b/client/ydb_rate_limiter/rate_limiter.h index 2ebf189407d..a3f5f22c4b0 100644 --- a/client/ydb_rate_limiter/rate_limiter.h +++ b/client/ydb_rate_limiter/rate_limiter.h @@ -2,8 +2,6 @@ #include -#include - namespace Ydb::RateLimiter { class DescribeResourceResult; class HierarchicalDrrSettings; @@ -95,31 +93,31 @@ struct TDescribeResourceResult : public TStatus { THierarchicalDrrProps(const Ydb::RateLimiter::HierarchicalDrrSettings&); // Resource consumption speed limit. - TMaybe GetMaxUnitsPerSecond() const { + std::optional GetMaxUnitsPerSecond() const { return MaxUnitsPerSecond_; } // Maximum burst size of resource consumption across the whole cluster // divided by max_units_per_second. - TMaybe GetMaxBurstSizeCoefficient() const { + std::optional GetMaxBurstSizeCoefficient() const { return MaxBurstSizeCoefficient_; } // Prefetch in local bucket up to PrefetchCoefficient*MaxUnitsPerSecond units (full size). - TMaybe GetPrefetchCoefficient() const { + std::optional GetPrefetchCoefficient() const { return PrefetchCoefficient_; } // Prefetching starts if there is less than PrefetchWatermark fraction of full local bucket left. - TMaybe GetPrefetchWatermark() const { + std::optional GetPrefetchWatermark() const { return PrefetchWatermark_; } private: - TMaybe MaxUnitsPerSecond_; - TMaybe MaxBurstSizeCoefficient_; - TMaybe PrefetchCoefficient_; - TMaybe PrefetchWatermark_; + std::optional MaxUnitsPerSecond_; + std::optional MaxBurstSizeCoefficient_; + std::optional PrefetchCoefficient_; + std::optional PrefetchWatermark_; }; TDescribeResourceResult(TStatus status, const Ydb::RateLimiter::DescribeResourceResult& result); diff --git a/client/ydb_table/impl/client_session.cpp b/client/ydb_table/impl/client_session.cpp index 39be6280cef..66b3114ec50 100644 --- a/client/ydb_table/impl/client_session.cpp +++ b/client/ydb_table/impl/client_session.cpp @@ -35,7 +35,7 @@ void TSession::TImpl::InvalidateQueryCache() { } } -TMaybe TSession::TImpl::GetQueryFromCache(const std::string& query, bool allowMigration) { +std::optional TSession::TImpl::GetQueryFromCache(const std::string& query, bool allowMigration) { if (!UseQueryCache_) { return {}; } @@ -49,7 +49,7 @@ TMaybe TSession::TImpl::GetQueryFromCache(const } } - return Nothing(); + return std::nullopt; } void TSession::TImpl::AddQueryToCache(const TDataQuery& query) { diff --git a/client/ydb_table/impl/client_session.h b/client/ydb_table/impl/client_session.h index a261598fd7d..fa77db7f538 100644 --- a/client/ydb_table/impl/client_session.h +++ b/client/ydb_table/impl/client_session.h @@ -46,7 +46,7 @@ class TSession::TImpl : public TKqpSessionCommon { void InvalidateQueryInCache(const std::string& key); void InvalidateQueryCache(); - TMaybe GetQueryFromCache(const std::string& query, bool allowMigration); + std::optional GetQueryFromCache(const std::string& query, bool allowMigration); void AddQueryToCache(const TDataQuery& query); const TLRUCache& GetQueryCacheUnsafe() const; diff --git a/client/ydb_table/impl/data_query.cpp b/client/ydb_table/impl/data_query.cpp index 3496dec714e..7ef703f3068 100644 --- a/client/ydb_table/impl/data_query.cpp +++ b/client/ydb_table/impl/data_query.cpp @@ -29,7 +29,7 @@ TDataQuery::TImpl::TImpl(const TSession& session, const std::string& text, bool : Session_(session) , Id_(id) , TextHash_(EncodeQuery(text, allowMigration)) - , Text_(keepText ? text : TMaybe()) + , Text_(keepText ? text : std::optional()) {} TDataQuery::TImpl::TImpl(const TSession& session, const std::string& text, bool keepText, const std::string& id, bool allowMigration, @@ -38,7 +38,7 @@ TDataQuery::TImpl::TImpl(const TSession& session, const std::string& text, bool , Id_(id) , ParameterTypes_(types) , TextHash_(EncodeQuery(text, allowMigration)) - , Text_(keepText ? text : TMaybe()) + , Text_(keepText ? text : std::optional()) {} const std::string& TDataQuery::TImpl::GetId() const { @@ -53,7 +53,7 @@ const std::string& TDataQuery::TImpl::GetTextHash() const { return TextHash_; } -const TMaybe& TDataQuery::TImpl::GetText() const { +const std::optional& TDataQuery::TImpl::GetText() const { return Text_; } diff --git a/client/ydb_table/impl/data_query.h b/client/ydb_table/impl/data_query.h index 985ade23869..041b5a8367e 100644 --- a/client/ydb_table/impl/data_query.h +++ b/client/ydb_table/impl/data_query.h @@ -22,14 +22,14 @@ class TDataQuery::TImpl { const std::string& GetId() const; const ::google::protobuf::Map& GetParameterTypes() const; const std::string& GetTextHash() const; - const TMaybe& GetText() const; + const std::optional& GetText() const; private: NTable::TSession Session_; std::string Id_; ::google::protobuf::Map ParameterTypes_; std::string TextHash_; - TMaybe Text_; + std::optional Text_; }; } // namespace NTable diff --git a/client/ydb_table/impl/readers.cpp b/client/ydb_table/impl/readers.cpp index ec591cb9e20..efada1287d8 100644 --- a/client/ydb_table/impl/readers.cpp +++ b/client/ydb_table/impl/readers.cpp @@ -81,8 +81,8 @@ TAsyncScanQueryPart TScanQueryPartIterator::TReaderImpl::ReadNext(std::shared_pt // TODO: Add headers for streaming calls. TPlainStatus plainStatus{clientStatus, std::move(issues), self->Endpoint_, {}}; TStatus status{std::move(plainStatus)}; - TMaybe queryStats; - TMaybe diagnostics; + std::optional queryStats; + std::optional diagnostics; if (self->Response_.result().has_query_stats()) { queryStats = TQueryStats(self->Response_.result().query_stats()); diff --git a/client/ydb_table/impl/table_client.cpp b/client/ydb_table/impl/table_client.cpp index d667ff9a132..986ef8197d5 100644 --- a/client/ydb_table/impl/table_client.cpp +++ b/client/ydb_table/impl/table_client.cpp @@ -654,7 +654,7 @@ TAsyncCommitTransactionResult TTableClient::TImpl::CommitTransaction(const TSess auto extractor = [promise] (google::protobuf::Any* any, TPlainStatus status) mutable { - TMaybe queryStats; + std::optional queryStats; if (any) { Ydb::Table::CommitTransactionResult result; any->UnpackTo(&result); @@ -748,20 +748,20 @@ NThreading::TFuturemutable_greater_or_equal(), from.GetValue()); } else { @@ -770,7 +770,7 @@ NThreading::TFuturemutable_less_or_equal(), to.GetValue()); } else { @@ -1135,19 +1135,19 @@ void TTableClient::TImpl::SetQuery(const TDataQuery& queryData, Ydb::Table::Quer void TTableClient::TImpl::SetQueryCachePolicy(const std::string&, const TExecDataQuerySettings& settings, Ydb::Table::QueryCachePolicy* queryCachePolicy) { - queryCachePolicy->set_keep_in_cache(settings.KeepInQueryCache_ ? settings.KeepInQueryCache_.GetRef() : false); + queryCachePolicy->set_keep_in_cache(settings.KeepInQueryCache_.value_or(false)); } void TTableClient::TImpl::SetQueryCachePolicy(const TDataQuery&, const TExecDataQuerySettings& settings, Ydb::Table::QueryCachePolicy* queryCachePolicy) { - queryCachePolicy->set_keep_in_cache(settings.KeepInQueryCache_ ? settings.KeepInQueryCache_.GetRef() : true); + queryCachePolicy->set_keep_in_cache(settings.KeepInQueryCache_.value_or(true)); } -TMaybe TTableClient::TImpl::GetQueryText(const std::string& queryText) { +std::optional TTableClient::TImpl::GetQueryText(const std::string& queryText) { return queryText; } -TMaybe TTableClient::TImpl::GetQueryText(const TDataQuery& queryData) { +std::optional TTableClient::TImpl::GetQueryText(const TDataQuery& queryData) { return queryData.GetText(); } diff --git a/client/ydb_table/impl/table_client.h b/client/ydb_table/impl/table_client.h index 91d0eaac7bc..c554f68c8fb 100644 --- a/client/ydb_table/impl/table_client.h +++ b/client/ydb_table/impl/table_client.h @@ -197,7 +197,7 @@ class TTableClient::TImpl: public TClientImplCommon, public SetQueryCachePolicy(query, settings, request.mutable_query_cache_policy()); auto promise = NewPromise(); - bool keepInCache = settings.KeepInQueryCache_ && settings.KeepInQueryCache_.GetRef(); + bool keepInCache = settings.KeepInQueryCache_ && settings.KeepInQueryCache_.value(); // We don't want to delay call of TSession dtor, so we can't capture it by copy // otherwise we break session pool and other clients logic. @@ -211,16 +211,16 @@ class TTableClient::TImpl: public TClientImplCommon, public auto extractor = [promise, sessionPtr, query, fromCache, keepInCache] (google::protobuf::Any* any, TPlainStatus status) mutable { std::vector res; - TMaybe tx; - TMaybe dataQuery; - TMaybe queryStats; + std::optional tx; + std::optional dataQuery; + std::optional queryStats; auto queryText = GetQueryText(query); if (any) { Ydb::Table::ExecuteQueryResult result; any->UnpackTo(&result); - for (size_t i = 0; i < result.result_sets_size(); i++) { + for (size_t i = 0; i < static_cast(result.result_sets_size()); i++) { res.push_back(TResultSet(*result.mutable_result_sets(i))); } @@ -248,8 +248,8 @@ class TTableClient::TImpl: public TClientImplCommon, public std::move(res), tx, dataQuery, fromCache, queryStats); delete sessionPtr; - tx.Clear(); - dataQuery.Clear(); + tx.reset(); + dataQuery.reset(); promise.SetValue(std::move(dataQueryResult)); }; @@ -277,9 +277,9 @@ class TTableClient::TImpl: public TClientImplCommon, public static void SetQueryCachePolicy(const TDataQuery&, const TExecDataQuerySettings& settings, Ydb::Table::QueryCachePolicy* queryCachePolicy); - static TMaybe GetQueryText(const std::string& queryText); + static std::optional GetQueryText(const std::string& queryText); - static TMaybe GetQueryText(const TDataQuery& queryData); + static std::optional GetQueryText(const TDataQuery& queryData); public: NSdkStats::TAtomicCounter<::NMonitoring::TRate> CacheMissCounter; diff --git a/client/ydb_table/query_stats/stats.h b/client/ydb_table/query_stats/stats.h index 621d9c2f247..5817ea1dfcc 100644 --- a/client/ydb_table/query_stats/stats.h +++ b/client/ydb_table/query_stats/stats.h @@ -2,8 +2,6 @@ #include -#include - class TDuration; namespace Ydb { diff --git a/client/ydb_table/table.cpp b/client/ydb_table/table.cpp index 4d6a339f914..850688fd198 100644 --- a/client/ydb_table/table.cpp +++ b/client/ydb_table/table.cpp @@ -66,7 +66,7 @@ const Ydb::Table::StorageSettings& TStorageSettings::GetProto() const { return Impl_->Proto_; } -TMaybe TStorageSettings::GetTabletCommitLog0() const { +std::optional TStorageSettings::GetTabletCommitLog0() const { if (GetProto().has_tablet_commit_log0()) { return GetProto().tablet_commit_log0().media(); } else { @@ -74,7 +74,7 @@ TMaybe TStorageSettings::GetTabletCommitLog0() const { } } -TMaybe TStorageSettings::GetTabletCommitLog1() const { +std::optional TStorageSettings::GetTabletCommitLog1() const { if (GetProto().has_tablet_commit_log1()) { return GetProto().tablet_commit_log1().media(); } else { @@ -82,7 +82,7 @@ TMaybe TStorageSettings::GetTabletCommitLog1() const { } } -TMaybe TStorageSettings::GetExternal() const { +std::optional TStorageSettings::GetExternal() const { if (GetProto().has_external()) { return GetProto().external().media(); } else { @@ -90,7 +90,7 @@ TMaybe TStorageSettings::GetExternal() const { } } -TMaybe TStorageSettings::GetStoreExternalBlobs() const { +std::optional TStorageSettings::GetStoreExternalBlobs() const { switch (GetProto().store_external_blobs()) { case Ydb::FeatureFlag::ENABLED: return true; @@ -125,7 +125,7 @@ const std::string& TColumnFamilyDescription::GetName() const { return GetProto().name(); } -TMaybe TColumnFamilyDescription::GetData() const { +std::optional TColumnFamilyDescription::GetData() const { if (GetProto().has_data()) { return GetProto().data().media(); } else { @@ -133,7 +133,7 @@ TMaybe TColumnFamilyDescription::GetData() const { } } -TMaybe TColumnFamilyDescription::GetCompression() const { +std::optional TColumnFamilyDescription::GetCompression() const { switch (GetProto().compression()) { case Ydb::Table::ColumnFamily::COMPRESSION_NONE: return EColumnFamilyCompression::None; @@ -144,7 +144,7 @@ TMaybe TColumnFamilyDescription::GetCompression() cons } } -TMaybe TColumnFamilyDescription::GetKeepInMemory() const { +std::optional TColumnFamilyDescription::GetKeepInMemory() const { switch (GetProto().keep_in_memory()) { case Ydb::FeatureFlag::ENABLED: return true; @@ -197,7 +197,7 @@ const Ydb::Table::PartitioningSettings& TPartitioningSettings::GetProto() const return Impl_->Proto_; } -TMaybe TPartitioningSettings::GetPartitioningBySize() const { +std::optional TPartitioningSettings::GetPartitioningBySize() const { switch (GetProto().partitioning_by_size()) { case Ydb::FeatureFlag::ENABLED: return true; @@ -208,7 +208,7 @@ TMaybe TPartitioningSettings::GetPartitioningBySize() const { } } -TMaybe TPartitioningSettings::GetPartitioningByLoad() const { +std::optional TPartitioningSettings::GetPartitioningByLoad() const { switch (GetProto().partitioning_by_load()) { case Ydb::FeatureFlag::ENABLED: return true; @@ -369,11 +369,11 @@ class TTableDescription::TImpl { PermissionToSchemeEntry(Proto_.self().permissions(), &Permissions_); PermissionToSchemeEntry(Proto_.self().effective_permissions(), &EffectivePermissions_); - TMaybe leftValue; + std::optional leftValue; for (const auto& bound : Proto_.shard_key_bounds()) { - TMaybe fromBound = leftValue + std::optional fromBound = leftValue ? TKeyBound::Inclusive(*leftValue) - : TMaybe(); + : std::optional(); TValue value(TType(bound.type()), bound.value()); const TKeyBound& toBound = TKeyBound::Exclusive(value); @@ -397,8 +397,8 @@ class TTableDescription::TImpl { if (describeSettings.WithKeyShardBoundary_) { Ranges_.emplace_back(TKeyRange( - leftValue ? TKeyBound::Inclusive(*leftValue) : TMaybe(), - TMaybe())); + leftValue ? TKeyBound::Inclusive(*leftValue) : std::optional(), + std::optional())); } } @@ -532,11 +532,11 @@ class TTableDescription::TImpl { return Changefeeds_; } - const TMaybe& GetTtlSettings() const { + const std::optional& GetTtlSettings() const { return TtlSettings_; } - const TMaybe& GetTiering() const { + const std::optional& GetTiering() const { return Tiering_; } @@ -588,11 +588,11 @@ class TTableDescription::TImpl { return CompactionPolicy_; } - const TMaybe& GetUniformPartitions() const { + const std::optional& GetUniformPartitions() const { return UniformPartitions_; } - const TMaybe& GetPartitionAtKeys() const { + const std::optional& GetPartitionAtKeys() const { return PartitionAtKeys_; } @@ -604,11 +604,11 @@ class TTableDescription::TImpl { return PartitioningSettings_; } - TMaybe GetKeyBloomFilter() const { + std::optional GetKeyBloomFilter() const { return KeyBloomFilter_; } - const TMaybe& GetReadReplicasSettings() const { + const std::optional& GetReadReplicasSettings() const { return ReadReplicasSettings_; } @@ -619,8 +619,8 @@ class TTableDescription::TImpl { std::vector Columns_; std::vector Indexes_; std::vector Changefeeds_; - TMaybe TtlSettings_; - TMaybe Tiering_; + std::optional TtlSettings_; + std::optional Tiering_; std::string Owner_; std::vector Permissions_; std::vector EffectivePermissions_; @@ -630,11 +630,11 @@ class TTableDescription::TImpl { std::vector ColumnFamilies_; THashMap Attributes_; std::string CompactionPolicy_; - TMaybe UniformPartitions_; - TMaybe PartitionAtKeys_; + std::optional UniformPartitions_; + std::optional PartitionAtKeys_; TPartitioningSettings PartitioningSettings_; - TMaybe KeyBloomFilter_; - TMaybe ReadReplicasSettings_; + std::optional KeyBloomFilter_; + std::optional ReadReplicasSettings_; bool HasStorageSettings_ = false; bool HasPartitioningSettings_ = false; EStoreType StoreType_ = EStoreType::Row; @@ -683,11 +683,11 @@ std::vector TTableDescription::GetChangefeedDescriptions return Impl_->GetChangefeedDescriptions(); } -TMaybe TTableDescription::GetTtlSettings() const { +std::optional TTableDescription::GetTtlSettings() const { return Impl_->GetTtlSettings(); } -TMaybe TTableDescription::GetTiering() const { +std::optional TTableDescription::GetTiering() const { return Impl_->GetTiering(); } @@ -855,11 +855,11 @@ const TPartitioningSettings& TTableDescription::GetPartitioningSettings() const return Impl_->GetPartitioningSettings(); } -TMaybe TTableDescription::GetKeyBloomFilter() const { +std::optional TTableDescription::GetKeyBloomFilter() const { return Impl_->GetKeyBloomFilter(); } -TMaybe TTableDescription::GetReadReplicasSettings() const { +std::optional TTableDescription::GetReadReplicasSettings() const { return Impl_->GetReadReplicasSettings(); } @@ -916,7 +916,7 @@ void TTableDescription::SerializeTo(Ydb::Table::CreateTableRequest& request) con } if (const auto& uniformPartitions = Impl_->GetUniformPartitions()) { - request.set_uniform_partitions(uniformPartitions.GetRef()); + request.set_uniform_partitions(uniformPartitions.value()); } if (const auto& partitionAtKeys = Impl_->GetPartitionAtKeys()) { @@ -935,7 +935,7 @@ void TTableDescription::SerializeTo(Ydb::Table::CreateTableRequest& request) con } if (auto keyBloomFilter = Impl_->GetKeyBloomFilter()) { - if (keyBloomFilter.GetRef()) { + if (keyBloomFilter.value()) { request.set_key_bloom_filter(Ydb::FeatureFlag::ENABLED); } else { request.set_key_bloom_filter(Ydb::FeatureFlag::DISABLED); @@ -1455,24 +1455,24 @@ TAsyncScanQueryPartIterator TTableClient::StreamExecuteScanQuery(const std::stri static void ConvertCreateTableSettingsToProto(const TCreateTableSettings& settings, Ydb::Table::TableProfile* proto) { if (settings.PresetName_) { - proto->set_preset_name(settings.PresetName_.GetRef()); + proto->set_preset_name(settings.PresetName_.value()); } if (settings.ExecutionPolicy_) { - proto->mutable_execution_policy()->set_preset_name(settings.ExecutionPolicy_.GetRef()); + proto->mutable_execution_policy()->set_preset_name(settings.ExecutionPolicy_.value()); } if (settings.CompactionPolicy_) { - proto->mutable_compaction_policy()->set_preset_name(settings.CompactionPolicy_.GetRef()); + proto->mutable_compaction_policy()->set_preset_name(settings.CompactionPolicy_.value()); } if (settings.PartitioningPolicy_) { - const auto& policy = settings.PartitioningPolicy_.GetRef(); + const auto& policy = settings.PartitioningPolicy_.value(); if (policy.PresetName_) { - proto->mutable_partitioning_policy()->set_preset_name(policy.PresetName_.GetRef()); + proto->mutable_partitioning_policy()->set_preset_name(policy.PresetName_.value()); } if (policy.AutoPartitioning_) { - proto->mutable_partitioning_policy()->set_auto_partitioning(static_cast(policy.AutoPartitioning_.GetRef())); + proto->mutable_partitioning_policy()->set_auto_partitioning(static_cast(policy.AutoPartitioning_.value())); } if (policy.UniformPartitions_) { - proto->mutable_partitioning_policy()->set_uniform_partitions(policy.UniformPartitions_.GetRef()); + proto->mutable_partitioning_policy()->set_uniform_partitions(policy.UniformPartitions_.value()); } if (policy.ExplicitPartitions_) { auto* borders = proto->mutable_partitioning_policy()->mutable_explicit_partitions(); @@ -1484,65 +1484,65 @@ static void ConvertCreateTableSettingsToProto(const TCreateTableSettings& settin } } if (settings.StoragePolicy_) { - const auto& policy = settings.StoragePolicy_.GetRef(); + const auto& policy = settings.StoragePolicy_.value(); if (policy.PresetName_) { - proto->mutable_storage_policy()->set_preset_name(policy.PresetName_.GetRef()); + proto->mutable_storage_policy()->set_preset_name(policy.PresetName_.value()); } if (policy.SysLog_) { - proto->mutable_storage_policy()->mutable_syslog()->set_media(policy.SysLog_.GetRef()); + proto->mutable_storage_policy()->mutable_syslog()->set_media(policy.SysLog_.value()); } if (policy.Log_) { - proto->mutable_storage_policy()->mutable_log()->set_media(policy.Log_.GetRef()); + proto->mutable_storage_policy()->mutable_log()->set_media(policy.Log_.value()); } if (policy.Data_) { - proto->mutable_storage_policy()->mutable_data()->set_media(policy.Data_.GetRef()); + proto->mutable_storage_policy()->mutable_data()->set_media(policy.Data_.value()); } if (policy.External_) { - proto->mutable_storage_policy()->mutable_external()->set_media(policy.External_.GetRef()); + proto->mutable_storage_policy()->mutable_external()->set_media(policy.External_.value()); } for (const auto& familyPolicy : policy.ColumnFamilies_) { auto* familyProto = proto->mutable_storage_policy()->add_column_families(); if (familyPolicy.Name_) { - familyProto->set_name(familyPolicy.Name_.GetRef()); + familyProto->set_name(familyPolicy.Name_.value()); } if (familyPolicy.Data_) { - familyProto->mutable_data()->set_media(familyPolicy.Data_.GetRef()); + familyProto->mutable_data()->set_media(familyPolicy.Data_.value()); } if (familyPolicy.External_) { - familyProto->mutable_external()->set_media(familyPolicy.External_.GetRef()); + familyProto->mutable_external()->set_media(familyPolicy.External_.value()); } if (familyPolicy.KeepInMemory_) { familyProto->set_keep_in_memory( - familyPolicy.KeepInMemory_.GetRef() + familyPolicy.KeepInMemory_.value() ? Ydb::FeatureFlag_Status::FeatureFlag_Status_ENABLED : Ydb::FeatureFlag_Status::FeatureFlag_Status_DISABLED ); } if (familyPolicy.Compressed_) { - familyProto->set_compression(familyPolicy.Compressed_.GetRef() + familyProto->set_compression(familyPolicy.Compressed_.value() ? Ydb::Table::ColumnFamilyPolicy::COMPRESSED : Ydb::Table::ColumnFamilyPolicy::UNCOMPRESSED); } } } if (settings.ReplicationPolicy_) { - const auto& policy = settings.ReplicationPolicy_.GetRef(); + const auto& policy = settings.ReplicationPolicy_.value(); if (policy.PresetName_) { - proto->mutable_replication_policy()->set_preset_name(policy.PresetName_.GetRef()); + proto->mutable_replication_policy()->set_preset_name(policy.PresetName_.value()); } if (policy.ReplicasCount_) { - proto->mutable_replication_policy()->set_replicas_count(policy.ReplicasCount_.GetRef()); + proto->mutable_replication_policy()->set_replicas_count(policy.ReplicasCount_.value()); } if (policy.CreatePerAvailabilityZone_) { proto->mutable_replication_policy()->set_create_per_availability_zone( - policy.CreatePerAvailabilityZone_.GetRef() + policy.CreatePerAvailabilityZone_.value() ? Ydb::FeatureFlag_Status::FeatureFlag_Status_ENABLED : Ydb::FeatureFlag_Status::FeatureFlag_Status_DISABLED ); } if (policy.AllowPromotion_) { proto->mutable_replication_policy()->set_allow_promotion( - policy.AllowPromotion_.GetRef() + policy.AllowPromotion_.value() ? Ydb::FeatureFlag_Status::FeatureFlag_Status_ENABLED : Ydb::FeatureFlag_Status::FeatureFlag_Status_DISABLED ); @@ -1677,13 +1677,13 @@ static Ydb::Table::AlterTableRequest MakeAlterTableProtoRequest( request.mutable_alter_partitioning_settings()->CopyFrom(settings.AlterPartitioningSettings_->GetProto()); } - if (settings.SetKeyBloomFilter_.Defined()) { + if (settings.SetKeyBloomFilter_.has_value()) { request.set_set_key_bloom_filter( - settings.SetKeyBloomFilter_.GetRef() ? Ydb::FeatureFlag::ENABLED : Ydb::FeatureFlag::DISABLED); + settings.SetKeyBloomFilter_.value() ? Ydb::FeatureFlag::ENABLED : Ydb::FeatureFlag::DISABLED); } - if (settings.SetReadReplicasSettings_.Defined()) { - const auto& replSettings = settings.SetReadReplicasSettings_.GetRef(); + if (settings.SetReadReplicasSettings_.has_value()) { + const auto& replSettings = settings.SetReadReplicasSettings_.value(); switch (replSettings.GetMode()) { case TReadReplicasSettings::EMode::PerAz: request.mutable_set_read_replicas_settings()->set_per_az_read_replicas_count( @@ -1943,7 +1943,7 @@ const std::string& TDataQuery::GetId() const { return Impl_->GetId(); } -const TMaybe& TDataQuery::GetText() const { +const std::optional& TDataQuery::GetText() const { return Impl_->GetText(); } @@ -2074,7 +2074,7 @@ TTableDescription TDescribeTableResult::GetTableDescription() const { //////////////////////////////////////////////////////////////////////////////// TDataQueryResult::TDataQueryResult(TStatus&& status, std::vector&& resultSets, - const TMaybe& transaction, const TMaybe& dataQuery, bool fromCache, const TMaybe &queryStats) + const std::optional& transaction, const std::optional& dataQuery, bool fromCache, const std::optional &queryStats) : TStatus(std::move(status)) , Transaction_(transaction) , ResultSets_(std::move(resultSets)) @@ -2099,11 +2099,11 @@ TResultSetParser TDataQueryResult::GetResultSetParser(size_t resultIndex) const return TResultSetParser(GetResultSet(resultIndex)); } -TMaybe TDataQueryResult::GetTransaction() const { +std::optional TDataQueryResult::GetTransaction() const { return Transaction_; } -TMaybe TDataQueryResult::GetQuery() const { +std::optional TDataQueryResult::GetQuery() const { return DataQuery_; } @@ -2111,13 +2111,13 @@ bool TDataQueryResult::IsQueryFromCache() const { return FromCache_; } -const TMaybe& TDataQueryResult::GetStats() const { +const std::optional& TDataQueryResult::GetStats() const { return QueryStats_; } const std::string TDataQueryResult::GetQueryPlan() const { - if (QueryStats_.Defined()) { - return NYdb::TProtoAccessor::GetProto(*QueryStats_.Get()).query_plan(); + if (QueryStats_.has_value()) { + return NYdb::TProtoAccessor::GetProto(*QueryStats_).query_plan(); } else { return ""; } @@ -2137,12 +2137,12 @@ const TTransaction& TBeginTransactionResult::GetTransaction() const { //////////////////////////////////////////////////////////////////////////////// -TCommitTransactionResult::TCommitTransactionResult(TStatus&& status, const TMaybe& queryStats) +TCommitTransactionResult::TCommitTransactionResult(TStatus&& status, const std::optional& queryStats) : TStatus(std::move(status)) , QueryStats_(queryStats) {} -const TMaybe& TCommitTransactionResult::GetStats() const { +const std::optional& TCommitTransactionResult::GetStats() const { return QueryStats_; } @@ -2751,12 +2751,12 @@ class TAlterTtlSettingsBuilder::TImpl { AlterTtlSettings_ = TAlterTtlSettings::Set(settings); } - const TMaybe& GetAlterTtlSettings() const { + const std::optional& GetAlterTtlSettings() const { return AlterTtlSettings_; } private: - TMaybe AlterTtlSettings_; + std::optional AlterTtlSettings_; }; TAlterTtlSettingsBuilder::TAlterTtlSettingsBuilder(TAlterTableSettings& parent) @@ -2795,28 +2795,28 @@ class TAlterTableSettings::TImpl { public: TImpl() { } - void SetAlterTtlSettings(const TMaybe& value) { + void SetAlterTtlSettings(const std::optional& value) { AlterTtlSettings_ = value; } - const TMaybe& GetAlterTtlSettings() const { + const std::optional& GetAlterTtlSettings() const { return AlterTtlSettings_; } private: - TMaybe AlterTtlSettings_; + std::optional AlterTtlSettings_; }; TAlterTableSettings::TAlterTableSettings() : Impl_(std::make_shared()) { } -TAlterTableSettings& TAlterTableSettings::AlterTtlSettings(const TMaybe& value) { +TAlterTableSettings& TAlterTableSettings::AlterTtlSettings(const std::optional& value) { Impl_->SetAlterTtlSettings(value); return *this; } -const TMaybe& TAlterTableSettings::GetAlterTtlSettings() const { +const std::optional& TAlterTableSettings::GetAlterTtlSettings() const { return Impl_->GetAlterTtlSettings(); } diff --git a/client/ydb_table/table.h b/client/ydb_table/table.h index 0496445caf9..39d36ec6485 100644 --- a/client/ydb_table/table.h +++ b/client/ydb_table/table.h @@ -11,7 +11,6 @@ #include #include -#include #include namespace Ydb { @@ -81,20 +80,20 @@ class TKeyBound { class TKeyRange { public: - TKeyRange(const TMaybe& from, const TMaybe& to) + TKeyRange(const std::optional& from, const std::optional& to) : From_(from) , To_(to) {} - const TMaybe& From() const { + const std::optional& From() const { return From_; } - const TMaybe& To() const { + const std::optional& To() const { return To_; } private: - TMaybe From_; - TMaybe To_; + std::optional From_; + std::optional To_; }; struct TTableColumn { @@ -203,7 +202,7 @@ class TBuildIndexOperation : public TOperation { EBuildIndexState State; float Progress; std::string Path; - TMaybe Desctiption; + std::optional Desctiption; }; const TMetadata& Metadata() const; @@ -398,10 +397,10 @@ class TStorageSettings { const Ydb::Table::StorageSettings& GetProto() const; - TMaybe GetTabletCommitLog0() const; - TMaybe GetTabletCommitLog1() const; - TMaybe GetExternal() const; - TMaybe GetStoreExternalBlobs() const; + std::optional GetTabletCommitLog0() const; + std::optional GetTabletCommitLog1() const; + std::optional GetExternal() const; + std::optional GetStoreExternalBlobs() const; private: class TImpl; @@ -416,9 +415,9 @@ class TColumnFamilyDescription { const Ydb::Table::ColumnFamily& GetProto() const; const std::string& GetName() const; - TMaybe GetData() const; - TMaybe GetCompression() const; - TMaybe GetKeepInMemory() const; + std::optional GetData() const; + std::optional GetCompression() const; + std::optional GetKeepInMemory() const; private: class TImpl; @@ -433,8 +432,8 @@ class TPartitioningSettings { const Ydb::Table::PartitioningSettings& GetProto() const; - TMaybe GetPartitioningBySize() const; - TMaybe GetPartitioningByLoad() const; + std::optional GetPartitioningBySize() const; + std::optional GetPartitioningByLoad() const; ui64 GetPartitionSizeMb() const; ui64 GetMinPartitionsCount() const; ui64 GetMaxPartitionsCount() const; @@ -486,8 +485,8 @@ class TTableDescription { std::vector GetTableColumns() const; std::vector GetIndexDescriptions() const; std::vector GetChangefeedDescriptions() const; - TMaybe GetTtlSettings() const; - TMaybe GetTiering() const; + std::optional GetTtlSettings() const; + std::optional GetTiering() const; EStoreType GetStoreType() const; // Deprecated. Use GetEntry() of TDescribeTableResult instead @@ -528,10 +527,10 @@ class TTableDescription { const TPartitioningSettings& GetPartitioningSettings() const; // Bloom filter by key - TMaybe GetKeyBloomFilter() const; + std::optional GetKeyBloomFilter() const; // Returns read replicas settings of the table - TMaybe GetReadReplicasSettings() const; + std::optional GetReadReplicasSettings() const; // Fills CreateTableRequest proto from this description void SerializeTo(Ydb::Table::CreateTableRequest& request) const; @@ -1179,7 +1178,7 @@ class TTxControl { TTxControl(const TTxSettings& begin); private: - TMaybe TxId_; + std::optional TxId_; TTxSettings BeginTx_; }; @@ -1452,8 +1451,8 @@ struct TAlterTableSettings : public TOperationRequestSettings& value); - const TMaybe& GetAlterTtlSettings() const; + TSelf& AlterTtlSettings(const std::optional& value); + const std::optional& GetAlterTtlSettings() const; FLUENT_SETTING(TAlterAttributes, AlterAttributes); @@ -1747,7 +1746,7 @@ class TDataQuery { public: const std::string& GetId() const; - const TMaybe& GetText() const; + const std::optional& GetText() const; TParamsBuilder GetParamsBuilder() const; TAsyncDataQueryResult Execute(const TTxControl& txControl, @@ -1814,29 +1813,29 @@ class TDescribeTableResult : public NScheme::TDescribePathResult { class TDataQueryResult : public TStatus { public: - TDataQueryResult(TStatus&& status, std::vector&& resultSets, const TMaybe& transaction, - const TMaybe& dataQuery, bool fromCache, const TMaybe& queryStats); + TDataQueryResult(TStatus&& status, std::vector&& resultSets, const std::optional& transaction, + const std::optional& dataQuery, bool fromCache, const std::optional& queryStats); const std::vector& GetResultSets() const; TResultSet GetResultSet(size_t resultIndex) const; TResultSetParser GetResultSetParser(size_t resultIndex) const; - TMaybe GetTransaction() const; + std::optional GetTransaction() const; - TMaybe GetQuery() const; + std::optional GetQuery() const; bool IsQueryFromCache() const; - const TMaybe& GetStats() const; + const std::optional& GetStats() const; const std::string GetQueryPlan() const; private: - TMaybe Transaction_; + std::optional Transaction_; std::vector ResultSets_; - TMaybe DataQuery_; + std::optional DataQuery_; bool FromCache_; - TMaybe QueryStats_; + std::optional QueryStats_; }; class TReadTableSnapshot { @@ -1895,15 +1894,15 @@ using TReadTableResultPart = TSimpleStreamPart; class TScanQueryPart : public TStreamPartStatus { public: - bool HasResultSet() const { return ResultSet_.Defined(); } + bool HasResultSet() const { return ResultSet_.has_value(); } const TResultSet& GetResultSet() const { return *ResultSet_; } TResultSet ExtractResultSet() { return std::move(*ResultSet_); } - bool HasQueryStats() const { return QueryStats_.Defined(); } + bool HasQueryStats() const { return QueryStats_.has_value(); } const TQueryStats& GetQueryStats() const { return *QueryStats_; } TQueryStats ExtractQueryStats() { return std::move(*QueryStats_); } - bool HasDiagnostics() const { return Diagnostics_.Defined(); } + bool HasDiagnostics() const { return Diagnostics_.has_value(); } const std::string& GetDiagnostics() const { return *Diagnostics_; } std::string&& ExtractDiagnostics() { return std::move(*Diagnostics_); } @@ -1911,13 +1910,13 @@ class TScanQueryPart : public TStreamPartStatus { : TStreamPartStatus(std::move(status)) {} - TScanQueryPart(TStatus&& status, const TMaybe& queryStats, const TMaybe& diagnostics) + TScanQueryPart(TStatus&& status, const std::optional& queryStats, const std::optional& diagnostics) : TStreamPartStatus(std::move(status)) , QueryStats_(queryStats) , Diagnostics_(diagnostics) {} - TScanQueryPart(TStatus&& status, TResultSet&& resultSet, const TMaybe& queryStats, const TMaybe& diagnostics) + TScanQueryPart(TStatus&& status, TResultSet&& resultSet, const std::optional& queryStats, const std::optional& diagnostics) : TStreamPartStatus(std::move(status)) , ResultSet_(std::move(resultSet)) , QueryStats_(queryStats) @@ -1925,9 +1924,9 @@ class TScanQueryPart : public TStreamPartStatus { {} private: - TMaybe ResultSet_; - TMaybe QueryStats_; - TMaybe Diagnostics_; + std::optional ResultSet_; + std::optional QueryStats_; + std::optional Diagnostics_; }; using TAsyncScanQueryPart = NThreading::TFuture; @@ -1957,12 +1956,12 @@ class TBeginTransactionResult : public TStatus { class TCommitTransactionResult : public TStatus { public: - TCommitTransactionResult(TStatus&& status, const TMaybe& queryStats); + TCommitTransactionResult(TStatus&& status, const std::optional& queryStats); - const TMaybe& GetStats() const; + const std::optional& GetStats() const; private: - TMaybe QueryStats_; + std::optional QueryStats_; }; class TCreateSessionResult: public TStatus { diff --git a/client/ydb_topic/impl/read_session.cpp b/client/ydb_topic/impl/read_session.cpp index 2ed95291b33..7675b32efc2 100644 --- a/client/ydb_topic/impl/read_session.cpp +++ b/client/ydb_topic/impl/read_session.cpp @@ -21,7 +21,7 @@ TReadSession::TReadSession(const TReadSessionSettings& settings, TDbDriverStatePtr dbDriverState) : Settings(settings) , SessionId(CreateGuidAsString()) - , Log(settings.Log_.GetOrElse(dbDriverState->Log)) + , Log(settings.Log_.value_or(dbDriverState->Log)) , Client(std::move(client)) , Connections(std::move(connections)) , DbDriverState(std::move(dbDriverState)) @@ -124,7 +124,7 @@ NThreading::TFuture TReadSession::WaitEvent() { return EventsQueue->WaitEvent(); } -std::vector TReadSession::GetEvents(bool block, TMaybe maxEventsCount, size_t maxByteSize) { +std::vector TReadSession::GetEvents(bool block, std::optional maxEventsCount, size_t maxByteSize) { auto res = EventsQueue->GetEvents(block, maxEventsCount, maxByteSize); if (EventsQueue->IsClosed()) { Abort(EStatus::ABORTED, "Aborted"); @@ -147,7 +147,7 @@ std::vector TReadSession::GetEvents(const TReadSessio return events; } -TMaybe TReadSession::GetEvent(bool block, size_t maxByteSize) { +std::optional TReadSession::GetEvent(bool block, size_t maxByteSize) { auto res = EventsQueue->GetEvent(block, maxByteSize); if (EventsQueue->IsClosed()) { Abort(EStatus::ABORTED, "Aborted"); @@ -155,7 +155,7 @@ TMaybe TReadSession::GetEvent(bool block, size_t maxB return res; } -TMaybe TReadSession::GetEvent(const TReadSessionGetEventSettings& settings) +std::optional TReadSession::GetEvent(const TReadSessionGetEventSettings& settings) { auto event = GetEvent(settings.Block_, settings.MaxByteSize_); if (event) { diff --git a/client/ydb_topic/impl/read_session.h b/client/ydb_topic/impl/read_session.h index 32ad1eb60ff..c48a6023ef4 100644 --- a/client/ydb_topic/impl/read_session.h +++ b/client/ydb_topic/impl/read_session.h @@ -21,12 +21,12 @@ class TReadSession : public IReadSession { NThreading::TFuture WaitEvent() override; std::vector GetEvents(bool block, - TMaybe maxEventsCount, + std::optional maxEventsCount, size_t maxByteSize) override; std::vector GetEvents(const TReadSessionGetEventSettings& settings) override; - TMaybe GetEvent(bool block, + std::optional GetEvent(bool block, size_t maxByteSize) override; - TMaybe GetEvent(const TReadSessionGetEventSettings& settings) override; + std::optional GetEvent(const TReadSessionGetEventSettings& settings) override; bool Close(TDuration timeout) override; diff --git a/client/ydb_topic/impl/read_session_event.cpp b/client/ydb_topic/impl/read_session_event.cpp index c4506e7d593..852103a4422 100644 --- a/client/ydb_topic/impl/read_session_event.cpp +++ b/client/ydb_topic/impl/read_session_event.cpp @@ -297,7 +297,7 @@ TStartPartitionSessionEvent::TStartPartitionSessionEvent(TPartitionSession::TPtr , EndOffset(endOffset) { } -void TStartPartitionSessionEvent::Confirm(TMaybe readOffset, TMaybe commitOffset) { +void TStartPartitionSessionEvent::Confirm(std::optional readOffset, std::optional commitOffset) { if (PartitionSession) { static_cast*>(PartitionSession.Get()) ->ConfirmCreate(readOffset, commitOffset); diff --git a/client/ydb_topic/impl/topic.cpp b/client/ydb_topic/impl/topic.cpp index 949dfab19be..2e36009d269 100644 --- a/client/ydb_topic/impl/topic.cpp +++ b/client/ydb_topic/impl/topic.cpp @@ -51,7 +51,7 @@ TTopicDescription::TTopicDescription(Ydb::Topic::DescribeTopicResult&& result) : Proto_(std::move(result)) , PartitioningSettings_(Proto_.partitioning_settings()) , RetentionPeriod_(TDuration::Seconds(Proto_.retention_period().seconds())) - , RetentionStorageMb_(Proto_.retention_storage_mb() > 0 ? TMaybe(Proto_.retention_storage_mb()) : Nothing()) + , RetentionStorageMb_(Proto_.retention_storage_mb() > 0 ? std::optional(Proto_.retention_storage_mb()) : std::nullopt) , PartitionWriteSpeedBytesPerSecond_(Proto_.partition_write_speed_bytes_per_second()) , PartitionWriteBurstBytes_(Proto_.partition_write_burst_bytes()) , MeteringMode_(TProtoAccessor::FromProto(Proto_.metering_mode())) @@ -156,7 +156,7 @@ const TDuration& TTopicDescription::GetRetentionPeriod() const { return RetentionPeriod_; } -TMaybe TTopicDescription::GetRetentionStorageMb() const { +std::optional TTopicDescription::GetRetentionStorageMb() const { return RetentionStorageMb_; } @@ -389,15 +389,15 @@ TPartitionInfo::TPartitionInfo(const Ydb::Topic::DescribeConsumerResult::Partiti } } -const TMaybe& TPartitionInfo::GetPartitionStats() const { +const std::optional& TPartitionInfo::GetPartitionStats() const { return PartitionStats_; } -const TMaybe& TPartitionInfo::GetPartitionConsumerStats() const { +const std::optional& TPartitionInfo::GetPartitionConsumerStats() const { return PartitionConsumerStats_; } -const TMaybe& TPartitionInfo::GetPartitionLocation() const { +const std::optional& TPartitionInfo::GetPartitionLocation() const { return PartitionLocation_; } diff --git a/client/ydb_topic/impl/topic_impl.cpp b/client/ydb_topic/impl/topic_impl.cpp index 603815e726c..cbbea0fd7fd 100644 --- a/client/ydb_topic/impl/topic_impl.cpp +++ b/client/ydb_topic/impl/topic_impl.cpp @@ -9,7 +9,7 @@ namespace NYdb::NTopic { std::shared_ptr TTopicClient::TImpl::CreateReadSession(const TReadSessionSettings& settings) { - TMaybe maybeSettings; + std::optional maybeSettings; if (!settings.DecompressionExecutor_ || !settings.EventHandlers_.HandlersExecutor_) { maybeSettings = settings; with_lock (Lock) { @@ -21,7 +21,7 @@ std::shared_ptr TTopicClient::TImpl::CreateReadSession(const TRead } } } - auto session = std::make_shared(maybeSettings.GetOrElse(settings), shared_from_this(), Connections_, DbDriverState_); + auto session = std::make_shared(maybeSettings.value_or(settings), shared_from_this(), Connections_, DbDriverState_); session->Start(); return std::move(session); } @@ -29,7 +29,7 @@ std::shared_ptr TTopicClient::TImpl::CreateReadSession(const TRead std::shared_ptr TTopicClient::TImpl::CreateWriteSession( const TWriteSessionSettings& settings ) { - TMaybe maybeSettings; + std::optional maybeSettings; if (!settings.CompressionExecutor_ || !settings.EventHandlers_.HandlersExecutor_) { maybeSettings = settings; with_lock (Lock) { @@ -42,7 +42,7 @@ std::shared_ptr TTopicClient::TImpl::CreateWriteSession( } } auto session = std::make_shared( - maybeSettings.GetOrElse(settings), shared_from_this(), Connections_, DbDriverState_ + maybeSettings.value_or(settings), shared_from_this(), Connections_, DbDriverState_ ); session->Start(TDuration::Zero()); return std::move(session); diff --git a/client/ydb_topic/impl/write_session.cpp b/client/ydb_topic/impl/write_session.cpp index c3ba716586b..a365f4fb323 100644 --- a/client/ydb_topic/impl/write_session.cpp +++ b/client/ydb_topic/impl/write_session.cpp @@ -23,11 +23,11 @@ NThreading::TFuture TWriteSession::GetInitSeqNo() { return TryGetImpl()->GetInitSeqNo(); } -TMaybe TWriteSession::GetEvent(bool block) { +std::optional TWriteSession::GetEvent(bool block) { return TryGetImpl()->EventsQueue->GetEvent(block); } -std::vector TWriteSession::GetEvents(bool block, TMaybe maxEventsCount) { +std::vector TWriteSession::GetEvents(bool block, std::optional maxEventsCount) { return TryGetImpl()->EventsQueue->GetEvents(block, maxEventsCount); } @@ -36,11 +36,11 @@ NThreading::TFuture TWriteSession::WaitEvent() { } void TWriteSession::WriteEncoded(TContinuationToken&& token, std::string_view data, ECodec codec, ui32 originalSize, - TMaybe seqNo, TMaybe createTimestamp) { + std::optional seqNo, std::optional createTimestamp) { auto message = TWriteMessage::CompressedMessage(std::move(data), codec, originalSize); - if (seqNo.Defined()) + if (seqNo.has_value()) message.SeqNo(*seqNo); - if (createTimestamp.Defined()) + if (createTimestamp.has_value()) message.CreateTimestamp(*createTimestamp); TryGetImpl()->WriteInternal(std::move(token), std::move(message)); } @@ -50,12 +50,12 @@ void TWriteSession::WriteEncoded(TContinuationToken&& token, TWriteMessage&& mes TryGetImpl()->WriteInternal(std::move(token), std::move(message)); } -void TWriteSession::Write(TContinuationToken&& token, std::string_view data, TMaybe seqNo, - TMaybe createTimestamp) { +void TWriteSession::Write(TContinuationToken&& token, std::string_view data, std::optional seqNo, + std::optional createTimestamp) { TWriteMessage message{std::move(data)}; - if (seqNo.Defined()) + if (seqNo.has_value()) message.SeqNo(*seqNo); - if (createTimestamp.Defined()) + if (createTimestamp.has_value()) message.CreateTimestamp(*createTimestamp); TryGetImpl()->WriteInternal(std::move(token), std::move(message)); } @@ -107,7 +107,7 @@ ui64 TSimpleBlockingWriteSession::GetInitSeqNo() { } bool TSimpleBlockingWriteSession::Write( - std::string_view data, TMaybe seqNo, TMaybe createTimestamp, const TDuration& blockTimeout + std::string_view data, std::optional seqNo, std::optional createTimestamp, const TDuration& blockTimeout ) { auto message = TWriteMessage(std::move(data)) .SeqNo(seqNo) @@ -119,42 +119,42 @@ bool TSimpleBlockingWriteSession::Write( TWriteMessage&& message, const TDuration& blockTimeout ) { auto continuationToken = WaitForToken(blockTimeout); - if (continuationToken.Defined()) { + if (continuationToken.has_value()) { Writer->Write(std::move(*continuationToken), std::move(message)); return true; } return false; } -TMaybe TSimpleBlockingWriteSession::WaitForToken(const TDuration& timeout) { +std::optional TSimpleBlockingWriteSession::WaitForToken(const TDuration& timeout) { TInstant startTime = TInstant::Now(); TDuration remainingTime = timeout; - TMaybe token = Nothing(); + std::optional token = std::nullopt; while (IsAlive() && remainingTime > TDuration::Zero()) { Writer->WaitEvent().Wait(remainingTime); for (auto event : Writer->GetEvents()) { if (auto* readyEvent = std::get_if(&event)) { - Y_ABORT_UNLESS(token.Empty()); + Y_ABORT_UNLESS(!token.has_value()); token = std::move(readyEvent->ContinuationToken); } else if (auto* ackEvent = std::get_if(&event)) { // discard } else if (auto* closeSessionEvent = std::get_if(&event)) { Closed.store(true); - return Nothing(); + return std::nullopt; } } - if (token.Defined()) { + if (token.has_value()) { return token; } remainingTime = timeout - (TInstant::Now() - startTime); } - return Nothing(); + return std::nullopt; } TWriterCounters::TPtr TSimpleBlockingWriteSession::GetCounters() { diff --git a/client/ydb_topic/impl/write_session.h b/client/ydb_topic/impl/write_session.h index 483ed60ffbc..85db4feaa42 100644 --- a/client/ydb_topic/impl/write_session.h +++ b/client/ydb_topic/impl/write_session.h @@ -28,16 +28,16 @@ class TWriteSession : public IWriteSession, std::shared_ptr connections, TDbDriverStatePtr dbDriverState); - TMaybe GetEvent(bool block = false) override; + std::optional GetEvent(bool block = false) override; std::vector GetEvents(bool block = false, - TMaybe maxEventsCount = Nothing()) override; + std::optional maxEventsCount = std::nullopt) override; NThreading::TFuture GetInitSeqNo() override; void Write(TContinuationToken&& continuationToken, std::string_view data, - TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing()) override; + std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt) override; void WriteEncoded(TContinuationToken&& continuationToken, std::string_view data, ECodec codec, ui32 originalSize, - TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing()) override; + std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt) override; void Write(TContinuationToken&& continuationToken, TWriteMessage&& message) override; @@ -67,7 +67,7 @@ class TSimpleBlockingWriteSession : public ISimpleBlockingWriteSession { std::shared_ptr connections, TDbDriverStatePtr dbDriverState); - bool Write(std::string_view data, TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing(), + bool Write(std::string_view data, std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt, const TDuration& blockTimeout = TDuration::Max()) override; bool Write(TWriteMessage&& message, const TDuration& blockTimeout = TDuration::Max()) override; @@ -83,7 +83,7 @@ class TSimpleBlockingWriteSession : public ISimpleBlockingWriteSession { std::shared_ptr Writer; private: - TMaybe WaitForToken(const TDuration& timeout); + std::optional WaitForToken(const TDuration& timeout); void HandleAck(TWriteSessionEvent::TAcksEvent&); void HandleReady(TWriteSessionEvent::TReadyToAcceptEvent&); void HandleClosed(const TSessionClosedEvent&); diff --git a/client/ydb_topic/impl/write_session_impl.cpp b/client/ydb_topic/impl/write_session_impl.cpp index 55859edc7f9..a7ee75de83b 100644 --- a/client/ydb_topic/impl/write_session_impl.cpp +++ b/client/ydb_topic/impl/write_session_impl.cpp @@ -57,8 +57,8 @@ TWriteSessionImpl::TWriteSessionImpl( , PrevToken(DbDriverState->CredentialsProvider ? DbDriverState->CredentialsProvider->GetAuthInfo() : "") , InitSeqNoPromise(NThreading::NewPromise()) , WakeupInterval( - Settings.BatchFlushInterval_.GetOrElse(TDuration::Zero()) ? - std::min(Settings.BatchFlushInterval_.GetOrElse(TDuration::Seconds(1)) / 5, TDuration::MilliSeconds(100)) + Settings.BatchFlushInterval_.value_or(TDuration::Zero()) ? + std::min(Settings.BatchFlushInterval_.value_or(TDuration::Seconds(1)) / 5, TDuration::MilliSeconds(100)) : TDuration::MilliSeconds(100) ) @@ -66,7 +66,7 @@ TWriteSessionImpl::TWriteSessionImpl( if (!Settings.RetryPolicy_) { Settings.RetryPolicy_ = IRetryPolicy::GetDefaultPolicy(); } - if (Settings.Counters_.Defined()) { + if (Settings.Counters_.has_value()) { Counters = *Settings.Counters_; } else { Counters = MakeIntrusive(new ::NMonitoring::TDynamicCounters()); @@ -104,7 +104,7 @@ void TWriteSessionImpl::Start(const TDuration& delay) { } Started = true; - if (Settings.PartitionId_.Defined() && Settings.DirectWriteToPartition_) + if (Settings.PartitionId_.has_value() && Settings.DirectWriteToPartition_) { with_lock (Lock) { PreferredPartitionLocation = {}; @@ -128,13 +128,13 @@ TWriteSessionImpl::THandleResult TWriteSessionImpl::RestartImpl(const TPlainStat } LOG_LAZY(DbDriverState->Log, TLOG_ERR, LogPrefix() << "Got error. " << status.ToDebugString()); SessionEstablished = false; - TMaybe nextDelay = TDuration::Zero(); + std::optional nextDelay = TDuration::Zero(); if (!RetryState) { RetryState = Settings.RetryPolicy_->CreateRetryState(); } nextDelay = RetryState->GetNextRetryDelay(status.Status); - if (nextDelay) { + if (nextDelay.has_value()) { result.StartDelay = *nextDelay; result.DoRestart = true; LOG_LAZY(DbDriverState->Log, TLOG_WARNING, LogPrefix() << "Write session will restart in " << result.StartDelay); @@ -151,7 +151,7 @@ TWriteSessionImpl::THandleResult TWriteSessionImpl::RestartImpl(const TPlainStat void TWriteSessionImpl::ConnectToPreferredPartitionLocation(const TDuration& delay) { Y_ABORT_UNLESS(Lock.IsLocked()); - Y_ABORT_UNLESS(Settings.PartitionId_.Defined() && Settings.DirectWriteToPartition_); + Y_ABORT_UNLESS(Settings.PartitionId_.has_value() && Settings.DirectWriteToPartition_); if (AtomicGet(Aborting)) { return; @@ -235,12 +235,12 @@ void TWriteSessionImpl::OnDescribePartition(const TStatus& status, const Ydb::To return; } - TMaybe preferredEndpoint; + std::optional preferredEndpoint; with_lock (Lock) { preferredEndpoint = GetPreferredEndpointImpl(*Settings.PartitionId_, partition.partition_location().node_id()); } - if (!preferredEndpoint.Defined()) { + if (!preferredEndpoint.has_value()) { with_lock (Lock) { handleResult = OnErrorImpl({EStatus::UNAVAILABLE, "Partition preferred endpoint is not found"}); } @@ -255,7 +255,7 @@ void TWriteSessionImpl::OnDescribePartition(const TStatus& status, const Ydb::To Connect(TDuration::Zero()); } -TMaybe TWriteSessionImpl::GetPreferredEndpointImpl(ui32 partitionId, ui64 partitionNodeId) { +std::optional TWriteSessionImpl::GetPreferredEndpointImpl(ui32 partitionId, ui64 partitionNodeId) { Y_ABORT_UNLESS(Lock.IsLocked()); TEndpointKey preferredEndpoint{"", partitionNodeId}; @@ -279,10 +279,10 @@ std::string GenerateProducerId() { } void TWriteSessionImpl::InitWriter() { // No Lock, very initial start - no race yet as well. - if (!Settings.DeduplicationEnabled_.Defined()) { + if (!Settings.DeduplicationEnabled_.has_value()) { Settings.DeduplicationEnabled_ = !(Settings.ProducerId_.empty()); } - else if (Settings.DeduplicationEnabled_.GetRef()) { + else if (Settings.DeduplicationEnabled_.value()) { if (Settings.ProducerId_.empty()) { Settings.ProducerId(GenerateProducerId()); } @@ -304,12 +304,12 @@ void TWriteSessionImpl::InitWriter() { // No Lock, very initial start - no race } // Client method NThreading::TFuture TWriteSessionImpl::GetInitSeqNo() { - if (!Settings.DeduplicationEnabled_.GetOrElse(true)) { + if (!Settings.DeduplicationEnabled_.value_or(true)) { LOG_LAZY(DbDriverState->Log, TLOG_ERR, LogPrefix() << "GetInitSeqNo called with deduplication disabled"); ThrowFatalError("Cannot call GetInitSeqNo when deduplication is disabled"); } if (Settings.ValidateSeqNo_) { - if (AutoSeqNoMode.Defined() && *AutoSeqNoMode) { + if (AutoSeqNoMode.has_value() && *AutoSeqNoMode) { LOG_LAZY(DbDriverState->Log, TLOG_ERR, LogPrefix() << "Cannot call GetInitSeqNo in Auto SeqNo mode"); ThrowFatalError("Cannot call GetInitSeqNo in Auto SeqNo mode"); } @@ -324,38 +324,38 @@ std::string DebugString(const TWriteSessionEvent::TEvent& event) { } // Client method -TMaybe TWriteSessionImpl::GetEvent(bool block) { +std::optional TWriteSessionImpl::GetEvent(bool block) { return EventsQueue->GetEvent(block); } // Client method -std::vector TWriteSessionImpl::GetEvents(bool block, TMaybe maxEventsCount) { +std::vector TWriteSessionImpl::GetEvents(bool block, std::optional maxEventsCount) { return EventsQueue->GetEvents(block, maxEventsCount); } ui64 TWriteSessionImpl::GetIdImpl(ui64 seqNo) { - Y_ABORT_UNLESS(AutoSeqNoMode.Defined()); - Y_ABORT_UNLESS(!*AutoSeqNoMode || InitSeqNo.Defined() && seqNo > *InitSeqNo); + Y_ABORT_UNLESS(AutoSeqNoMode.has_value()); + Y_ABORT_UNLESS(!*AutoSeqNoMode || InitSeqNo.has_value() && seqNo > *InitSeqNo); return *AutoSeqNoMode ? seqNo - *InitSeqNo : seqNo; } ui64 TWriteSessionImpl::GetSeqNoImpl(ui64 id) { - Y_ABORT_UNLESS(AutoSeqNoMode.Defined()); - Y_ABORT_UNLESS(InitSeqNo.Defined()); + Y_ABORT_UNLESS(AutoSeqNoMode.has_value()); + Y_ABORT_UNLESS(InitSeqNo.has_value()); return *AutoSeqNoMode ? id + *InitSeqNo : id; } -ui64 TWriteSessionImpl::GetNextIdImpl(const TMaybe& seqNo) { +ui64 TWriteSessionImpl::GetNextIdImpl(const std::optional& seqNo) { Y_ABORT_UNLESS(Lock.IsLocked()); ui64 id = ++NextId; - if (!AutoSeqNoMode.Defined()) { - AutoSeqNoMode = !seqNo.Defined(); + if (!AutoSeqNoMode.has_value()) { + AutoSeqNoMode = !seqNo.has_value(); } - if (seqNo.Defined()) { - if (!Settings.DeduplicationEnabled_.GetOrElse(true)) { + if (seqNo.has_value()) { + if (!Settings.DeduplicationEnabled_.value_or(true)) { LOG_LAZY(DbDriverState->Log, TLOG_ERR, LogPrefix() << "SeqNo is provided on write when deduplication is disabled"); ThrowFatalError("Cannot provide SeqNo on Write() when deduplication is disabled"); } @@ -401,7 +401,7 @@ NThreading::TFuture TWriteSessionImpl::WaitEvent() { } void TWriteSessionImpl::WriteInternal(TContinuationToken&&, TWriteMessage&& message) { - TInstant createdAtValue = message.CreateTimestamp_.Defined() ? *message.CreateTimestamp_ : TInstant::Now(); + TInstant createdAtValue = message.CreateTimestamp_.value_or(TInstant::Now()); bool readyToAccept = false; size_t bufferSize = message.Data.size(); with_lock(Lock) { @@ -602,7 +602,7 @@ void TWriteSessionImpl::InitImpl() { init->set_path(Settings.Path_); init->set_producer_id(Settings.ProducerId_); - if (Settings.PartitionId_.Defined()) { + if (Settings.PartitionId_.has_value()) { if (Settings.DirectWriteToPartition_) { auto* partitionWithGeneration = init->mutable_partition_with_generation(); partitionWithGeneration->set_partition_id(*Settings.PartitionId_); @@ -707,7 +707,7 @@ void TWriteSessionImpl::OnReadDone(NYdbGrpc::TGrpcStatus&& grpcStatus, size_t co errorStatus = NPersQueue::MakeErrorFromProto(*ServerMessage); } else { processResult = ProcessServerMessageImpl(); - needSetValue = !InitSeqNoSetDone && processResult.InitSeqNo.Defined() && (InitSeqNoSetDone = true); + needSetValue = !InitSeqNoSetDone && processResult.InitSeqNo.has_value() && (InitSeqNoSetDone = true); if (errorStatus.Ok() && processResult.Ok) { doRead = true; } @@ -741,7 +741,7 @@ NUtils::TYdbStringBuilder TWriteSessionImpl::LogPrefix() const { NUtils::TYdbStringBuilder ret; ret << " SessionId [" << SessionId << "] "; - if (Settings.PartitionId_.Defined()) { + if (Settings.PartitionId_.has_value()) { ret << " PartitionId [" << *Settings.PartitionId_ << "] "; if (Settings.DirectWriteToPartition_) ret << " Generation [" << PreferredPartitionLocation.Generation << "] "; @@ -798,11 +798,11 @@ TWriteSessionImpl::TProcessSrvMessageResult TWriteSessionImpl::ProcessServerMess SessionId = initResponse.session_id(); PartitionId = initResponse.partition_id(); ui64 newLastSeqNo = initResponse.last_seq_no(); - if (!Settings.DeduplicationEnabled_.GetOrElse(true)) { + if (!Settings.DeduplicationEnabled_.value_or(true)) { newLastSeqNo = 0; } result.InitSeqNo = newLastSeqNo; - if (!InitSeqNo.Defined()) { + if (!InitSeqNo.has_value()) { InitSeqNo = newLastSeqNo; } @@ -1056,8 +1056,8 @@ void TWriteSessionImpl::FlushWriteIfRequiredImpl() { if (!CurrentBatch.Empty() && !CurrentBatch.FlushRequested) { MessagesAcquired += static_cast(CurrentBatch.Acquire()); - if (TInstant::Now() - CurrentBatch.StartedAt >= Settings.BatchFlushInterval_.GetOrElse(TDuration::Zero()) - || CurrentBatch.CurrentSize >= Settings.BatchFlushSizeBytes_.GetOrElse(0) + if (TInstant::Now() - CurrentBatch.StartedAt >= Settings.BatchFlushInterval_.value_or(TDuration::Zero()) + || CurrentBatch.CurrentSize >= Settings.BatchFlushSizeBytes_.value_or(0) || CurrentBatch.CurrentSize >= MaxBlockSize || CurrentBatch.Messages.size() >= MaxBlockMessageCount || CurrentBatch.HasCodec() @@ -1101,7 +1101,7 @@ size_t TWriteSessionImpl::WriteBatchImpl() { block.OriginalSize += datum.size(); block.OriginalMemoryUsage = CurrentBatch.Data.size(); block.OriginalDataRefs.emplace_back(datum); - if (CurrentBatch.Messages[i].Codec.Defined()) { + if (CurrentBatch.Messages[i].Codec.has_value()) { Y_ABORT_UNLESS(CurrentBatch.Messages.size() == 1); block.CodecID = static_cast(*currMessage.Codec); block.OriginalSize = currMessage.OriginalSize; diff --git a/client/ydb_topic/impl/write_session_impl.h b/client/ydb_topic/impl/write_session_impl.h index d705196ebff..8cc230e01cd 100644 --- a/client/ydb_topic/impl/write_session_impl.h +++ b/client/ydb_topic/impl/write_session_impl.h @@ -44,8 +44,8 @@ class TWriteSessionEventsQueue: public NPersQueue::TBaseSessionEventsQueue GetEvent(bool block = false) { - TMaybe eventInfo; + std::optional GetEvent(bool block = false) { + std::optional eventInfo; { std::lock_guard guard(Mutex); if (block) { @@ -54,21 +54,21 @@ class TWriteSessionEventsQueue: public NPersQueue::TBaseSessionEventsQueueOnUserRetrievedEvent(); return std::move(eventInfo->Event); } - std::vector GetEvents(bool block = false, TMaybe maxEventsCount = Nothing()) { + std::vector GetEvents(bool block = false, std::optional maxEventsCount = std::nullopt) { std::vector eventInfos; { std::lock_guard guard(Mutex); if (block) { WaitEventsImpl(); } - eventInfos.reserve(Min(Events.size() + CloseEvent.Defined(), maxEventsCount ? *maxEventsCount : std::numeric_limits::max())); + eventInfos.reserve(Min(Events.size() + CloseEvent.has_value(), maxEventsCount ? *maxEventsCount : std::numeric_limits::max())); while (!Events.empty()) { eventInfos.emplace_back(GetEventImpl()); if (maxEventsCount && eventInfos.size() >= *maxEventsCount) { @@ -172,12 +172,12 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, ui64 Id; TInstant CreatedAt; std::string_view DataRef; - TMaybe Codec; + std::optional Codec; ui32 OriginalSize; // only for coded messages std::vector> MessageMeta; const NTable::TTransaction* Tx; - TMessage(ui64 id, const TInstant& createdAt, std::string_view data, TMaybe codec = {}, + TMessage(ui64 id, const TInstant& createdAt, std::string_view data, std::optional codec = {}, ui32 originalSize = 0, const std::vector>& messageMeta = {}, const NTable::TTransaction* tx = nullptr) : Id(id) @@ -198,7 +198,7 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, bool Acquired = false; bool FlushRequested = false; - void Add(ui64 id, const TInstant& createdAt, std::string_view data, TMaybe codec, ui32 originalSize, + void Add(ui64 id, const TInstant& createdAt, std::string_view data, std::optional codec, ui32 originalSize, const std::vector>& messageMeta, const NTable::TTransaction* tx) { if (StartedAt == TInstant::Zero()) @@ -209,7 +209,7 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, } bool HasCodec() const { - return Messages.empty() ? false : Messages.front().Codec.Defined(); + return Messages.empty() ? false : Messages.front().Codec.has_value(); } bool Acquire() { @@ -310,7 +310,7 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, }; struct TProcessSrvMessageResult { THandleResult HandleResult; - TMaybe InitSeqNo; + std::optional InitSeqNo; std::vector Events; bool Ok = true; }; @@ -328,15 +328,15 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, std::shared_ptr connections, TDbDriverStatePtr dbDriverState); - TMaybe GetEvent(bool block = false); + std::optional GetEvent(bool block = false); std::vector GetEvents(bool block = false, - TMaybe maxEventsCount = Nothing()); + std::optional maxEventsCount = std::nullopt); NThreading::TFuture GetInitSeqNo(); void Write(TContinuationToken&& continuationToken, TWriteMessage&& message); - void Write(TContinuationToken&&, std::string_view, TMaybe seqNo = Nothing(), - TMaybe createTimestamp = Nothing()) { + void Write(TContinuationToken&&, std::string_view, std::optional seqNo = std::nullopt, + std::optional createTimestamp = std::nullopt) { Y_UNUSED(seqNo); Y_UNUSED(createTimestamp); Y_ABORT("Do not use this method"); @@ -345,7 +345,7 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, void WriteEncoded(TContinuationToken&& continuationToken, TWriteMessage&& message); void WriteEncoded(TContinuationToken&&, std::string_view, ECodec, ui32, - TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing()) { + std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt) { Y_UNUSED(seqNo); Y_UNUSED(createTimestamp); Y_ABORT("Do not use this method"); @@ -399,7 +399,7 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, TClientMessage GetInitClientMessage(); bool CleanupOnAcknowledged(ui64 id); bool IsReadyToSendNextImpl() const; - ui64 GetNextIdImpl(const TMaybe& seqNo); + ui64 GetNextIdImpl(const std::optional& seqNo); ui64 GetSeqNoImpl(ui64 id); ui64 GetIdImpl(ui64 seqNo); void SendImpl(); @@ -419,7 +419,7 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, void ConnectToPreferredPartitionLocation(const TDuration& delay); void OnDescribePartition(const TStatus& status, const Ydb::Topic::DescribePartitionResult& proto, const NYdbGrpc::IQueueClientContextPtr& describePartitionContext); - TMaybe GetPreferredEndpointImpl(ui32 partitionId, ui64 partitionNodeId); + std::optional GetPreferredEndpointImpl(ui32 partitionId, ui64 partitionNodeId); private: TWriteSessionSettings Settings; @@ -471,8 +471,8 @@ class TWriteSessionImpl : public TContinuationTokenIssuer, TPartitionLocation PreferredPartitionLocation = {}; ui64 NextId = 0; ui64 MinUnsentId = 1; - TMaybe InitSeqNo; - TMaybe AutoSeqNoMode; + std::optional InitSeqNo; + std::optional AutoSeqNoMode; bool ValidateSeqNoMode = false; NThreading::TPromise InitSeqNoPromise; diff --git a/client/ydb_topic/topic.h b/client/ydb_topic/topic.h index 26996595c7a..d61503fb049 100644 --- a/client/ydb_topic/topic.h +++ b/client/ydb_topic/topic.h @@ -11,7 +11,6 @@ #include #include -#include #include #include #include @@ -156,18 +155,18 @@ class TPartitionInfo { const std::vector GetChildPartitionIds() const; const std::vector GetParentPartitionIds() const; - const TMaybe& GetPartitionStats() const; - const TMaybe& GetPartitionConsumerStats() const; - const TMaybe& GetPartitionLocation() const; + const std::optional& GetPartitionStats() const; + const std::optional& GetPartitionConsumerStats() const; + const std::optional& GetPartitionLocation() const; private: ui64 PartitionId_; bool Active_; std::vector ChildPartitionIds_; std::vector ParentPartitionIds_; - TMaybe PartitionStats_; - TMaybe PartitionConsumerStats_; - TMaybe PartitionLocation_; + std::optional PartitionStats_; + std::optional PartitionConsumerStats_; + std::optional PartitionLocation_; }; class TPartitioningSettings { @@ -210,7 +209,7 @@ class TTopicDescription { const TDuration& GetRetentionPeriod() const; - TMaybe GetRetentionStorageMb() const; + std::optional GetRetentionStorageMb() const; ui64 GetPartitionWriteSpeedBytesPerSecond() const; @@ -234,7 +233,7 @@ class TTopicDescription { std::vector SupportedCodecs_; TPartitioningSettings PartitioningSettings_; TDuration RetentionPeriod_; - TMaybe RetentionStorageMb_; + std::optional RetentionStorageMb_; ui64 PartitionWriteSpeedBytesPerSecond_; ui64 PartitionWriteBurstBytes_; EMeteringMode MeteringMode_; @@ -999,7 +998,7 @@ struct TReadSessionEvent { //! Confirm partition session creation. //! This signals that user is ready to receive data from this partition session. //! If maybe is empty then no rewinding - void Confirm(TMaybe readOffset = Nothing(), TMaybe commitOffset = Nothing()); + void Confirm(std::optional readOffset = std::nullopt, std::optional commitOffset = std::nullopt); private: ui64 CommittedOffset; @@ -1236,7 +1235,7 @@ struct TWriteSessionEvent { ui64 SeqNo; EEventState State; //! Filled only for EES_WRITTEN. Empty for ALREADY and DISCARDED. - TMaybe Details; + std::optional Details; //! Write stats from server. See TWriteStat. nullptr for DISCARDED event. TWriteStat::TPtr Stat; }; @@ -1594,7 +1593,7 @@ struct TWriteMessage { } bool Compressed() const { - return Codec.Defined(); + return Codec.has_value(); } //! Message body. @@ -1603,7 +1602,7 @@ struct TWriteMessage { //! Codec and original size for compressed message. //! Do not specify or change these options directly, use CompressedMessage() //! method to create an object for compressed message. - TMaybe Codec; + std::optional Codec; ui32 OriginalSize = 0; //! Message SeqNo, optional. If not provided SDK core will calculate SeqNo automatically. @@ -1635,7 +1634,7 @@ class ISimpleBlockingWriteSession : public TThrRefBase { //! Write single message. Deprecated method with only basic message options. - virtual bool Write(std::string_view data, TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing(), + virtual bool Write(std::string_view data, std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt, const TDuration& blockTimeout = TDuration::Max()) = 0; //! Blocks till SeqNo is discovered from server. Returns 0 in case of failure on init. @@ -1663,13 +1662,13 @@ class IWriteSession { virtual NThreading::TFuture WaitEvent() = 0; //! Wait and return next event. Use WaitEvent() for non-blocking wait. - virtual TMaybe GetEvent(bool block = false) = 0; + virtual std::optional GetEvent(bool block = false) = 0; //! Get several events in one call. //! If blocking = false, instantly returns up to maxEventsCount available events. //! If blocking = true, blocks till maxEventsCount events are available. //! If maxEventsCount is unset, write session decides the count to return itself. - virtual std::vector GetEvents(bool block = false, TMaybe maxEventsCount = Nothing()) = 0; + virtual std::vector GetEvents(bool block = false, std::optional maxEventsCount = std::nullopt) = 0; //! Future that is set when initial SeqNo is available. virtual NThreading::TFuture GetInitSeqNo() = 0; @@ -1679,8 +1678,8 @@ class IWriteSession { virtual void Write(TContinuationToken&& continuationToken, TWriteMessage&& message) = 0; //! Write single message. Old method with only basic message options. - virtual void Write(TContinuationToken&& continuationToken, std::string_view data, TMaybe seqNo = Nothing(), - TMaybe createTimestamp = Nothing()) = 0; + virtual void Write(TContinuationToken&& continuationToken, std::string_view data, std::optional seqNo = std::nullopt, + std::optional createTimestamp = std::nullopt) = 0; //! Write single message that is already coded by codec. //! continuationToken - a token earlier provided to client with ReadyToAccept event. @@ -1688,7 +1687,7 @@ class IWriteSession { //! Write single message that is already compressed by codec. Old method with only basic message options. virtual void WriteEncoded(TContinuationToken&& continuationToken, std::string_view data, ECodec codec, ui32 originalSize, - TMaybe seqNo = Nothing(), TMaybe createTimestamp = Nothing()) = 0; + std::optional seqNo = std::nullopt, std::optional createTimestamp = std::nullopt) = 0; //! Wait for all writes to complete (no more that closeTimeout()), than close. Empty maybe - means infinite timeout. @@ -1727,16 +1726,16 @@ class IReadSession { //! //! If maxEventsCount is not specified, //! read session chooses event batch size automatically. - virtual std::vector GetEvents(bool block = false, TMaybe maxEventsCount = Nothing(), + virtual std::vector GetEvents(bool block = false, std::optional maxEventsCount = std::nullopt, size_t maxByteSize = std::numeric_limits::max()) = 0; virtual std::vector GetEvents(const TReadSessionGetEventSettings& settings) = 0; //! Get single event. - virtual TMaybe GetEvent(bool block = false, + virtual std::optional GetEvent(bool block = false, size_t maxByteSize = std::numeric_limits::max()) = 0; - virtual TMaybe GetEvent(const TReadSessionGetEventSettings& settings) = 0; + virtual std::optional GetEvent(const TReadSessionGetEventSettings& settings) = 0; //! Close read session. //! Waits for all commit acknowledgments to arrive. diff --git a/client/ydb_topic/ut/basic_usage_ut.cpp b/client/ydb_topic/ut/basic_usage_ut.cpp index 46f183f3054..e200ab4347c 100644 --- a/client/ydb_topic/ut/basic_usage_ut.cpp +++ b/client/ydb_topic/ut/basic_usage_ut.cpp @@ -259,7 +259,7 @@ Y_UNIT_TEST_SUITE(BasicUsage) { writeSettings.CompressionExecutor(executor); ui64 count = 100u; - TMaybe shouldCaptureData = {true}; + std::optional shouldCaptureData = {true}; auto& client = setup->GetPersQueueClient(); auto session = client.CreateSimpleBlockingWriteSession(writeSettings); diff --git a/client/ydb_topic/ut/describe_topic_ut.cpp b/client/ydb_topic/ut/describe_topic_ut.cpp index 555bbd3c8d3..044974eb03e 100644 --- a/client/ydb_topic/ut/describe_topic_ut.cpp +++ b/client/ydb_topic/ut/describe_topic_ut.cpp @@ -295,7 +295,7 @@ namespace NYdb::NTopic::NTests { // Event 1: start partition session { - TMaybe event = readSession->GetEvent(true); + std::optional event = readSession->GetEvent(true); UNIT_ASSERT(event); auto startPartitionSession = std::get_if(event.Get()); UNIT_ASSERT_C(startPartitionSession, DebugString(*event)); @@ -305,7 +305,7 @@ namespace NYdb::NTopic::NTests { // Event 2: data received { - TMaybe event = readSession->GetEvent(true); + std::optional event = readSession->GetEvent(true); UNIT_ASSERT(event); auto dataReceived = std::get_if(event.Get()); UNIT_ASSERT_C(dataReceived, DebugString(*event)); @@ -315,7 +315,7 @@ namespace NYdb::NTopic::NTests { // Event 3: commit acknowledgement { - TMaybe event = readSession->GetEvent(true); + std::optional event = readSession->GetEvent(true); UNIT_ASSERT(event); auto commitOffsetAck = std::get_if(event.Get()); diff --git a/client/ydb_topic/ut/local_partition_ut.cpp b/client/ydb_topic/ut/local_partition_ut.cpp index 6cb86808eb2..94e1ad28630 100644 --- a/client/ydb_topic/ut/local_partition_ut.cpp +++ b/client/ydb_topic/ut/local_partition_ut.cpp @@ -64,7 +64,7 @@ namespace NYdb::NTopic::NTests { auto readSession = client.CreateReadSession(CreateReadSessionSettings()); - TMaybe event = readSession->GetEvent(true); + std::optional event = readSession->GetEvent(true); UNIT_ASSERT(event); auto startPartitionSession = std::get_if(event.Get()); UNIT_ASSERT_C(startPartitionSession, DebugString(*event)); diff --git a/client/ydb_types/fluent_settings_helpers.h b/client/ydb_types/fluent_settings_helpers.h index ff1d4094bc0..a29f98321c2 100644 --- a/client/ydb_types/fluent_settings_helpers.h +++ b/client/ydb_types/fluent_settings_helpers.h @@ -1,7 +1,5 @@ #pragma once -#include - #define FLUENT_SETTING(type, name) \ type name##_; \ TSelf& name(const type& value) { \ @@ -10,8 +8,8 @@ } #define FLUENT_SETTING_OPTIONAL(type, name) \ - TMaybe name##_; \ - TSelf& name(const TMaybe& value) { \ + std::optional name##_; \ + TSelf& name(const std::optional& value) { \ name##_ = value; \ return static_cast(*this); \ } @@ -44,7 +42,7 @@ } #define FLUENT_SETTING_OPTIONAL_VECTOR(type, name) \ - TMaybe> name##_; \ + std::optional> name##_; \ TSelf& Append##name(const type& value) { \ if (!name##_) name##_ = std::vector{}; \ name##_->push_back(value); \ diff --git a/client/ydb_types/s3_settings.h b/client/ydb_types/s3_settings.h index f654a9dedb5..daaaaa25a36 100644 --- a/client/ydb_types/s3_settings.h +++ b/client/ydb_types/s3_settings.h @@ -2,6 +2,8 @@ #include "fluent_settings_helpers.h" +#include + namespace NYdb { enum class ES3Scheme { diff --git a/client/ydb_value/value.cpp b/client/ydb_value/value.cpp index 49aadf833cd..af52fba4ece 100644 --- a/client/ydb_value/value.cpp +++ b/client/ydb_value/value.cpp @@ -1750,111 +1750,111 @@ TPgValue TValueParser::GetPg() const { #define RET_OPT_VALUE(Type, Name) \ Impl_->OpenOptional(); \ - auto value = Impl_->IsNull() ? TMaybe() : Impl_->Get##Name(); \ + auto value = Impl_->IsNull() ? std::optional() : Impl_->Get##Name(); \ Impl_->CloseOptional(); \ return value; -TMaybe TValueParser::GetOptionalBool() const { +std::optional TValueParser::GetOptionalBool() const { RET_OPT_VALUE(bool, Bool); } -TMaybe TValueParser::GetOptionalInt8() const { +std::optional TValueParser::GetOptionalInt8() const { RET_OPT_VALUE(i8, Int8); } -TMaybe TValueParser::GetOptionalUint8() const { +std::optional TValueParser::GetOptionalUint8() const { RET_OPT_VALUE(ui8, Uint8); } -TMaybe TValueParser::GetOptionalInt16() const { +std::optional TValueParser::GetOptionalInt16() const { RET_OPT_VALUE(i16, Int16); } -TMaybe TValueParser::GetOptionalUint16() const { +std::optional TValueParser::GetOptionalUint16() const { RET_OPT_VALUE(ui16, Uint16); } -TMaybe TValueParser::GetOptionalInt32() const { +std::optional TValueParser::GetOptionalInt32() const { RET_OPT_VALUE(i32, Int32); } -TMaybe TValueParser::GetOptionalUint32() const { +std::optional TValueParser::GetOptionalUint32() const { RET_OPT_VALUE(ui32, Uint32); } -TMaybe TValueParser::GetOptionalInt64() const { +std::optional TValueParser::GetOptionalInt64() const { RET_OPT_VALUE(i64, Int64); } -TMaybe TValueParser::GetOptionalUint64() const { +std::optional TValueParser::GetOptionalUint64() const { RET_OPT_VALUE(ui64, Uint64); } -TMaybe TValueParser::GetOptionalFloat() const { +std::optional TValueParser::GetOptionalFloat() const { RET_OPT_VALUE(float, Float); } -TMaybe TValueParser::GetOptionalDouble() const { +std::optional TValueParser::GetOptionalDouble() const { RET_OPT_VALUE(double, Double); } -TMaybe TValueParser::GetOptionalDate() const { +std::optional TValueParser::GetOptionalDate() const { RET_OPT_VALUE(TInstant, Date); } -TMaybe TValueParser::GetOptionalDatetime() const { +std::optional TValueParser::GetOptionalDatetime() const { RET_OPT_VALUE(TInstant, Datetime); } -TMaybe TValueParser::GetOptionalTimestamp() const { +std::optional TValueParser::GetOptionalTimestamp() const { RET_OPT_VALUE(TInstant, Timestamp); } -TMaybe TValueParser::GetOptionalInterval() const { +std::optional TValueParser::GetOptionalInterval() const { RET_OPT_VALUE(i64, Interval); } -TMaybe TValueParser::GetOptionalTzDate() const { +std::optional TValueParser::GetOptionalTzDate() const { RET_OPT_VALUE(std::string, TzDate); } -TMaybe TValueParser::GetOptionalTzDatetime() const { +std::optional TValueParser::GetOptionalTzDatetime() const { RET_OPT_VALUE(std::string, TzDatetime); } -TMaybe TValueParser::GetOptionalTzTimestamp() const { +std::optional TValueParser::GetOptionalTzTimestamp() const { RET_OPT_VALUE(std::string, TzTimestamp); } -TMaybe TValueParser::GetOptionalString() const { +std::optional TValueParser::GetOptionalString() const { RET_OPT_VALUE(std::string, String); } -TMaybe TValueParser::GetOptionalUtf8() const { +std::optional TValueParser::GetOptionalUtf8() const { RET_OPT_VALUE(std::string, Utf8); } -TMaybe TValueParser::GetOptionalYson() const { +std::optional TValueParser::GetOptionalYson() const { RET_OPT_VALUE(std::string, Yson); } -TMaybe TValueParser::GetOptionalJson() const { +std::optional TValueParser::GetOptionalJson() const { RET_OPT_VALUE(std::string, Json); } -TMaybe TValueParser::GetOptionalUuid() const { +std::optional TValueParser::GetOptionalUuid() const { RET_OPT_VALUE(TUuidValue, Uuid); } -TMaybe TValueParser::GetOptionalJsonDocument() const { +std::optional TValueParser::GetOptionalJsonDocument() const { RET_OPT_VALUE(std::string, JsonDocument); } -TMaybe TValueParser::GetOptionalDyNumber() const { +std::optional TValueParser::GetOptionalDyNumber() const { RET_OPT_VALUE(std::string, DyNumber); } -TMaybe TValueParser::GetOptionalDecimal() const { +std::optional TValueParser::GetOptionalDecimal() const { RET_OPT_VALUE(TDecimalValue, Decimal); } @@ -2913,127 +2913,127 @@ TDerived& TValueBuilderBase::Pg(const TPgValue& value) { return static_cast(*this); template -TDerived& TValueBuilderBase::OptionalBool(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalBool(const std::optional& value) { SET_OPT_VALUE_MAYBE(Bool); } template -TDerived& TValueBuilderBase::OptionalInt8(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalInt8(const std::optional& value) { SET_OPT_VALUE_MAYBE(Int8); } template -TDerived& TValueBuilderBase::OptionalUint8(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalUint8(const std::optional& value) { SET_OPT_VALUE_MAYBE(Uint8); } template -TDerived& TValueBuilderBase::OptionalInt16(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalInt16(const std::optional& value) { SET_OPT_VALUE_MAYBE(Int16); } template -TDerived& TValueBuilderBase::OptionalUint16(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalUint16(const std::optional& value) { SET_OPT_VALUE_MAYBE(Uint16); } template -TDerived& TValueBuilderBase::OptionalInt32(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalInt32(const std::optional& value) { SET_OPT_VALUE_MAYBE(Int32); } template -TDerived& TValueBuilderBase::OptionalUint32(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalUint32(const std::optional& value) { SET_OPT_VALUE_MAYBE(Uint32); } template -TDerived& TValueBuilderBase::OptionalInt64(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalInt64(const std::optional& value) { SET_OPT_VALUE_MAYBE(Int64); } template -TDerived& TValueBuilderBase::OptionalUint64(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalUint64(const std::optional& value) { SET_OPT_VALUE_MAYBE(Uint64); } template -TDerived& TValueBuilderBase::OptionalFloat(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalFloat(const std::optional& value) { SET_OPT_VALUE_MAYBE(Float); } template -TDerived& TValueBuilderBase::OptionalDouble(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalDouble(const std::optional& value) { SET_OPT_VALUE_MAYBE(Double); } template -TDerived& TValueBuilderBase::OptionalDate(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalDate(const std::optional& value) { SET_OPT_VALUE_MAYBE(Date); } template -TDerived& TValueBuilderBase::OptionalDatetime(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalDatetime(const std::optional& value) { SET_OPT_VALUE_MAYBE(Datetime); } template -TDerived& TValueBuilderBase::OptionalTimestamp(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalTimestamp(const std::optional& value) { SET_OPT_VALUE_MAYBE(Timestamp); } template -TDerived& TValueBuilderBase::OptionalInterval(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalInterval(const std::optional& value) { SET_OPT_VALUE_MAYBE(Interval); } template -TDerived& TValueBuilderBase::OptionalTzDate(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalTzDate(const std::optional& value) { SET_OPT_VALUE_MAYBE(TzDate); } template -TDerived& TValueBuilderBase::OptionalTzDatetime(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalTzDatetime(const std::optional& value) { SET_OPT_VALUE_MAYBE(TzDatetime); } template -TDerived& TValueBuilderBase::OptionalTzTimestamp(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalTzTimestamp(const std::optional& value) { SET_OPT_VALUE_MAYBE(TzTimestamp); } template -TDerived& TValueBuilderBase::OptionalString(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalString(const std::optional& value) { SET_OPT_VALUE_MAYBE(String); } template -TDerived& TValueBuilderBase::OptionalUtf8(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalUtf8(const std::optional& value) { SET_OPT_VALUE_MAYBE(Utf8); } template -TDerived& TValueBuilderBase::OptionalYson(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalYson(const std::optional& value) { SET_OPT_VALUE_MAYBE(Yson); } template -TDerived& TValueBuilderBase::OptionalJson(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalJson(const std::optional& value) { SET_OPT_VALUE_MAYBE(Json); } template -TDerived& TValueBuilderBase::OptionalUuid(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalUuid(const std::optional& value) { SET_OPT_VALUE_MAYBE(Uuid); } template -TDerived& TValueBuilderBase::OptionalJsonDocument(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalJsonDocument(const std::optional& value) { SET_OPT_VALUE_MAYBE(JsonDocument); } template -TDerived& TValueBuilderBase::OptionalDyNumber(const TMaybe& value) { +TDerived& TValueBuilderBase::OptionalDyNumber(const std::optional& value) { SET_OPT_VALUE_MAYBE(DyNumber); } diff --git a/client/ydb_value/value.h b/client/ydb_value/value.h index c2561d846b9..32aa959709a 100644 --- a/client/ydb_value/value.h +++ b/client/ydb_value/value.h @@ -1,7 +1,6 @@ #pragma once #include -#include #include @@ -314,32 +313,32 @@ class TValueParser : public TMoveOnly { const std::string& GetJsonDocument() const; const std::string& GetDyNumber() const; - TMaybe GetOptionalBool() const; - TMaybe GetOptionalInt8() const; - TMaybe GetOptionalUint8() const; - TMaybe GetOptionalInt16() const; - TMaybe GetOptionalUint16() const; - TMaybe GetOptionalInt32() const; - TMaybe GetOptionalUint32() const; - TMaybe GetOptionalInt64() const; - TMaybe GetOptionalUint64() const; - TMaybe GetOptionalFloat() const; - TMaybe GetOptionalDouble() const; - TMaybe GetOptionalDate() const; - TMaybe GetOptionalDatetime() const; - TMaybe GetOptionalTimestamp() const; - TMaybe GetOptionalInterval() const; - TMaybe GetOptionalTzDate() const; - TMaybe GetOptionalTzDatetime() const; - TMaybe GetOptionalTzTimestamp() const; - TMaybe GetOptionalString() const; - TMaybe GetOptionalUtf8() const; - TMaybe GetOptionalYson() const; - TMaybe GetOptionalJson() const; - TMaybe GetOptionalDecimal() const; - TMaybe GetOptionalUuid() const; - TMaybe GetOptionalJsonDocument() const; - TMaybe GetOptionalDyNumber() const; + std::optional GetOptionalBool() const; + std::optional GetOptionalInt8() const; + std::optional GetOptionalUint8() const; + std::optional GetOptionalInt16() const; + std::optional GetOptionalUint16() const; + std::optional GetOptionalInt32() const; + std::optional GetOptionalUint32() const; + std::optional GetOptionalInt64() const; + std::optional GetOptionalUint64() const; + std::optional GetOptionalFloat() const; + std::optional GetOptionalDouble() const; + std::optional GetOptionalDate() const; + std::optional GetOptionalDatetime() const; + std::optional GetOptionalTimestamp() const; + std::optional GetOptionalInterval() const; + std::optional GetOptionalTzDate() const; + std::optional GetOptionalTzDatetime() const; + std::optional GetOptionalTzTimestamp() const; + std::optional GetOptionalString() const; + std::optional GetOptionalUtf8() const; + std::optional GetOptionalYson() const; + std::optional GetOptionalJson() const; + std::optional GetOptionalDecimal() const; + std::optional GetOptionalUuid() const; + std::optional GetOptionalJsonDocument() const; + std::optional GetOptionalDyNumber() const; // Optional void OpenOptional(); @@ -420,31 +419,31 @@ class TValueBuilderBase : public TMoveOnly { TDerived& JsonDocument(const std::string& value); TDerived& DyNumber(const std::string& value); - TDerived& OptionalBool(const TMaybe& value); - TDerived& OptionalInt8(const TMaybe& value); - TDerived& OptionalUint8(const TMaybe& value); - TDerived& OptionalInt16(const TMaybe& value); - TDerived& OptionalUint16(const TMaybe& value); - TDerived& OptionalInt32(const TMaybe& value); - TDerived& OptionalUint32(const TMaybe& value); - TDerived& OptionalInt64(const TMaybe& value); - TDerived& OptionalUint64(const TMaybe& value); - TDerived& OptionalFloat(const TMaybe& value); - TDerived& OptionalDouble(const TMaybe& value); - TDerived& OptionalDate(const TMaybe& value); - TDerived& OptionalDatetime(const TMaybe& value); - TDerived& OptionalTimestamp(const TMaybe& value); - TDerived& OptionalInterval(const TMaybe& value); - TDerived& OptionalTzDate(const TMaybe& value); - TDerived& OptionalTzDatetime(const TMaybe& value); - TDerived& OptionalTzTimestamp(const TMaybe& value); - TDerived& OptionalString(const TMaybe& value); - TDerived& OptionalUtf8(const TMaybe& value); - TDerived& OptionalYson(const TMaybe& value); - TDerived& OptionalJson(const TMaybe& value); - TDerived& OptionalUuid(const TMaybe& value); - TDerived& OptionalJsonDocument(const TMaybe& value); - TDerived& OptionalDyNumber(const TMaybe& value); + TDerived& OptionalBool(const std::optional& value); + TDerived& OptionalInt8(const std::optional& value); + TDerived& OptionalUint8(const std::optional& value); + TDerived& OptionalInt16(const std::optional& value); + TDerived& OptionalUint16(const std::optional& value); + TDerived& OptionalInt32(const std::optional& value); + TDerived& OptionalUint32(const std::optional& value); + TDerived& OptionalInt64(const std::optional& value); + TDerived& OptionalUint64(const std::optional& value); + TDerived& OptionalFloat(const std::optional& value); + TDerived& OptionalDouble(const std::optional& value); + TDerived& OptionalDate(const std::optional& value); + TDerived& OptionalDatetime(const std::optional& value); + TDerived& OptionalTimestamp(const std::optional& value); + TDerived& OptionalInterval(const std::optional& value); + TDerived& OptionalTzDate(const std::optional& value); + TDerived& OptionalTzDatetime(const std::optional& value); + TDerived& OptionalTzTimestamp(const std::optional& value); + TDerived& OptionalString(const std::optional& value); + TDerived& OptionalUtf8(const std::optional& value); + TDerived& OptionalYson(const std::optional& value); + TDerived& OptionalJson(const std::optional& value); + TDerived& OptionalUuid(const std::optional& value); + TDerived& OptionalJsonDocument(const std::optional& value); + TDerived& OptionalDyNumber(const std::optional& value); // Optional TDerived& BeginOptional(); diff --git a/client/ydb_value/value_ut.cpp b/client/ydb_value/value_ut.cpp index d41a5c31b88..243961d76c2 100644 --- a/client/ydb_value/value_ut.cpp +++ b/client/ydb_value/value_ut.cpp @@ -521,7 +521,7 @@ Y_UNIT_TEST_SUITE(YdbValue) { UNIT_ASSERT(parser.TryNextElement()); UNIT_ASSERT_VALUES_EQUAL(parser.GetOptionalInt8(), -5); UNIT_ASSERT(parser.TryNextElement()); - UNIT_ASSERT_VALUES_EQUAL(parser.GetOptionalDouble(), TMaybe()); + UNIT_ASSERT_VALUES_EQUAL(parser.GetOptionalDouble(), std::optional()); UNIT_ASSERT(parser.TryNextElement()); UNIT_ASSERT_VALUES_EQUAL(parser.GetOptionalUint64(), (ui64)7); UNIT_ASSERT(parser.TryNextElement()); diff --git a/examples/basic_example/basic_example.cpp b/examples/basic_example/basic_example.cpp index 7c3a5e0015e..a8f05591c57 100644 --- a/examples/basic_example/basic_example.cpp +++ b/examples/basic_example/basic_example.cpp @@ -82,7 +82,7 @@ static void CreateTables(TTableClient client, const TString& path) { //! Describe existing table. static void DescribeTable(TTableClient client, const TString& path, const TString& name) { - TMaybe desc; + std::optional desc; ThrowOnError(client.RetryOperationSync([path, name, &desc](TSession session) { auto result = session.DescribeTable(JoinPath(path, name)).GetValueSync(); @@ -164,7 +164,7 @@ static TStatus FillTableDataTransaction(TSession session, const TString& path) { //! Shows basic usage of YDB data queries and transactions. static TStatus SelectSimpleTransaction(TSession session, const TString& path, - TMaybe& resultSet) + std::optional& resultSet) { auto query = Sprintf(R"( PRAGMA TablePathPrefix("%s"); @@ -207,7 +207,7 @@ static TStatus UpsertSimpleTransaction(TSession session, const TString& path) { //! Shows usage of parameters in data queries. static TStatus SelectWithParamsTransaction(TSession session, const TString& path, - ui64 seriesId, ui64 seasonId, TMaybe& resultSet) + ui64 seriesId, ui64 seasonId, std::optional& resultSet) { auto query = Sprintf(R"( --!syntax_v1 @@ -247,7 +247,7 @@ static TStatus SelectWithParamsTransaction(TSession session, const TString& path //! Shows usage of prepared queries. static TStatus PreparedSelectTransaction(TSession session, const TString& path, - ui64 seriesId, ui64 seasonId, ui64 episodeId, TMaybe& resultSet) + ui64 seriesId, ui64 seasonId, ui64 episodeId, std::optional& resultSet) { // Once prepared, query data is stored in the session and identified by QueryId. // Local query cache is used to keep track of queries, prepared in current session. @@ -300,7 +300,7 @@ static TStatus PreparedSelectTransaction(TSession session, const TString& path, //! Shows usage of transactions consisting of multiple data queries with client logic between them. static TStatus MultiStepTransaction(TSession session, const TString& path, ui64 seriesId, ui64 seasonId, - TMaybe& resultSet) + std::optional& resultSet) { auto query1 = Sprintf(R"( --!syntax_v1 @@ -433,7 +433,7 @@ static TStatus ExplicitTclTransaction(TSession session, const TString& path, con /////////////////////////////////////////////////////////////////////////////// void SelectSimple(TTableClient client, const TString& path) { - TMaybe resultSet; + std::optional resultSet; ThrowOnError(client.RetryOperationSync([path, &resultSet](TSession session) { return SelectSimpleTransaction(session, path, resultSet); })); @@ -455,7 +455,7 @@ void UpsertSimple(TTableClient client, const TString& path) { } void SelectWithParams(TTableClient client, const TString& path) { - TMaybe resultSet; + std::optional resultSet; ThrowOnError(client.RetryOperationSync([path, &resultSet](TSession session) { return SelectWithParamsTransaction(session, path, 2, 3, resultSet); })); @@ -470,7 +470,7 @@ void SelectWithParams(TTableClient client, const TString& path) { } void PreparedSelect(TTableClient client, const TString& path, ui32 seriesId, ui32 seasonId, ui32 episodeId) { - TMaybe resultSet; + std::optional resultSet; ThrowOnError(client.RetryOperationSync([path, seriesId, seasonId, episodeId, &resultSet](TSession session) { return PreparedSelectTransaction(session, path, seriesId, seasonId, episodeId, resultSet); })); @@ -487,7 +487,7 @@ void PreparedSelect(TTableClient client, const TString& path, ui32 seriesId, ui3 } void MultiStep(TTableClient client, const TString& path) { - TMaybe resultSet; + std::optional resultSet; ThrowOnError(client.RetryOperationSync([path, &resultSet](TSession session) { return MultiStepTransaction(session, path, 2, 5, resultSet); })); diff --git a/examples/pagination/pagination.cpp b/examples/pagination/pagination.cpp index a5972725115..dfc157dac96 100644 --- a/examples/pagination/pagination.cpp +++ b/examples/pagination/pagination.cpp @@ -81,7 +81,7 @@ static TStatus FillTableDataTransaction(TSession& session, const TString& path) //! Shows usage of query paging. static TStatus SelectPagingTransaction(TSession& session, const TString& path, - ui64 pageLimit, const TString& lastCity, ui32 lastNumber, TMaybe& resultSet) + ui64 pageLimit, const TString& lastCity, ui32 lastNumber, std::optional& resultSet) { auto query = Sprintf(R"( --!syntax_v1 @@ -138,7 +138,7 @@ static TStatus SelectPagingTransaction(TSession& session, const TString& path, } bool SelectPaging(TTableClient client, const TString& path, ui64 pageLimit, TString& lastCity, ui32& lastNumber) { - TMaybe resultSet; + std::optional resultSet; ThrowOnError(client.RetryOperationSync([path, pageLimit, &lastCity, lastNumber, &resultSet](TSession session) { return SelectPagingTransaction(session, path, pageLimit, lastCity, lastNumber, resultSet); })); diff --git a/examples/topic_reader/eventloop/main.cpp b/examples/topic_reader/eventloop/main.cpp index b96de7992f1..9516ad4b08f 100644 --- a/examples/topic_reader/eventloop/main.cpp +++ b/examples/topic_reader/eventloop/main.cpp @@ -89,7 +89,7 @@ int main(int argc, const char* argv[]) { // Cerr << ...; // }); // Get event - TMaybe event = ReadSession->GetEvent(true/*block - will block if no event received yet*/); + std::optional event = ReadSession->GetEvent(true/*block - will block if no event received yet*/); Cerr << "Got new read session event: " << DebugString(*event) << Endl; if (auto* dataEvent = std::get_if(&*event)) { diff --git a/examples/ttl/ttl.cpp b/examples/ttl/ttl.cpp index 15a68912c21..71eda547168 100644 --- a/examples/ttl/ttl.cpp +++ b/examples/ttl/ttl.cpp @@ -92,7 +92,7 @@ static TStatus AddDocumentTransaction(TSession session, const TString& path, //! Reads document contents. static TStatus ReadDocumentTransaction(TSession session, const TString& path, - const TString& url, TMaybe& resultSet) + const TString& url, std::optional& resultSet) { auto query = Sprintf(R"( --!syntax_v1 @@ -125,7 +125,7 @@ static TStatus ReadDocumentTransaction(TSession session, const TString& path, //! Reads a batch of entries from expiration queue static TStatus ReadExpiredBatchTransaction(TSession session, const TString& path, const ui32 queue, - const ui64 timestamp, const ui64 prevTimestamp, const ui64 prevDocId, TMaybe& resultSet) + const ui64 timestamp, const ui64 prevTimestamp, const ui64 prevDocId, std::optional& resultSet) { auto query = Sprintf(R"( --!syntax_v1 @@ -226,7 +226,7 @@ void AddDocument(TTableClient client, const TString& path, const TString& url, void ReadDocument(TTableClient client, const TString& path, const TString& url) { Cout << "> ReadDocument \"" << url << "\":" << Endl; - TMaybe resultSet; + std::optional resultSet; ThrowOnError(client.RetryOperationSync([path, url, &resultSet] (TSession session) { return ReadDocumentTransaction(session, path, url, resultSet); })); @@ -249,7 +249,7 @@ void DeleteExpired(TTableClient client, const TString& path, const ui32 queue, c ui64 lastTimestamp = 0; ui64 lastDocId = 0; while (!empty) { - TMaybe resultSet; + std::optional resultSet; ThrowOnError(client.RetryOperationSync([path, queue, timestamp, lastDocId, lastTimestamp, &resultSet] (TSession session) { return ReadExpiredBatchTransaction(session, path, queue, timestamp, lastTimestamp, lastDocId, resultSet); })); diff --git a/library/cpp/coroutine/engine/impl.cpp b/library/cpp/coroutine/engine/impl.cpp index c999fe0e10c..ea52ac3f21d 100644 --- a/library/cpp/coroutine/engine/impl.cpp +++ b/library/cpp/coroutine/engine/impl.cpp @@ -133,7 +133,7 @@ TContExecutor::TContExecutor( NCoro::IScheduleCallback* scheduleCallback, NCoro::IEnterPollerCallback* enterPollerCallback, NCoro::NStack::EGuard defaultGuard, - TMaybe poolSettings, + std::optional poolSettings, NCoro::ITime* time ) : ScheduleCallback_(scheduleCallback) @@ -243,7 +243,7 @@ TCont* TContExecutor::Create( TContFunc func, void* arg, const char* name, - TMaybe customStackSize + std::optional customStackSize ) noexcept { return CreateOwned([=](TCont* cont) { func(cont, arg); @@ -253,7 +253,7 @@ TCont* TContExecutor::Create( TCont* TContExecutor::CreateOwned( NCoro::TTrampoline::TFunc func, const char* name, - TMaybe customStackSize + std::optional customStackSize ) noexcept { Allocated_ += 1; if (!customStackSize) { diff --git a/library/cpp/coroutine/engine/impl.h b/library/cpp/coroutine/engine/impl.h index 9f8018e1dd6..91e235aa049 100644 --- a/library/cpp/coroutine/engine/impl.h +++ b/library/cpp/coroutine/engine/impl.h @@ -14,7 +14,6 @@ #include #include #include -#include #include @@ -173,7 +172,7 @@ class TContExecutor { NCoro::IScheduleCallback* = nullptr, NCoro::IEnterPollerCallback* = nullptr, NCoro::NStack::EGuard stackGuard = NCoro::NStack::EGuard::Canary, - TMaybe poolSettings = Nothing(), + std::optional poolSettings = std::nullopt, NCoro::ITime* time = nullptr ); @@ -198,7 +197,7 @@ class TContExecutor { TCont* Create( Functor& f, const char* name, - TMaybe customStackSize = Nothing() + std::optional customStackSize = std::nullopt ) noexcept { return Create((TContFunc)ContHelperFunc, (void*)&f, name, customStackSize); } @@ -207,7 +206,7 @@ class TContExecutor { TCont* Create( T* obj, const char* name, - TMaybe customStackSize = Nothing() + std::optional customStackSize = std::nullopt ) noexcept { return Create(ContHelperMemberFunc, obj, name, customStackSize); } @@ -216,13 +215,13 @@ class TContExecutor { TContFunc func, void* arg, const char* name, - TMaybe customStackSize = Nothing() + std::optional customStackSize = std::nullopt ) noexcept; TCont* CreateOwned( NCoro::TTrampoline::TFunc func, const char* name, - TMaybe customStackSize = Nothing() + std::optional customStackSize = std::nullopt ) noexcept; NCoro::TContPoller* Poller() noexcept { diff --git a/library/cpp/coroutine/engine/stack/stack_allocator.cpp b/library/cpp/coroutine/engine/stack/stack_allocator.cpp index bf12134e6b6..7f32d0e7f4c 100644 --- a/library/cpp/coroutine/engine/stack/stack_allocator.cpp +++ b/library/cpp/coroutine/engine/stack/stack_allocator.cpp @@ -3,7 +3,7 @@ namespace NCoro::NStack { - THolder GetAllocator(TMaybe poolSettings, EGuard guardType) { + THolder GetAllocator(std::optional poolSettings, EGuard guardType) { THolder allocator; if (poolSettings) { if (guardType == EGuard::Canary) { diff --git a/library/cpp/coroutine/engine/stack/stack_allocator.h b/library/cpp/coroutine/engine/stack/stack_allocator.h index 03e1ac56047..0a866982a9b 100644 --- a/library/cpp/coroutine/engine/stack/stack_allocator.h +++ b/library/cpp/coroutine/engine/stack/stack_allocator.h @@ -3,12 +3,11 @@ #include "stack.h" #include "stack_common.h" -#include #include #include #include - +#include namespace NCoro::NStack { @@ -45,7 +44,7 @@ namespace NCoro::NStack { virtual void DoFreeStack(NDetails::TStack& stack) noexcept = 0; }; - THolder GetAllocator(TMaybe poolSettings, EGuard guardType); + THolder GetAllocator(std::optional poolSettings, EGuard guardType); } diff --git a/library/cpp/coroutine/engine/stack/ut/stack_allocator_ut.cpp b/library/cpp/coroutine/engine/stack/ut/stack_allocator_ut.cpp index f8287937216..dfb97354faf 100644 --- a/library/cpp/coroutine/engine/stack/ut/stack_allocator_ut.cpp +++ b/library/cpp/coroutine/engine/stack/ut/stack_allocator_ut.cpp @@ -19,7 +19,7 @@ namespace NCoro::NStack::Tests { EAllocator allocType; std::tie(guardType, allocType) = GetParam(); - TMaybe poolSettings; + std::optional poolSettings; if (allocType == EAllocator::Pool) { poolSettings = TPoolAllocatorSettings{}; } @@ -69,13 +69,13 @@ namespace NCoro::NStack::Tests { template<> THolder GetAllocator(EGuard guardType) { - TMaybe poolSettings = TPoolAllocatorSettings{}; + std::optional poolSettings = TPoolAllocatorSettings{}; return GetAllocator(poolSettings, guardType); } template<> THolder GetAllocator(EGuard guardType) { - TMaybe poolSettings; + std::optional poolSettings; return GetAllocator(poolSettings, guardType); } diff --git a/library/cpp/getopt/last_getopt_demo/demo.cpp b/library/cpp/getopt/last_getopt_demo/demo.cpp index 60977dd6baa..66f81e94547 100644 --- a/library/cpp/getopt/last_getopt_demo/demo.cpp +++ b/library/cpp/getopt/last_getopt_demo/demo.cpp @@ -39,8 +39,8 @@ class TMain: public TMainClassArgs { std::string ExplicitMethod_; std::string ImplicitMethod_ = "GET"; std::string UserAgent_; - TMaybe PostData_; - TMaybe PostFile_; + std::optional PostData_; + std::optional PostFile_; std::vector Headers_; protected: diff --git a/library/cpp/getopt/small/last_getopt_opt.h b/library/cpp/getopt/small/last_getopt_opt.h index a03a42e4372..b82e50d7b26 100644 --- a/library/cpp/getopt/small/last_getopt_opt.h +++ b/library/cpp/getopt/small/last_getopt_opt.h @@ -46,7 +46,7 @@ namespace NLastGetopt { TLongNames LongNames_; private: - typedef TMaybe TdOptVal; + typedef std::optional TdOptVal; typedef std::vector> TOptHandlers; public: @@ -263,7 +263,7 @@ namespace NLastGetopt { * checks if default value is set. */ bool HasDefaultValue() const { - return DefaultValue_.Defined(); + return DefaultValue_.has_value(); } /** @@ -623,12 +623,6 @@ namespace NLastGetopt { return StoreResultT(target); } - // Uses TMaybe to store FromString(arg) - template - TOpt& StoreResult(TMaybe* target) { - return StoreResultT(target); - } - template TOpt& StoreResult(std::optional* target) { return StoreResultT(target); diff --git a/library/cpp/getopt/small/last_getopt_opts.cpp b/library/cpp/getopt/small/last_getopt_opts.cpp index 95a128bfd1f..4e0fac64d22 100644 --- a/library/cpp/getopt/small/last_getopt_opts.cpp +++ b/library/cpp/getopt/small/last_getopt_opts.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include diff --git a/library/cpp/getopt/small/modchooser.cpp b/library/cpp/getopt/small/modchooser.cpp index 118a01fa6a4..a56185070bd 100644 --- a/library/cpp/getopt/small/modchooser.cpp +++ b/library/cpp/getopt/small/modchooser.cpp @@ -331,12 +331,12 @@ int TMainClassArgs::Run(int argc, const char** argv) { } const NLastGetopt::TOpts& TMainClassArgs::GetOptions() { - if (Opts_.Empty()) { + if (!Opts_.has_value()) { Opts_ = NLastGetopt::TOpts(); - RegisterOptions(Opts_.GetRef()); + RegisterOptions(Opts_.value()); } - return Opts_.GetRef(); + return Opts_.value(); } void TMainClassArgs::RegisterOptions(NLastGetopt::TOpts& opts) { @@ -357,12 +357,12 @@ int TMainClassModes::Run(int argc, const char** argv) { } const TModChooser& TMainClassModes::GetSubModes() { - if (Modes_.Empty()) { - Modes_.ConstructInPlace(); - RegisterModes(Modes_.GetRef()); + if (!Modes_.has_value()) { + Modes_.emplace(); + RegisterModes(Modes_.value()); } - return Modes_.GetRef(); + return Modes_.value(); } void TMainClassModes::RegisterModes(TModChooser& modes) { diff --git a/library/cpp/getopt/small/modchooser.h b/library/cpp/getopt/small/modchooser.h index 30a43bbc953..ebeb3a46294 100644 --- a/library/cpp/getopt/small/modchooser.h +++ b/library/cpp/getopt/small/modchooser.h @@ -203,7 +203,7 @@ class TMainClassArgs: public TMainClass { virtual int DoRun(NLastGetopt::TOptsParseResult&& parsedOptions) = 0; private: - TMaybe Opts_; + std::optional Opts_; }; //! Mode class that uses sub-modes to dispatch commands further. @@ -223,5 +223,5 @@ class TMainClassModes: public TMainClass { virtual void RegisterModes(TModChooser& modes); private: - TMaybe Modes_; + std::optional Modes_; }; diff --git a/library/cpp/getopt/ut/last_getopt_ut.cpp b/library/cpp/getopt/ut/last_getopt_ut.cpp index bcf89f53a11..96360384b22 100644 --- a/library/cpp/getopt/ut/last_getopt_ut.cpp +++ b/library/cpp/getopt/ut/last_getopt_ut.cpp @@ -453,8 +453,8 @@ Y_UNIT_TEST_SUITE(TLastGetoptTests) { TOptsNoDefault opts; std::string data; int number; - TMaybe optionalString0, optionalString1; - TMaybe optionalNumber0, optionalNumber1; + std::optional optionalString0, optionalString1; + std::optional optionalNumber0, optionalNumber1; opts.AddLongOption('d', "data").StoreResult(&data); opts.AddLongOption('n', "number").StoreResult(&number); opts.AddLongOption("optional-string-0").StoreResult(&optionalString0); diff --git a/library/cpp/http/io/chunk.cpp b/library/cpp/http/io/chunk.cpp index 43052d5a8ff..11d7f40b7ce 100644 --- a/library/cpp/http/io/chunk.cpp +++ b/library/cpp/http/io/chunk.cpp @@ -46,14 +46,14 @@ static inline char* ToHex(size_t len, char* buf) { class TChunkedInput::TImpl { public: - inline TImpl(IInputStream* slave, TMaybe* trailers) + inline TImpl(IInputStream* slave, std::optional* trailers) : Slave_(slave) , Trailers_(trailers) , Pending_(0) , LastChunkReaded_(false) { if (Trailers_) { - Trailers_->Clear(); + Trailers_->reset(); } } @@ -124,7 +124,7 @@ class TChunkedInput::TImpl { } if (Trailers_) { - Trailers_->ConstructInPlace(Slave_); + Trailers_->emplace(Slave_); } LastChunkReaded_ = true; @@ -133,12 +133,12 @@ class TChunkedInput::TImpl { private: IInputStream* Slave_; - TMaybe* Trailers_; + std::optional* Trailers_; size_t Pending_; bool LastChunkReaded_; }; -TChunkedInput::TChunkedInput(IInputStream* slave, TMaybe* trailers) +TChunkedInput::TChunkedInput(IInputStream* slave, std::optional* trailers) : Impl_(new TImpl(slave, trailers)) { } diff --git a/library/cpp/http/io/chunk.h b/library/cpp/http/io/chunk.h index 88d89fafda2..7ccfd2f676c 100644 --- a/library/cpp/http/io/chunk.h +++ b/library/cpp/http/io/chunk.h @@ -1,9 +1,12 @@ #pragma once +#include #include -#include +#include #include +#include + class THttpHeaders; /// @addtogroup Streams_Chunked @@ -15,7 +18,7 @@ class TChunkedInput: public IInputStream { public: /// Если передан указатель на trailers, то туда будут записаны HTTP trailer'ы (возможно пустые), /// которые идут после чанков. - TChunkedInput(IInputStream* slave, TMaybe* trailers = nullptr); + TChunkedInput(IInputStream* slave, std::optional* trailers = nullptr); ~TChunkedInput() override; private: diff --git a/library/cpp/http/io/stream.cpp b/library/cpp/http/io/stream.cpp index c939e490928..c407045dd28 100644 --- a/library/cpp/http/io/stream.cpp +++ b/library/cpp/http/io/stream.cpp @@ -174,7 +174,7 @@ class THttpInput::TImpl { return Headers_; } - inline const TMaybe& Trailers() const noexcept { + inline const std::optional& Trailers() const noexcept { return Trailers_; } @@ -212,7 +212,7 @@ class THttpInput::TImpl { size_t processed = operation(len); if (processed == 0 && len > 0) { if (!ChunkedInput_) { - Trailers_.ConstructInPlace(); + Trailers_.emplace(); } else { // Read the header of the trailing chunk. It remains in // the TChunkedInput stream if the HTTP response is compressed. @@ -372,7 +372,7 @@ class THttpInput::TImpl { std::string FirstLine_; THttpHeaders Headers_; - TMaybe Trailers_; + std::optional Trailers_; bool KeepAlive_; TAcceptCodings Codings_; @@ -406,7 +406,7 @@ const THttpHeaders& THttpInput::Headers() const noexcept { return Impl_->Headers(); } -const TMaybe& THttpInput::Trailers() const noexcept { +const std::optional& THttpInput::Trailers() const noexcept { return Impl_->Trailers(); } diff --git a/library/cpp/http/io/stream.h b/library/cpp/http/io/stream.h index 235afc74471..eab39978427 100644 --- a/library/cpp/http/io/stream.h +++ b/library/cpp/http/io/stream.h @@ -3,7 +3,6 @@ #include "headers.h" #include -#include #include #include #include @@ -41,7 +40,7 @@ class THttpInput: public IInputStream { /// Поток должен быть вычитан полностью прежде чем trailer'ы будут доступны. /// Пока поток не вычитан до конца возвращается Nothing. /// https://tools.ietf.org/html/rfc7230#section-4.1.2 - const TMaybe& Trailers() const noexcept; + const std::optional& Trailers() const noexcept; /* * first line - response or request diff --git a/library/cpp/http/io/stream_ut.cpp b/library/cpp/http/io/stream_ut.cpp index 55cb641c28e..1b5bbb97506 100644 --- a/library/cpp/http/io/stream_ut.cpp +++ b/library/cpp/http/io/stream_ut.cpp @@ -498,7 +498,7 @@ Y_UNIT_TEST_SUITE(THttpStreamTest) { "Bar: baz\r\n" "\r\n"); THttpInput i(&response); - TMaybe trailers = i.Trailers(); + std::optional trailers = i.Trailers(); UNIT_ASSERT(!trailers.Defined()); i.ReadAll(); trailers = i.Trailers(); @@ -516,7 +516,7 @@ Y_UNIT_TEST_SUITE(THttpStreamTest) { "0\r\n" "\r\n"); THttpInput i(&response); - TMaybe trailers = i.Trailers(); + std::optional trailers = i.Trailers(); UNIT_ASSERT(!trailers.Defined()); i.ReadAll(); trailers = i.Trailers(); @@ -530,7 +530,7 @@ Y_UNIT_TEST_SUITE(THttpStreamTest) { "\r\n" "bar"); THttpInput i(&response); - TMaybe trailers = i.Trailers(); + std::optional trailers = i.Trailers(); UNIT_ASSERT(!trailers.Defined()); i.ReadAll(); trailers = i.Trailers(); diff --git a/library/cpp/http/misc/httpreqdata.cpp b/library/cpp/http/misc/httpreqdata.cpp index cc891a6fdc5..3826a4f8b0b 100644 --- a/library/cpp/http/misc/httpreqdata.cpp +++ b/library/cpp/http/misc/httpreqdata.cpp @@ -38,12 +38,12 @@ void TBaseServerRequestData::AppendQueryString(std::string_view str) { } void TBaseServerRequestData::SetRemoteAddr(std::string_view addr) { - Addr_.ConstructInPlace(addr.substr(0, INET6_ADDRSTRLEN - 1)); + Addr_.emplace(addr.substr(0, INET6_ADDRSTRLEN - 1)); } std::string_view TBaseServerRequestData::RemoteAddr() const { if (!Addr_) { - auto& addr = Addr_.ConstructInPlace(); + auto& addr = Addr_.emplace(); addr.resize(INET6_ADDRSTRLEN); if (GetRemoteAddr(Socket_, addr.begin(), addr.size())) { if (auto pos = addr.find('\0'); pos != std::string::npos) { @@ -95,7 +95,7 @@ std::string_view TBaseServerRequestData::Environment(std::string_view key) const void TBaseServerRequestData::Clear() { HeadersIn_.clear(); - Addr_ = Nothing(); + Addr_ = std::nullopt; Path_.clear(); Query_ = {}; OrigQuery_ = {}; diff --git a/library/cpp/http/misc/httpreqdata.h b/library/cpp/http/misc/httpreqdata.h index 128ce94767e..b6c75a5be35 100644 --- a/library/cpp/http/misc/httpreqdata.h +++ b/library/cpp/http/misc/httpreqdata.h @@ -10,8 +10,6 @@ #include #include -#include - using THttpHeadersContainer = THashMap; class TBaseServerRequestData { @@ -83,7 +81,7 @@ class TBaseServerRequestData { void AddHeader(const std::string& name, const std::string& value); private: - mutable TMaybe Addr_; + mutable std::optional Addr_; std::string Host_; std::string Port_; std::string Path_; diff --git a/library/cpp/http/simple/http_client.cpp b/library/cpp/http/simple/http_client.cpp index f85384b1830..49be079c961 100644 --- a/library/cpp/http/simple/http_client.cpp +++ b/library/cpp/http/simple/http_client.cpp @@ -63,7 +63,7 @@ TKeepAliveHttpClient::THttpCode TKeepAliveHttpClient::DoRequestRaw(const std::st } void TKeepAliveHttpClient::DisableVerificationForHttps() { - HttpsVerification.Clear(); + HttpsVerification.reset(); Connection.Reset(); } @@ -221,8 +221,8 @@ namespace NPrivate { TDuration sockTimeout, TDuration connTimeout, bool isHttps, - const TMaybe& clientCert, - const TMaybe& verifyCert) + const std::optional& clientCert, + const std::optional& verifyCert) : Addr(Resolve(host, port)) , Socket(Connect(Addr, sockTimeout, connTimeout, host, port)) , SocketIn(Socket) diff --git a/library/cpp/http/simple/http_client.h b/library/cpp/http/simple/http_client.h index 4f8c4c1efb1..af1f5c16e3e 100644 --- a/library/cpp/http/simple/http_client.h +++ b/library/cpp/http/simple/http_client.h @@ -113,8 +113,8 @@ class TKeepAliveHttpClient { THolder Connection; bool IsClosingRequired; - TMaybe ClientCertificate; - TMaybe HttpsVerification; + std::optional ClientCertificate; + std::optional HttpsVerification; private: THttpInput* GetHttpInput(); @@ -199,8 +199,8 @@ namespace NPrivate { TDuration sockTimeout, TDuration connTimeout, bool isHttps, - const TMaybe& clientCert, - const TMaybe& verifyCert); + const std::optional& clientCert, + const std::optional& verifyCert); bool IsOk() const { return IsNotSocketClosedByOtherSide(Socket); diff --git a/library/cpp/iterator/concatenate.h b/library/cpp/iterator/concatenate.h index 64d2cd451a3..1eb914b6991 100644 --- a/library/cpp/iterator/concatenate.h +++ b/library/cpp/iterator/concatenate.h @@ -32,8 +32,8 @@ namespace NPrivate { friend struct TConcatenatorWithIndex; // important, that it is a static function, compiler better optimizes such code - template - static TValue GetCurrentValue(std::size_t position, TMaybeConstIteratorState& iterators) { + template + static TValue GetCurrentValue(std::size_t position, TOptConstIteratorState& iterators) { if constexpr (index >= sizeof...(TContainers)) { // never happened when use of iterator is correct return *std::get<0>(iterators); diff --git a/library/cpp/json/json_writer.h b/library/cpp/json/json_writer.h index 47005260f03..45168797c5c 100644 --- a/library/cpp/json/json_writer.h +++ b/library/cpp/json/json_writer.h @@ -8,7 +8,6 @@ #include #include -#include #include @@ -144,13 +143,13 @@ namespace NJson { } template - void WriteOptional(const std::string_view& key, const TMaybe& value) { + void WriteOptional(const std::string_view& key, const std::optional& value) { if (value) { Write(key, *value); } } - void WriteOptional(const std::string_view&, const TNothing&) { + void WriteOptional(const std::string_view&, const std::nullopt_t&) { // nothing to do } diff --git a/library/cpp/json/ut/json_writer_ut.cpp b/library/cpp/json/ut/json_writer_ut.cpp index 1e211fa7865..ba085996561 100644 --- a/library/cpp/json/ut/json_writer_ut.cpp +++ b/library/cpp/json/ut/json_writer_ut.cpp @@ -141,7 +141,7 @@ Y_UNIT_TEST_SUITE(TJsonWriterTest) { std::stringStream out; - TMaybe nothing = Nothing(); + std::optional nothing = std::nullopt; TJsonWriter json(&out, false); json.OpenMap(); @@ -156,7 +156,7 @@ Y_UNIT_TEST_SUITE(TJsonWriterTest) { std::stringStream out; - TMaybe empty; + std::optional empty; TJsonWriter json(&out, false); json.OpenMap(); diff --git a/library/cpp/monlib/dynamic_counters/page.cpp b/library/cpp/monlib/dynamic_counters/page.cpp index c9481cb09a7..1d1e7aeec48 100644 --- a/library/cpp/monlib/dynamic_counters/page.cpp +++ b/library/cpp/monlib/dynamic_counters/page.cpp @@ -14,7 +14,7 @@ namespace { currentCounters(nullptr); } -TMaybe ParseFormat(std::string_view str) { +std::optional ParseFormat(std::string_view str) { if (str == std::string_view("json")) { return EFormat::JSON; } else if (str == std::string_view("spack")) { @@ -22,7 +22,7 @@ TMaybe ParseFormat(std::string_view str) { } else if (str == std::string_view("prometheus")) { return EFormat::PROMETHEUS; } else { - return Nothing(); + return std::nullopt; } } @@ -42,7 +42,7 @@ void TDynamicCountersPage::Output(NMonitoring::IMonHttpRequest& request) { .SkipEmpty() .Collect(&parts); - TMaybe format = !parts.empty() ? ParseFormat(parts.back()) : Nothing(); + std::optional format = !parts.empty() ? ParseFormat(parts.back()) : std::nullopt; if (format) { parts.pop_back(); } diff --git a/library/cpp/monlib/encode/prometheus/prometheus_decoder.cpp b/library/cpp/monlib/encode/prometheus/prometheus_decoder.cpp index a905665dc10..5472cd905af 100644 --- a/library/cpp/monlib/encode/prometheus/prometheus_decoder.cpp +++ b/library/cpp/monlib/encode/prometheus/prometheus_decoder.cpp @@ -9,7 +9,6 @@ #include #include #include -#include #include #include @@ -85,12 +84,12 @@ namespace NMonitoring { } void SetLabels(TLabelsMap&& labels) { - if (Labels_.Defined()) { + if (Labels_.has_value()) { Y_ENSURE(Labels_ == labels, "mixed labels in one histogram, prev: " << LabelsToStr(*Labels_) << ", current: " << LabelsToStr(labels)); } else { - Labels_.ConstructInPlace(std::move(labels)); + Labels_.emplace(std::move(labels)); } } @@ -135,7 +134,7 @@ namespace NMonitoring { Y_ENSURE_EX(!Empty(), TPrometheusDecodeException() << "histogram cannot be empty"); Time_ = TInstant::Zero(); PrevBucket_ = ZERO_BUCKET; - Labels_.Clear(); + Labels_.reset(); auto snapshot = ExplicitHistogramSnapshot(Bounds_, Values_, true); Bounds_.clear(); @@ -146,7 +145,7 @@ namespace NMonitoring { private: std::string_view Name_; - TMaybe Labels_; + std::optional Labels_; TInstant Time_; TBucketBounds Bounds_; TBucketValues Values_; diff --git a/library/cpp/monlib/encode/prometheus/prometheus_encoder.cpp b/library/cpp/monlib/encode/prometheus/prometheus_encoder.cpp index b65dcef28c1..05a4dcd2d26 100644 --- a/library/cpp/monlib/encode/prometheus/prometheus_encoder.cpp +++ b/library/cpp/monlib/encode/prometheus/prometheus_encoder.cpp @@ -369,7 +369,7 @@ namespace NMonitoring { MetricState_.Labels.Add(l.Name(), l.Value()); } - TMaybe nameLabel = MetricState_.Labels.Extract(MetricNameLabel_); + std::optional nameLabel = MetricState_.Labels.Extract(MetricNameLabel_); Y_ENSURE(nameLabel, "labels " << MetricState_.Labels << " does not contain label '" << MetricNameLabel_ << '\''); diff --git a/library/cpp/monlib/metrics/labels.h b/library/cpp/monlib/metrics/labels.h index 48c2e23b233..1d406156d69 100644 --- a/library/cpp/monlib/metrics/labels.h +++ b/library/cpp/monlib/metrics/labels.h @@ -5,7 +5,6 @@ #include #include #include -#include #include #include @@ -255,12 +254,12 @@ namespace NMonitoring { } // XXX for backward compatibility - TMaybe> Find(std::string_view name) const { + std::optional> Find(std::string_view name) const { auto it = FindIf(Labels_, [name](const TLabelImpl& label) { return name == std::string_view{label.Name()}; }); if (it == Labels_.end()) { - return Nothing(); + return std::nullopt; } return *it; } @@ -281,12 +280,12 @@ namespace NMonitoring { return &(*this)[idx]; } - TMaybe> Extract(std::string_view name) { + std::optional> Extract(std::string_view name) { auto it = FindIf(Labels_, [name](const TLabelImpl& label) { return name == std::string_view{label.Name()}; }); if (it == Labels_.end()) { - return Nothing(); + return std::nullopt; } TLabel tmp = *it; Labels_.erase(it); diff --git a/library/cpp/openssl/io/stream.h b/library/cpp/openssl/io/stream.h index 6eca27f51da..8126042a2c9 100644 --- a/library/cpp/openssl/io/stream.h +++ b/library/cpp/openssl/io/stream.h @@ -1,10 +1,11 @@ #pragma once -#include #include #include #include +#include + class TOpenSslClientIO: public IInputStream, public IOutputStream { public: struct TOptions { @@ -20,8 +21,8 @@ class TOpenSslClientIO: public IInputStream, public IOutputStream { std::string PrivateKeyPassword_; }; - TMaybe VerifyCert_; - TMaybe ClientCert_; + std::optional VerifyCert_; + std::optional ClientCert_; // TODO - keys, cyphers, etc }; diff --git a/library/cpp/retry/retry.cpp b/library/cpp/retry/retry.cpp index 588e5d4ada7..1ed6b9ac7dc 100644 --- a/library/cpp/retry/retry.cpp +++ b/library/cpp/retry/retry.cpp @@ -17,9 +17,9 @@ class TRetryOptionsWithRetCodePolicy : public IRetryPolicy { { } - TMaybe GetNextRetryDelay(bool ret) override { + std::optional GetNextRetryDelay(bool ret) override { if (ret || Attempt == Opts.RetryCount) { - return Nothing(); + return std::nullopt; } return Opts.GetTimeToSleep(Attempt++); } diff --git a/library/cpp/retry/retry.h b/library/cpp/retry/retry.h index cb1f6a4ba46..91bbfe84c2a 100644 --- a/library/cpp/retry/retry.h +++ b/library/cpp/retry/retry.h @@ -5,7 +5,6 @@ #include #include -#include #include #include #include @@ -103,9 +102,9 @@ class TRetryOptionsPolicy : public IRetryPolicy { { } - TMaybe GetNextRetryDelay(const TException&) override { + std::optional GetNextRetryDelay(const TException&) override { if (Attempt == Opts.RetryCount) { - return Nothing(); + return std::nullopt; } return Opts.GetTimeToSleep(Attempt++); } @@ -136,7 +135,7 @@ typename IRetryPolicy::TPtr MakeRetryPolicy(const NRetry::TRe } template -TMaybe DoWithRetry(std::function func, const typename IRetryPolicy::TPtr& retryPolicy, bool throwLast = true, std::function onFail = {}, std::function sleepFunction = {}) { +std::optional DoWithRetry(std::function func, const typename IRetryPolicy::TPtr& retryPolicy, bool throwLast = true, std::function onFail = {}, std::function sleepFunction = {}) { typename IRetryPolicy::IRetryState::TPtr retryState; while (true) { try { @@ -150,7 +149,7 @@ TMaybe DoWithRetry(std::function func, const typename IRetry retryState = retryPolicy->CreateRetryState(); } - if (const TMaybe delay = retryState->GetNextRetryDelay(ex)) { + if (const std::optional delay = retryState->GetNextRetryDelay(ex)) { if (*delay) { if (sleepFunction) { sleepFunction(*delay); @@ -166,16 +165,16 @@ TMaybe DoWithRetry(std::function func, const typename IRetry } } } - return Nothing(); + return std::nullopt; } template -TMaybe DoWithRetry(std::function func, std::function onFail, TRetryOptions retryOptions, bool throwLast = true) { +std::optional DoWithRetry(std::function func, std::function onFail, TRetryOptions retryOptions, bool throwLast = true) { return DoWithRetry(std::move(func), MakeRetryPolicy(retryOptions), throwLast, std::move(onFail), retryOptions.SleepFunction); } template -TMaybe DoWithRetry(std::function func, TRetryOptions retryOptions, bool throwLast = true) { +std::optional DoWithRetry(std::function func, TRetryOptions retryOptions, bool throwLast = true) { return DoWithRetry(std::move(func), MakeRetryPolicy(retryOptions), throwLast, {}, retryOptions.SleepFunction); } @@ -203,7 +202,7 @@ TRetCode DoWithRetryOnRetCode(std::function func, const typename IRe auto retryState = retryPolicy->CreateRetryState(); while (true) { TRetCode code = func(); - if (const TMaybe delay = retryState->GetNextRetryDelay(code)) { + if (const std::optional delay = retryState->GetNextRetryDelay(code)) { if (*delay) { if (sleepFunction) { sleepFunction(*delay); diff --git a/library/cpp/retry/retry_policy.h b/library/cpp/retry/retry_policy.h index 20075b8fc3c..92bb136e2d1 100644 --- a/library/cpp/retry/retry_policy.h +++ b/library/cpp/retry/retry_policy.h @@ -1,6 +1,5 @@ #pragma once #include -#include #include #include @@ -40,7 +39,7 @@ struct IRetryPolicy { //! Calculate delay before next retry if next retry is allowed. //! Returns empty maybe if retry is not allowed anymore. - [[nodiscard]] virtual TMaybe GetNextRetryDelay(typename TTypeTraits::TFuncParam... args) = 0; + [[nodiscard]] virtual std::optional GetNextRetryDelay(typename TTypeTraits::TFuncParam... args) = 0; }; virtual ~IRetryPolicy() = default; @@ -80,8 +79,8 @@ struct TNoRetryPolicy : IRetryPolicy { using IRetryState = typename IRetryPolicy::IRetryState; struct TNoRetryState : IRetryState { - TMaybe GetNextRetryDelay(typename TTypeTraits::TFuncParam...) override { - return Nothing(); + std::optional GetNextRetryDelay(typename TTypeTraits::TFuncParam...) override { + return std::nullopt; } }; @@ -122,10 +121,10 @@ struct TExponentialBackoffPolicy : IRetryPolicy { { } - TMaybe GetNextRetryDelay(typename TTypeTraits::TFuncParam... args) override { + std::optional GetNextRetryDelay(typename TTypeTraits::TFuncParam... args) override { const ERetryErrorClass errorClass = RetryClassFunction(args...); if (errorClass == ERetryErrorClass::NoRetry || AttemptsDone >= MaxRetries || StartTime && TInstant::Now() - StartTime >= MaxTime) { - return Nothing(); + return std::nullopt; } if (errorClass == ERetryErrorClass::LongRetry) { @@ -211,10 +210,10 @@ struct TFixedIntervalPolicy : IRetryPolicy { { } - TMaybe GetNextRetryDelay(typename TTypeTraits::TFuncParam... args) override { + std::optional GetNextRetryDelay(typename TTypeTraits::TFuncParam... args) override { const ERetryErrorClass errorClass = RetryClassFunction(args...); if (errorClass == ERetryErrorClass::NoRetry || AttemptsDone >= MaxRetries || StartTime && TInstant::Now() - StartTime >= MaxTime) { - return Nothing(); + return std::nullopt; } const TDuration delay = NRetryDetails::RandomizeDelay(errorClass == ERetryErrorClass::LongRetry ? LongRetryDelay : Delay); diff --git a/library/cpp/testing/gtest_extensions/pretty_printers.h b/library/cpp/testing/gtest_extensions/pretty_printers.h index 8171f77c13d..29608ee6248 100644 --- a/library/cpp/testing/gtest_extensions/pretty_printers.h +++ b/library/cpp/testing/gtest_extensions/pretty_printers.h @@ -2,7 +2,6 @@ #include #include -#include #include #include #include @@ -59,9 +58,9 @@ void PrintTo(TBasicStringBuf value, std::ostream* stream } template -void PrintTo(const TMaybe& value, std::ostream* stream) { - if (value.Defined()) { - ::testing::internal::UniversalPrint(value.GetRef(), stream); +void PrintTo(const std::optional& value, std::ostream* stream) { + if (value.has_value()) { + ::testing::internal::UniversalPrint(value.value(), stream); } else { *stream << "nothing"; } diff --git a/library/cpp/testing/gtest_extensions/ut/gtest_extensions_ut.cpp b/library/cpp/testing/gtest_extensions/ut/gtest_extensions_ut.cpp index 4d5f3c44775..06c0bd2ecf3 100644 --- a/library/cpp/testing/gtest_extensions/ut/gtest_extensions_ut.cpp +++ b/library/cpp/testing/gtest_extensions/ut/gtest_extensions_ut.cpp @@ -1,7 +1,6 @@ #include #include -#include #include #include @@ -241,12 +240,6 @@ TEST(PrettyPrinters, String) { EXPECT_EQ(GtestPrint(std::string_view("hello world")), "\"hello world\""); } -TEST(PrettyPrinters, Maybe) { - EXPECT_EQ(GtestPrint(TMaybe("hello world")), "\"hello world\""); - EXPECT_EQ(GtestPrint(TMaybe()), "nothing"); - EXPECT_EQ(GtestPrint(Nothing()), "nothing"); -} - struct T1 { int x; }; diff --git a/library/cpp/testing/unittest/junit.h b/library/cpp/testing/unittest/junit.h index b2a179222ba..43cded23c6b 100644 --- a/library/cpp/testing/unittest/junit.h +++ b/library/cpp/testing/unittest/junit.h @@ -1,7 +1,6 @@ #include "registar.h" #include -#include #include #include @@ -135,7 +134,7 @@ class TJUnitProcessor : public ITestSuiteProcessor { const std::string ExecName; // cmd line param const EOutputFormat OutputFormat; std::string ResultReportFileName; - TMaybe TmpReportFile; + std::optional TmpReportFile; std::map Suites; THolder StdErrCapturer; THolder StdOutCapturer; diff --git a/library/cpp/threading/future/core/future-inl.h b/library/cpp/threading/future/core/future-inl.h index cb3af4129c0..b2fee154471 100644 --- a/library/cpp/threading/future/core/future-inl.h +++ b/library/cpp/threading/future/core/future-inl.h @@ -644,8 +644,8 @@ namespace NThreading { } template - inline TMaybe TFuture::StateId() const noexcept { - return State != nullptr ? MakeMaybe(*State) : Nothing(); + inline std::optional TFuture::StateId() const noexcept { + return State != nullptr ? MakeMaybe(*State) : std::nullopt; } template @@ -747,8 +747,8 @@ namespace NThreading { return bool(State); } - inline TMaybe TFuture::StateId() const noexcept { - return State != nullptr ? MakeMaybe(*State) : Nothing(); + inline std::optional TFuture::StateId() const noexcept { + return State != nullptr ? std::optional(*State) : std::nullopt; } inline void TFuture::EnsureInitialized() const { diff --git a/library/cpp/threading/future/core/future.h b/library/cpp/threading/future/core/future.h index 1840f5815bd..6fd37e8a72e 100644 --- a/library/cpp/threading/future/core/future.h +++ b/library/cpp/threading/future/core/future.h @@ -6,7 +6,6 @@ #include #include -#include #include #include @@ -118,7 +117,7 @@ namespace NThreading { //! If the future is initialized returns the future state identifier. Otherwise returns an empty optional /** The state identifier is guaranteed to be unique during the future state lifetime and could be reused after its death **/ - TMaybe StateId() const noexcept; + std::optional StateId() const noexcept; void EnsureInitialized() const; }; @@ -178,7 +177,7 @@ namespace NThreading { //! If the future is initialized returns the future state identifier. Otherwise returns an empty optional /** The state identifier is guaranteed to be unique during the future state lifetime and could be reused after its death **/ - TMaybe StateId() const noexcept; + std::optional StateId() const noexcept; void EnsureInitialized() const; }; diff --git a/library/cpp/threading/future/wait/wait_group-inl.h b/library/cpp/threading/future/wait/wait_group-inl.h index a7da536f20e..c5e83aef8e3 100644 --- a/library/cpp/threading/future/wait/wait_group-inl.h +++ b/library/cpp/threading/future/wait/wait_group-inl.h @@ -6,7 +6,6 @@ #include "wait_policy.h" -#include #include #include diff --git a/library/cpp/yson/detail.h b/library/cpp/yson/detail.h index 04331235419..27a9b014216 100644 --- a/library/cpp/yson/detail.h +++ b/library/cpp/yson/detail.h @@ -3,8 +3,6 @@ #include "public.h" #include "zigzag.h" - -#include #include #include #include @@ -376,7 +374,7 @@ namespace NYson { private: using TBaseStream = TCodedStream>>; std::vector Buffer_; - TMaybe MemoryLimit_; + std::optional MemoryLimit_; void CheckMemoryLimit() { if (MemoryLimit_ && Buffer_.capacity() > *MemoryLimit_) { @@ -387,7 +385,7 @@ namespace NYson { } public: - TLexerBase(const TBlockStream& blockStream, TMaybe memoryLimit) + TLexerBase(const TBlockStream& blockStream, std::optional memoryLimit) : TBaseStream(blockStream) , MemoryLimit_(memoryLimit) { diff --git a/library/cpp/yson/lexer_detail.h b/library/cpp/yson/lexer_detail.h index 441e5fc7a12..53de546d4d4 100644 --- a/library/cpp/yson/lexer_detail.h +++ b/library/cpp/yson/lexer_detail.h @@ -148,7 +148,7 @@ namespace NYson { } public: - TLexer(const TBlockStream& blockStream, TMaybe memoryLimit) + TLexer(const TBlockStream& blockStream, std::optional memoryLimit) : TBase(blockStream, memoryLimit) { } @@ -280,7 +280,7 @@ namespace NYson { public: TStatelesYsonLexerImpl() - : Lexer(TStringReader(), Nothing()) + : Lexer(TStringReader(), std::nullopt) { } diff --git a/library/cpp/yson/parser.cpp b/library/cpp/yson/parser.cpp index 4968bb517d6..24e8f59dce1 100644 --- a/library/cpp/yson/parser.cpp +++ b/library/cpp/yson/parser.cpp @@ -16,7 +16,7 @@ namespace NYson { IInputStream* stream, EYsonType type, bool enableLinePositionInfo, - TMaybe memoryLimit = Nothing()) + std::optional memoryLimit = std::nullopt) : Consumer_(consumer) , Stream_(stream) , Type_(type) @@ -40,7 +40,7 @@ namespace NYson { IInputStream* Stream_; EYsonType Type_; bool EnableLinePositionInfo_; - TMaybe MemoryLimit_; + std::optional MemoryLimit_; }; //////////////////////////////////////////////////////////////////////////////// @@ -50,7 +50,7 @@ namespace NYson { IInputStream* stream, EYsonType type, bool enableLinePositionInfo, - TMaybe memoryLimit) + std::optional memoryLimit) : Impl(new TImpl(consumer, stream, type, enableLinePositionInfo, memoryLimit)) { } @@ -72,7 +72,7 @@ namespace NYson { TImpl( NYT::NYson::IYsonConsumer* consumer, bool enableLinePositionInfo, - TMaybe memoryLimit) + std::optional memoryLimit) : Impl( enableLinePositionInfo ? static_cast(new TStatelessYsonParserImpl(consumer, memoryLimit)) @@ -90,7 +90,7 @@ namespace NYson { TStatelessYsonParser::TStatelessYsonParser( NYT::NYson::IYsonConsumer* consumer, bool enableLinePositionInfo, - TMaybe memoryLimit) + std::optional memoryLimit) : Impl(new TImpl(consumer, enableLinePositionInfo, memoryLimit)) { } @@ -109,7 +109,7 @@ namespace NYson { NYT::NYson::IYsonConsumer* consumer, EYsonType type, bool enableLinePositionInfo, - TMaybe memoryLimit) { + std::optional memoryLimit) { ParseYsonStreamImpl( TStringReader(buffer.begin(), buffer.end()), consumer, @@ -126,7 +126,7 @@ namespace NYson { NYT::NYson::IYsonConsumer* consumer, IInputStream* stream, bool enableLinePositionInfo, - TMaybe memoryLimit = Nothing()) + std::optional memoryLimit = std::nullopt) : Consumer_(consumer) , Stream_(stream) , EnableLinePositionInfo_(enableLinePositionInfo) @@ -150,7 +150,7 @@ namespace NYson { NYT::NYson::IYsonConsumer* Consumer_; IInputStream* Stream_; bool EnableLinePositionInfo_; - TMaybe MemoryLimit_; + std::optional MemoryLimit_; TBuffer Buffer_; TStreamReader Reader_; THolder Impl_; @@ -162,7 +162,7 @@ namespace NYson { NYT::NYson::IYsonConsumer* consumer, IInputStream* stream, bool enableLinePositionInfo, - TMaybe memoryLimit) + std::optional memoryLimit) : Impl(new TImpl(consumer, stream, enableLinePositionInfo, memoryLimit)) { } diff --git a/library/cpp/yson/parser.h b/library/cpp/yson/parser.h index b2e4dbe4fdc..b2b473c51d0 100644 --- a/library/cpp/yson/parser.h +++ b/library/cpp/yson/parser.h @@ -2,7 +2,6 @@ #include "public.h" -#include #include class IInputStream; @@ -21,7 +20,7 @@ namespace NYson { IInputStream* stream, EYsonType type = ::NYson::EYsonType::Node, bool enableLinePositionInfo = false, - TMaybe memoryLimit = Nothing()); + std::optional memoryLimit = std::nullopt); ~TYsonParser(); @@ -39,7 +38,7 @@ namespace NYson { TStatelessYsonParser( NYT::NYson::IYsonConsumer* consumer, bool enableLinePositionInfo = false, - TMaybe memoryLimit = Nothing()); + std::optional memoryLimit = std::nullopt); ~TStatelessYsonParser(); @@ -58,7 +57,7 @@ namespace NYson { NYT::NYson::IYsonConsumer* consumer, IInputStream* stream, bool enableLinePositionInfo = false, - TMaybe memoryLimit = Nothing()); + std::optional memoryLimit = std::nullopt); ~TYsonListParser(); @@ -76,7 +75,7 @@ namespace NYson { NYT::NYson::IYsonConsumer* consumer, EYsonType type = ::NYson::EYsonType::Node, bool enableLinePositionInfo = false, - TMaybe memoryLimit = Nothing()); + std::optional memoryLimit = std::nullopt); //////////////////////////////////////////////////////////////////////////////// diff --git a/library/cpp/yson/parser_detail.h b/library/cpp/yson/parser_detail.h index e8b6f670408..8972f07b4d3 100644 --- a/library/cpp/yson/parser_detail.h +++ b/library/cpp/yson/parser_detail.h @@ -14,7 +14,7 @@ namespace NYson { TConsumer* Consumer; public: - TParser(const TBlockStream& blockStream, TConsumer* consumer, TMaybe memoryLimit) + TParser(const TBlockStream& blockStream, TConsumer* consumer, std::optional memoryLimit) : TBase(blockStream, memoryLimit) , Consumer(consumer) { @@ -308,7 +308,7 @@ namespace NYson { NYT::NYson::IYsonConsumer* consumer, EYsonType parsingMode, bool enableLinePositionInfo, - TMaybe memoryLimit) { + std::optional memoryLimit) { if (enableLinePositionInfo) { using TImpl = NDetail::TParser; TImpl impl(blockStream, consumer, memoryLimit); @@ -336,7 +336,7 @@ namespace NYson { TParser Parser; public: - TStatelessYsonParserImpl(TConsumer* consumer, TMaybe memoryLimit) + TStatelessYsonParserImpl(TConsumer* consumer, std::optional memoryLimit) : Parser(TStringReader(), consumer, memoryLimit) { } @@ -364,7 +364,7 @@ namespace NYson { bool First = true; public: - TYsonListParserImpl(const TBlockStream& blockStream, TConsumer* consumer, TMaybe memoryLimit) + TYsonListParserImpl(const TBlockStream& blockStream, TConsumer* consumer, std::optional memoryLimit) : Parser(blockStream, consumer, memoryLimit) { } diff --git a/tools/enum_parser/enum_parser/main.cpp b/tools/enum_parser/enum_parser/main.cpp index 5c5fdbf16c1..41141343565 100644 --- a/tools/enum_parser/enum_parser/main.cpp +++ b/tools/enum_parser/enum_parser/main.cpp @@ -20,7 +20,6 @@ #include #include -#include #include #include @@ -70,10 +69,10 @@ void OutKey(IOutputStream& out, const std::string& key, const T& value, bool esc out << "\"" << key << "\": " << quoted << ",\n"; } -/// Simplifed JSON map encoder for TMaybe -void OutKey(IOutputStream& out, const std::string& key, const TMaybe& value) { +/// Simplifed JSON map encoder for optional +void OutKey(IOutputStream& out, const std::string& key, const std::optional& value) { std::string quoted; - if (value) { + if (value.has_value()) { quoted = JsonQuote(ToString(*value)); } else { quoted = "null"; diff --git a/tools/enum_parser/parse_enum/parse_enum.cpp b/tools/enum_parser/parse_enum/parse_enum.cpp index e235366a9d9..9acac953b38 100644 --- a/tools/enum_parser/parse_enum/parse_enum.cpp +++ b/tools/enum_parser/parse_enum/parse_enum.cpp @@ -56,7 +56,7 @@ class TEnumContext: public TCppFullSax { void AddEnumItem() { if (CurrentItem.CppName.empty()) { // uninitialized element should have no value too - Y_ASSERT(!CurrentItem.Value.Defined()); + Y_ASSERT(!CurrentItem.Value.has_value()); return; } diff --git a/tools/enum_parser/parse_enum/parse_enum.h b/tools/enum_parser/parse_enum/parse_enum.h index e9b7ec315be..31e5071cd19 100644 --- a/tools/enum_parser/parse_enum/parse_enum.h +++ b/tools/enum_parser/parse_enum/parse_enum.h @@ -1,8 +1,9 @@ #pragma once +#include #include -#include +#include #include #include @@ -10,7 +11,7 @@ class TEnumParser { public: struct TItem { - TMaybe Value; + std::optional Value; std::string CppName; std::vector Aliases; std::string CommentText; diff --git a/util/CMakeLists.darwin-arm64.txt b/util/CMakeLists.darwin-arm64.txt index 23ae0ba543b..64062d810ca 100644 --- a/util/CMakeLists.darwin-arm64.txt +++ b/util/CMakeLists.darwin-arm64.txt @@ -93,7 +93,6 @@ target_joined_source(yutil ${CMAKE_SOURCE_DIR}/util/generic/list.cpp ${CMAKE_SOURCE_DIR}/util/generic/map.cpp ${CMAKE_SOURCE_DIR}/util/generic/mapfindptr.cpp - ${CMAKE_SOURCE_DIR}/util/generic/maybe.cpp ${CMAKE_SOURCE_DIR}/util/generic/mem_copy.cpp ${CMAKE_SOURCE_DIR}/util/generic/noncopyable.cpp ${CMAKE_SOURCE_DIR}/util/generic/object_counter.cpp diff --git a/util/CMakeLists.darwin-x86_64.txt b/util/CMakeLists.darwin-x86_64.txt index e159ab06c8b..a7e01b304af 100644 --- a/util/CMakeLists.darwin-x86_64.txt +++ b/util/CMakeLists.darwin-x86_64.txt @@ -92,7 +92,6 @@ target_joined_source(yutil ${CMAKE_SOURCE_DIR}/util/generic/list.cpp ${CMAKE_SOURCE_DIR}/util/generic/map.cpp ${CMAKE_SOURCE_DIR}/util/generic/mapfindptr.cpp - ${CMAKE_SOURCE_DIR}/util/generic/maybe.cpp ${CMAKE_SOURCE_DIR}/util/generic/mem_copy.cpp ${CMAKE_SOURCE_DIR}/util/generic/noncopyable.cpp ${CMAKE_SOURCE_DIR}/util/generic/object_counter.cpp diff --git a/util/CMakeLists.linux-aarch64.txt b/util/CMakeLists.linux-aarch64.txt index eee1114ed8d..a9d2830cafb 100644 --- a/util/CMakeLists.linux-aarch64.txt +++ b/util/CMakeLists.linux-aarch64.txt @@ -96,7 +96,6 @@ target_joined_source(yutil ${CMAKE_SOURCE_DIR}/util/generic/list.cpp ${CMAKE_SOURCE_DIR}/util/generic/map.cpp ${CMAKE_SOURCE_DIR}/util/generic/mapfindptr.cpp - ${CMAKE_SOURCE_DIR}/util/generic/maybe.cpp ${CMAKE_SOURCE_DIR}/util/generic/mem_copy.cpp ${CMAKE_SOURCE_DIR}/util/generic/noncopyable.cpp ${CMAKE_SOURCE_DIR}/util/generic/object_counter.cpp diff --git a/util/CMakeLists.linux-x86_64.txt b/util/CMakeLists.linux-x86_64.txt index e4aa8bf0b79..874c7c2b329 100644 --- a/util/CMakeLists.linux-x86_64.txt +++ b/util/CMakeLists.linux-x86_64.txt @@ -95,7 +95,6 @@ target_joined_source(yutil ${CMAKE_SOURCE_DIR}/util/generic/list.cpp ${CMAKE_SOURCE_DIR}/util/generic/map.cpp ${CMAKE_SOURCE_DIR}/util/generic/mapfindptr.cpp - ${CMAKE_SOURCE_DIR}/util/generic/maybe.cpp ${CMAKE_SOURCE_DIR}/util/generic/mem_copy.cpp ${CMAKE_SOURCE_DIR}/util/generic/noncopyable.cpp ${CMAKE_SOURCE_DIR}/util/generic/object_counter.cpp diff --git a/util/CMakeLists.windows-x86_64.txt b/util/CMakeLists.windows-x86_64.txt index ff38abd2066..e99aababc4b 100644 --- a/util/CMakeLists.windows-x86_64.txt +++ b/util/CMakeLists.windows-x86_64.txt @@ -99,7 +99,6 @@ target_joined_source(yutil ${CMAKE_SOURCE_DIR}/util/generic/list.cpp ${CMAKE_SOURCE_DIR}/util/generic/map.cpp ${CMAKE_SOURCE_DIR}/util/generic/mapfindptr.cpp - ${CMAKE_SOURCE_DIR}/util/generic/maybe.cpp ${CMAKE_SOURCE_DIR}/util/generic/mem_copy.cpp ${CMAKE_SOURCE_DIR}/util/generic/noncopyable.cpp ${CMAKE_SOURCE_DIR}/util/generic/object_counter.cpp diff --git a/util/draft/ip.h b/util/draft/ip.h index eb947cd2cd5..c894b72e447 100644 --- a/util/draft/ip.h +++ b/util/draft/ip.h @@ -5,7 +5,6 @@ #include #include -#include #include #ifdef _unix_ @@ -62,11 +61,11 @@ static inline TIp6 Ip6FromString(const char* ipStr) { return res; } -static inline TMaybe TryParseIp6FromString(const char* ipStr) { +static inline std::optional TryParseIp6FromString(const char* ipStr) { TIp6 res; if (inet_pton(AF_INET6, ipStr, &res.Data) == 0) { - return Nothing(); + return std::nullopt; } return res; diff --git a/util/generic/fwd.h b/util/generic/fwd.h index 18f4e5b6572..a0e54eb389b 100644 --- a/util/generic/fwd.h +++ b/util/generic/fwd.h @@ -145,14 +145,6 @@ using TArrayPtr = TAutoPtr; template using TMallocPtr = TAutoPtr; -//maybe -namespace NMaybe { - struct TPolicyUndefinedExcept; -} - -template -class TMaybe; - struct TGUID; template diff --git a/util/generic/lazy_value.h b/util/generic/lazy_value.h index e54cdb31d0d..c3a8eb26004 100644 --- a/util/generic/lazy_value.h +++ b/util/generic/lazy_value.h @@ -1,6 +1,5 @@ #pragma once -#include "maybe.h" #include "function.h" template @@ -40,7 +39,7 @@ class TLazyValueBase { } private: - mutable TMaybe ValueHolder; + mutable std::optional ValueHolder; TInitializer Initializer; }; diff --git a/util/generic/maybe.cpp b/util/generic/maybe.cpp deleted file mode 100644 index c238002739f..00000000000 --- a/util/generic/maybe.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "maybe.h" -#include - -[[noreturn]] void NMaybe::TPolicyUndefinedExcept::OnEmpty(const std::type_info& valueTypeInfo) { - ythrow yexception() << "TMaybe is empty, value type: "sv << TypeName(valueTypeInfo); -} - -[[noreturn]] void NMaybe::TPolicyUndefinedFail::OnEmpty(const std::type_info& valueTypeInfo) { - const TString typeName = TypeName(valueTypeInfo); - Y_ABORT("TMaybe is empty, value type: %s", typeName.c_str()); -} - -template <> -void Out(IOutputStream& o, const TNothing&) { - o << "(empty maybe)"; -} diff --git a/util/generic/maybe.h b/util/generic/maybe.h deleted file mode 100644 index 8498afda348..00000000000 --- a/util/generic/maybe.h +++ /dev/null @@ -1,723 +0,0 @@ -#pragma once - -#include - -#include "maybe_traits.h" -#include "yexception.h" - -#include -#include -#include -#include - -namespace NMaybe { - struct TPolicyUndefinedExcept { - [[noreturn]] static void OnEmpty(const std::type_info& valueTypeInfo); - }; - - struct TPolicyUndefinedFail { - [[noreturn]] static void OnEmpty(const std::type_info& valueTypeInfo); - }; -} - -struct TNothing { - explicit constexpr TNothing(int) noexcept { - } -}; - -constexpr TNothing NothingObject{0}; - -constexpr TNothing Nothing() noexcept { - return NothingObject; -} - -constexpr bool operator==(TNothing, TNothing) noexcept { - return true; -} - -template -class TMaybe: private TMaybeBase { -public: - using TInPlace = NMaybe::TInPlace; - -private: - static_assert(!std::is_same, TNothing>::value, - "Instantiation of TMaybe with a TNothing type is ill-formed"); - static_assert(!std::is_same, TInPlace>::value, - "Instantiation of TMaybe with a TInPlace type is ill-formed"); - static_assert(!std::is_reference::value, - "Instantiation of TMaybe with reference type is ill-formed"); - static_assert(std::is_destructible::value, - "Instantiation of TMaybe with non-destructible type is ill-formed"); - - template - struct TConstructibleFromMaybeSomehow { - public: - static constexpr bool value = std::is_constructible&>::value || - std::is_constructible&>::value || - std::is_constructible&&>::value || - std::is_constructible&&>::value || - std::is_convertible&, T>::value || - std::is_convertible&, T>::value || - std::is_convertible&&, T>::value || - std::is_convertible&&, T>::value; - }; - - template - struct TAssignableFromMaybeSomehow { - public: - static constexpr bool value = TConstructibleFromMaybeSomehow::value || - std::is_assignable&>::value || - std::is_assignable&>::value || - std::is_assignable&&>::value || - std::is_assignable&&>::value; - }; - - template - struct TImplicitCopyCtor { - public: - static constexpr bool value = std::is_constructible::value && - std::is_convertible::value && - !TConstructibleFromMaybeSomehow::value; - }; - - template - struct TExplicitCopyCtor { - public: - static constexpr bool value = std::is_constructible::value && - !std::is_convertible::value && - !TConstructibleFromMaybeSomehow::value; - }; - - template - struct TImplicitMoveCtor { - public: - static constexpr bool value = std::is_constructible::value && - std::is_convertible::value && - !TConstructibleFromMaybeSomehow::value; - }; - - template - struct TExplicitMoveCtor { - public: - static constexpr bool value = std::is_constructible::value && - !std::is_convertible::value && - !TConstructibleFromMaybeSomehow::value; - }; - - template - struct TCopyAssignable { - public: - static constexpr bool value = std::is_constructible::value && - std::is_assignable::value && - !TAssignableFromMaybeSomehow::value; - }; - - template - struct TMoveAssignable { - public: - static constexpr bool value = std::is_constructible::value && - std::is_assignable::value && - !TAssignableFromMaybeSomehow::value; - }; - - template - struct TImplicitAnyCtor { - public: - using UDec = std::decay_t; - - static constexpr bool value = std::is_constructible::value && - std::is_convertible::value && - !std::is_same::value && - !std::is_same::value; - }; - - template - struct TExplicitAnyCtor { - public: - using UDec = std::decay_t; - static constexpr bool value = std::is_constructible::value && - !std::is_convertible::value && - !std::is_same::value && - !std::is_same::value; - }; - - template - struct TAssignableFromAny { - public: - using UDec = std::decay_t; - static constexpr bool value = !std::is_same::value && - std::is_constructible::value && - std::is_assignable::value && - (!std::is_scalar::value || !std::is_same::value); - }; - - using TBase = TMaybeBase; - -public: - using value_type = T; - using TValueType = value_type; - - TMaybe() noexcept = default; - - constexpr TMaybe(const TMaybe&) = default; - constexpr TMaybe(TMaybe&&) = default; - - template - constexpr explicit TMaybe(TInPlace, Args&&... args) - : TBase(TInPlace{}, std::forward(args)...) - { - } - - template - constexpr explicit TMaybe(TInPlace, std::initializer_list il, TArgs&&... args) - : TBase(TInPlace{}, il, std::forward(args)...) - { - } - - constexpr TMaybe(TNothing) noexcept { - } - - template ::value>> - TMaybe(const TMaybe& right) { - if (right.Defined()) { - new (Data()) T(right.GetRef()); - this->Defined_ = true; - } - } - - template ::value, bool> = false> - explicit TMaybe(const TMaybe& right) { - if (right.Defined()) { - new (Data()) T(right.GetRef()); - this->Defined_ = true; - } - } - - template ::value>> - TMaybe(TMaybe&& right) noexcept(std::is_nothrow_constructible::value) { - if (right.Defined()) { - new (Data()) T(std::move(right.GetRef())); - this->Defined_ = true; - } - } - - template ::value, bool> = false> - explicit TMaybe(TMaybe&& right) noexcept(std::is_nothrow_constructible::value) { - if (right.Defined()) { - new (Data()) T(std::move(right.GetRef())); - this->Defined_ = true; - } - } - - template ::value>> - constexpr TMaybe(U&& right) - : TBase(TInPlace{}, std::forward(right)) - { - } - - template ::value, bool> = false> - constexpr explicit TMaybe(U&& right) - : TBase(TInPlace{}, std::forward(right)) - { - } - - ~TMaybe() = default; - - constexpr TMaybe& operator=(const TMaybe&) = default; - constexpr TMaybe& operator=(TMaybe&&) = default; - - TMaybe& operator=(TNothing) noexcept { - Clear(); - return *this; - } - - template - std::enable_if_t::value, TMaybe&> operator=(U&& right) { - if (Defined()) { - *Data() = std::forward(right); - } else { - Init(std::forward(right)); - } - return *this; - } - - template - std::enable_if_t::value, - TMaybe&> - operator=(const TMaybe& right) { - if (right.Defined()) { - if (Defined()) { - *Data() = right.GetRef(); - } else { - Init(right.GetRef()); - } - } else { - Clear(); - } - - return *this; - } - - template - std::enable_if_t::value, - TMaybe&> - operator=(TMaybe&& right) noexcept( - std::is_nothrow_assignable::value&& std::is_nothrow_constructible::value) - { - if (right.Defined()) { - if (Defined()) { - *Data() = std::move(right.GetRef()); - } else { - Init(std::move(right.GetRef())); - } - } else { - Clear(); - } - - return *this; - } - - template - T& ConstructInPlace(Args&&... args) { - Clear(); - Init(std::forward(args)...); - return *Data(); - } - - Y_REINITIALIZES_OBJECT void Clear() noexcept { - if (Defined()) { - 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)); - } - } - - const T* Get() const noexcept Y_LIFETIME_BOUND { - return Defined() ? Data() : nullptr; - } - - T* Get() noexcept Y_LIFETIME_BOUND { - return Defined() ? Data() : nullptr; - } - - constexpr const T& GetRef() const& Y_LIFETIME_BOUND { - CheckDefined(); - - return *Data(); - } - - constexpr T& GetRef() & Y_LIFETIME_BOUND { - CheckDefined(); - - return *Data(); - } - - constexpr const T&& GetRef() const&& Y_LIFETIME_BOUND { - CheckDefined(); - - return std::move(*Data()); - } - - constexpr T&& GetRef() && Y_LIFETIME_BOUND { - CheckDefined(); - - return std::move(*Data()); - } - - constexpr const T& operator*() const& Y_LIFETIME_BOUND { - return GetRef(); - } - - constexpr T& operator*() & Y_LIFETIME_BOUND { - return GetRef(); - } - - constexpr const T&& operator*() const&& Y_LIFETIME_BOUND { - return std::move(GetRef()); - } - - constexpr T&& operator*() && Y_LIFETIME_BOUND { - return std::move(GetRef()); - } - - constexpr const T* operator->() const Y_LIFETIME_BOUND { - return &GetRef(); - } - - constexpr T* operator->() Y_LIFETIME_BOUND { - return &GetRef(); - } - - constexpr const T& GetOrElse(const T& elseValue Y_LIFETIME_BOUND) const Y_LIFETIME_BOUND { - return Defined() ? *Data() : elseValue; - } - - constexpr T& GetOrElse(T& elseValue Y_LIFETIME_BOUND) Y_LIFETIME_BOUND { - return Defined() ? *Data() : elseValue; - } - - constexpr const TMaybe& OrElse(const TMaybe& elseValue Y_LIFETIME_BOUND) const noexcept Y_LIFETIME_BOUND { - return Defined() ? *this : elseValue; - } - - constexpr TMaybe& OrElse(TMaybe& elseValue Y_LIFETIME_BOUND) Y_LIFETIME_BOUND { - return Defined() ? *this : elseValue; - } - - template - TMaybe Cast() const { - return Defined() ? TMaybe(*Data()) : TMaybe(); - } - - constexpr explicit operator bool() const noexcept { - return Defined(); - } - - void Save(IOutputStream* out) const { - const bool defined = Defined(); - - ::Save(out, defined); - - if (defined) { - ::Save(out, *Data()); - } - } - - void Load(IInputStream* in) { - bool defined; - - ::Load(in, defined); - - if (defined) { - if (!Defined()) { - ConstructInPlace(); - } - - ::Load(in, *Data()); - } else { - Clear(); - } - } - - void Swap(TMaybe& other) { - if (this->Defined_ == other.Defined_) { - if (this->Defined_) { - ::DoSwap(this->Data_, other.Data_); - } - } else { - if (this->Defined_) { - other.Init(std::move(this->Data_)); - this->Clear(); - } else { - this->Init(std::move(other.Data_)); - other.Clear(); - } - } - } - - void swap(TMaybe& other) { - Swap(other); - } - -private: - constexpr const T* Data() const noexcept Y_LIFETIME_BOUND { - return std::addressof(this->Data_); - } - - constexpr T* Data() noexcept Y_LIFETIME_BOUND { - return std::addressof(this->Data_); - } - - template - void Init(Args&&... args) { - new (Data()) T(std::forward(args)...); - this->Defined_ = true; - } -}; - -template -using TMaybeFail = TMaybe; - -template -constexpr TMaybe, TPolicy> MakeMaybe(T&& value) { - return TMaybe, TPolicy>(std::forward(value)); -} - -template -constexpr TMaybe MakeMaybe(TArgs&&... args) { - return TMaybe(typename TMaybe::TInPlace{}, std::forward(args)...); -} - -template -constexpr TMaybe MakeMaybe(std::initializer_list il, TArgs&&... args) { - return TMaybe(typename TMaybe::TInPlace{}, il, std::forward(args)...); -} - -template -void Swap(TMaybe& lhs, TMaybe& rhs) { - lhs.Swap(rhs); -} - -template -void swap(TMaybe& lhs, TMaybe& rhs) { - lhs.Swap(rhs); -} - -template -struct THash> { - constexpr size_t operator()(const TMaybe& data) const { - return (data.Defined()) ? THash()(data.GetRef()) : 42; - } -}; - -// Comparisons between TMaybe -template -constexpr bool operator==(const ::TMaybe& left, const ::TMaybe& right) { - return (static_cast(left) != static_cast(right)) - ? false - : ( - !static_cast(left) - ? true - : *left == *right); -} - -template -constexpr bool operator!=(const TMaybe& left, const TMaybe& right) { - return !(left == right); -} - -template -constexpr bool operator<(const TMaybe& left, const TMaybe& right) { - return (!static_cast(right)) - ? false - : ( - !static_cast(left) - ? true - : (*left < *right)); -} - -template -constexpr bool operator>(const TMaybe& left, const TMaybe& right) { - return right < left; -} - -template -constexpr bool operator<=(const TMaybe& left, const TMaybe& right) { - return !(right < left); -} - -template -constexpr bool operator>=(const TMaybe& left, const TMaybe& right) { - return !(left < right); -} - -// Comparisons with TNothing -template -constexpr bool operator==(const TMaybe& left, TNothing) noexcept { - return !static_cast(left); -} - -template -constexpr bool operator==(TNothing, const TMaybe& right) noexcept { - return !static_cast(right); -} - -template -constexpr bool operator!=(const TMaybe& left, TNothing) noexcept { - return static_cast(left); -} - -template -constexpr bool operator!=(TNothing, const TMaybe& right) noexcept { - return static_cast(right); -} - -template -constexpr bool operator<(const TMaybe&, TNothing) noexcept { - return false; -} - -template -constexpr bool operator<(TNothing, const TMaybe& right) noexcept { - return static_cast(right); -} - -template -constexpr bool operator<=(const TMaybe& left, TNothing) noexcept { - return !static_cast(left); -} - -template -constexpr bool operator<=(TNothing, const TMaybe&) noexcept { - return true; -} - -template -constexpr bool operator>(const TMaybe& left, TNothing) noexcept { - return static_cast(left); -} - -template -constexpr bool operator>(TNothing, const TMaybe&) noexcept { - return false; -} - -template -constexpr bool operator>=(const TMaybe&, TNothing) noexcept { - return true; -} - -template -constexpr bool operator>=(TNothing, const TMaybe& right) noexcept { - return !static_cast(right); -} - -// Comparisons with T - -template -constexpr bool operator==(const TMaybe& maybe, const T& value) { - return static_cast(maybe) ? *maybe == value : false; -} - -template -constexpr bool operator==(const T& value, const TMaybe& maybe) { - return static_cast(maybe) ? *maybe == value : false; -} - -template -constexpr bool operator!=(const TMaybe& maybe, const T& value) { - return static_cast(maybe) ? !(*maybe == value) : true; -} - -template -constexpr bool operator!=(const T& value, const TMaybe& maybe) { - return static_cast(maybe) ? !(*maybe == value) : true; -} - -template -constexpr bool operator<(const TMaybe& maybe, const T& value) { - return static_cast(maybe) ? std::less{}(*maybe, value) : true; -} - -template -constexpr bool operator<(const T& value, const TMaybe& maybe) { - return static_cast(maybe) ? std::less{}(value, *maybe) : false; -} - -template -constexpr bool operator<=(const TMaybe& maybe, const T& value) { - return !(maybe > value); -} - -template -constexpr bool operator<=(const T& value, const TMaybe& maybe) { - return !(value > maybe); -} - -template -constexpr bool operator>(const TMaybe& maybe, const T& value) { - return static_cast(maybe) ? value < maybe : false; -} - -template -constexpr bool operator>(const T& value, const TMaybe& maybe) { - return static_cast(maybe) ? maybe < value : true; -} - -template -constexpr bool operator>=(const TMaybe& maybe, const T& value) { - return !(maybe < value); -} - -template -constexpr bool operator>=(const T& value, const TMaybe& maybe) { - return !(value < maybe); -} - -// Comparison with values convertible to T - -template ::value, int> = 0> -constexpr bool operator==(const ::TMaybe& maybe, const U& value) { - return static_cast(maybe) ? *maybe == value : false; -} - -template ::value, int> = 0> -constexpr bool operator==(const U& value, const ::TMaybe& maybe) { - return static_cast(maybe) ? *maybe == value : false; -} - -template ::value, int> = 0> -constexpr bool operator!=(const TMaybe& maybe, const U& value) { - return static_cast(maybe) ? !(*maybe == value) : true; -} - -template ::value, int> = 0> -constexpr bool operator!=(const U& value, const TMaybe& maybe) { - return static_cast(maybe) ? !(*maybe == value) : true; -} - -template ::value, int> = 0> -constexpr bool operator<(const TMaybe& maybe, const U& value) { - return static_cast(maybe) ? std::less{}(*maybe, value) : true; -} - -template ::value, int> = 0> -constexpr bool operator<(const U& value, const TMaybe& maybe) { - return static_cast(maybe) ? std::less{}(value, *maybe) : false; -} - -template ::value, int> = 0> -constexpr bool operator<=(const TMaybe& maybe, const U& value) { - return !(maybe > value); -} - -template ::value, int> = 0> -constexpr bool operator<=(const U& value, const TMaybe& maybe) { - return !(value > maybe); -} - -template ::value, int> = 0> -constexpr bool operator>(const TMaybe& maybe, const U& value) { - return static_cast(maybe) ? value < maybe : false; -} - -template ::value, int> = 0> -constexpr bool operator>(const U& value, const TMaybe& maybe) { - return static_cast(maybe) ? maybe < value : true; -} - -template ::value, int> = 0> -constexpr bool operator>=(const TMaybe& maybe, const U& value) { - return !(maybe < value); -} - -template ::value, int> = 0> -constexpr bool operator>=(const U& value, const TMaybe& maybe) { - return !(value < maybe); -} - -class IOutputStream; - -template -inline IOutputStream& operator<<(IOutputStream& out, const TMaybe& maybe) { - if (maybe.Defined()) { - out << *maybe; - } else { - out << TStringBuf("(empty maybe)"); - } - return out; -} diff --git a/util/generic/maybe.pxd b/util/generic/maybe.pxd deleted file mode 100644 index 15161dd2044..00000000000 --- a/util/generic/maybe.pxd +++ /dev/null @@ -1,35 +0,0 @@ -cdef extern from "" nogil: - cdef cppclass TNothing: - pass - - cdef TNothing Nothing() - - cdef cppclass TMaybe[T]: - TMaybe(...) except + - - TMaybe& operator=(...) except + - - void ConstructInPlace(...) except + - void Clear() except + - - bint Defined() - bint Empty() - - void CheckDefined() except + - - T* Get() except + - T& GetRef() except + - - T GetOrElse(T&) except + - TMaybe OrElse(TMaybe&) except + - - TMaybe[U] Cast[U]() except + - - void Swap(TMaybe& other) except + - - bint operator ==[U](U&) except + - bint operator !=[U](U&) except + - bint operator <[U](U&) except + - bint operator >[U](U&) except + - bint operator <=[U](U&) except + - bint operator >=[U](U&) except + diff --git a/util/generic/maybe_traits.h b/util/generic/maybe_traits.h deleted file mode 100644 index 702912c8fa1..00000000000 --- a/util/generic/maybe_traits.h +++ /dev/null @@ -1,185 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace NMaybe { - struct TInPlace {}; - - template ::value> - struct TStorageBase { - constexpr TStorageBase() noexcept - : NullState_('\0') - { - } - - template - constexpr TStorageBase(TInPlace, Args&&... args) - : Data_(std::forward(args)...) - , Defined_(true) - { - } - - constexpr TStorageBase(TStorageBase&&) = default; - constexpr TStorageBase(const TStorageBase&) = default; - - ~TStorageBase() = default; - - TStorageBase& operator=(const TStorageBase&) = default; - TStorageBase& operator=(TStorageBase&&) = default; - - union { - char NullState_; - T Data_; - }; - bool Defined_ = false; - }; - - template - struct TStorageBase { - constexpr TStorageBase() noexcept - : NullState_('\0') - { - } - - template - constexpr TStorageBase(TInPlace, Args&&... args) - : Data_(std::forward(args)...) - , Defined_(true) - { - } - - constexpr TStorageBase(TStorageBase&&) = default; - constexpr TStorageBase(const TStorageBase&) = default; - - ~TStorageBase() { - if (this->Defined_) { - this->Data_.~T(); - } - } - - TStorageBase& operator=(const TStorageBase&) = default; - TStorageBase& operator=(TStorageBase&&) = default; - - union { - char NullState_; - T Data_; - }; - bool Defined_ = false; - }; - - // -------------------- COPY CONSTRUCT -------------------- - - template ::value> - struct TCopyBase: TStorageBase { - using TStorageBase::TStorageBase; - }; - - template - struct TCopyBase: TStorageBase { - using TStorageBase::TStorageBase; - - constexpr TCopyBase() = default; - constexpr TCopyBase(const TCopyBase& rhs) { - if (rhs.Defined_) { - new (std::addressof(this->Data_)) T(rhs.Data_); - this->Defined_ = true; - } - } - constexpr TCopyBase(TCopyBase&&) = default; - TCopyBase& operator=(const TCopyBase&) = default; - TCopyBase& operator=(TCopyBase&&) = default; - }; - - // -------------------- MOVE CONSTRUCT -------------------- - - template ::value> - struct TMoveBase: TCopyBase { - using TCopyBase::TCopyBase; - }; - - template - struct TMoveBase: TCopyBase { - using TCopyBase::TCopyBase; - - constexpr TMoveBase() noexcept = default; - constexpr TMoveBase(const TMoveBase&) = default; - constexpr TMoveBase(TMoveBase&& rhs) noexcept(std::is_nothrow_move_constructible::value) { - if (rhs.Defined_) { - new (std::addressof(this->Data_)) T(std::move(rhs.Data_)); - this->Defined_ = true; - } - } - TMoveBase& operator=(const TMoveBase&) = default; - TMoveBase& operator=(TMoveBase&&) = default; - }; - - // -------------------- COPY ASSIGN -------------------- - - template ::value> - struct TCopyAssignBase: TMoveBase { - using TMoveBase::TMoveBase; - }; - - template - struct TCopyAssignBase: TMoveBase { - using TMoveBase::TMoveBase; - - constexpr TCopyAssignBase() noexcept = default; - constexpr TCopyAssignBase(const TCopyAssignBase&) = default; - constexpr TCopyAssignBase(TCopyAssignBase&&) = default; - TCopyAssignBase& operator=(const TCopyAssignBase& rhs) { - if (this->Defined_) { - if (rhs.Defined_) { - this->Data_ = rhs.Data_; - } else { - this->Data_.~T(); - this->Defined_ = false; - } - } else if (rhs.Defined_) { - new (std::addressof(this->Data_)) T(rhs.Data_); - this->Defined_ = true; - } - return *this; - } - TCopyAssignBase& operator=(TCopyAssignBase&&) = default; - }; - - // -------------------- MOVE ASSIGN -------------------- - - template ::value> - struct TMoveAssignBase: TCopyAssignBase { - using TCopyAssignBase::TCopyAssignBase; - }; - - template - struct TMoveAssignBase: TCopyAssignBase { - using TCopyAssignBase::TCopyAssignBase; - - constexpr TMoveAssignBase() noexcept = default; - constexpr TMoveAssignBase(const TMoveAssignBase&) = default; - constexpr TMoveAssignBase(TMoveAssignBase&&) = default; - TMoveAssignBase& operator=(const TMoveAssignBase&) = default; - TMoveAssignBase& operator=(TMoveAssignBase&& rhs) noexcept( - std::is_nothrow_move_assignable::value&& - std::is_nothrow_move_constructible::value) - { - if (this->Defined_) { - if (rhs.Defined_) { - this->Data_ = std::move(rhs.Data_); - } else { - this->Data_.~T(); - this->Defined_ = false; - } - } else if (rhs.Defined_) { - new (std::addressof(this->Data_)) T(std::move(rhs.Data_)); - this->Defined_ = true; - } - return *this; - } - }; -} - -template -using TMaybeBase = NMaybe::TMoveAssignBase; diff --git a/util/generic/maybe_ut.cpp b/util/generic/maybe_ut.cpp deleted file mode 100644 index 5d64a38c52a..00000000000 --- a/util/generic/maybe_ut.cpp +++ /dev/null @@ -1,1006 +0,0 @@ -#include -#include -#include -#include - -#include "maybe.h" - -class TIncrementOnDestroy { -private: - int* Ptr_; - -public: - TIncrementOnDestroy(int* ptr) noexcept - : Ptr_(ptr) - { - } - - ~TIncrementOnDestroy() { - ++*Ptr_; - } -}; - -Y_UNIT_TEST_SUITE(TMaybeTest) { - Y_UNIT_TEST(TestStatic) { - using T1 = TMaybe; - static_assert(std::is_trivially_copy_constructible::value, ""); - static_assert(std::is_trivially_destructible::value, ""); - - using T2 = TMaybe; - static_assert(std::is_trivially_copy_constructible::value, ""); - static_assert(std::is_trivially_destructible::value, ""); - - using T3 = TMaybe>; - static_assert(std::is_trivially_copy_constructible::value, ""); - static_assert(std::is_trivially_destructible::value, ""); - - using T4 = TMaybe; - static_assert(!std::is_trivially_copy_constructible::value, ""); - static_assert(!std::is_trivially_destructible::value, ""); - } - - Y_UNIT_TEST(TestWarning) { - TMaybe x; - TStringStream ss; - TString line; - - while (ss.ReadLine(line)) { - x = line.size(); - } - - if (x == 5u) { - ss << "5\n"; - } - } - - Y_UNIT_TEST(TTestConstructorDestructor) { - int a = 0; - int b = 0; - - TMaybe(); - UNIT_ASSERT_VALUES_EQUAL(a, b); - - TMaybe(TIncrementOnDestroy(&a)); - b += 2; - UNIT_ASSERT_VALUES_EQUAL(a, b); - - { - TMaybe m1 = TIncrementOnDestroy(&a); - b += 1; - UNIT_ASSERT_VALUES_EQUAL(a, b); - - TMaybe m2 = m1; - UNIT_ASSERT_VALUES_EQUAL(a, b); - - TMaybe m3; - m3 = m1; - UNIT_ASSERT_VALUES_EQUAL(a, b); - } - - b += 3; - UNIT_ASSERT_VALUES_EQUAL(a, b); - - { - TMaybe m4 = TIncrementOnDestroy(&a); - b += 1; - UNIT_ASSERT_VALUES_EQUAL(a, b); - - m4 = TIncrementOnDestroy(&a); - b += 1; - UNIT_ASSERT_VALUES_EQUAL(a, b); - - m4.Clear(); - b += 1; - UNIT_ASSERT_VALUES_EQUAL(a, b); - - m4.Clear(); - UNIT_ASSERT_VALUES_EQUAL(a, b); - } - } - - Y_UNIT_TEST(TestAssignmentClear) { - TMaybe m5; - UNIT_ASSERT(!m5.Defined()); - UNIT_ASSERT(m5.Empty()); - UNIT_ASSERT(m5 == TMaybe()); - UNIT_ASSERT(m5 == Nothing()); - UNIT_ASSERT(m5 != TMaybe(4)); - - m5 = 4; - - UNIT_ASSERT(m5.Defined()); - UNIT_ASSERT(!m5.Empty()); - - UNIT_ASSERT_VALUES_EQUAL(4, m5.GetRef()); - UNIT_ASSERT(m5 == TMaybe(4)); - UNIT_ASSERT(m5 != TMaybe(3)); - UNIT_ASSERT(m5 != TMaybe()); - UNIT_ASSERT(m5 != Nothing()); - - m5 = TMaybe(5); - UNIT_ASSERT(m5.Defined()); - UNIT_ASSERT_VALUES_EQUAL(5, m5.GetRef()); - UNIT_ASSERT(m5 == TMaybe(5)); - UNIT_ASSERT(m5 != TMaybe(4)); - - m5 = TMaybe(); - UNIT_ASSERT(m5.Empty()); - UNIT_ASSERT(m5 == TMaybe()); - UNIT_ASSERT(m5 == Nothing()); - UNIT_ASSERT(m5 != TMaybe(5)); - - m5 = 4; - m5 = Nothing(); - - UNIT_ASSERT(m5.Empty()); - UNIT_ASSERT(m5 == TMaybe()); - UNIT_ASSERT(m5 == Nothing()); - UNIT_ASSERT(m5 != TMaybe(5)); - - m5 = {}; - UNIT_ASSERT(m5.Empty()); - } - - Y_UNIT_TEST(TestInPlace) { - TMaybe m; - - UNIT_ASSERT(!m); - - m.ConstructInPlace(1); - - UNIT_ASSERT(m == 1); - - auto& x = m.ConstructInPlace(2); - - UNIT_ASSERT(m == 2); - x = 7; - UNIT_ASSERT(m == 7); - } - - Y_UNIT_TEST(TestMove) { - struct TMovable { - int Flag = 0; - - TMovable(int flag) - : Flag(flag) - { - } - - TMovable(const TMovable&) = delete; - TMovable& operator=(const TMovable&) = delete; - - TMovable(TMovable&& other) { - std::swap(Flag, other.Flag); - } - TMovable& operator=(TMovable&& other) { - std::swap(Flag, other.Flag); - return *this; - } - }; - - // Move ctor from value - TMovable value1(1); - TMaybe m1(std::move(value1)); - UNIT_ASSERT(m1.Defined()); - UNIT_ASSERT_VALUES_EQUAL(m1->Flag, 1); - - // Move assignment from value - TMovable value2(2); - TMaybe m2; - m2 = std::move(value2); - UNIT_ASSERT(m2.Defined()); - UNIT_ASSERT_VALUES_EQUAL(m2->Flag, 2); - - // Move ctor from maybe - TMaybe m3(std::move(m1)); - UNIT_ASSERT(m3.Defined()); - UNIT_ASSERT_VALUES_EQUAL(m3->Flag, 1); - - // Move assignment from maybe - TMaybe m4; - m4 = std::move(m2); - UNIT_ASSERT(m4.Defined()); - UNIT_ASSERT_VALUES_EQUAL(m4->Flag, 2); - - // Move value from temporary maybe instance - TMovable o5 = *MakeMaybe(5); - UNIT_ASSERT_VALUES_EQUAL(o5.Flag, 5); - TMovable o6 = MakeMaybe(6).GetRef(); - UNIT_ASSERT_VALUES_EQUAL(o6.Flag, 6); - } - - Y_UNIT_TEST(TestCast) { - // Undefined maybe casts to undefined maybe - TMaybe shortMaybe; - const auto undefinedMaybe = shortMaybe.Cast(); - UNIT_ASSERT(!undefinedMaybe.Defined()); - - // Defined maybe casts to defined maybe of another type - shortMaybe = 34; - const auto longMaybe = shortMaybe.Cast(); - UNIT_ASSERT(longMaybe.Defined()); - UNIT_ASSERT_VALUES_EQUAL(34, longMaybe.GetRef()); - } - - Y_UNIT_TEST(TestGetOr) { - UNIT_ASSERT_VALUES_EQUAL(TMaybe().GetOrElse("xxx"), TString("xxx")); - UNIT_ASSERT_VALUES_EQUAL(TMaybe("yyy").GetOrElse("xxx"), TString("yyy")); - - { - TString xxx = "xxx"; - UNIT_ASSERT_VALUES_EQUAL(TMaybe().GetOrElse(xxx).append('x'), TString("xxxx")); - UNIT_ASSERT_VALUES_EQUAL(xxx, "xxxx"); - } - - { - TString xxx = "xxx"; - UNIT_ASSERT_VALUES_EQUAL(TMaybe("yyy").GetOrElse(xxx).append('x'), TString("yyyx")); - UNIT_ASSERT_VALUES_EQUAL(xxx, "xxx"); - } - } - - /* - == - != - < - <= - > - >= -*/ - - Y_UNIT_TEST(TestCompareEqualEmpty) { - TMaybe m1; - TMaybe m2; - - UNIT_ASSERT(m1 == m2); - UNIT_ASSERT(!(m1 != m2)); - UNIT_ASSERT(!(m1 < m2)); - UNIT_ASSERT(m1 <= m2); - UNIT_ASSERT(!(m1 > m2)); - UNIT_ASSERT(m1 >= m2); - } - - Y_UNIT_TEST(TestCompareEqualNonEmpty) { - TMaybe m1{1}; - TMaybe m2{1}; - - UNIT_ASSERT(m1 == m2); - UNIT_ASSERT(!(m1 != m2)); - UNIT_ASSERT(!(m1 < m2)); - UNIT_ASSERT(m1 <= m2); - UNIT_ASSERT(!(m1 > m2)); - UNIT_ASSERT(m1 >= m2); - } - - Y_UNIT_TEST(TestCompareOneLessThanOther) { - TMaybe m1{1}; - TMaybe m2{2}; - - UNIT_ASSERT(!(m1 == m2)); - UNIT_ASSERT(m1 != m2); - UNIT_ASSERT(m1 < m2); - UNIT_ASSERT(m1 <= m2); - UNIT_ASSERT(!(m1 > m2)); - UNIT_ASSERT(!(m1 >= m2)); - } - - Y_UNIT_TEST(TestCompareTMaybeAndT_Equal) { - TMaybe m{1}; - int v{1}; - - UNIT_ASSERT(m == v); - UNIT_ASSERT(!(m != v)); - UNIT_ASSERT(!(m < v)); - UNIT_ASSERT(m <= v); - UNIT_ASSERT(!(m > v)); - UNIT_ASSERT(m >= v); - - UNIT_ASSERT(v == m); - UNIT_ASSERT(!(v != m)); - UNIT_ASSERT(!(v < m)); - UNIT_ASSERT(v <= m); - UNIT_ASSERT(!(v > m)); - UNIT_ASSERT(v >= m); - } - - Y_UNIT_TEST(TestCompareTMaybeAndT_TMaybeLessThanT) { - TMaybe m{1}; - int v{2}; - - UNIT_ASSERT(!(m == v)); - UNIT_ASSERT(m != v); - UNIT_ASSERT(m < v); - UNIT_ASSERT(m <= v); - UNIT_ASSERT(!(m > v)); - UNIT_ASSERT(!(m >= v)); - - UNIT_ASSERT(!(v == m)); - UNIT_ASSERT(v != m); - UNIT_ASSERT(!(v < m)); - UNIT_ASSERT(!(v <= m)); - UNIT_ASSERT(v > m); - UNIT_ASSERT(v >= m); - } - - Y_UNIT_TEST(TestCompareTMaybeAndT_TMaybeGreaterThanT) { - TMaybe m{2}; - int v{1}; - - UNIT_ASSERT(!(m == v)); - UNIT_ASSERT(m != v); - UNIT_ASSERT(!(m < v)); - UNIT_ASSERT(!(m <= v)); - UNIT_ASSERT(m > v); - UNIT_ASSERT(m >= v); - - UNIT_ASSERT(!(v == m)); - UNIT_ASSERT(v != m); - UNIT_ASSERT(v < m); - UNIT_ASSERT(v <= m); - UNIT_ASSERT(!(v > m)); - UNIT_ASSERT(!(v >= m)); - } - - Y_UNIT_TEST(TestCompareEmptyTMaybeAndT) { - TMaybe m; - int v{1}; - - UNIT_ASSERT(!(m == v)); - UNIT_ASSERT(m != v); - UNIT_ASSERT(m < v); - UNIT_ASSERT(m <= v); - UNIT_ASSERT(!(m > v)); - UNIT_ASSERT(!(m >= v)); - - UNIT_ASSERT(!(v == m)); - UNIT_ASSERT(v != m); - UNIT_ASSERT(!(v < m)); - UNIT_ASSERT(!(v <= m)); - UNIT_ASSERT(v > m); - UNIT_ASSERT(v >= m); - } - - Y_UNIT_TEST(TestCompareEmptyTMaybeAndNothing) { - TMaybe m; - auto n = Nothing(); - - UNIT_ASSERT(m == n); - UNIT_ASSERT(!(m != n)); - UNIT_ASSERT(!(m < n)); - UNIT_ASSERT(m <= n); - UNIT_ASSERT(!(m > n)); - UNIT_ASSERT(m >= n); - - UNIT_ASSERT(n == m); - UNIT_ASSERT(!(n != m)); - UNIT_ASSERT(!(n < m)); - UNIT_ASSERT(n <= m); - UNIT_ASSERT(!(n > m)); - UNIT_ASSERT(n >= m); - } - - Y_UNIT_TEST(TestCompareNonEmptyTMaybeAndNothing) { - TMaybe m{1}; - auto n = Nothing(); - - UNIT_ASSERT(!(m == n)); - UNIT_ASSERT(m != n); - UNIT_ASSERT(!(m < n)); - UNIT_ASSERT(!(m <= n)); - UNIT_ASSERT(m > n); - UNIT_ASSERT(m >= n); - - UNIT_ASSERT(!(n == m)); - UNIT_ASSERT(n != m); - UNIT_ASSERT(n < m); - UNIT_ASSERT(n <= m); - UNIT_ASSERT(!(n > m)); - UNIT_ASSERT(!(n >= m)); - } - - Y_UNIT_TEST(TestCompareTMaybeAndConvertibleT_Equal) { - TMaybe m{1}; - unsigned int v{1}; - - UNIT_ASSERT(m == v); - UNIT_ASSERT(!(m != v)); - UNIT_ASSERT(!(m < v)); - UNIT_ASSERT(m <= v); - UNIT_ASSERT(!(m > v)); - UNIT_ASSERT(m >= v); - - UNIT_ASSERT(v == m); - UNIT_ASSERT(!(v != m)); - UNIT_ASSERT(!(v < m)); - UNIT_ASSERT(v <= m); - UNIT_ASSERT(!(v > m)); - UNIT_ASSERT(v >= m); - } - - Y_UNIT_TEST(TestCompareTMaybeAndConvertibleT_TMaybeLessThanT) { - TMaybe m{1}; - unsigned int v{2}; - - UNIT_ASSERT(!(m == v)); - UNIT_ASSERT(m != v); - UNIT_ASSERT(m < v); - UNIT_ASSERT(m <= v); - UNIT_ASSERT(!(m > v)); - UNIT_ASSERT(!(m >= v)); - - UNIT_ASSERT(!(v == m)); - UNIT_ASSERT(v != m); - UNIT_ASSERT(!(v < m)); - UNIT_ASSERT(!(v <= m)); - UNIT_ASSERT(v > m); - UNIT_ASSERT(v >= m); - } - - Y_UNIT_TEST(TestCompareTMaybeAndConvertibleT_TMaybeGreaterThanT) { - TMaybe m{2}; - unsigned int v{1}; - - UNIT_ASSERT(!(m == v)); - UNIT_ASSERT(m != v); - UNIT_ASSERT(!(m < v)); - UNIT_ASSERT(!(m <= v)); - UNIT_ASSERT(m > v); - UNIT_ASSERT(m >= v); - - UNIT_ASSERT(!(v == m)); - UNIT_ASSERT(v != m); - UNIT_ASSERT(v < m); - UNIT_ASSERT(v <= m); - UNIT_ASSERT(!(v > m)); - UNIT_ASSERT(!(v >= m)); - } - - Y_UNIT_TEST(TestCompareEmptyTMaybeAndConvertibleT) { - TMaybe m; - unsigned int v{1}; - - UNIT_ASSERT(!(m == v)); - UNIT_ASSERT(m != v); - UNIT_ASSERT(m < v); - UNIT_ASSERT(m <= v); - UNIT_ASSERT(!(m > v)); - UNIT_ASSERT(!(m >= v)); - - UNIT_ASSERT(!(v == m)); - UNIT_ASSERT(v != m); - UNIT_ASSERT(!(v < m)); - UNIT_ASSERT(!(v <= m)); - UNIT_ASSERT(v > m); - UNIT_ASSERT(v >= m); - } - - Y_UNIT_TEST(TestMakeMaybe) { - { - auto m1 = MakeMaybe(1); - UNIT_ASSERT(*m1 == 1); - } - - { - struct TMockClass { - TMockClass(int i) - : I_(i) - { - } - - TMockClass(const TMockClass& other) - : I_(other.I_) - { - IsCopyConstructorCalled_ = true; - } - - TMockClass& operator=(const TMockClass& other) { - if (this != &other) { - I_ = other.I_; - IsCopyAssignmentOperatorCalled_ = true; - } - - return *this; - } - - TMockClass(TMockClass&& other) - : I_(other.I_) - { - IsMoveConstructorCalled_ = true; - } - - TMockClass& operator=(TMockClass&& other) { - if (this != &other) { - I_ = other.I_; - IsMoveAssignmentOperatorCalled_ = true; - } - - return *this; - } - - int I_; - bool IsCopyConstructorCalled_{false}; - bool IsMoveConstructorCalled_{false}; - bool IsCopyAssignmentOperatorCalled_{false}; - bool IsMoveAssignmentOperatorCalled_{false}; - }; - - auto m2 = MakeMaybe(1); - UNIT_ASSERT(m2->I_ == 1); - UNIT_ASSERT(!m2->IsCopyConstructorCalled_); - UNIT_ASSERT(!m2->IsMoveConstructorCalled_); - UNIT_ASSERT(!m2->IsCopyAssignmentOperatorCalled_); - UNIT_ASSERT(!m2->IsMoveAssignmentOperatorCalled_); - } - - { - auto m3 = MakeMaybe>({1, 2, 3, 4, 5}); - UNIT_ASSERT(m3->size() == 5); - UNIT_ASSERT(m3->at(0) == 1); - UNIT_ASSERT(m3->at(1) == 2); - UNIT_ASSERT(m3->at(2) == 3); - UNIT_ASSERT(m3->at(3) == 4); - UNIT_ASSERT(m3->at(4) == 5); - } - - { - struct TMockStruct4 { - TMockStruct4(int a, int b, int c) - : A_(a) - , B_(b) - , C_(c) - { - } - - int A_; - int B_; - int C_; - }; - - auto m4 = MakeMaybe(1, 2, 3); - UNIT_ASSERT(m4->A_ == 1); - UNIT_ASSERT(m4->B_ == 2); - UNIT_ASSERT(m4->C_ == 3); - } - - { - struct TMockStruct5 { - TMockStruct5(const std::vector& vec, bool someFlag) - : Vec_(vec) - , SomeFlag_(someFlag) - { - } - - std::vector Vec_; - bool SomeFlag_; - }; - - auto m5 = MakeMaybe({1, 2, 3}, true); - UNIT_ASSERT(m5->Vec_.size() == 3); - UNIT_ASSERT(m5->Vec_[0] == 1); - UNIT_ASSERT(m5->Vec_[1] == 2); - UNIT_ASSERT(m5->Vec_[2] == 3); - UNIT_ASSERT(m5->SomeFlag_); - } - } - - Y_UNIT_TEST(TestSwappingUsingMemberSwap) { - { - TMaybe m1 = 1; - TMaybe m2 = 2; - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(*m2 == 2); - - m1.Swap(m2); - - UNIT_ASSERT(*m1 == 2); - UNIT_ASSERT(*m2 == 1); - } - - { - TMaybe m1 = 1; - TMaybe m2 = Nothing(); - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(m2 == Nothing()); - - m1.Swap(m2); - - UNIT_ASSERT(m1 == Nothing()); - UNIT_ASSERT(*m2 == 1); - } - - { - TMaybe m1 = Nothing(); - TMaybe m2 = 1; - - UNIT_ASSERT(m1 == Nothing()); - UNIT_ASSERT(*m2 == 1); - - m1.Swap(m2); - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(m2 == Nothing()); - } - } - - Y_UNIT_TEST(TestSwappingUsingMemberLittleSwap) { - { - TMaybe m1 = 1; - TMaybe m2 = 2; - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(*m2 == 2); - - m1.swap(m2); - - UNIT_ASSERT(*m1 == 2); - UNIT_ASSERT(*m2 == 1); - } - - { - TMaybe m1 = 1; - TMaybe m2 = Nothing(); - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(m2 == Nothing()); - - m1.swap(m2); - - UNIT_ASSERT(m1 == Nothing()); - UNIT_ASSERT(*m2 == 1); - } - - { - TMaybe m1 = Nothing(); - TMaybe m2 = 1; - - UNIT_ASSERT(m1 == Nothing()); - UNIT_ASSERT(*m2 == 1); - - m1.swap(m2); - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(m2 == Nothing()); - } - } - - Y_UNIT_TEST(TestSwappingUsingGlobalSwap) { - { - TMaybe m1 = 1; - TMaybe m2 = 2; - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(*m2 == 2); - - ::Swap(m1, m2); - - UNIT_ASSERT(*m1 == 2); - UNIT_ASSERT(*m2 == 1); - } - - { - TMaybe m1 = 1; - TMaybe m2 = Nothing(); - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(m2 == Nothing()); - - ::Swap(m1, m2); - - UNIT_ASSERT(m1 == Nothing()); - UNIT_ASSERT(*m2 == 1); - } - - { - TMaybe m1 = Nothing(); - TMaybe m2 = 1; - - UNIT_ASSERT(m1 == Nothing()); - UNIT_ASSERT(*m2 == 1); - - ::Swap(m1, m2); - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(m2 == Nothing()); - } - } - - Y_UNIT_TEST(TestSwappingUsingGlobalDoSwap) { - { - TMaybe m1 = 1; - TMaybe m2 = 2; - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(*m2 == 2); - - ::DoSwap(m1, m2); - - UNIT_ASSERT(*m1 == 2); - UNIT_ASSERT(*m2 == 1); - } - - { - TMaybe m1 = 1; - TMaybe m2 = Nothing(); - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(m2 == Nothing()); - - ::DoSwap(m1, m2); - - UNIT_ASSERT(m1 == Nothing()); - UNIT_ASSERT(*m2 == 1); - } - - { - TMaybe m1 = Nothing(); - TMaybe m2 = 1; - - UNIT_ASSERT(m1 == Nothing()); - UNIT_ASSERT(*m2 == 1); - - ::DoSwap(m1, m2); - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(m2 == Nothing()); - } - } - - Y_UNIT_TEST(TestSwappingUsingStdSwap) { - { - TMaybe m1 = 1; - TMaybe m2 = 2; - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(*m2 == 2); - - ::std::swap(m1, m2); - - UNIT_ASSERT(*m1 == 2); - UNIT_ASSERT(*m2 == 1); - } - - { - TMaybe m1 = 1; - TMaybe m2 = Nothing(); - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(m2 == Nothing()); - - ::std::swap(m1, m2); - - UNIT_ASSERT(m1 == Nothing()); - UNIT_ASSERT(*m2 == 1); - } - - { - TMaybe m1 = Nothing(); - TMaybe m2 = 1; - - UNIT_ASSERT(m1 == Nothing()); - UNIT_ASSERT(*m2 == 1); - - ::std::swap(m1, m2); - - UNIT_ASSERT(*m1 == 1); - UNIT_ASSERT(m2 == Nothing()); - } - } - - Y_UNIT_TEST(TestOutputStreamEmptyMaybe) { - TString s; - TStringOutput output(s); - output << TMaybe(); - UNIT_ASSERT_EQUAL("(empty maybe)", s); - } - - Y_UNIT_TEST(TestOutputStreamNothing) { - TString s; - TStringOutput output(s); - output << Nothing(); - UNIT_ASSERT_VALUES_EQUAL("(empty maybe)", s); - } - - Y_UNIT_TEST(TestOutputStreamDefinedMaybe) { - TString s; - TStringOutput output(s); - output << TMaybe(42); - UNIT_ASSERT_EQUAL("42", s); - } - - Y_UNIT_TEST(TestMaybeCovarianceImplicit) { - struct TestStruct { - TestStruct(int value) - : Value_(value) - { - } - - operator int() const { - return Value_; - } - - static TMaybe Unwrap(TMaybe testStructMaybe) { - return testStructMaybe; - } - - int Value_; - }; - - TMaybe testMaybeFull = TestStruct::Unwrap(TMaybe(42)); - UNIT_ASSERT(testMaybeFull.Defined()); - UNIT_ASSERT_EQUAL(testMaybeFull.GetRef(), 42); - - TMaybe testMaybeEmpty = TestStruct::Unwrap(TMaybe()); - UNIT_ASSERT(!testMaybeEmpty.Defined()); - } - - Y_UNIT_TEST(TestMaybeCovarianceExplicit) { - struct TestStruct { - explicit TestStruct(int value) - : Value_(value) - { - } - int Value_; - }; - - TMaybe testStructMaybeFull(TMaybe(42)); - UNIT_ASSERT(testStructMaybeFull.Defined()); - UNIT_ASSERT_EQUAL(testStructMaybeFull.GetRef().Value_, 42); - - TMaybe empty; - TMaybe testStructMaybeEmpty(empty); - UNIT_ASSERT(!testStructMaybeEmpty.Defined()); - } - - Y_UNIT_TEST(TestMaybeCovarianceAssign) { - struct TestStruct { - explicit TestStruct(int value) - : Value_(value) - { - } - TestStruct& operator=(int value) { - Value_ = value; - return *this; - } - int Value_; - }; - - TMaybe testStructMaybe(Nothing()); - UNIT_ASSERT(!testStructMaybe.Defined()); - - testStructMaybe = TMaybe(42); - UNIT_ASSERT(testStructMaybe.Defined()); - UNIT_ASSERT_EQUAL(testStructMaybe.GetRef().Value_, 42); - - testStructMaybe = TMaybe(23); - UNIT_ASSERT(testStructMaybe.Defined()); - UNIT_ASSERT_EQUAL(testStructMaybe.GetRef().Value_, 23); - - testStructMaybe = TMaybe(); - UNIT_ASSERT(!testStructMaybe.Defined()); - } - - Y_UNIT_TEST(TestMaybeCovarianceNonTrivial) { - struct TestStruct { - enum { - FromValue, - FromMaybe, - }; - TestStruct(int value) - : Value_(value) - , From_(FromValue) - { - } - TestStruct(TMaybe value) - : Value_(value.Defined() ? value.GetRef() : 0) - , From_(FromMaybe) - { - } - int Value_; - int From_; - }; - - TMaybe testStructFromMaybe(TMaybe(42)); - UNIT_ASSERT(testStructFromMaybe.Defined()); - UNIT_ASSERT_EQUAL(testStructFromMaybe.GetRef().From_, TestStruct::FromMaybe); - UNIT_ASSERT_EQUAL(testStructFromMaybe.GetRef().Value_, 42); - - TMaybe empty; - TMaybe testStructFromEmptyMaybe(empty); - UNIT_ASSERT(testStructFromEmptyMaybe.Defined()); - UNIT_ASSERT_EQUAL(testStructFromEmptyMaybe.GetRef().From_, TestStruct::FromMaybe); - UNIT_ASSERT_EQUAL(testStructFromEmptyMaybe.GetRef().Value_, 0); - - TMaybe testStructFromValue(23); - UNIT_ASSERT(testStructFromValue.Defined()); - UNIT_ASSERT_EQUAL(testStructFromValue.GetRef().From_, TestStruct::FromValue); - UNIT_ASSERT_EQUAL(testStructFromValue.GetRef().Value_, 23); - } - - Y_UNIT_TEST(TestMaybeCovarianceNonTrivialAssign) { - struct TestStruct { - enum { - FromValue, - FromMaybe, - }; - TestStruct(int value) - : Value_(value) - , From_(FromValue) - { - } - TestStruct(TMaybe value) - : Value_(value.Defined() ? value.GetRef() : 0) - , From_(FromMaybe) - { - } - TestStruct& operator=(int value) { - Value_ = value; - From_ = FromValue; - return *this; - } - TestStruct& operator=(TMaybe value) { - Value_ = value.Defined() ? value.GetRef() : 0; - From_ = FromMaybe; - return *this; - } - int Value_; - int From_; - }; - - TMaybe testStructMaybe(Nothing()); - testStructMaybe = TMaybe(42); - UNIT_ASSERT(testStructMaybe.Defined()); - UNIT_ASSERT_EQUAL(testStructMaybe.GetRef().From_, TestStruct::FromMaybe); - UNIT_ASSERT_EQUAL(testStructMaybe.GetRef().Value_, 42); - - testStructMaybe = TMaybe(); - UNIT_ASSERT(testStructMaybe.Defined()); - UNIT_ASSERT_EQUAL(testStructMaybe.GetRef().From_, TestStruct::FromMaybe); - UNIT_ASSERT_EQUAL(testStructMaybe.GetRef().Value_, 0); - - testStructMaybe = 23; - UNIT_ASSERT(testStructMaybe.Defined()); - UNIT_ASSERT_EQUAL(testStructMaybe.GetRef().From_, TestStruct::FromValue); - UNIT_ASSERT_EQUAL(testStructMaybe.GetRef().Value_, 23); - } - - Y_UNIT_TEST(TestMaybeConvertion) { - struct TSrc {}; - struct TDst { - bool FromMaybeConstructorApplied; - - explicit TDst(TSrc) - : FromMaybeConstructorApplied(false) - { - } - - explicit TDst(TMaybe) - : FromMaybeConstructorApplied(true) - { - } - - TDst& operator=(TSrc) { - FromMaybeConstructorApplied = false; - return *this; - } - TDst& operator=(TMaybe) { - FromMaybeConstructorApplied = true; - return *this; - } - }; - - auto m = TMaybe(TMaybe()); - UNIT_ASSERT(m.Defined()); - UNIT_ASSERT(m->FromMaybeConstructorApplied); - - m = TMaybe(); - UNIT_ASSERT(m.Defined()); - UNIT_ASSERT(m->FromMaybeConstructorApplied); - } - - Y_UNIT_TEST(TestOnEmptyException) { - TMaybe v; - UNIT_ASSERT_EXCEPTION_CONTAINS(v.GetRef(), yexception, "StringBuf"); - } -} diff --git a/util/generic/maybe_ut.pyx b/util/generic/maybe_ut.pyx deleted file mode 100644 index c514d9b62c0..00000000000 --- a/util/generic/maybe_ut.pyx +++ /dev/null @@ -1,185 +0,0 @@ -from util.generic.maybe cimport TMaybe, Nothing - -import pytest -import unittest - - -def _check_from_py(TMaybe[int] x): - return x.Defined() - - -def _check_to_py_value(): - cdef TMaybe[int] tmp = TMaybe[int](42) - return tmp - - -def _check_to_py_nothing(): - cdef TMaybe[int] tmp = Nothing() - return tmp - - -class TestMaybe(unittest.TestCase): - - def test_ctor1(self): - cdef TMaybe[int] tmp = TMaybe[int]() - self.assertFalse(tmp.Defined()) - - def test_ctor2(self): - cdef TMaybe[int] tmp = TMaybe[int](42) - self.assertTrue(tmp.Defined()) - self.assertEqual(tmp.GetRef(), 42) - - def test_ctor3(self): - cdef TMaybe[int] tmp = Nothing() - self.assertFalse(tmp.Defined()) - - def test_operator_assign(self): - cdef TMaybe[int] tmp - tmp = 42 - self.assertTrue(tmp.Defined()) - self.assertEqual(tmp.GetRef(), 42) - - def test_compare(self): - cdef TMaybe[int] tmp1 = 17 - cdef TMaybe[int] tmp2 = 42 - cdef TMaybe[int] nothing - - # == - self.assertTrue(tmp1 == 17) - self.assertTrue(tmp1 == tmp1) - self.assertTrue(nothing == nothing) - - self.assertFalse(tmp1 == 16) - self.assertFalse(tmp1 == tmp2) - self.assertFalse(tmp1 == nothing) - - # != - self.assertTrue(tmp1 != 16) - self.assertTrue(tmp1 != tmp2) - self.assertTrue(tmp1 != nothing) - - self.assertFalse(tmp1 != 17) - self.assertFalse(tmp1 != tmp1) - self.assertFalse(nothing != nothing) - - # < - self.assertTrue(nothing < tmp1) - self.assertTrue(nothing < tmp2) - self.assertTrue(tmp1 < tmp2) - self.assertTrue(nothing < 0) - self.assertTrue(tmp1 < 18) - - self.assertFalse(nothing < nothing) - self.assertFalse(tmp1 < tmp1) - self.assertFalse(tmp2 < tmp1) - self.assertFalse(tmp1 < 16) - - # <= - self.assertTrue(nothing <= nothing) - self.assertTrue(nothing <= tmp1) - self.assertTrue(nothing <= tmp2) - self.assertTrue(tmp1 <= tmp1) - self.assertTrue(tmp1 <= tmp2) - self.assertTrue(nothing <= 0) - self.assertTrue(tmp1 <= 18) - - self.assertFalse(tmp2 <= tmp1) - self.assertFalse(tmp1 <= 16) - - # > - self.assertTrue(tmp1 > nothing) - self.assertTrue(tmp2 > nothing) - self.assertTrue(tmp2 > tmp1) - self.assertTrue(tmp1 > 16) - - self.assertFalse(nothing > nothing) - self.assertFalse(nothing > 0) - self.assertFalse(tmp1 > tmp1) - self.assertFalse(tmp1 > tmp2) - self.assertFalse(tmp1 > 18) - - # >= - self.assertTrue(nothing >= nothing) - self.assertTrue(tmp1 >= nothing) - self.assertTrue(tmp2 >= nothing) - self.assertTrue(tmp2 >= tmp1) - self.assertTrue(tmp1 >= tmp1) - self.assertTrue(tmp1 >= 16) - - self.assertFalse(nothing >= 0) - self.assertFalse(tmp1 >= tmp2) - self.assertFalse(tmp1 >= 18) - - def test_construct_in_place(self): - cdef TMaybe[int] tmp - tmp.ConstructInPlace(42) - self.assertTrue(tmp.Defined()) - self.assertEqual(tmp.GetRef(), 42) - - def test_clear(self): - cdef TMaybe[int] tmp = 42 - tmp.Clear() - self.assertFalse(tmp.Defined()) - - def test_defined(self): - cdef TMaybe[int] tmp - self.assertFalse(tmp.Defined()) - self.assertTrue(tmp.Empty()) - tmp = 42 - self.assertTrue(tmp.Defined()) - self.assertFalse(tmp.Empty()) - - def test_check_defined(self): - cdef TMaybe[int] tmp - with pytest.raises(RuntimeError): - tmp.CheckDefined() - tmp = 42 - tmp.CheckDefined() - - def test_get(self): - cdef TMaybe[int] tmp = 42 - cdef int* p = tmp.Get() - self.assertTrue(p != NULL) - self.assertEqual(p[0], 42) - - def test_get_ref(self): - cdef TMaybe[int] tmp = 42 - self.assertTrue(tmp.Defined()) - self.assertEqual(tmp.GetRef(), 42) - - def test_get_or_else(self): - cdef TMaybe[int] tmp = 42 - self.assertEqual(tmp.GetOrElse(13), 42) - tmp.Clear() - self.assertEqual(tmp.GetOrElse(13), 13) - - def test_or_else(self): - cdef TMaybe[int] tmp = 42 - cdef TMaybe[int] nothing - self.assertFalse(nothing.OrElse(nothing).Defined()) - self.assertEqual(tmp.OrElse(nothing).GetRef(), 42) - self.assertEqual(nothing.OrElse(tmp).GetRef(), 42) - self.assertEqual(tmp.OrElse(tmp).GetRef(), 42) - - def test_cast(self): - cdef TMaybe[int] tmp = 42 - cdef TMaybe[char] tmp2 = tmp.Cast[char]() - self.assertEqual(tmp2.GetRef(), 42) - - def test_swap(self): - cdef TMaybe[int] tmp1 = 42 - cdef TMaybe[int] tmp2 - tmp2.Swap(tmp1) - self.assertFalse(tmp1.Defined()) - self.assertEqual(tmp2.GetRef(), 42) - - def test_from_py(self): - self.assertTrue(_check_from_py(42)) - self.assertFalse(_check_from_py(None)) - - with self.assertRaises(TypeError): - _check_from_py("ttt") - - def test_to_py(self): - self.assertEqual(_check_to_py_value(), 42) - self.assertEqual(_check_to_py_nothing(), None) diff --git a/util/generic/ut/ya.make b/util/generic/ut/ya.make index 9f6f45daa75..5626e952253 100644 --- a/util/generic/ut/ya.make +++ b/util/generic/ut/ya.make @@ -28,7 +28,6 @@ SRCS( generic/lazy_value_ut.cpp generic/map_ut.cpp generic/mapfindptr_ut.cpp - generic/maybe_ut.cpp generic/mem_copy_ut.cpp generic/objects_counter_ut.cpp generic/overloaded_ut.cpp diff --git a/util/generic/ut_cython/test_generic.py b/util/generic/ut_cython/test_generic.py index f03252e80b0..7e9bb4d6126 100644 --- a/util/generic/ut_cython/test_generic.py +++ b/util/generic/ut_cython/test_generic.py @@ -7,7 +7,6 @@ from util.generic.hash_set_ut import TestHashSet from util.generic.list_ut import TestList from util.generic.map_ut import TestMap -from util.generic.maybe_ut import TestMaybe from util.generic.ptr_ut import TestHolder from util.generic.string_ut import TestStroka from util.generic.vector_ut import TestVector @@ -22,7 +21,6 @@ 'TestHolder', 'TestList', 'TestMap', - 'TestMaybe', 'TestStroka', 'TestVector', ] diff --git a/util/generic/ut_cython/ya.make b/util/generic/ut_cython/ya.make index ea923ff4133..d80c29cd788 100644 --- a/util/generic/ut_cython/ya.make +++ b/util/generic/ut_cython/ya.make @@ -12,7 +12,6 @@ PY_SRCS( hash_ut.pyx list_ut.pyx map_ut.pyx - maybe_ut.pyx ptr_ut.pyx string_ut.pyx vector_ut.pyx diff --git a/util/generic/xrange_ut.cpp b/util/generic/xrange_ut.cpp index 61dbf24e733..7bca2562ce5 100644 --- a/util/generic/xrange_ut.cpp +++ b/util/generic/xrange_ut.cpp @@ -1,7 +1,6 @@ #include "xrange.h" #include "algorithm.h" -#include "maybe.h" #include "vector.h" #include #include @@ -158,7 +157,7 @@ Y_UNIT_TEST_SUITE(XRange) { } template - static void TestIteratorDifferenceImpl(TRange range, int a, int b, TMaybe step) { + static void TestIteratorDifferenceImpl(TRange range, int a, int b, std::optional step) { auto fmtCase = [&]() -> TString { return TStringBuilder() << "xrange(" << a << ", " << b << (step ? ", " + ToString(*step) : TString{}) << ")"; }; auto begin = std::begin(range); auto end = std::end(range); diff --git a/util/string/cast.h b/util/string/cast.h index 564baa93d5c..26818c8626e 100644 --- a/util/string/cast.h +++ b/util/string/cast.h @@ -2,12 +2,13 @@ #include #include -#include #include #include #include #include +#include + /* * specialized for all arithmetic types */ @@ -272,32 +273,32 @@ inline bool TryFromString(const TUtf16String& s, T& result) { } template -inline TMaybe TryFromString(TBasicStringBuf s) { - TMaybe result{NMaybe::TInPlace{}}; +inline std::optional TryFromString(TBasicStringBuf s) { + std::optional result{std::in_place}; if (!TryFromString(s, *result)) { - result.Clear(); + result.reset(); } return result; } template -inline TMaybe TryFromString(const TChar* data) { +inline std::optional TryFromString(const TChar* data) { return TryFromString(TBasicStringBuf(data)); } template -inline TMaybe TryFromString(const TString& s) { +inline std::optional TryFromString(const TString& s) { return TryFromString(TStringBuf(s)); } template -inline TMaybe TryFromString(const std::string& s) { +inline std::optional TryFromString(const std::string& s) { return TryFromString(TStringBuf(s)); } template -inline TMaybe TryFromString(const TUtf16String& s) { +inline std::optional TryFromString(const TUtf16String& s) { return TryFromString(TWtringBuf(s)); } diff --git a/util/string/cast_ut.cpp b/util/string/cast_ut.cpp index 443f8a79f8e..41300bab871 100644 --- a/util/string/cast_ut.cpp +++ b/util/string/cast_ut.cpp @@ -437,32 +437,6 @@ Y_UNIT_TEST_SUITE(TCastTest) { UNIT_ASSERT_VALUES_EQUAL(FromStringWithDefault(s4), size_t()); } - Y_UNIT_TEST(TestMaybe) { - TMaybe res; - - TString s1("100500"); - UNIT_CHECK_GENERATED_NO_EXCEPTION(res = TryFromString(s1), yexception); - UNIT_ASSERT_VALUES_EQUAL(res, 100500); - - UNIT_ASSERT_VALUES_EQUAL(TryFromString("100500"), 100500); - - TString s2("100q500"); - UNIT_CHECK_GENERATED_NO_EXCEPTION(res = TryFromString(s2), yexception); - UNIT_ASSERT(res.Empty()); - - TUtf16String s3 = u"-100500"; - UNIT_CHECK_GENERATED_NO_EXCEPTION(res = TryFromString(s3), yexception); - UNIT_ASSERT(res.Empty()); - - TUtf16String s4 = u"-f100500"; - UNIT_CHECK_GENERATED_NO_EXCEPTION(res = TryFromString(s4), yexception); - UNIT_ASSERT(res.Empty()); - - std::string s5 = "100500"; - UNIT_CHECK_GENERATED_NO_EXCEPTION(res = TryFromString(s5), yexception); - UNIT_ASSERT_VALUES_EQUAL(res, 100500); - } - Y_UNIT_TEST(TestBool) { // True cases UNIT_ASSERT_VALUES_EQUAL(FromString("yes"), true); diff --git a/util/string/split.h b/util/string/split.h index a28824b4b3b..228ce09d20e 100644 --- a/util/string/split.h +++ b/util/string/split.h @@ -432,12 +432,12 @@ void GetNext(TStringBuf& s, D delim, P& param) { } template -void GetNext(TStringBuf& s, D delim, TMaybe

& param) { +void GetNext(TStringBuf& s, D delim, std::optional

& param) { TStringBuf next = s.NextTok(delim); if (next.IsInited()) { param = FromString

(next); } else { - param.Clear(); + param.reset(); } } diff --git a/util/string/split_ut.cpp b/util/string/split_ut.cpp index f9b171db85e..96a216fa11d 100644 --- a/util/string/split_ut.cpp +++ b/util/string/split_ut.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include @@ -267,8 +266,8 @@ Y_UNIT_TEST_SUITE(SplitStringTest) { Y_UNIT_TEST(ConvenientSplitTestWithMaybe) { TString data("abc 42"); TString str; - TMaybe num2 = 1; - TMaybe maybe = 1; + std::optional num2 = 1; + std::optional maybe = 1; Split(data, ' ', str, num2, maybe); @@ -286,10 +285,10 @@ Y_UNIT_TEST_SUITE(SplitStringTest) { UNIT_ASSERT_EXCEPTION(Split(data, ' ', s1, s2, s3, s4), yexception); } - Y_UNIT_TEST(ConvenientSplitTestMaybeExceptions) { + Y_UNIT_TEST(ConvenientSplitTestOptionalExceptions) { TString data("abc 22 33"); TString s1, s2; - TMaybe m1, m2; + std::optional m1, m2; UNIT_ASSERT_EXCEPTION(Split(data, ' ', s1, m1), yexception); UNIT_ASSERT_EXCEPTION(Split(data, ' ', m1, m2), yexception); diff --git a/util/system/shellcommand.cpp b/util/system/shellcommand.cpp index 5b9d4de6656..0fa2f9af140 100644 --- a/util/system/shellcommand.cpp +++ b/util/system/shellcommand.cpp @@ -201,7 +201,7 @@ class TShellCommand::TImpl TThread* WatchThread; bool TerminateFlag = false; - TMaybe ExitCode; + std::optional ExitCode; TString CollectedOutput; TString CollectedError; TString InternalError; @@ -328,7 +328,7 @@ class TShellCommand::TImpl return static_cast(ExecutionStatus.load(std::memory_order_acquire)); } - inline TMaybe GetExitCode() const { + inline std::optional GetExitCode() const { return ExitCode; } @@ -1028,7 +1028,7 @@ void TShellCommand::TImpl::Communicate(TProcessInfo* pi) { // Otherwise there is no way for input stream provider to discover // that process has exited and stream shouldn't wait for new data. bool cleanExit = false; - TMaybe processExitCode; + std::optional processExitCode; #if defined(_unix_) processExitCode = WEXITSTATUS(status); if (WIFEXITED(status) && processExitCode == 0) { @@ -1121,7 +1121,7 @@ TShellCommand::ECommandStatus TShellCommand::GetStatus() const { return Impl->GetStatus(); } -TMaybe TShellCommand::GetExitCode() const { +std::optional TShellCommand::GetExitCode() const { return Impl->GetExitCode(); } diff --git a/util/system/shellcommand.h b/util/system/shellcommand.h index 0bd1b9272da..61e40a5d129 100644 --- a/util/system/shellcommand.h +++ b/util/system/shellcommand.h @@ -4,7 +4,6 @@ #include #include #include -#include #include #include #include "file.h" @@ -421,7 +420,7 @@ class TShellCommand: public TNonCopyable { * * @return exit code */ - TMaybe GetExitCode() const; + std::optional GetExitCode() const; /** * @brief get id of underlying process diff --git a/util/ya.make b/util/ya.make index 30347969cdb..e259d5d7d05 100644 --- a/util/ya.make +++ b/util/ya.make @@ -112,7 +112,6 @@ JOIN_SRCS( generic/list.cpp generic/map.cpp generic/mapfindptr.cpp - generic/maybe.cpp generic/mem_copy.cpp generic/noncopyable.cpp generic/object_counter.cpp diff --git a/util/ysaveload_ut.cpp b/util/ysaveload_ut.cpp index 17f36b3d70d..44828f09d3b 100644 --- a/util/ysaveload_ut.cpp +++ b/util/ysaveload_ut.cpp @@ -13,7 +13,6 @@ #include #include -#include static inline char* AllocateFromPool(TMemoryPool& pool, size_t len) { return (char*)pool.Allocate(len); @@ -195,22 +194,22 @@ class TSaveLoadTest: public TTestBase { } { - TMaybe h(10); + std::optional h(10); Save(&S_, h); } { - TMaybe h(20); + std::optional h(20); Save(&S_, h); } { - TMaybe h; + std::optional h; Save(&S_, h); } { - TMaybe h; + std::optional h; Save(&S_, h); } @@ -339,26 +338,26 @@ class TSaveLoadTest: public TTestBase { } { - TMaybe h(5); + std::optional h(5); Load(&S_, h); UNIT_ASSERT_EQUAL(*h, 10); } { - TMaybe h; + std::optional h; Load(&S_, h); UNIT_ASSERT_EQUAL(*h, 20); } { - TMaybe h; + std::optional h; UNIT_ASSERT(!h); Load(&S_, h); UNIT_ASSERT(!h); } { - TMaybe h(7); + std::optional h(7); UNIT_ASSERT(!!h); Load(&S_, h); UNIT_ASSERT(!h); diff --git a/ydb/library/yql/public/issue/yql_issue.cpp b/ydb/library/yql/public/issue/yql_issue.cpp index 95b334e83f8..511dc33a9d6 100644 --- a/ydb/library/yql/public/issue/yql_issue.cpp +++ b/ydb/library/yql/public/issue/yql_issue.cpp @@ -227,7 +227,7 @@ void TIssues::PrintWithProgramTo( TIssue ExceptionToIssue(const std::exception& e, const TPosition& pos) { std::string_view messageBuf = e.what(); auto parsedPos = TryParseTerminationMessage(messageBuf); - auto issue = TIssue(parsedPos.GetOrElse(pos), messageBuf); + auto issue = TIssue(parsedPos.value_or(pos), messageBuf); const TErrorException* errorException = dynamic_cast(&e); if (errorException) { issue.SetCode(errorException->GetCode(), ESeverity::TSeverityIds_ESeverityId_S_ERROR); @@ -239,7 +239,7 @@ TIssue ExceptionToIssue(const std::exception& e, const TPosition& pos) { static constexpr std::string_view TerminationMessageMarker = "Terminate was called, reason("; -TMaybe TryParseTerminationMessage(std::string_view& message) { +std::optional TryParseTerminationMessage(std::string_view& message) { size_t len = 0; size_t startPos = message.find(TerminationMessageMarker); size_t endPos = 0; @@ -272,7 +272,7 @@ TMaybe TryParseTerminationMessage(std::string_view& message) { } } - return Nothing(); + return std::nullopt; } } // namspace NYql diff --git a/ydb/library/yql/public/issue/yql_issue.h b/ydb/library/yql/public/issue/yql_issue.h index e11c23e1dc8..80b58ebaf6f 100644 --- a/ydb/library/yql/public/issue/yql_issue.h +++ b/ydb/library/yql/public/issue/yql_issue.h @@ -2,7 +2,6 @@ #include #include -#include #include #include #include @@ -345,7 +344,7 @@ class TErrorException : public yexception { }; TIssue ExceptionToIssue(const std::exception& e, const TPosition& pos = TPosition()); -TMaybe TryParseTerminationMessage(std::string_view& message); +std::optional TryParseTerminationMessage(std::string_view& message); } // namespace NYql