Merge remote-tracking branch 'td/master'

This commit is contained in:
Andrea Cavalli 2021-12-10 16:59:45 +01:00
commit c037048ec3
33 changed files with 192 additions and 124 deletions

View File

@ -3,17 +3,20 @@ Language: Cpp
# BasedOnStyle: Google # BasedOnStyle: Google
AccessModifierOffset: -1 AccessModifierOffset: -1
AlignAfterOpenBracket: Align AlignAfterOpenBracket: Align
AlignConsecutiveMacros: false AlignArrayOfStructures: None
AlignConsecutiveAssignments: false AlignConsecutiveMacros: None
AlignConsecutiveDeclarations: false AlignConsecutiveAssignments: None
AlignConsecutiveBitFields: None
AlignConsecutiveDeclarations: None
AlignEscapedNewlines: Left AlignEscapedNewlines: Left
AlignOperands: true AlignOperands: Align
AlignTrailingComments: true AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true AllowAllArgumentsOnNextLine: true
AllowAllConstructorInitializersOnNextLine: true AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: Never AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: None # All AllowShortFunctionsOnASingleLine: None # All
AllowShortIfStatementsOnASingleLine: Never # WithoutElse AllowShortIfStatementsOnASingleLine: Never # WithoutElse
AllowShortLambdasOnASingleLine: Inline # All AllowShortLambdasOnASingleLine: Inline # All
@ -24,10 +27,11 @@ AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: true BinPackArguments: true
BinPackParameters: true BinPackParameters: true
BitFieldColonSpacing: Both
BraceWrapping: BraceWrapping:
AfterCaseLabel: false AfterCaseLabel: false
AfterClass: false AfterClass: false
AfterControlStatement: false AfterControlStatement: Never
AfterEnum: false AfterEnum: false
AfterFunction: false AfterFunction: false
AfterNamespace: false AfterNamespace: false
@ -37,12 +41,15 @@ BraceWrapping:
AfterExternBlock: false AfterExternBlock: false
BeforeCatch: false BeforeCatch: false
BeforeElse: false BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false IndentBraces: false
SplitEmptyFunction: true SplitEmptyFunction: true
SplitEmptyRecord: true SplitEmptyRecord: true
SplitEmptyNamespace: true SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach BreakBeforeBraces: Attach
BreakBeforeConceptDeclarations: true
BreakBeforeInheritanceComma: true # false BreakBeforeInheritanceComma: true # false
BreakInheritanceList: BeforeComma # BeforeColon BreakInheritanceList: BeforeComma # BeforeColon
BreakBeforeTernaryOperators: true BreakBeforeTernaryOperators: true
@ -60,21 +67,30 @@ Cpp11BracedListStyle: true
DeriveLineEnding: true DeriveLineEnding: true
DerivePointerAlignment: true DerivePointerAlignment: true
DisableFormat: false DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: false ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true FixNamespaceComments: true
ForEachMacros: ForEachMacros:
- Q_FOREACH_THIS_LIST_MUST_BE_NON_EMPTY - Q_FOREACH_THIS_LIST_MUST_BE_NON_EMPTY
IncludeBlocks: Preserve IncludeBlocks: Preserve
#IndentCaseBlocks: false IncludeCategories:
- Regex: '.*'
Priority: 0
IndentAccessModifiers: false
IndentCaseBlocks: false
IndentCaseLabels: true IndentCaseLabels: true
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true IndentGotoLabels: true
IndentPPDirectives: None IndentPPDirectives: None
IndentRequires: false
IndentWidth: 2 IndentWidth: 2
IndentWrappedFunctionNames: false IndentWrappedFunctionNames: false
# InsertTrailingCommas: None # InsertTrailingCommas: None
# JavaScriptQuotes: Leave # JavaScriptQuotes: Leave
# JavaScriptWrapImports: true # JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false KeepEmptyLinesAtTheStartOfBlocks: false
LambdaBodyIndentation: Signature
MacroBlockBegin: '' MacroBlockBegin: ''
MacroBlockEnd: '' MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1 MaxEmptyLinesToKeep: 1
@ -91,15 +107,22 @@ PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000 PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10 PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000 PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 200 PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Right PointerAlignment: Right
PPIndentWidth: -1
ReferenceAlignment: Pointer
ReflowComments: false # true ReflowComments: false # true
SortIncludes: false # disabled, because we need case insensitive sort ShortNamespaceLines: 0 # 1
SortIncludes: CaseInsensitive # CaseSensitive
# SortJavaStaticImport: Before
SortUsingDeclarations: false # true SortUsingDeclarations: false # true
SpaceAfterCStyleCast: false SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true SpaceAfterTemplateKeyword: true
SpaceAroundPointerQualifiers: Default
SpaceBeforeAssignmentOperators: true SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true SpaceBeforeInheritanceColon: true
@ -109,10 +132,13 @@ SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: false SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2 SpacesBeforeTrailingComments: 2
SpacesInAngles: false SpacesInAngles: Never
SpacesInConditionalStatement: false SpacesInConditionalStatement: false
SpacesInContainerLiterals: true SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false SpacesInCStyleCastParentheses: false
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: 1 # -1
SpacesInParentheses: false SpacesInParentheses: false
SpacesInSquareBrackets: false SpacesInSquareBrackets: false
Standard: Auto Standard: Auto

View File

@ -219,7 +219,7 @@ function split_file($file, $chunks, $undo) {
$new_content = $common.$namespace_begin.$f.$namespace_end; $new_content = $common.$namespace_begin.$f.$namespace_end;
$std_methods = array(); $std_methods = array();
preg_match_all('/std::[a-z_0-9]*/', $new_content, $std_methods); preg_match_all('/std::[a-z_0-9]*|td::unique(?!_)/', $new_content, $std_methods);
$std_methods = array_unique($std_methods[0]); $std_methods = array_unique($std_methods[0]);
$needed_std_headers = array(); $needed_std_headers = array();
@ -230,6 +230,7 @@ function split_file($file, $chunks, $undo) {
'std::uint32_t' => '', 'std::uint32_t' => '',
'std::int32_t' => '', 'std::int32_t' => '',
'std::int64_t' => '', 'std::int64_t' => '',
'td::unique' => 'algorithm',
'std::fill' => 'algorithm', 'std::fill' => 'algorithm',
'std::find' => 'algorithm', 'std::find' => 'algorithm',
'std::max' => 'algorithm', 'std::max' => 'algorithm',

View File

@ -45,9 +45,9 @@ extern void *__libc_stack_end;
static void *get_bp() { static void *get_bp() {
void *bp; void *bp;
#if defined(__i386__) #if defined(__i386__)
__asm__ volatile("movl %%ebp, %[r]" : [ r ] "=r"(bp)); __asm__ volatile("movl %%ebp, %[r]" : [r] "=r"(bp));
#elif defined(__x86_64__) #elif defined(__x86_64__)
__asm__ volatile("movq %%rbp, %[r]" : [ r ] "=r"(bp)); __asm__ volatile("movq %%rbp, %[r]" : [r] "=r"(bp));
#endif #endif
return bp; return bp;
} }

View File

@ -1079,6 +1079,7 @@ class ToggleSlowModeQuery final : public Td::ResultHandler {
class ReportChannelSpamQuery final : public Td::ResultHandler { class ReportChannelSpamQuery final : public Td::ResultHandler {
Promise<Unit> promise_; Promise<Unit> promise_;
ChannelId channel_id_; ChannelId channel_id_;
DialogId sender_dialog_id_;
public: public:
explicit ReportChannelSpamQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) { explicit ReportChannelSpamQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) {
@ -1086,6 +1087,7 @@ class ReportChannelSpamQuery final : public Td::ResultHandler {
void send(ChannelId channel_id, DialogId sender_dialog_id, const vector<MessageId> &message_ids) { void send(ChannelId channel_id, DialogId sender_dialog_id, const vector<MessageId> &message_ids) {
channel_id_ = channel_id; channel_id_ = channel_id;
sender_dialog_id_ = sender_dialog_id;
auto input_channel = td_->contacts_manager_->get_input_channel(channel_id); auto input_channel = td_->contacts_manager_->get_input_channel(channel_id);
CHECK(input_channel != nullptr); CHECK(input_channel != nullptr);
@ -1110,7 +1112,9 @@ class ReportChannelSpamQuery final : public Td::ResultHandler {
} }
void on_error(Status status) final { void on_error(Status status) final {
// td_->contacts_manager_->on_get_channel_error(channel_id_, status, "ReportChannelSpamQuery"); if (sender_dialog_id_.get_type() != DialogType::Channel) {
td_->contacts_manager_->on_get_channel_error(channel_id_, status, "ReportChannelSpamQuery");
}
promise_.set_error(std::move(status)); promise_.set_error(std::move(status));
} }
}; };
@ -2127,14 +2131,16 @@ class EditChannelAdminQuery final : public Td::ResultHandler {
class EditChannelBannedQuery final : public Td::ResultHandler { class EditChannelBannedQuery final : public Td::ResultHandler {
Promise<Unit> promise_; Promise<Unit> promise_;
ChannelId channel_id_; ChannelId channel_id_;
DialogId participant_dialog_id_;
public: public:
explicit EditChannelBannedQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) { explicit EditChannelBannedQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) {
} }
void send(ChannelId channel_id, tl_object_ptr<telegram_api::InputPeer> &&input_peer, void send(ChannelId channel_id, DialogId participant_dialog_id, tl_object_ptr<telegram_api::InputPeer> &&input_peer,
const DialogParticipantStatus &status) { const DialogParticipantStatus &status) {
channel_id_ = channel_id; channel_id_ = channel_id;
participant_dialog_id_ = participant_dialog_id;
auto input_channel = td_->contacts_manager_->get_input_channel(channel_id); auto input_channel = td_->contacts_manager_->get_input_channel(channel_id);
CHECK(input_channel != nullptr); CHECK(input_channel != nullptr);
send_query(G()->net_query_creator().create(telegram_api::channels_editBanned( send_query(G()->net_query_creator().create(telegram_api::channels_editBanned(
@ -2154,7 +2160,9 @@ class EditChannelBannedQuery final : public Td::ResultHandler {
} }
void on_error(Status status) final { void on_error(Status status) final {
td_->contacts_manager_->on_get_channel_error(channel_id_, status, "EditChannelBannedQuery"); if (participant_dialog_id_.get_type() != DialogType::Channel) {
td_->contacts_manager_->on_get_channel_error(channel_id_, status, "EditChannelBannedQuery");
}
promise_.set_error(std::move(status)); promise_.set_error(std::move(status));
td_->updates_manager_->get_difference("EditChannelBannedQuery"); td_->updates_manager_->get_difference("EditChannelBannedQuery");
} }
@ -2737,7 +2745,9 @@ class GetChannelParticipantQuery final : public Td::ResultHandler {
return; return;
} }
// td_->contacts_manager_->on_get_channel_error(channel_id_, status, "GetChannelParticipantQuery"); if (participant_dialog_id_.get_type() != DialogType::Channel) {
td_->contacts_manager_->on_get_channel_error(channel_id_, status, "GetChannelParticipantQuery");
}
promise_.set_error(std::move(status)); promise_.set_error(std::move(status));
} }
}; };
@ -7573,7 +7583,8 @@ void ContactsManager::restrict_channel_participant(ChannelId channel_id, DialogI
if (participant_dialog_id.get_type() == DialogType::User) { if (participant_dialog_id.get_type() == DialogType::User) {
speculative_add_channel_user(channel_id, participant_dialog_id.get_user_id(), status, old_status); speculative_add_channel_user(channel_id, participant_dialog_id.get_user_id(), status, old_status);
} }
td_->create_handler<EditChannelBannedQuery>(std::move(promise))->send(channel_id, std::move(input_peer), status); td_->create_handler<EditChannelBannedQuery>(std::move(promise))
->send(channel_id, participant_dialog_id, std::move(input_peer), status);
} }
ChannelId ContactsManager::migrate_chat_to_megagroup(ChatId chat_id, Promise<Unit> &promise) { ChannelId ContactsManager::migrate_chat_to_megagroup(ChatId chat_id, Promise<Unit> &promise) {

View File

@ -2873,12 +2873,17 @@ class BlockFromRepliesQuery final : public Td::ResultHandler {
class DeleteParticipantHistoryQuery final : public Td::ResultHandler { class DeleteParticipantHistoryQuery final : public Td::ResultHandler {
Promise<AffectedHistory> promise_; Promise<AffectedHistory> promise_;
ChannelId channel_id_;
DialogId sender_dialog_id_;
public: public:
explicit DeleteParticipantHistoryQuery(Promise<AffectedHistory> &&promise) : promise_(std::move(promise)) { explicit DeleteParticipantHistoryQuery(Promise<AffectedHistory> &&promise) : promise_(std::move(promise)) {
} }
void send(ChannelId channel_id, DialogId sender_dialog_id) { void send(ChannelId channel_id, DialogId sender_dialog_id) {
channel_id_ = channel_id;
sender_dialog_id_ = sender_dialog_id;
auto input_channel = td_->contacts_manager_->get_input_channel(channel_id); auto input_channel = td_->contacts_manager_->get_input_channel(channel_id);
if (input_channel == nullptr) { if (input_channel == nullptr) {
return promise_.set_error(Status::Error(400, "Chat is not accessible")); return promise_.set_error(Status::Error(400, "Chat is not accessible"));
@ -2902,7 +2907,9 @@ class DeleteParticipantHistoryQuery final : public Td::ResultHandler {
} }
void on_error(Status status) final { void on_error(Status status) final {
// td_->contacts_manager_->on_get_channel_error(channel_id_, status, "DeleteParticipantHistoryQuery"); if (sender_dialog_id_.get_type() != DialogType::Channel) {
td_->contacts_manager_->on_get_channel_error(channel_id_, status, "DeleteParticipantHistoryQuery");
}
promise_.set_error(std::move(status)); promise_.set_error(std::move(status));
} }
}; };
@ -12178,6 +12185,30 @@ void MessagesManager::set_dialog_online_member_count(DialogId dialog_id, int32 o
return; return;
} }
if (online_member_count < 0) {
LOG(ERROR) << "Receive online_member_count = " << online_member_count << " in " << dialog_id;
online_member_count = 0;
}
switch (dialog_id.get_type()) {
case DialogType::Chat: {
auto participant_count = td_->contacts_manager_->get_chat_participant_count(dialog_id.get_chat_id());
if (online_member_count > participant_count) {
online_member_count = participant_count;
}
break;
}
case DialogType::Channel: {
auto participant_count = td_->contacts_manager_->get_channel_participant_count(dialog_id.get_channel_id());
if (participant_count != 0 && online_member_count > participant_count) {
online_member_count = participant_count;
}
break;
}
default:
break;
}
auto &info = dialog_online_member_counts_[dialog_id]; auto &info = dialog_online_member_counts_[dialog_id];
LOG(INFO) << "Change number of online members from " << info.online_member_count << " to " << online_member_count LOG(INFO) << "Change number of online members from " << info.online_member_count << " to " << online_member_count
<< " in " << dialog_id << " from " << source; << " in " << dialog_id << " from " << source;

View File

@ -132,7 +132,7 @@ class Td final : public Actor {
void set_is_bot_online(bool is_bot_online); void set_is_bot_online(bool is_bot_online);
template <class ActorT, class... ArgsT> template <class ActorT, class... ArgsT>
ActorId<ActorT> create_net_actor(ArgsT &&... args) { ActorId<ActorT> create_net_actor(ArgsT &&...args) {
LOG_CHECK(close_flag_ < 1) << close_flag_ LOG_CHECK(close_flag_ < 1) << close_flag_
#if TD_CLANG || TD_GCC #if TD_CLANG || TD_GCC
<< ' ' << __PRETTY_FUNCTION__ << ' ' << __PRETTY_FUNCTION__
@ -243,7 +243,7 @@ class Td final : public Actor {
}; };
template <class HandlerT, class... Args> template <class HandlerT, class... Args>
std::shared_ptr<HandlerT> create_handler(Args &&... args) { std::shared_ptr<HandlerT> create_handler(Args &&...args) {
LOG_CHECK(close_flag_ < 2) << close_flag_ LOG_CHECK(close_flag_ < 2) << close_flag_
#if TD_CLANG || TD_GCC #if TD_CLANG || TD_GCC
<< ' ' << __PRETTY_FUNCTION__ << ' ' << __PRETTY_FUNCTION__

View File

@ -712,7 +712,7 @@ class CliClient final : public Actor {
} }
template <class FirstType, class SecondType, class... Types> template <class FirstType, class SecondType, class... Types>
static void get_args(string &args, FirstType &first_arg, SecondType &second_arg, Types &... other_args) { static void get_args(string &args, FirstType &first_arg, SecondType &second_arg, Types &...other_args) {
string arg; string arg;
std::tie(arg, args) = split(args); std::tie(arg, args) = split(args);
get_args(arg, first_arg); get_args(arg, first_arg);

View File

@ -199,7 +199,7 @@ using tl_object_ptr = tl::unique_ptr<Type>;
* \return Wrapped pointer to the created TL-object. * \return Wrapped pointer to the created TL-object.
*/ */
template <class Type, class... Args> template <class Type, class... Args>
tl_object_ptr<Type> make_tl_object(Args &&... args) { tl_object_ptr<Type> make_tl_object(Args &&...args) {
return tl_object_ptr<Type>(new Type(std::forward<Args>(args)...)); return tl_object_ptr<Type>(new Type(std::forward<Args>(args)...));
} }

View File

@ -62,7 +62,7 @@ class ConcurrentScheduler final : private Scheduler::Callback {
void finish(); void finish();
template <class ActorT, class... Args> template <class ActorT, class... Args>
ActorOwn<ActorT> create_actor_unsafe(int32 sched_id, Slice name, Args &&... args) { ActorOwn<ActorT> create_actor_unsafe(int32 sched_id, Slice name, Args &&...args) {
#if TD_THREAD_UNSUPPORTED || TD_EVENTFD_UNSUPPORTED #if TD_THREAD_UNSUPPORTED || TD_EVENTFD_UNSUPPORTED
sched_id = 0; sched_id = 0;
#endif #endif

View File

@ -404,7 +404,7 @@ template <class PromiseT>
class CancellablePromise final : public PromiseT { class CancellablePromise final : public PromiseT {
public: public:
template <class... ArgsT> template <class... ArgsT>
CancellablePromise(CancellationToken cancellation_token, ArgsT &&... args) CancellablePromise(CancellationToken cancellation_token, ArgsT &&...args)
: PromiseT(std::forward<ArgsT>(args)...), cancellation_token_(std::move(cancellation_token)) { : PromiseT(std::forward<ArgsT>(args)...), cancellation_token_(std::move(cancellation_token)) {
} }
bool is_cancellable() const final { bool is_cancellable() const final {
@ -421,7 +421,7 @@ class CancellablePromise final : public PromiseT {
template <class... ArgsT> template <class... ArgsT>
class JoinPromise final : public PromiseInterface<Unit> { class JoinPromise final : public PromiseInterface<Unit> {
public: public:
explicit JoinPromise(ArgsT &&... arg) : promises_(std::forward<ArgsT>(arg)...) { explicit JoinPromise(ArgsT &&...arg) : promises_(std::forward<ArgsT>(arg)...) {
} }
void set_value(Unit &&) final { void set_value(Unit &&) final {
tuple_for_each(promises_, [](auto &promise) { promise.set_value(Unit()); }); tuple_for_each(promises_, [](auto &promise) { promise.set_value(Unit()); });
@ -438,7 +438,7 @@ class JoinPromise final : public PromiseInterface<Unit> {
class SendClosure { class SendClosure {
public: public:
template <class... ArgsT> template <class... ArgsT>
void operator()(ArgsT &&... args) const { void operator()(ArgsT &&...args) const {
send_closure(std::forward<ArgsT>(args)...); send_closure(std::forward<ArgsT>(args)...);
} }
}; };
@ -453,7 +453,7 @@ class SendClosure {
//} //}
template <class... ArgsT> template <class... ArgsT>
auto promise_send_closure(ArgsT &&... args) { auto promise_send_closure(ArgsT &&...args) {
return [t = std::make_tuple(std::forward<ArgsT>(args)...)](auto &&res) mutable { return [t = std::make_tuple(std::forward<ArgsT>(args)...)](auto &&res) mutable {
call_tuple(SendClosure(), std::tuple_cat(std::move(t), std::make_tuple(std::forward<decltype(res)>(res)))); call_tuple(SendClosure(), std::tuple_cat(std::move(t), std::make_tuple(std::forward<decltype(res)>(res))));
}; };
@ -679,7 +679,7 @@ class PromiseFuture {
template <ActorSendType send_type, class T, class ActorAT, class ActorBT, class ResultT, class... DestArgsT, template <ActorSendType send_type, class T, class ActorAT, class ActorBT, class ResultT, class... DestArgsT,
class... ArgsT> class... ArgsT>
FutureActor<T> send_promise(ActorId<ActorAT> actor_id, ResultT (ActorBT::*func)(PromiseActor<T> &&, DestArgsT...), FutureActor<T> send_promise(ActorId<ActorAT> actor_id, ResultT (ActorBT::*func)(PromiseActor<T> &&, DestArgsT...),
ArgsT &&... args) { ArgsT &&...args) {
PromiseFuture<T> pf; PromiseFuture<T> pf;
Scheduler::instance()->send_closure<send_type>( Scheduler::instance()->send_closure<send_type>(
std::move(actor_id), create_immediate_closure(func, pf.move_promise(), std::forward<ArgsT>(args)...)); std::move(actor_id), create_immediate_closure(func, pf.move_promise(), std::forward<ArgsT>(args)...));
@ -716,7 +716,7 @@ class PromiseCreator {
} }
template <class... ArgsT> template <class... ArgsT>
static Promise<> join(ArgsT &&... args) { static Promise<> join(ArgsT &&...args) {
return Promise<>(td::make_unique<detail::JoinPromise<ArgsT...>>(std::forward<ArgsT>(args)...)); return Promise<>(td::make_unique<detail::JoinPromise<ArgsT...>>(std::forward<ArgsT>(args)...));
} }

View File

@ -90,10 +90,10 @@ class Actor : public ObserverBase {
bool empty() const; bool empty() const;
template <class FuncT, class... ArgsT> template <class FuncT, class... ArgsT>
auto self_closure(FuncT &&func, ArgsT &&... args); auto self_closure(FuncT &&func, ArgsT &&...args);
template <class SelfT, class FuncT, class... ArgsT> template <class SelfT, class FuncT, class... ArgsT>
auto self_closure(SelfT *self, FuncT &&func, ArgsT &&... args); auto self_closure(SelfT *self, FuncT &&func, ArgsT &&...args);
template <class LambdaT> template <class LambdaT>
auto self_lambda(LambdaT &&lambda); auto self_lambda(LambdaT &&lambda);

View File

@ -146,12 +146,12 @@ ActorShared<SelfT> Actor::actor_shared(SelfT *self, uint64 id) {
} }
template <class FuncT, class... ArgsT> template <class FuncT, class... ArgsT>
auto Actor::self_closure(FuncT &&func, ArgsT &&... args) { auto Actor::self_closure(FuncT &&func, ArgsT &&...args) {
return self_closure(this, std::forward<FuncT>(func), std::forward<ArgsT>(args)...); return self_closure(this, std::forward<FuncT>(func), std::forward<ArgsT>(args)...);
} }
template <class SelfT, class FuncT, class... ArgsT> template <class SelfT, class FuncT, class... ArgsT>
auto Actor::self_closure(SelfT *self, FuncT &&func, ArgsT &&... args) { auto Actor::self_closure(SelfT *self, FuncT &&func, ArgsT &&...args) {
return EventCreator::closure(actor_id(self), std::forward<FuncT>(func), std::forward<ArgsT>(args)...); return EventCreator::closure(actor_id(self), std::forward<FuncT>(func), std::forward<ArgsT>(args)...);
} }

View File

@ -66,7 +66,7 @@ class ClosureEvent final : public CustomEvent {
return new ClosureEvent<ClosureT>(closure_.clone()); return new ClosureEvent<ClosureT>(closure_.clone());
} }
template <class... ArgsT> template <class... ArgsT>
explicit ClosureEvent(ArgsT &&... args) : closure_(std::forward<ArgsT>(args)...) { explicit ClosureEvent(ArgsT &&...args) : closure_(std::forward<ArgsT>(args)...) {
} }
void start_migrate(int32 sched_id) final { void start_migrate(int32 sched_id) final {
@ -152,7 +152,7 @@ class Event {
new ClosureEvent<typename FromImmediateClosureT::Delayed>(std::forward<FromImmediateClosureT>(closure))); new ClosureEvent<typename FromImmediateClosureT::Delayed>(std::forward<FromImmediateClosureT>(closure)));
} }
template <class... ArgsT> template <class... ArgsT>
static Event delayed_closure(ArgsT &&... args) { static Event delayed_closure(ArgsT &&...args) {
using DelayedClosureT = decltype(create_delayed_closure(std::forward<ArgsT>(args)...)); using DelayedClosureT = decltype(create_delayed_closure(std::forward<ArgsT>(args)...));
return custom(new ClosureEvent<DelayedClosureT>(std::forward<ArgsT>(args)...)); return custom(new ClosureEvent<DelayedClosureT>(std::forward<ArgsT>(args)...));
} }

View File

@ -56,7 +56,7 @@ class EventFull {
class EventCreator { class EventCreator {
public: public:
template <class ActorIdT, class FunctionT, class... ArgsT> template <class ActorIdT, class FunctionT, class... ArgsT>
static EventFull closure(ActorIdT &&actor_id, FunctionT function, ArgsT &&... args) { static EventFull closure(ActorIdT &&actor_id, FunctionT function, ArgsT &&...args) {
using ActorT = typename std::decay_t<ActorIdT>::ActorT; using ActorT = typename std::decay_t<ActorIdT>::ActorT;
using FunctionClassT = member_function_class_t<FunctionT>; using FunctionClassT = member_function_class_t<FunctionT>;
static_assert(std::is_base_of<FunctionClassT, ActorT>::value, "unsafe send_closure"); static_assert(std::is_base_of<FunctionClassT, ActorT>::value, "unsafe send_closure");

View File

@ -84,9 +84,9 @@ class Scheduler {
int32 sched_count() const; int32 sched_count() const;
template <class ActorT, class... Args> template <class ActorT, class... Args>
TD_WARN_UNUSED_RESULT ActorOwn<ActorT> create_actor(Slice name, Args &&... args); TD_WARN_UNUSED_RESULT ActorOwn<ActorT> create_actor(Slice name, Args &&...args);
template <class ActorT, class... Args> template <class ActorT, class... Args>
TD_WARN_UNUSED_RESULT ActorOwn<ActorT> create_actor_on_scheduler(Slice name, int32 sched_id, Args &&... args); TD_WARN_UNUSED_RESULT ActorOwn<ActorT> create_actor_on_scheduler(Slice name, int32 sched_id, Args &&...args);
template <class ActorT> template <class ActorT>
TD_WARN_UNUSED_RESULT ActorOwn<ActorT> register_actor(Slice name, ActorT *actor_ptr, int32 sched_id = -1); TD_WARN_UNUSED_RESULT ActorOwn<ActorT> register_actor(Slice name, ActorT *actor_ptr, int32 sched_id = -1);
template <class ActorT> template <class ActorT>
@ -244,9 +244,9 @@ class Scheduler {
/*** Interface to current scheduler ***/ /*** Interface to current scheduler ***/
template <class ActorT, class... Args> template <class ActorT, class... Args>
TD_WARN_UNUSED_RESULT ActorOwn<ActorT> create_actor(Slice name, Args &&... args); TD_WARN_UNUSED_RESULT ActorOwn<ActorT> create_actor(Slice name, Args &&...args);
template <class ActorT, class... Args> template <class ActorT, class... Args>
TD_WARN_UNUSED_RESULT ActorOwn<ActorT> create_actor_on_scheduler(Slice name, int32 sched_id, Args &&... args); TD_WARN_UNUSED_RESULT ActorOwn<ActorT> create_actor_on_scheduler(Slice name, int32 sched_id, Args &&...args);
template <class ActorT> template <class ActorT>
TD_WARN_UNUSED_RESULT ActorOwn<ActorT> register_actor(Slice name, ActorT *actor_ptr, int32 sched_id = -1); TD_WARN_UNUSED_RESULT ActorOwn<ActorT> register_actor(Slice name, ActorT *actor_ptr, int32 sched_id = -1);
template <class ActorT> template <class ActorT>
@ -256,7 +256,7 @@ template <class ActorT>
TD_WARN_UNUSED_RESULT ActorOwn<ActorT> register_existing_actor(unique_ptr<ActorT> actor_ptr); TD_WARN_UNUSED_RESULT ActorOwn<ActorT> register_existing_actor(unique_ptr<ActorT> actor_ptr);
template <class ActorIdT, class FunctionT, class... ArgsT> template <class ActorIdT, class FunctionT, class... ArgsT>
void send_closure(ActorIdT &&actor_id, FunctionT function, ArgsT &&... args) { void send_closure(ActorIdT &&actor_id, FunctionT function, ArgsT &&...args) {
using ActorT = typename std::decay_t<ActorIdT>::ActorT; using ActorT = typename std::decay_t<ActorIdT>::ActorT;
using FunctionClassT = member_function_class_t<FunctionT>; using FunctionClassT = member_function_class_t<FunctionT>;
static_assert(std::is_base_of<FunctionClassT, ActorT>::value, "unsafe send_closure"); static_assert(std::is_base_of<FunctionClassT, ActorT>::value, "unsafe send_closure");
@ -266,7 +266,7 @@ void send_closure(ActorIdT &&actor_id, FunctionT function, ArgsT &&... args) {
} }
template <class ActorIdT, class FunctionT, class... ArgsT> template <class ActorIdT, class FunctionT, class... ArgsT>
void send_closure_later(ActorIdT &&actor_id, FunctionT function, ArgsT &&... args) { void send_closure_later(ActorIdT &&actor_id, FunctionT function, ArgsT &&...args) {
using ActorT = typename std::decay_t<ActorIdT>::ActorT; using ActorT = typename std::decay_t<ActorIdT>::ActorT;
using FunctionClassT = member_function_class_t<FunctionT>; using FunctionClassT = member_function_class_t<FunctionT>;
static_assert(std::is_base_of<FunctionClassT, ActorT>::value, "unsafe send_closure"); static_assert(std::is_base_of<FunctionClassT, ActorT>::value, "unsafe send_closure");
@ -276,17 +276,17 @@ void send_closure_later(ActorIdT &&actor_id, FunctionT function, ArgsT &&... arg
} }
template <class... ArgsT> template <class... ArgsT>
void send_lambda(ActorRef actor_ref, ArgsT &&... args) { void send_lambda(ActorRef actor_ref, ArgsT &&...args) {
Scheduler::instance()->send_lambda<ActorSendType::Immediate>(actor_ref, std::forward<ArgsT>(args)...); Scheduler::instance()->send_lambda<ActorSendType::Immediate>(actor_ref, std::forward<ArgsT>(args)...);
} }
template <class... ArgsT> template <class... ArgsT>
void send_event(ActorRef actor_ref, ArgsT &&... args) { void send_event(ActorRef actor_ref, ArgsT &&...args) {
Scheduler::instance()->send<ActorSendType::Immediate>(actor_ref, std::forward<ArgsT>(args)...); Scheduler::instance()->send<ActorSendType::Immediate>(actor_ref, std::forward<ArgsT>(args)...);
} }
template <class... ArgsT> template <class... ArgsT>
void send_event_later(ActorRef actor_ref, ArgsT &&... args) { void send_event_later(ActorRef actor_ref, ArgsT &&...args) {
Scheduler::instance()->send<ActorSendType::Later>(actor_ref, std::forward<ArgsT>(args)...); Scheduler::instance()->send<ActorSendType::Later>(actor_ref, std::forward<ArgsT>(args)...);
} }

View File

@ -69,12 +69,12 @@ inline int32 Scheduler::sched_count() const {
} }
template <class ActorT, class... Args> template <class ActorT, class... Args>
ActorOwn<ActorT> Scheduler::create_actor(Slice name, Args &&... args) { ActorOwn<ActorT> Scheduler::create_actor(Slice name, Args &&...args) {
return register_actor_impl(name, new ActorT(std::forward<Args>(args)...), Actor::Deleter::Destroy, sched_id_); return register_actor_impl(name, new ActorT(std::forward<Args>(args)...), Actor::Deleter::Destroy, sched_id_);
} }
template <class ActorT, class... Args> template <class ActorT, class... Args>
ActorOwn<ActorT> Scheduler::create_actor_on_scheduler(Slice name, int32 sched_id, Args &&... args) { ActorOwn<ActorT> Scheduler::create_actor_on_scheduler(Slice name, int32 sched_id, Args &&...args) {
return register_actor_impl(name, new ActorT(std::forward<Args>(args)...), Actor::Deleter::Destroy, sched_id); return register_actor_impl(name, new ActorT(std::forward<Args>(args)...), Actor::Deleter::Destroy, sched_id);
} }
@ -334,12 +334,12 @@ inline void Scheduler::run(Timestamp timeout) {
/*** Interface to current scheduler ***/ /*** Interface to current scheduler ***/
template <class ActorT, class... Args> template <class ActorT, class... Args>
ActorOwn<ActorT> create_actor(Slice name, Args &&... args) { ActorOwn<ActorT> create_actor(Slice name, Args &&...args) {
return Scheduler::instance()->create_actor<ActorT>(name, std::forward<Args>(args)...); return Scheduler::instance()->create_actor<ActorT>(name, std::forward<Args>(args)...);
} }
template <class ActorT, class... Args> template <class ActorT, class... Args>
ActorOwn<ActorT> create_actor_on_scheduler(Slice name, int32 sched_id, Args &&... args) { ActorOwn<ActorT> create_actor_on_scheduler(Slice name, int32 sched_id, Args &&...args) {
return Scheduler::instance()->create_actor_on_scheduler<ActorT>(name, sched_id, std::forward<Args>(args)...); return Scheduler::instance()->create_actor_on_scheduler<ActorT>(name, sched_id, std::forward<Args>(args)...);
} }

View File

@ -83,7 +83,7 @@ class ImmediateClosure {
template <class ActorT, class ResultT, class... DestArgsT, class... SrcArgsT> template <class ActorT, class ResultT, class... DestArgsT, class... SrcArgsT>
ImmediateClosure<ActorT, ResultT (ActorT::*)(DestArgsT...), SrcArgsT &&...> create_immediate_closure( ImmediateClosure<ActorT, ResultT (ActorT::*)(DestArgsT...), SrcArgsT &&...> create_immediate_closure(
ResultT (ActorT::*func)(DestArgsT...), SrcArgsT &&... args) { ResultT (ActorT::*func)(DestArgsT...), SrcArgsT &&...args) {
return ImmediateClosure<ActorT, ResultT (ActorT::*)(DestArgsT...), SrcArgsT &&...>(func, return ImmediateClosure<ActorT, ResultT (ActorT::*)(DestArgsT...), SrcArgsT &&...>(func,
std::forward<SrcArgsT>(args)...); std::forward<SrcArgsT>(args)...);
} }
@ -160,7 +160,7 @@ DelayedClosure<ArgsT...> to_delayed_closure(DelayedClosure<ArgsT...> &&other) {
} }
template <class ActorT, class ResultT, class... DestArgsT, class... SrcArgsT> template <class ActorT, class ResultT, class... DestArgsT, class... SrcArgsT>
auto create_delayed_closure(ResultT (ActorT::*func)(DestArgsT...), SrcArgsT &&... args) { auto create_delayed_closure(ResultT (ActorT::*func)(DestArgsT...), SrcArgsT &&...args) {
return DelayedClosure<ActorT, ResultT (ActorT::*)(DestArgsT...), SrcArgsT &&...>(func, return DelayedClosure<ActorT, ResultT (ActorT::*)(DestArgsT...), SrcArgsT &&...>(func,
std::forward<SrcArgsT>(args)...); std::forward<SrcArgsT>(args)...);
} }

View File

@ -156,7 +156,7 @@ class ObjectPool {
}; };
template <class... ArgsT> template <class... ArgsT>
OwnerPtr create(ArgsT &&... args) { OwnerPtr create(ArgsT &&...args) {
Storage *storage = get_storage(); Storage *storage = get_storage();
storage->init_data(std::forward<ArgsT>(args)...); storage->init_data(std::forward<ArgsT>(args)...);
return OwnerPtr(storage, this); return OwnerPtr(storage, this);
@ -201,7 +201,7 @@ class ObjectPool {
std::atomic<int32> generation{1}; std::atomic<int32> generation{1};
template <class... ArgsT> template <class... ArgsT>
void init_data(ArgsT &&... args) { void init_data(ArgsT &&...args) {
// new (&data) DataT(std::forward<ArgsT>(args)...); // new (&data) DataT(std::forward<ArgsT>(args)...);
data = DataT(std::forward<ArgsT>(args)...); data = DataT(std::forward<ArgsT>(args)...);
} }

View File

@ -49,7 +49,7 @@ class SharedPtrRaw
CHECK(option_magic_ == Magic); CHECK(option_magic_ == Magic);
} }
template <class... ArgsT> template <class... ArgsT>
void init_data(ArgsT &&... args) { void init_data(ArgsT &&...args) {
new (&option_data_) DataT(std::forward<ArgsT>(args)...); new (&option_data_) DataT(std::forward<ArgsT>(args)...);
} }
void destroy_data() { void destroy_data() {
@ -158,13 +158,13 @@ class SharedPtr {
} }
template <class... ArgsT> template <class... ArgsT>
static SharedPtr<T, DeleterT> create(ArgsT &&... args) { static SharedPtr<T, DeleterT> create(ArgsT &&...args) {
auto raw = make_unique<Raw>(DeleterT()); auto raw = make_unique<Raw>(DeleterT());
raw->init_data(std::forward<ArgsT>(args)...); raw->init_data(std::forward<ArgsT>(args)...);
return SharedPtr<T, DeleterT>(raw.release()); return SharedPtr<T, DeleterT>(raw.release());
} }
template <class D, class... ArgsT> template <class D, class... ArgsT>
static SharedPtr<T, DeleterT> create_with_deleter(D &&d, ArgsT &&... args) { static SharedPtr<T, DeleterT> create_with_deleter(D &&d, ArgsT &&...args) {
auto raw = make_unique<Raw>(std::forward<D>(d)); auto raw = make_unique<Raw>(std::forward<D>(d));
raw->init_data(std::forward<ArgsT>(args)...); raw->init_data(std::forward<ArgsT>(args)...);
return SharedPtr<T, DeleterT>(raw.release()); return SharedPtr<T, DeleterT>(raw.release());
@ -201,7 +201,7 @@ class SharedObjectPool {
} }
template <class... ArgsT> template <class... ArgsT>
Ptr alloc(ArgsT &&... args) { Ptr alloc(ArgsT &&...args) {
auto *raw = alloc_raw(); auto *raw = alloc_raw();
raw->init_data(std::forward<ArgsT>(args)...); raw->init_data(std::forward<ArgsT>(args)...);
return Ptr(raw); return Ptr(raw);

View File

@ -416,7 +416,7 @@ class Result {
} }
struct emplace_t {}; struct emplace_t {};
template <class... ArgsT> template <class... ArgsT>
Result(emplace_t, ArgsT &&... args) : status_(), value_(std::forward<ArgsT>(args)...) { Result(emplace_t, ArgsT &&...args) : status_(), value_(std::forward<ArgsT>(args)...) {
} }
Result(Status &&status) : status_(std::move(status)) { Result(Status &&status) : status_(std::move(status)) {
CHECK(status_.is_error()); CHECK(status_.is_error());
@ -451,7 +451,7 @@ class Result {
return *this; return *this;
} }
template <class... ArgsT> template <class... ArgsT>
void emplace(ArgsT &&... args) { void emplace(ArgsT &&...args) {
if (status_.is_ok()) { if (status_.is_ok()) {
value_.~T(); value_.~T();
} }

View File

@ -22,7 +22,7 @@ class VectorQueue {
} }
template <class... Args> template <class... Args>
void emplace(Args &&... args) { void emplace(Args &&...args) {
vector_.emplace_back(std::forward<Args>(args)...); vector_.emplace_back(std::forward<Args>(args)...);
} }

View File

@ -8,7 +8,6 @@
#include "td/utils/logging.h" #include "td/utils/logging.h"
#include "td/utils/port/thread_local.h" #include "td/utils/port/thread_local.h"
#include "td/utils/ThreadSafeCounter.h"
#include <cstddef> #include <cstddef>
#include <new> #include <new>
@ -26,18 +25,12 @@ TD_THREAD_LOCAL BufferAllocator::BufferRawTls *BufferAllocator::buffer_raw_tls;
std::atomic<size_t> BufferAllocator::buffer_mem; std::atomic<size_t> BufferAllocator::buffer_mem;
static ThreadSafeCounter buffer_slice_size_;
int64 BufferAllocator::get_buffer_slice_size() { int64 BufferAllocator::get_buffer_slice_size() {
return buffer_slice_size_.sum(); return 0;
} }
void BufferAllocator::track_buffer_slice(int64 size) { void BufferAllocator::track_buffer_slice(int64 size) {
if (size == 0) { return;
return;
}
buffer_slice_size_.add(size);
} }
size_t BufferAllocator::get_buffer_mem() { size_t BufferAllocator::get_buffer_mem() {

View File

@ -301,7 +301,7 @@ StringBuilder &operator<<(StringBuilder &sb, const Concat<T> &concat) {
} }
template <class... ArgsT> template <class... ArgsT>
auto concat(const ArgsT &... args) { auto concat(const ArgsT &...args) {
return Concat<decltype(std::tie(args...))>{std::tie(args...)}; return Concat<decltype(std::tie(args...))>{std::tie(args...)};
} }

View File

@ -54,7 +54,7 @@ struct is_reference_wrapper<std::reference_wrapper<U>> : std::true_type {};
template <class Base, class T, class Derived, class... Args> template <class Base, class T, class Derived, class... Args>
auto invoke_impl(T Base::*pmf, Derived &&ref, auto invoke_impl(T Base::*pmf, Derived &&ref,
Args &&... args) noexcept(noexcept((std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...))) Args &&...args) noexcept(noexcept((std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...)))
-> std::enable_if_t<std::is_function<T>::value && std::is_base_of<Base, std::decay<Derived>>::value, -> std::enable_if_t<std::is_function<T>::value && std::is_base_of<Base, std::decay<Derived>>::value,
decltype((std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...))> { decltype((std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...))> {
return (std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...); return (std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...);
@ -62,7 +62,7 @@ auto invoke_impl(T Base::*pmf, Derived &&ref,
template <class Base, class T, class RefWrap, class... Args> template <class Base, class T, class RefWrap, class... Args>
auto invoke_impl(T Base::*pmf, RefWrap &&ref, auto invoke_impl(T Base::*pmf, RefWrap &&ref,
Args &&... args) noexcept(noexcept((ref.get().*pmf)(std::forward<Args>(args)...))) Args &&...args) noexcept(noexcept((ref.get().*pmf)(std::forward<Args>(args)...)))
-> std::enable_if_t<std::is_function<T>::value && is_reference_wrapper<std::decay_t<RefWrap>>::value, -> std::enable_if_t<std::is_function<T>::value && is_reference_wrapper<std::decay_t<RefWrap>>::value,
decltype((ref.get().*pmf)(std::forward<Args>(args)...))> decltype((ref.get().*pmf)(std::forward<Args>(args)...))>
@ -72,7 +72,7 @@ auto invoke_impl(T Base::*pmf, RefWrap &&ref,
template <class Base, class T, class Pointer, class... Args> template <class Base, class T, class Pointer, class... Args>
auto invoke_impl(T Base::*pmf, Pointer &&ptr, auto invoke_impl(T Base::*pmf, Pointer &&ptr,
Args &&... args) noexcept(noexcept(((*std::forward<Pointer>(ptr)).*pmf)(std::forward<Args>(args)...))) Args &&...args) noexcept(noexcept(((*std::forward<Pointer>(ptr)).*pmf)(std::forward<Args>(args)...)))
-> std::enable_if_t<std::is_function<T>::value && !is_reference_wrapper<std::decay_t<Pointer>>::value && -> std::enable_if_t<std::is_function<T>::value && !is_reference_wrapper<std::decay_t<Pointer>>::value &&
!std::is_base_of<Base, std::decay_t<Pointer>>::value, !std::is_base_of<Base, std::decay_t<Pointer>>::value,
decltype(((*std::forward<Pointer>(ptr)).*pmf)(std::forward<Args>(args)...))> { decltype(((*std::forward<Pointer>(ptr)).*pmf)(std::forward<Args>(args)...))> {
@ -102,7 +102,7 @@ auto invoke_impl(T Base::*pmd, Pointer &&ptr) noexcept(noexcept((*std::forward<P
} }
template <class F, class... Args> template <class F, class... Args>
auto invoke_impl(F &&f, Args &&... args) noexcept(noexcept(std::forward<F>(f)(std::forward<Args>(args)...))) auto invoke_impl(F &&f, Args &&...args) noexcept(noexcept(std::forward<F>(f)(std::forward<Args>(args)...)))
-> std::enable_if_t<!std::is_member_pointer<std::decay_t<F>>::value, -> std::enable_if_t<!std::is_member_pointer<std::decay_t<F>>::value,
decltype(std::forward<F>(f)(std::forward<Args>(args)...))> { decltype(std::forward<F>(f)(std::forward<Args>(args)...))> {
return std::forward<F>(f)(std::forward<Args>(args)...); return std::forward<F>(f)(std::forward<Args>(args)...);
@ -110,7 +110,7 @@ auto invoke_impl(F &&f, Args &&... args) noexcept(noexcept(std::forward<F>(f)(st
template <class F, class... ArgTypes> template <class F, class... ArgTypes>
auto invoke(F &&f, auto invoke(F &&f,
ArgTypes &&... args) noexcept(noexcept(invoke_impl(std::forward<F>(f), std::forward<ArgTypes>(args)...))) ArgTypes &&...args) noexcept(noexcept(invoke_impl(std::forward<F>(f), std::forward<ArgTypes>(args)...)))
-> decltype(invoke_impl(std::forward<F>(f), std::forward<ArgTypes>(args)...)) { -> decltype(invoke_impl(std::forward<F>(f), std::forward<ArgTypes>(args)...)) {
return invoke_impl(std::forward<F>(f), std::forward<ArgTypes>(args)...); return invoke_impl(std::forward<F>(f), std::forward<ArgTypes>(args)...);
} }
@ -176,29 +176,29 @@ void tuple_for_each(const std::tuple<Args...> &tuple, const F &func) {
} }
template <size_t N, class Arg, class... Args, std::enable_if_t<N == 0, int> = 0> template <size_t N, class Arg, class... Args, std::enable_if_t<N == 0, int> = 0>
auto &&get_nth_argument(Arg &&arg, Args &&... args) { auto &&get_nth_argument(Arg &&arg, Args &&...args) {
return std::forward<Arg>(arg); return std::forward<Arg>(arg);
} }
template <size_t N, class Arg, class... Args, std::enable_if_t<N != 0, int> = 0> template <size_t N, class Arg, class... Args, std::enable_if_t<N != 0, int> = 0>
auto &&get_nth_argument(Arg &&arg, Args &&... args) { auto &&get_nth_argument(Arg &&arg, Args &&...args) {
return get_nth_argument<N - 1>(std::forward<Args &&>(args)...); return get_nth_argument<N - 1>(std::forward<Args &&>(args)...);
} }
template <class... Args> template <class... Args>
auto &&get_last_argument(Args &&... args) { auto &&get_last_argument(Args &&...args) {
return get_nth_argument<sizeof...(Args) - 1>(std::forward<Args &&>(args)...); return get_nth_argument<sizeof...(Args) - 1>(std::forward<Args &&>(args)...);
} }
namespace detail { namespace detail {
template <class F, class... Args, std::size_t... S> template <class F, class... Args, std::size_t... S>
auto call_n_arguments_impl(IntSeq<S...>, F &&f, Args &&... args) { auto call_n_arguments_impl(IntSeq<S...>, F &&f, Args &&...args) {
return f(get_nth_argument<S>(std::forward<Args>(args)...)...); return f(get_nth_argument<S>(std::forward<Args>(args)...)...);
} }
} // namespace detail } // namespace detail
template <size_t N, class F, class... Args> template <size_t N, class F, class... Args>
auto call_n_arguments(F &&f, Args &&... args) { auto call_n_arguments(F &&f, Args &&...args) {
return detail::call_n_arguments_impl(detail::IntRange<N>(), f, std::forward<Args>(args)...); return detail::call_n_arguments_impl(detail::IntRange<N>(), f, std::forward<Args>(args)...);
} }

View File

@ -75,7 +75,7 @@ class optional {
} }
template <class... ArgsT> template <class... ArgsT>
void emplace(ArgsT &&... args) { void emplace(ArgsT &&...args) {
impl_.emplace(std::forward<ArgsT>(args)...); impl_.emplace(std::forward<ArgsT>(args)...);
} }

View File

@ -30,8 +30,8 @@
#define REF_NEW ref new #define REF_NEW ref new
#define CLRCALL #define CLRCALL
#define DEPRECATED_ATTRIBUTE(message) ::Windows::Foundation::Metadata::Deprecated(message,\ #define DEPRECATED_ATTRIBUTE(message) \
::Windows::Foundation::Metadata::DeprecationType::Deprecate, 0x0) ::Windows::Foundation::Metadata::Deprecated(message, ::Windows::Foundation::Metadata::DeprecationType::Deprecate, 0x0)
namespace CxCli { namespace CxCli {
@ -49,7 +49,7 @@ using Platform::NullReferenceException;
template <class Key, class Value> template <class Key, class Value>
class ConcurrentDictionary { class ConcurrentDictionary {
public: public:
bool TryGetValue(Key key, Value &value) { bool TryGetValue(Key key, Value &value) {
std::lock_guard<std::mutex> guard(mutex_); std::lock_guard<std::mutex> guard(mutex_);
auto it = impl_.find(key); auto it = impl_.find(key);
@ -69,11 +69,12 @@ public:
impl_.erase(it); impl_.erase(it);
return true; return true;
} }
Value &operator [] (Key key) { Value &operator[](Key key) {
std::lock_guard<std::mutex> guard(mutex_); std::lock_guard<std::mutex> guard(mutex_);
return impl_[key]; return impl_[key];
} }
private:
private:
std::mutex mutex_; std::mutex mutex_;
std::map<Key, Value> impl_; std::map<Key, Value> impl_;
}; };
@ -82,7 +83,7 @@ inline std::int64_t Increment(volatile std::int64_t &value) {
return InterlockedIncrement64(&value); return InterlockedIncrement64(&value);
} }
inline std::string string_to_unmanaged(String^ str) { inline std::string string_to_unmanaged(String ^ str) {
if (!str) { if (!str) {
return std::string(); return std::string();
} }
@ -93,12 +94,12 @@ inline std::string string_to_unmanaged(String^ str) {
return r_unmanaged_str.move_as_ok(); return r_unmanaged_str.move_as_ok();
} }
inline String^ string_from_unmanaged(const std::string &from) { inline String ^ string_from_unmanaged(const std::string &from) {
auto tmp = td::to_wstring(from).ok(); auto tmp = td::to_wstring(from).ok();
return REF_NEW String(tmp.c_str(), static_cast<unsigned>(tmp.size())); return REF_NEW String(tmp.c_str(), static_cast<unsigned>(tmp.size()));
} }
} // namespace CxCli } // namespace CxCli
#elif TD_CLI #elif TD_CLI
@ -128,27 +129,27 @@ using System::NullReferenceException;
using System::Collections::Concurrent::ConcurrentDictionary; using System::Collections::Concurrent::ConcurrentDictionary;
inline std::int64_t Increment(std::int64_t %value) { inline std::int64_t Increment(std::int64_t % value) {
return System::Threading::Interlocked::Increment(value); return System::Threading::Interlocked::Increment(value);
} }
inline std::string string_to_unmanaged(String^ str) { inline std::string string_to_unmanaged(String ^ str) {
if (!str || str->Length == 0) { if (!str || str->Length == 0) {
return std::string(); return std::string();
} }
Array<System::Byte>^ bytes = System::Text::Encoding::UTF8->GetBytes(str); Array<System::Byte> ^ bytes = System::Text::Encoding::UTF8->GetBytes(str);
cli::pin_ptr<System::Byte> pinned_ptr = &bytes[0]; cli::pin_ptr<System::Byte> pinned_ptr = &bytes[0];
std::string result(reinterpret_cast<const char *>(&pinned_ptr[0]), bytes->Length); std::string result(reinterpret_cast<const char *>(&pinned_ptr[0]), bytes->Length);
return result; return result;
} }
inline String^ string_from_unmanaged(const std::string &from) { inline String ^ string_from_unmanaged(const std::string &from) {
if (from.empty()) { if (from.empty()) {
return String::Empty; return String::Empty;
} }
Array<System::Byte>^ bytes = REF_NEW Vector<System::Byte>(static_cast<ArrayIndexType>(from.size())); Array<System::Byte> ^ bytes = REF_NEW Vector<System::Byte>(static_cast<ArrayIndexType>(from.size()));
cli::pin_ptr<System::Byte> pinned_ptr = &bytes[0]; cli::pin_ptr<System::Byte> pinned_ptr = &bytes[0];
for (size_t i = 0; i < from.size(); ++i) { for (size_t i = 0; i < from.size(); ++i) {
pinned_ptr[i] = from[i]; pinned_ptr[i] = from[i];
@ -156,6 +157,6 @@ inline String^ string_from_unmanaged(const std::string &from) {
return System::Text::Encoding::UTF8->GetString(bytes); return System::Text::Encoding::UTF8->GetString(bytes);
} }
} // namespace CxCli } // namespace CxCli
#endif #endif

View File

@ -103,7 +103,7 @@ StringBuilder &operator<<(StringBuilder &sb, const PrintFlags &print_flags) {
namespace detail { namespace detail {
class FileFdImpl { class FileFdImpl {
public: public:
PollableFdInfo info; PollableFdInfo info_;
}; };
} // namespace detail } // namespace detail
@ -242,8 +242,8 @@ Result<FileFd> FileFd::open(CSlice filepath, int32 flags, int32 mode) {
FileFd FileFd::from_native_fd(NativeFd native_fd) { FileFd FileFd::from_native_fd(NativeFd native_fd) {
auto impl = make_unique<detail::FileFdImpl>(); auto impl = make_unique<detail::FileFdImpl>();
impl->info.set_native_fd(std::move(native_fd)); impl->info_.set_native_fd(std::move(native_fd));
impl->info.add_flags(PollFlags::Write()); impl->info_.add_flags(PollFlags::Write());
return FileFd(std::move(impl)); return FileFd(std::move(impl));
} }
@ -648,11 +648,11 @@ Status FileFd::truncate_to_current_position(int64 current_position) {
} }
PollableFdInfo &FileFd::get_poll_info() { PollableFdInfo &FileFd::get_poll_info() {
CHECK(!empty()); CHECK(!empty());
return impl_->info; return impl_->info_;
} }
const PollableFdInfo &FileFd::get_poll_info() const { const PollableFdInfo &FileFd::get_poll_info() const {
CHECK(!empty()); CHECK(!empty());
return impl_->info; return impl_->info_;
} }
} // namespace td } // namespace td

View File

@ -43,7 +43,7 @@ namespace detail {
#if TD_PORT_WINDOWS #if TD_PORT_WINDOWS
class SocketFdImpl final : private Iocp::Callback { class SocketFdImpl final : private Iocp::Callback {
public: public:
explicit SocketFdImpl(NativeFd native_fd) : info(std::move(native_fd)) { explicit SocketFdImpl(NativeFd native_fd) : info_(std::move(native_fd)) {
VLOG(fd) << get_native_fd() << " create from native_fd"; VLOG(fd) << get_native_fd() << " create from native_fd";
get_poll_info().add_flags(PollFlags::Write()); get_poll_info().add_flags(PollFlags::Write());
Iocp::get()->subscribe(get_native_fd(), this); Iocp::get()->subscribe(get_native_fd(), this);
@ -51,7 +51,7 @@ class SocketFdImpl final : private Iocp::Callback {
notify_iocp_connected(); notify_iocp_connected();
} }
SocketFdImpl(NativeFd native_fd, const IPAddress &addr) : info(std::move(native_fd)) { SocketFdImpl(NativeFd native_fd, const IPAddress &addr) : info_(std::move(native_fd)) {
VLOG(fd) << get_native_fd() << " create from native_fd and connect"; VLOG(fd) << get_native_fd() << " create from native_fd and connect";
get_poll_info().add_flags(PollFlags::Write()); get_poll_info().add_flags(PollFlags::Write());
Iocp::get()->subscribe(get_native_fd(), this); Iocp::get()->subscribe(get_native_fd(), this);
@ -88,14 +88,14 @@ class SocketFdImpl final : private Iocp::Callback {
} }
PollableFdInfo &get_poll_info() { PollableFdInfo &get_poll_info() {
return info; return info_;
} }
const PollableFdInfo &get_poll_info() const { const PollableFdInfo &get_poll_info() const {
return info; return info_;
} }
const NativeFd &get_native_fd() const { const NativeFd &get_native_fd() const {
return info.native_fd(); return info_.native_fd();
} }
Result<size_t> write(Slice data) { Result<size_t> write(Slice data) {
@ -161,7 +161,7 @@ class SocketFdImpl final : private Iocp::Callback {
} }
private: private:
PollableFdInfo info; PollableFdInfo info_;
SpinLock lock_; SpinLock lock_;
std::atomic<int> refcnt_{1}; std::atomic<int> refcnt_{1};
@ -283,7 +283,12 @@ class SocketFdImpl final : private Iocp::Callback {
if (overlapped == reinterpret_cast<WSAOVERLAPPED *>(&close_overlapped_)) { if (overlapped == reinterpret_cast<WSAOVERLAPPED *>(&close_overlapped_)) {
return on_close(); return on_close();
} }
UNREACHABLE(); LOG(ERROR) << this << ' ' << overlapped << ' ' << &read_overlapped_ << ' ' << &write_overlapped_ << ' '
<< reinterpret_cast<WSAOVERLAPPED *>(&close_overlapped_) << ' ' << size;
LOG(FATAL) << get_native_fd() << ' ' << info_.get_flags_local() << ' ' << refcnt_.load() << ' ' << close_flag_
<< ' ' << need_close_after_write_ << ' ' << is_connected_ << ' ' << is_read_active_ << ' '
<< is_write_active_ << ' ' << is_write_waiting_.load() << ' ' << input_reader_.size() << ' '
<< output_reader_.size();
} }
void on_error(Status status) { void on_error(Status status) {
@ -335,7 +340,7 @@ class SocketFdImpl final : private Iocp::Callback {
void on_close() { void on_close() {
VLOG(fd) << get_native_fd() << " on close"; VLOG(fd) << get_native_fd() << " on close";
close_flag_ = true; close_flag_ = true;
info.set_native_fd({}); info_.set_native_fd({});
} }
bool dec_refcnt() { bool dec_refcnt() {
VLOG(fd) << get_native_fd() << " dec_refcnt from " << refcnt_; VLOG(fd) << get_native_fd() << " dec_refcnt from " << refcnt_;
@ -386,18 +391,18 @@ static InitWSA init_wsa;
#else #else
class SocketFdImpl { class SocketFdImpl {
public: public:
PollableFdInfo info; PollableFdInfo info_;
explicit SocketFdImpl(NativeFd fd) : info(std::move(fd)) { explicit SocketFdImpl(NativeFd fd) : info_(std::move(fd)) {
} }
PollableFdInfo &get_poll_info() { PollableFdInfo &get_poll_info() {
return info; return info_;
} }
const PollableFdInfo &get_poll_info() const { const PollableFdInfo &get_poll_info() const {
return info; return info_;
} }
const NativeFd &get_native_fd() const { const NativeFd &get_native_fd() const {
return info.native_fd(); return info_.native_fd();
} }
Result<size_t> writev(Span<IoSlice> slices) { Result<size_t> writev(Span<IoSlice> slices) {

View File

@ -29,7 +29,7 @@ namespace td {
namespace detail { namespace detail {
class EventFdLinuxImpl { class EventFdLinuxImpl {
public: public:
PollableFdInfo info; PollableFdInfo info_;
}; };
EventFdLinux::EventFdLinux() = default; EventFdLinux::EventFdLinux() = default;
@ -42,7 +42,7 @@ void EventFdLinux::init() {
auto eventfd_errno = errno; auto eventfd_errno = errno;
LOG_IF(FATAL, !fd) << Status::PosixError(eventfd_errno, "eventfd call failed"); LOG_IF(FATAL, !fd) << Status::PosixError(eventfd_errno, "eventfd call failed");
impl_ = make_unique<EventFdLinuxImpl>(); impl_ = make_unique<EventFdLinuxImpl>();
impl_->info.set_native_fd(std::move(fd)); impl_->info_.set_native_fd(std::move(fd));
} }
bool EventFdLinux::empty() { bool EventFdLinux::empty() {
@ -58,14 +58,14 @@ Status EventFdLinux::get_pending_error() {
} }
PollableFdInfo &EventFdLinux::get_poll_info() { PollableFdInfo &EventFdLinux::get_poll_info() {
return impl_->info; return impl_->info_;
} }
// NB: will be called from multiple threads // NB: will be called from multiple threads
void EventFdLinux::release() { void EventFdLinux::release() {
const uint64 value = 1; const uint64 value = 1;
auto slice = Slice(reinterpret_cast<const char *>(&value), sizeof(value)); auto slice = Slice(reinterpret_cast<const char *>(&value), sizeof(value));
auto native_fd = impl_->info.native_fd().fd(); auto native_fd = impl_->info_.native_fd().fd();
auto result = [&]() -> Result<size_t> { auto result = [&]() -> Result<size_t> {
auto write_res = detail::skip_eintr([&] { return write(native_fd, slice.begin(), slice.size()); }); auto write_res = detail::skip_eintr([&] { return write(native_fd, slice.begin(), slice.size()); });
@ -86,7 +86,7 @@ void EventFdLinux::release() {
} }
void EventFdLinux::acquire() { void EventFdLinux::acquire() {
impl_->info.sync_with_poll(); impl_->info_.sync_with_poll();
SCOPE_EXIT { SCOPE_EXIT {
// Clear flags without EAGAIN and EWOULDBLOCK // Clear flags without EAGAIN and EWOULDBLOCK
// Looks like it is safe thing to do with eventfd // Looks like it is safe thing to do with eventfd
@ -94,7 +94,7 @@ void EventFdLinux::acquire() {
}; };
uint64 res; uint64 res;
auto slice = MutableSlice(reinterpret_cast<char *>(&res), sizeof(res)); auto slice = MutableSlice(reinterpret_cast<char *>(&res), sizeof(res));
auto native_fd = impl_->info.native_fd().fd(); auto native_fd = impl_->info_.native_fd().fd();
auto result = [&]() -> Result<size_t> { auto result = [&]() -> Result<size_t> {
CHECK(!slice.empty()); CHECK(!slice.empty());
auto read_res = detail::skip_eintr([&] { return ::read(native_fd, slice.begin(), slice.size()); }); auto read_res = detail::skip_eintr([&] { return ::read(native_fd, slice.begin(), slice.size()); });

View File

@ -40,7 +40,7 @@ class ThreadPthread {
return *this; return *this;
} }
template <class Function, class... Args> template <class Function, class... Args>
explicit ThreadPthread(Function &&f, Args &&... args) { explicit ThreadPthread(Function &&f, Args &&...args) {
auto func = create_destructor([args = std::make_tuple(decay_copy(std::forward<Function>(f)), auto func = create_destructor([args = std::make_tuple(decay_copy(std::forward<Function>(f)),
decay_copy(std::forward<Args>(args))...)]() mutable { decay_copy(std::forward<Args>(args))...)]() mutable {
invoke_tuple(std::move(args)); invoke_tuple(std::move(args));

View File

@ -34,7 +34,7 @@ class ThreadStl {
join(); join();
} }
template <class Function, class... Args> template <class Function, class... Args>
explicit ThreadStl(Function &&f, Args &&... args) { explicit ThreadStl(Function &&f, Args &&...args) {
thread_ = std::thread([args = std::make_tuple(decay_copy(std::forward<Function>(f)), thread_ = std::thread([args = std::make_tuple(decay_copy(std::forward<Function>(f)),
decay_copy(std::forward<Args>(args))...)]() mutable { decay_copy(std::forward<Args>(args))...)]() mutable {
ThreadIdGuard thread_id_guard; ThreadIdGuard thread_id_guard;

View File

@ -29,7 +29,7 @@ namespace td {
// If raw_ptr is not nullptr, allocate T as in std::make_unique<T>(args...) and store pointer into raw_ptr // If raw_ptr is not nullptr, allocate T as in std::make_unique<T>(args...) and store pointer into raw_ptr
template <class T, class P, class... ArgsT> template <class T, class P, class... ArgsT>
bool init_thread_local(P &raw_ptr, ArgsT &&... args); bool init_thread_local(P &raw_ptr, ArgsT &&...args);
// Destroy all thread locals, and store nullptr into corresponding pointers // Destroy all thread locals, and store nullptr into corresponding pointers
void clear_thread_locals(); void clear_thread_locals();
@ -42,7 +42,7 @@ namespace detail {
void add_thread_local_destructor(unique_ptr<Destructor> destructor); void add_thread_local_destructor(unique_ptr<Destructor> destructor);
template <class T, class P, class... ArgsT> template <class T, class P, class... ArgsT>
void do_init_thread_local(P &raw_ptr, ArgsT &&... args) { void do_init_thread_local(P &raw_ptr, ArgsT &&...args) {
auto ptr = std::make_unique<T>(std::forward<ArgsT>(args)...); auto ptr = std::make_unique<T>(std::forward<ArgsT>(args)...);
raw_ptr = ptr.get(); raw_ptr = ptr.get();
@ -54,7 +54,7 @@ void do_init_thread_local(P &raw_ptr, ArgsT &&... args) {
} // namespace detail } // namespace detail
template <class T, class P, class... ArgsT> template <class T, class P, class... ArgsT>
bool init_thread_local(P &raw_ptr, ArgsT &&... args) { bool init_thread_local(P &raw_ptr, ArgsT &&...args) {
if (likely(raw_ptr != nullptr)) { if (likely(raw_ptr != nullptr)) {
return false; return false;
} }

View File

@ -99,7 +99,7 @@ bool operator!=(const unique_ptr<T> &p, std::nullptr_t) {
} }
template <class Type, class... Args> template <class Type, class... Args>
unique_ptr<Type> make_unique(Args &&... args) { unique_ptr<Type> make_unique(Args &&...args) {
return unique_ptr<Type>(new Type(std::forward<Args>(args)...)); return unique_ptr<Type>(new Type(std::forward<Args>(args)...));
} }