diff --git a/benchmark/bench_actor.cpp b/benchmark/bench_actor.cpp index 6f49c7aad..63cc1fca3 100644 --- a/benchmark/bench_actor.cpp +++ b/benchmark/bench_actor.cpp @@ -58,8 +58,7 @@ class RingBench final : public td::Benchmark { } else { // TODO: it is three times faster than send_event // maybe send event could be further optimized? - ::td::Scheduler::instance()->hack(static_cast>(next_actor), - td::Event::raw(static_cast(n - 1))); + next_actor.get_actor_unsafe()->raw_event(td::Event::raw(static_cast(n - 1)).data); } } else if (type == 4) { send_lambda(next_actor, [n, ptr = next_actor.get_actor_unsafe()] { ptr->pass(n - 1); }); diff --git a/benchmark/bench_http_reader.cpp b/benchmark/bench_http_reader.cpp index a37c9718c..3babb748a 100644 --- a/benchmark/bench_http_reader.cpp +++ b/benchmark/bench_http_reader.cpp @@ -22,7 +22,7 @@ class HttpReaderBench final : public td::Benchmark { } void run(int n) final { - int cnt = static_cast(block_size / http_query.size()); + auto cnt = static_cast(block_size / http_query.size()); td::HttpQuery q; int parsed = 0; int sent = 0; @@ -58,7 +58,7 @@ class BufferBench final : public td::Benchmark { } void run(int n) final { - int cnt = static_cast(block_size / http_query.size()); + auto cnt = static_cast(block_size / http_query.size()); for (int i = 0; i < n; i += cnt) { for (int j = 0; j < cnt; j++) { writer_.append(http_query); @@ -84,7 +84,7 @@ class FindBoundaryBench final : public td::Benchmark { } void run(int n) final { - int cnt = static_cast(block_size / http_query.size()); + auto cnt = static_cast(block_size / http_query.size()); for (int i = 0; i < n; i += cnt) { for (int j = 0; j < cnt; j++) { writer_.append(http_query); diff --git a/benchmark/bench_misc.cpp b/benchmark/bench_misc.cpp index f5f57f4d6..148f24de7 100644 --- a/benchmark/bench_misc.cpp +++ b/benchmark/bench_misc.cpp @@ -105,7 +105,8 @@ BENCH(NewObj, "new struct, then delete") { #if !TD_THREAD_UNSUPPORTED BENCH(ThreadNew, "new struct, then delete in 2 threads") { - NewObjBench a, b; + NewObjBench a; + NewObjBench b; td::thread ta([&] { a.run(n / 2); }); td::thread tb([&] { b.run(n - n / 2); }); ta.join(); diff --git a/benchmark/bench_queue.cpp b/benchmark/bench_queue.cpp index 749a37770..f9a724fd3 100644 --- a/benchmark/bench_queue.cpp +++ b/benchmark/bench_queue.cpp @@ -591,7 +591,7 @@ class QueueBenchmark2 final : public td::Benchmark { void server_process(qvalue_t value) { int no = value & 0x00FFFFFF; - int co = static_cast(static_cast(value) >> 24); + auto co = static_cast(static_cast(value) >> 24); // std::fprintf(stderr, "-->%d %d\n", co, no); if (co < 0 || co >= connections_n || no != server_conn[co]++) { std::fprintf(stderr, "%d %d\n", co, no); @@ -632,7 +632,7 @@ class QueueBenchmark2 final : public td::Benchmark { void client_process(qvalue_t value) { int no = value & 0x00FFFFFF; - int co = static_cast(static_cast(value) >> 24); + auto co = static_cast(static_cast(value) >> 24); // std::fprintf(stderr, "<--%d %d\n", co, no); if (co < 0 || co >= connections_n || no != client_conn[co]++) { std::fprintf(stderr, "%d %d\n", co, no); @@ -733,7 +733,7 @@ class QueueBenchmark final : public td::Benchmark { while (active_connections > 0) { qvalue_t value = server.get(); int no = value & 0x00FFFFFF; - int co = static_cast(value >> 24); + auto co = static_cast(value >> 24); // std::fprintf(stderr, "-->%d %d\n", co, no); if (co < 0 || co >= connections_n || no != conn[co]++) { std::fprintf(stderr, "%d %d\n", co, no); @@ -764,7 +764,7 @@ class QueueBenchmark final : public td::Benchmark { while (active_connections > 0) { qvalue_t value = client.get(); int no = value & 0x00FFFFFF; - int co = static_cast(value >> 24); + auto co = static_cast(value >> 24); // std::fprintf(stderr, "<--%d %d\n", co, no); if (co < 0 || co >= connections_n || no != conn[co]++) { std::fprintf(stderr, "%d %d\n", co, no); @@ -797,7 +797,7 @@ class QueueBenchmark final : public td::Benchmark { for (int i = 0; i < connections_n; i++) { qvalue_t value = client.get(); int no = value & 0x00FFFFFF; - int co = static_cast(value >> 24); + auto co = static_cast(value >> 24); // std::fprintf(stderr, "<--%d %d\n", co, no); if (co < 0 || co >= connections_n || no != conn[co]++) { std::fprintf(stderr, "%d %d\n", co, no); diff --git a/example/java/td_jni.cpp b/example/java/td_jni.cpp index 7e2974feb..02d142896 100644 --- a/example/java/td_jni.cpp +++ b/example/java/td_jni.cpp @@ -50,10 +50,10 @@ static jint Client_nativeClientReceive(JNIEnv *env, jclass clazz, jintArray clie auto *manager = get_manager(); auto response = manager->receive(timeout); while (response.object) { - jint client_id = static_cast(response.client_id); + auto client_id = static_cast(response.client_id); env->SetIntArrayRegion(client_ids, result_size, 1, &client_id); - jlong request_id = static_cast(response.request_id); + auto request_id = static_cast(response.request_id); env->SetLongArrayRegion(ids, result_size, 1, &request_id); jobject object; diff --git a/memprof/memprof.cpp b/memprof/memprof.cpp index 7277b0bc5..b33d11943 100644 --- a/memprof/memprof.cpp +++ b/memprof/memprof.cpp @@ -58,7 +58,7 @@ static int fast_backtrace(void **buffer, int size) { void *ip; }; - stack_frame *bp = reinterpret_cast(get_bp()); + auto *bp = reinterpret_cast(get_bp()); int i = 0; while (i < size && #if TD_LINUX @@ -153,7 +153,7 @@ std::size_t get_ht_size() { std::int32_t get_ht_pos(const Backtrace &bt, bool force = false) { auto hash = get_hash(bt); - std::int32_t pos = static_cast(hash % ht.size()); + auto pos = static_cast(hash % ht.size()); bool was_overflow = false; while (true) { auto pos_hash = ht[pos].hash.load(); @@ -237,7 +237,7 @@ static void *malloc_with_frame(std::size_t size, const Backtrace &frame) { } static malloc_info *get_info(void *data_void) { - char *data = static_cast(data_void); + auto *data = static_cast(data_void); auto *buf = data - RESERVED_SIZE; auto *info = reinterpret_cast(buf); diff --git a/td/generate/tl_writer_td.cpp b/td/generate/tl_writer_td.cpp index 0664678bb..08ba92185 100644 --- a/td/generate/tl_writer_td.cpp +++ b/td/generate/tl_writer_td.cpp @@ -261,9 +261,8 @@ std::string TD_TL_writer::gen_constructor_parameter(int field_num, const std::st } else if (field_type == "UInt128 " || field_type == "UInt256 " || field_type == "string " || (string_type == bytes_type && field_type == "bytes ")) { res += field_type + "const &"; - } else if (field_type.compare(0, 5, "array") == 0 || field_type == "bytes ") { - res += field_type + "&&"; - } else if (field_type.compare(0, 10, "object_ptr") == 0) { + } else if (field_type.compare(0, 5, "array") == 0 || field_type == "bytes " || + field_type.compare(0, 10, "object_ptr") == 0) { res += field_type + "&&"; } else { assert(false && "unreachable"); diff --git a/td/mtproto/AuthData.cpp b/td/mtproto/AuthData.cpp index 2dfff4bcd..dedca5031 100644 --- a/td/mtproto/AuthData.cpp +++ b/td/mtproto/AuthData.cpp @@ -78,7 +78,7 @@ bool AuthData::update_server_time_difference(double diff) { } else { return false; } - LOG(DEBUG) << "SERVER_TIME: " << format::as_hex(static_cast(get_server_time(Time::now_cached()))); + LOG(DEBUG) << "SERVER_TIME: " << format::as_hex(static_cast(get_server_time(Time::now_cached()))); return true; } @@ -100,7 +100,7 @@ std::vector AuthData::get_future_salts() const { int64 AuthData::next_message_id(double now) { double server_time = get_server_time(now); - int64 t = static_cast(server_time * (1ll << 32)); + auto t = static_cast(server_time * (1ll << 32)); // randomize lower bits for clocks with low precision // TODO(perf) do not do this for systems with good precision?.. @@ -119,13 +119,13 @@ int64 AuthData::next_message_id(double now) { bool AuthData::is_valid_outbound_msg_id(int64 id, double now) const { double server_time = get_server_time(now); - auto id_time = static_cast(id / (1ll << 32)); - return server_time - 300 / 2 < id_time && id_time < server_time + 60 / 2; + auto id_time = static_cast(id) / static_cast(1ll << 32); + return server_time - 300 / 2 < id_time && id_time < server_time + 30; } bool AuthData::is_valid_inbound_msg_id(int64 id, double now) const { double server_time = get_server_time(now); - auto id_time = static_cast(id / (1ll << 32)); + auto id_time = static_cast(id) / static_cast(1ll << 32); return server_time - 300 < id_time && id_time < server_time + 30; } diff --git a/td/mtproto/ConnectionManager.h b/td/mtproto/ConnectionManager.h index fa5aea92a..ef3926322 100644 --- a/td/mtproto/ConnectionManager.h +++ b/td/mtproto/ConnectionManager.h @@ -24,7 +24,7 @@ class ConnectionManager : public Actor { ConnectionToken(const ConnectionToken &) = delete; ConnectionToken &operator=(const ConnectionToken &) = delete; ConnectionToken(ConnectionToken &&) = default; - ConnectionToken &operator=(ConnectionToken &&other) { + ConnectionToken &operator=(ConnectionToken &&other) noexcept { reset(); connection_manager_ = std::move(other.connection_manager_); return *this; diff --git a/td/mtproto/CryptoStorer.h b/td/mtproto/CryptoStorer.h index 67763c6dc..ead442f7f 100644 --- a/td/mtproto/CryptoStorer.h +++ b/td/mtproto/CryptoStorer.h @@ -192,8 +192,9 @@ class CryptoImpl { public: CryptoImpl(const vector &to_send, Slice header, vector &&to_ack, int64 ping_id, int ping_timeout, int max_delay, int max_after, int max_wait, int future_salt_n, vector get_info, - vector resend, vector cancel, bool destroy_key, AuthData *auth_data, uint64 *container_id, - uint64 *get_info_id, uint64 *resend_id, uint64 *ping_message_id, uint64 *parent_message_id) + vector resend, const vector &cancel, bool destroy_key, AuthData *auth_data, + uint64 *container_id, uint64 *get_info_id, uint64 *resend_id, uint64 *ping_message_id, + uint64 *parent_message_id) : query_storer_(to_send, header) , ack_empty_(to_ack.empty()) , ack_storer_(!ack_empty_, mtproto_api::msgs_ack(std::move(to_ack)), auth_data) @@ -206,7 +207,7 @@ class CryptoImpl { , resend_storer_(resend_not_empty_, mtproto_api::msg_resend_req(std::move(resend)), auth_data, true) , cancel_not_empty_(!cancel.empty()) , cancel_cnt_(static_cast(cancel.size())) - , cancel_storer_(cancel_not_empty_, std::move(cancel), auth_data, true) + , cancel_storer_(cancel_not_empty_, cancel, auth_data, true) , destroy_key_storer_(destroy_key, mtproto_api::destroy_auth_key(), auth_data, true) , tmp_storer_(query_storer_, ack_storer_) , tmp2_storer_(tmp_storer_, http_wait_storer_) diff --git a/td/mtproto/Handshake.cpp b/td/mtproto/Handshake.cpp index 23b32e758..f47d2f8f1 100644 --- a/td/mtproto/Handshake.cpp +++ b/td/mtproto/Handshake.cpp @@ -95,7 +95,8 @@ Status AuthKeyHandshake::on_res_pq(Slice message, Callback *connection, PublicRs } auto rsa_key = r_rsa_key.move_as_ok(); - string p, q; + string p; + string q; if (pq_factorize(res_pq->pq_, &p, &q) == -1) { return Status::Error("Failed to factorize"); } @@ -129,7 +130,7 @@ Status AuthKeyHandshake::on_res_pq(Slice message, Callback *connection, PublicRs string aes_key(32, '\0'); Random::secure_bytes(MutableSlice(aes_key)); - string data_with_hash = data + sha256(aes_key + data); + string data_with_hash = PSTRING() << data << sha256(aes_key + data); std::reverse(data_with_hash.begin(), data_with_hash.begin() + data.size()); string decrypted_data(256, '\0'); @@ -246,17 +247,32 @@ Status AuthKeyHandshake::on_server_dh_params(Slice message, Callback *connection Status AuthKeyHandshake::on_dh_gen_response(Slice message, Callback *connection) { TRY_RESULT(answer, fetch_result(message, false)); switch (answer->get_id()) { - case mtproto_api::dh_gen_ok::ID: + case mtproto_api::dh_gen_ok::ID: { + auto dh_gen_ok = move_tl_object_as(answer); + if (dh_gen_ok->nonce_ != nonce_) { + return Status::Error("Nonce mismatch"); + } + if (dh_gen_ok->server_nonce_ != server_nonce_) { + return Status::Error("Server nonce mismatch"); + } + + UInt<160> auth_key_sha1; + sha1(auth_key_.key(), auth_key_sha1.raw); + auto new_nonce_hash = sha1(PSLICE() << new_nonce_.as_slice() << '\x01' << auth_key_sha1.as_slice().substr(0, 8)); + if (dh_gen_ok->new_nonce_hash1_.as_slice() != Slice(new_nonce_hash).substr(4)) { + return Status::Error("New nonce hash mismatch"); + } state_ = Finish; - break; + return Status::OK(); + } case mtproto_api::dh_gen_fail::ID: return Status::Error("DhGenFail"); case mtproto_api::dh_gen_retry::ID: return Status::Error("DhGenRetry"); default: + UNREACHABLE(); return Status::Error("Unknown set_client_DH_params response"); } - return Status::OK(); } void AuthKeyHandshake::send(Callback *connection, const Storer &storer) { diff --git a/td/mtproto/Handshake.h b/td/mtproto/Handshake.h index 435350d94..b3979ed20 100644 --- a/td/mtproto/Handshake.h +++ b/td/mtproto/Handshake.h @@ -97,7 +97,7 @@ class AuthKeyHandshake { static string store_object(const mtproto_api::Object &object); void send(Callback *connection, const Storer &storer); - void do_send(Callback *connection, const Storer &storer); + static void do_send(Callback *connection, const Storer &storer); Status on_start(Callback *connection) TD_WARN_UNUSED_RESULT; Status on_res_pq(Slice message, Callback *connection, PublicRsaKeyInterface *public_rsa_key) TD_WARN_UNUSED_RESULT; diff --git a/td/mtproto/HandshakeConnection.h b/td/mtproto/HandshakeConnection.h index f7760ce05..49ef722b0 100644 --- a/td/mtproto/HandshakeConnection.h +++ b/td/mtproto/HandshakeConnection.h @@ -65,7 +65,7 @@ class HandshakeConnection final } Status on_raw_packet(const PacketInfo &packet_info, BufferSlice packet) final { - if (packet_info.no_crypto_flag == false) { + if (!packet_info.no_crypto_flag) { return Status::Error("Expected not encrypted packet"); } diff --git a/td/mtproto/Ping.cpp b/td/mtproto/Ping.cpp index b3dadcc7c..f92368c50 100644 --- a/td/mtproto/Ping.cpp +++ b/td/mtproto/Ping.cpp @@ -19,7 +19,7 @@ namespace td { namespace mtproto { -ActorOwn<> create_ping_actor(string debug, unique_ptr raw_connection, unique_ptr auth_data, +ActorOwn<> create_ping_actor(Slice actor_name, unique_ptr raw_connection, unique_ptr auth_data, Promise> promise, ActorShared<> parent) { class PingActor final : public Actor { public: @@ -99,7 +99,7 @@ ActorOwn<> create_ping_actor(string debug, unique_ptr raw_connect } } }; - return ActorOwn<>(create_actor(PSLICE() << "PingActor<" << debug << ">", std::move(raw_connection), + return ActorOwn<>(create_actor(PSLICE() << "PingActor<" << actor_name << ">", std::move(raw_connection), std::move(auth_data), std::move(promise), std::move(parent))); } diff --git a/td/mtproto/Ping.h b/td/mtproto/Ping.h index 7dc9aa4e0..25aded068 100644 --- a/td/mtproto/Ping.h +++ b/td/mtproto/Ping.h @@ -17,7 +17,7 @@ namespace td { namespace mtproto { -ActorOwn<> create_ping_actor(string debug, unique_ptr raw_connection, unique_ptr auth_data, +ActorOwn<> create_ping_actor(Slice actor_name, unique_ptr raw_connection, unique_ptr auth_data, Promise> promise, ActorShared<> parent); } // namespace mtproto diff --git a/td/mtproto/RawConnection.cpp b/td/mtproto/RawConnection.cpp index d26f48a1d..2e4ec5dad 100644 --- a/td/mtproto/RawConnection.cpp +++ b/td/mtproto/RawConnection.cpp @@ -37,7 +37,7 @@ class RawConnectionDefault final : public RawConnection { public: RawConnectionDefault(SocketFd socket_fd, TransportType transport_type, unique_ptr stats_callback) : socket_fd_(std::move(socket_fd)) - , transport_(create_transport(transport_type)) + , transport_(create_transport(std::move(transport_type))) , stats_callback_(std::move(stats_callback)) { transport_->init(&socket_fd_.input_buffer(), &socket_fd_.output_buffer()); } diff --git a/td/mtproto/RawConnection.h b/td/mtproto/RawConnection.h index 1afd78372..98cee88e0 100644 --- a/td/mtproto/RawConnection.h +++ b/td/mtproto/RawConnection.h @@ -48,7 +48,7 @@ class RawConnection { virtual bool can_send() const = 0; virtual TransportType get_transport_type() const = 0; virtual void send_crypto(const Storer &storer, int64 session_id, int64 salt, const AuthKey &auth_key, - uint64 quick_ack_token = 0) = 0; + uint64 quick_ack_token) = 0; virtual uint64 send_no_crypto(const Storer &storer) = 0; virtual PollableFdInfo &get_poll_info() = 0; diff --git a/td/mtproto/SessionConnection.cpp b/td/mtproto/SessionConnection.cpp index 228edae56..f69d01c11 100644 --- a/td/mtproto/SessionConnection.cpp +++ b/td/mtproto/SessionConnection.cpp @@ -893,7 +893,8 @@ void SessionConnection::flush_packet() { } } - size_t send_till = 0, send_size = 0; + size_t send_till = 0; + size_t send_size = 0; // send at most 1020 queries, of total size 2^15 // don't send anything if have no salt if (has_salt) { diff --git a/td/mtproto/SessionConnection.h b/td/mtproto/SessionConnection.h index 3da23a4fc..3661378b5 100644 --- a/td/mtproto/SessionConnection.h +++ b/td/mtproto/SessionConnection.h @@ -212,7 +212,8 @@ class SessionConnection final }; } - Status parse_message(TlParser &parser, MsgInfo *info, Slice *packet, bool crypto_flag = true) TD_WARN_UNUSED_RESULT; + static Status parse_message(TlParser &parser, MsgInfo *info, Slice *packet, + bool crypto_flag = true) TD_WARN_UNUSED_RESULT; Status parse_packet(TlParser &parser) TD_WARN_UNUSED_RESULT; Status on_packet_container(const MsgInfo &info, Slice packet) TD_WARN_UNUSED_RESULT; Status on_packet_rpc_result(const MsgInfo &info, Slice packet) TD_WARN_UNUSED_RESULT; diff --git a/td/mtproto/TcpTransport.cpp b/td/mtproto/TcpTransport.cpp index 98760aa1e..2570403dd 100644 --- a/td/mtproto/TcpTransport.cpp +++ b/td/mtproto/TcpTransport.cpp @@ -272,8 +272,8 @@ void ObfuscatedTransport::do_write_tls(BufferBuilder &&builder) { do_write(builder.extract()); } -void ObfuscatedTransport::do_write(BufferSlice &&slice) { - output_->append(std::move(slice)); +void ObfuscatedTransport::do_write(BufferSlice &&message) { + output_->append(std::move(message)); } } // namespace tcp diff --git a/td/mtproto/TcpTransport.h b/td/mtproto/TcpTransport.h index 2d188bbd8..4a2b918d9 100644 --- a/td/mtproto/TcpTransport.h +++ b/td/mtproto/TcpTransport.h @@ -128,8 +128,8 @@ class OldTransport final : public IStreamTransport { class ObfuscatedTransport final : public IStreamTransport { public: - ObfuscatedTransport(int16 dc_id, const ProxySecret &secret) - : dc_id_(dc_id), secret_(secret), impl_(secret_.use_random_padding()) { + ObfuscatedTransport(int16 dc_id, ProxySecret secret) + : dc_id_(dc_id), secret_(std::move(secret)), impl_(secret_.use_random_padding()) { } Result read_next(BufferSlice *message, uint32 *quick_ack) final TD_WARN_UNUSED_RESULT; @@ -172,6 +172,7 @@ class ObfuscatedTransport final : public IStreamTransport { TransportType get_type() const final { return TransportType{TransportType::ObfuscatedTcp, dc_id_, secret_}; } + bool use_random_padding() const final { return secret_.use_random_padding(); } diff --git a/td/telegram/AuthManager.cpp b/td/telegram/AuthManager.cpp index ed1b9634e..e2a6f39e1 100644 --- a/td/telegram/AuthManager.cpp +++ b/td/telegram/AuthManager.cpp @@ -162,7 +162,7 @@ void AuthManager::check_bot_token(uint64 query_id, string bot_token) { } on_new_query(query_id); - bot_token_ = bot_token; + bot_token_ = std::move(bot_token); was_check_bot_token_ = true; start_net_query(NetQueryType::BotAuthentication, G()->net_query_creator().create_unauth( @@ -258,8 +258,8 @@ void AuthManager::set_phone_number(uint64 query_id, string phone_number, on_new_query(query_id); - start_net_query(NetQueryType::SendCode, G()->net_query_creator().create_unauth( - send_code_helper_.send_code(phone_number, settings, api_id_, api_hash_))); + start_net_query(NetQueryType::SendCode, G()->net_query_creator().create_unauth(send_code_helper_.send_code( + std::move(phone_number), settings, api_id_, api_hash_))); } void AuthManager::resend_authentication_code(uint64 query_id) { @@ -425,8 +425,8 @@ void AuthManager::on_query_error(Status status) { on_query_error(id, std::move(status)); } -void AuthManager::on_query_error(uint64 id, Status status) { - send_closure(G()->td(), &Td::send_error, id, std::move(status)); +void AuthManager::on_query_error(uint64 query_id, Status status) { + send_closure(G()->td(), &Td::send_error, query_id, std::move(status)); } void AuthManager::on_query_ok() { diff --git a/td/telegram/AuthManager.h b/td/telegram/AuthManager.h index d1850f508..cdff296c6 100644 --- a/td/telegram/AuthManager.h +++ b/td/telegram/AuthManager.h @@ -126,15 +126,16 @@ class AuthManager final : public NetActor { TermsOfService terms_of_service_; DbState() = default; + static DbState wait_code(int32 api_id, string api_hash, SendCodeHelper send_code_helper) { - DbState state(State::WaitCode, api_id, api_hash); + DbState state(State::WaitCode, api_id, std::move(api_hash)); state.send_code_helper_ = std::move(send_code_helper); return state; } static DbState wait_qr_code_confirmation(int32 api_id, string api_hash, vector other_user_ids, string login_token, double login_token_expires_at) { - DbState state(State::WaitQrCodeConfirmation, api_id, api_hash); + DbState state(State::WaitQrCodeConfirmation, api_id, std::move(api_hash)); state.other_user_ids_ = std::move(other_user_ids); state.login_token_ = std::move(login_token); state.login_token_expires_at_ = login_token_expires_at; @@ -142,14 +143,14 @@ class AuthManager final : public NetActor { } static DbState wait_password(int32 api_id, string api_hash, WaitPasswordState wait_password_state) { - DbState state(State::WaitPassword, api_id, api_hash); + DbState state(State::WaitPassword, api_id, std::move(api_hash)); state.wait_password_state_ = std::move(wait_password_state); return state; } static DbState wait_registration(int32 api_id, string api_hash, SendCodeHelper send_code_helper, TermsOfService terms_of_service) { - DbState state(State::WaitRegistration, api_id, api_hash); + DbState state(State::WaitRegistration, api_id, std::move(api_hash)); state.send_code_helper_ = std::move(send_code_helper); state.terms_of_service_ = std::move(terms_of_service); return state; @@ -161,8 +162,8 @@ class AuthManager final : public NetActor { void parse(ParserT &parser); private: - DbState(State state, int32 api_id, string api_hash) - : state_(state), api_id_(api_id), api_hash_(api_hash), state_timestamp_(Timestamp::now()) { + DbState(State state, int32 api_id, string &&api_hash) + : state_(state), api_id_(api_id), api_hash_(std::move(api_hash)), state_timestamp_(Timestamp::now()) { } }; @@ -216,7 +217,6 @@ class AuthManager final : public NetActor { void on_new_query(uint64 query_id); void on_query_error(Status status); - void on_query_error(uint64 id, Status status); void on_query_ok(); void start_net_query(NetQueryType net_query_type, NetQueryPtr net_query); @@ -232,7 +232,7 @@ class AuthManager final : public NetActor { void on_get_password_result(NetQueryPtr &result); void on_request_password_recovery_result(NetQueryPtr &result); void on_check_password_recovery_code_result(NetQueryPtr &result); - void on_authentication_result(NetQueryPtr &result, bool expected_flag); + void on_authentication_result(NetQueryPtr &result, bool is_from_current_query); void on_log_out_result(NetQueryPtr &result); void on_delete_account_result(NetQueryPtr &result); void on_get_login_token(tl_object_ptr login_token); @@ -242,7 +242,9 @@ class AuthManager final : public NetActor { void update_state(State new_state, bool force = false, bool should_save_state = true); tl_object_ptr get_authorization_state_object(State authorization_state) const; - void send_ok(uint64 query_id); + + static void send_ok(uint64 query_id); + static void on_query_error(uint64 query_id, Status status); void start_up() final; void tear_down() final; diff --git a/td/telegram/BackgroundManager.cpp b/td/telegram/BackgroundManager.cpp index f6603a995..3d8f5bc5c 100644 --- a/td/telegram/BackgroundManager.cpp +++ b/td/telegram/BackgroundManager.cpp @@ -453,7 +453,7 @@ void BackgroundManager::get_backgrounds(bool for_dark_theme, } Result BackgroundManager::get_background_url(const string &name, - td_api::object_ptr background_type) const { + td_api::object_ptr background_type) { TRY_RESULT(type, BackgroundType::get_background_type(background_type.get())); auto url = PSTRING() << G()->shared_config().get_option_string("t_me_url", "https://t.me/") << "bg/"; auto link = type.get_link(); @@ -526,7 +526,7 @@ std::pair BackgroundManager::search_background(con if (queries.size() == 1) { LOG(INFO) << "Trying to load background " << slug << " from database"; G()->td_db()->get_sqlite_pmc()->get( - get_background_name_database_key(slug), PromiseCreator::lambda([slug](string value) { + get_background_name_database_key(slug), PromiseCreator::lambda([slug](string value) mutable { send_closure(G()->background_manager(), &BackgroundManager::on_load_background_from_database, std::move(slug), std::move(value)); })); @@ -563,7 +563,7 @@ void BackgroundManager::on_load_background_from_database(string name, string val } else { if (background.name != name) { LOG(ERROR) << "Expected background " << name << ", but received " << background.name; - name_to_background_id_.emplace(name, background.id); + name_to_background_id_.emplace(std::move(name), background.id); } add_background(background, false); } diff --git a/td/telegram/BackgroundManager.h b/td/telegram/BackgroundManager.h index dedada376..8a7b74df9 100644 --- a/td/telegram/BackgroundManager.h +++ b/td/telegram/BackgroundManager.h @@ -38,8 +38,8 @@ class BackgroundManager final : public Actor { void get_backgrounds(bool for_dark_theme, Promise> &&promise); - Result get_background_url(const string &name, - td_api::object_ptr background_type) const; + static Result get_background_url(const string &name, + td_api::object_ptr background_type); void reload_background(BackgroundId background_id, int64 access_hash, Promise &&promise); diff --git a/td/telegram/BackgroundType.cpp b/td/telegram/BackgroundType.cpp index ef0b8f8d5..8bda298ae 100644 --- a/td/telegram/BackgroundType.cpp +++ b/td/telegram/BackgroundType.cpp @@ -222,7 +222,7 @@ bool BackgroundFill::is_dark() const { (fourth_color_ == -1 || (fourth_color_ & 0x808080) == 0); default: UNREACHABLE(); - return 0; + return false; } } diff --git a/td/telegram/CallActor.cpp b/td/telegram/CallActor.cpp index 259d00a45..225ac6605 100644 --- a/td/telegram/CallActor.cpp +++ b/td/telegram/CallActor.cpp @@ -457,7 +457,7 @@ void CallActor::on_begin_exchanging_key() { call_state_.type = CallState::Type::ExchangingKey; call_state_need_flush_ = true; int64 call_receive_timeout_ms = G()->shared_config().get_option_integer("call_receive_timeout_ms", 20000); - double timeout = static_cast(call_receive_timeout_ms) * 0.001; + auto timeout = static_cast(call_receive_timeout_ms) * 0.001; LOG(INFO) << "Set call timeout to " << timeout; set_timeout_in(timeout); } @@ -484,7 +484,7 @@ Status CallActor::do_update_call(telegram_api::phoneCall &call) { get_emojis_fingerprint(call_state_.key, is_outgoing_ ? dh_handshake_.get_g_b() : dh_handshake_.get_g_a()); for (auto &connection : call.connections_) { - call_state_.connections.push_back(CallConnection(*connection)); + call_state_.connections.emplace_back(*connection); } call_state_.protocol = CallProtocol(*call.protocol_); call_state_.allow_p2p = (call.flags_ & telegram_api::phoneCall::P2P_ALLOWED_MASK) != 0; @@ -636,7 +636,7 @@ void CallActor::try_send_request_query() { auto query = G()->net_query_creator().create(tl_query); state_ = State::WaitRequestResult; int64 call_receive_timeout_ms = G()->shared_config().get_option_integer("call_receive_timeout_ms", 20000); - double timeout = static_cast(call_receive_timeout_ms) * 0.001; + auto timeout = static_cast(call_receive_timeout_ms) * 0.001; LOG(INFO) << "Set call timeout to " << timeout; set_timeout_in(timeout); query->total_timeout_limit_ = max(timeout, 10.0); diff --git a/td/telegram/CallActor.h b/td/telegram/CallActor.h index ae67b73ae..c4d255d55 100644 --- a/td/telegram/CallActor.h +++ b/td/telegram/CallActor.h @@ -70,7 +70,7 @@ struct CallState { enum class Type : int32 { Empty, Pending, ExchangingKey, Ready, HangingUp, Discarded, Error } type{Type::Empty}; CallProtocol protocol; - std::vector connections; + vector connections; CallDiscardReason discard_reason{CallDiscardReason::Empty}; bool is_created{false}; bool is_received{false}; diff --git a/td/telegram/CallbackQueriesManager.cpp b/td/telegram/CallbackQueriesManager.cpp index 9b72b10cf..825674359 100644 --- a/td/telegram/CallbackQueriesManager.cpp +++ b/td/telegram/CallbackQueriesManager.cpp @@ -79,7 +79,9 @@ class GetBotCallbackAnswerQuery final : public Td::ResultHandler { return on_error(id, result_ptr.move_as_error()); } - td->callback_queries_manager_->on_get_callback_query_answer(result_ptr.move_as_ok(), std::move(promise_)); + auto answer = result_ptr.move_as_ok(); + bool show_alert = (answer->flags_ & telegram_api::messages_botCallbackAnswer::ALERT_MASK) != 0; + promise_.set_value(td_api::make_object(answer->message_, show_alert, answer->url_)); } void on_error(uint64 id, Status status) final { @@ -288,12 +290,4 @@ void CallbackQueriesManager::send_get_callback_answer_query( ->send(dialog_id, full_message_id.get_message_id(), payload, std::move(password)); } -void CallbackQueriesManager::on_get_callback_query_answer( - tl_object_ptr &&answer, - Promise> &&promise) { - CHECK(answer != nullptr); - bool show_alert = (answer->flags_ & BOT_CALLBACK_ANSWER_FLAG_NEED_SHOW_ALERT) != 0; - promise.set_value(td_api::make_object(answer->message_, show_alert, answer->url_)); -} - } // namespace td diff --git a/td/telegram/CallbackQueriesManager.h b/td/telegram/CallbackQueriesManager.h index f20c75fbb..cbde7fc78 100644 --- a/td/telegram/CallbackQueriesManager.h +++ b/td/telegram/CallbackQueriesManager.h @@ -42,16 +42,13 @@ class CallbackQueriesManager { void send_callback_query(FullMessageId full_message_id, tl_object_ptr &&payload, Promise> &&promise); - void on_get_callback_query_answer(tl_object_ptr &&answer, - Promise> &&promise); - private: static constexpr int32 BOT_CALLBACK_ANSWER_FLAG_HAS_MESSAGE = 1 << 0; static constexpr int32 BOT_CALLBACK_ANSWER_FLAG_NEED_SHOW_ALERT = 1 << 1; static constexpr int32 BOT_CALLBACK_ANSWER_FLAG_HAS_URL = 1 << 2; - tl_object_ptr get_query_payload(int32 flags, BufferSlice &&data, - string &&game_short_name); + static tl_object_ptr get_query_payload(int32 flags, BufferSlice &&data, + string &&game_short_name); void send_get_callback_answer_query(FullMessageId full_message_id, tl_object_ptr &&payload, diff --git a/td/telegram/Client.cpp b/td/telegram/Client.cpp index fdf5ce431..d670854c6 100644 --- a/td/telegram/Client.cpp +++ b/td/telegram/Client.cpp @@ -640,9 +640,9 @@ Client::Response Client::execute(Request &&request) { return response; } +Client::Client(Client &&other) noexcept = default; +Client &Client::operator=(Client &&other) noexcept = default; Client::~Client() = default; -Client::Client(Client &&other) = default; -Client &Client::operator=(Client &&other) = default; ClientManager::ClientManager() : impl_(std::make_unique()) { } @@ -682,9 +682,9 @@ void ClientManager::set_log_message_callback(int max_verbosity_level, LogMessage } } +ClientManager::ClientManager(ClientManager &&other) noexcept = default; +ClientManager &ClientManager::operator=(ClientManager &&other) noexcept = default; ClientManager::~ClientManager() = default; -ClientManager::ClientManager(ClientManager &&other) = default; -ClientManager &ClientManager::operator=(ClientManager &&other) = default; ClientManager *ClientManager::get_manager_singleton() { static ClientManager client_manager; diff --git a/td/telegram/Client.h b/td/telegram/Client.h index e811b5475..1e3bc2962 100644 --- a/td/telegram/Client.h +++ b/td/telegram/Client.h @@ -119,12 +119,12 @@ class Client final { /** * Move constructor. */ - Client(Client &&other); + Client(Client &&other) noexcept; /** * Move assignment operator. */ - Client &operator=(Client &&other); + Client &operator=(Client &&other) noexcept; private: class Impl; @@ -267,12 +267,12 @@ class ClientManager final { /** * Move constructor. */ - ClientManager(ClientManager &&other); + ClientManager(ClientManager &&other) noexcept; /** * Move assignment operator. */ - ClientManager &operator=(ClientManager &&other); + ClientManager &operator=(ClientManager &&other) noexcept; /** * Returns a pointer to a singleton ClientManager instance. diff --git a/td/telegram/ClientActor.cpp b/td/telegram/ClientActor.cpp index 746363e9f..9352e5d0d 100644 --- a/td/telegram/ClientActor.cpp +++ b/td/telegram/ClientActor.cpp @@ -26,9 +26,9 @@ void ClientActor::request(uint64 id, td_api::object_ptr reques ClientActor::~ClientActor() = default; -ClientActor::ClientActor(ClientActor &&other) = default; +ClientActor::ClientActor(ClientActor &&other) noexcept = default; -ClientActor &ClientActor::operator=(ClientActor &&other) = default; +ClientActor &ClientActor::operator=(ClientActor &&other) noexcept = default; td_api::object_ptr ClientActor::execute(td_api::object_ptr request) { return Td::static_request(std::move(request)); diff --git a/td/telegram/ClientActor.h b/td/telegram/ClientActor.h index 1d6c52c72..90ad5cae1 100644 --- a/td/telegram/ClientActor.h +++ b/td/telegram/ClientActor.h @@ -64,19 +64,20 @@ class ClientActor final : public Actor { /** * Destroys the ClientActor and the TDLib instance. */ - ~ClientActor(); + ~ClientActor() final; /** * Move constructor. */ - ClientActor(ClientActor &&other); + ClientActor(ClientActor &&other) noexcept; /** * Move assignment operator. */ - ClientActor &operator=(ClientActor &&other); + ClientActor &operator=(ClientActor &&other) noexcept; ClientActor(const ClientActor &other) = delete; + ClientActor &operator=(const ClientActor &other) = delete; private: diff --git a/td/telegram/ConfigManager.cpp b/td/telegram/ConfigManager.cpp index cf85c2f7d..90ac22b3c 100644 --- a/td/telegram/ConfigManager.cpp +++ b/td/telegram/ConfigManager.cpp @@ -379,7 +379,8 @@ ActorOwn<> get_simple_config_firebase_firestore(Promise prom prefer_ipv6, std::move(get_config)); } -ActorOwn<> get_full_config(DcOption option, Promise promise, ActorShared<> parent) { +static ActorOwn<> get_full_config(DcOption option, Promise> promise, + ActorShared<> parent) { class SessionCallback final : public Session::Callback { public: SessionCallback(ActorShared<> parent, DcOption option) : parent_(std::move(parent)), option_(std::move(option)) { @@ -496,7 +497,7 @@ ActorOwn<> get_full_config(DcOption option, Promise promise, ActorSh class GetConfigActor final : public NetQueryCallback { public: - GetConfigActor(DcOption option, Promise promise, ActorShared<> parent) + GetConfigActor(DcOption option, Promise> promise, ActorShared<> parent) : option_(std::move(option)), promise_(std::move(promise)), parent_(std::move(parent)) { } @@ -542,11 +543,12 @@ ActorOwn<> get_full_config(DcOption option, Promise promise, ActorSh DcOption option_; ActorOwn session_; - Promise promise_; + Promise> promise_; ActorShared<> parent_; }; - return ActorOwn<>(create_actor("GetConfigActor", option, std::move(promise), std::move(parent))); + return ActorOwn<>( + create_actor("GetConfigActor", std::move(option), std::move(promise), std::move(parent))); } class ConfigRecoverer final : public Actor { @@ -556,7 +558,7 @@ class ConfigRecoverer final : public Actor { } void on_dc_options_update(DcOptions dc_options) { - dc_options_update_ = dc_options; + dc_options_update_ = std::move(dc_options); update_dc_options(); loop(); } @@ -676,22 +678,22 @@ class ConfigRecoverer final : public Actor { } } - void on_full_config(Result r_full_config, bool dummy) { + void on_full_config(Result> r_full_config, bool dummy) { full_config_query_.reset(); if (r_full_config.is_ok()) { full_config_ = r_full_config.move_as_ok(); - VLOG(config_recoverer) << "Got FullConfig " << to_string(full_config_); + VLOG(config_recoverer) << "Receive " << to_string(full_config_); full_config_expires_at_ = get_config_expire_time(); send_closure(G()->connection_creator(), &ConnectionCreator::on_dc_options, DcOptions(full_config_->dc_options_)); } else { - VLOG(config_recoverer) << "Get FullConfig error " << r_full_config.error(); - full_config_ = FullConfig(); + VLOG(config_recoverer) << "Failed to get config: " << r_full_config.error(); + full_config_ = nullptr; full_config_expires_at_ = get_failed_config_expire_time(); } loop(); } - bool expect_blocking() const { + static bool expect_blocking() { return G()->shared_config().get_option_boolean("expect_blocking", true); } @@ -729,7 +731,7 @@ class ConfigRecoverer final : public Actor { size_t date_option_i_{0}; - FullConfig full_config_; + tl_object_ptr full_config_; double full_config_expires_at_{0}; ActorOwn<> full_config_query_; @@ -760,6 +762,7 @@ class ConfigRecoverer final : public Actor { double max_connecting_delay() const { return expect_blocking() ? 5 : 20; } + void loop() final { if (close_flag_) { return; @@ -829,12 +832,13 @@ class ConfigRecoverer final : public Actor { if (need_full_config) { ref_cnt_++; VLOG(config_recoverer) << "Ask full config with dc_options_i_ = " << dc_options_i_; - full_config_query_ = - get_full_config(dc_options_.dc_options[dc_options_i_], - PromiseCreator::lambda([actor_id = actor_id(this)](Result r_full_config) { - send_closure(actor_id, &ConfigRecoverer::on_full_config, std::move(r_full_config), false); - }), - actor_shared(this)); + full_config_query_ = get_full_config( + dc_options_.dc_options[dc_options_i_], + PromiseCreator::lambda( + [actor_id = actor_id(this)](Result> r_full_config) { + send_closure(actor_id, &ConfigRecoverer::on_full_config, std::move(r_full_config), false); + }), + actor_shared(this)); dc_options_i_ = (dc_options_i_ + 1) % dc_options_.dc_options.size(); } @@ -1041,13 +1045,12 @@ void ConfigManager::set_archive_and_mute(bool archive_and_mute, Promise && void ConfigManager::on_dc_options_update(DcOptions dc_options) { save_dc_options_update(dc_options); - send_closure(config_recoverer_, &ConfigRecoverer::on_dc_options_update, std::move(dc_options)); - if (dc_options.dc_options.empty()) { - return; + if (!dc_options.dc_options.empty()) { + expire_time_ = Timestamp::now(); + save_config_expire(expire_time_); + set_timeout_in(expire_time_.in()); } - expire_time_ = Timestamp::now(); - save_config_expire(expire_time_); - set_timeout_in(expire_time_.in()); + send_closure(config_recoverer_, &ConfigRecoverer::on_dc_options_update, std::move(dc_options)); } void ConfigManager::request_config_from_dc_impl(DcId dc_id) { @@ -1283,7 +1286,7 @@ void ConfigManager::on_result(NetQueryPtr res) { } } -void ConfigManager::save_dc_options_update(DcOptions dc_options) { +void ConfigManager::save_dc_options_update(const DcOptions &dc_options) { if (dc_options.dc_options.empty()) { G()->td_db()->get_binlog_pmc()->erase("dc_options_update"); return; diff --git a/td/telegram/ConfigManager.h b/td/telegram/ConfigManager.h index 65caf655b..48662c48e 100644 --- a/td/telegram/ConfigManager.h +++ b/td/telegram/ConfigManager.h @@ -78,10 +78,6 @@ class HttpDate { static Result parse_http_date(std::string slice); }; -using FullConfig = tl_object_ptr; - -ActorOwn<> get_full_config(DcId dc_id, IPAddress ip_address, Promise promise); - class ConfigRecoverer; class ConfigManager final : public NetQueryCallback { public: @@ -155,7 +151,7 @@ class ConfigManager final : public NetQueryCallback { static Timestamp load_config_expire_time(); static void save_config_expire(Timestamp timestamp); - static void save_dc_options_update(DcOptions dc_options); + static void save_dc_options_update(const DcOptions &dc_options); static DcOptions load_dc_options_update(); ActorShared<> create_reference(); diff --git a/td/telegram/ConfigShared.cpp b/td/telegram/ConfigShared.cpp index da72c7a93..b821f69e9 100644 --- a/td/telegram/ConfigShared.cpp +++ b/td/telegram/ConfigShared.cpp @@ -23,7 +23,7 @@ void ConfigShared::set_callback(unique_ptr callback) { return; } - for (auto key_value : config_pmc_->get_all()) { + for (const auto &key_value : config_pmc_->get_all()) { on_option_updated(key_value.first); } } diff --git a/td/telegram/ContactsManager.cpp b/td/telegram/ContactsManager.cpp index 78449fca0..5cf2b5d13 100644 --- a/td/telegram/ContactsManager.cpp +++ b/td/telegram/ContactsManager.cpp @@ -581,7 +581,7 @@ class ImportContactsQuery final : public Td::ResultHandler { return promise_.set_error(Status::Error(429, "Too Many Requests: retry after 3600")); } - int64 total_size = static_cast(input_contacts_.size()); + auto total_size = static_cast(input_contacts_.size()); vector> contacts; contacts.reserve(ptr->retry_contacts_.size()); for (auto &client_id : ptr->retry_contacts_) { @@ -589,7 +589,7 @@ class ImportContactsQuery final : public Td::ResultHandler { LOG(ERROR) << "Wrong client_id " << client_id << " returned"; continue; } - size_t i = static_cast(client_id); + auto i = static_cast(client_id); contacts.push_back(input_contacts_[i].get_input_phone_contact(client_id)); } @@ -2272,7 +2272,8 @@ class EditChannelAdminQuery final : public Td::ResultHandler { explicit EditChannelAdminQuery(Promise &&promise) : promise_(std::move(promise)) { } - void send(ChannelId channel_id, tl_object_ptr &&input_user, DialogParticipantStatus status) { + void send(ChannelId channel_id, tl_object_ptr &&input_user, + const DialogParticipantStatus &status) { channel_id_ = channel_id; auto input_channel = td->contacts_manager_->get_input_channel(channel_id); CHECK(input_channel != nullptr); @@ -2307,7 +2308,8 @@ class EditChannelBannedQuery final : public Td::ResultHandler { explicit EditChannelBannedQuery(Promise &&promise) : promise_(std::move(promise)) { } - void send(ChannelId channel_id, tl_object_ptr &&input_peer, DialogParticipantStatus status) { + void send(ChannelId channel_id, tl_object_ptr &&input_peer, + const DialogParticipantStatus &status) { channel_id_ = channel_id; auto input_channel = td->contacts_manager_->get_input_channel(channel_id); CHECK(input_channel != nullptr); @@ -2686,7 +2688,7 @@ class GetUserPhotosQuery final : public Td::ResultHandler { auto photos = move_tl_object_as(ptr); td->contacts_manager_->on_get_users(std::move(photos->users_), "GetUserPhotosQuery"); - int32 photos_size = narrow_cast(photos->photos_.size()); + auto photos_size = narrow_cast(photos->photos_.size()); td->contacts_manager_->on_get_user_photos(user_id_, offset_, limit_, photos_size, std::move(photos->photos_)); } else { CHECK(constructor_id == telegram_api::photos_photosSlice::ID); @@ -2925,7 +2927,7 @@ class GetChannelParticipantsQuery final : public Td::ResultHandler { : promise_(std::move(promise)) { } - void send(ChannelId channel_id, ChannelParticipantsFilter filter, int32 offset, int32 limit) { + void send(ChannelId channel_id, const ChannelParticipantsFilter &filter, int32 offset, int32 limit) { auto input_channel = td->contacts_manager_->get_input_channel(channel_id); if (input_channel == nullptr) { return promise_.set_error(Status::Error(400, "Supergroup not found")); @@ -5182,7 +5184,7 @@ td_api::object_ptr ContactsManager::convert_authorization_objec authorization->country_, authorization->region_); } -void ContactsManager::confirm_qr_code_authentication(string link, +void ContactsManager::confirm_qr_code_authentication(const string &link, Promise> &&promise) { Slice prefix("tg://login?token="); if (!begins_with(to_lower(link), prefix)) { @@ -5373,7 +5375,7 @@ std::pair, vector> ContactsManager::import_contacts(const return {}; } -void ContactsManager::remove_contacts(vector user_ids, Promise &&promise) { +void ContactsManager::remove_contacts(const vector &user_ids, Promise &&promise) { LOG(INFO) << "Delete contacts: " << format::as_array(user_ids); if (!are_contacts_loaded_) { load_contacts(std::move(promise)); @@ -5587,7 +5589,7 @@ std::pair, vector> ContactsManager::change_imported_contac std::pair, vector> to_add; for (auto &new_contact : different_new_contacts) { to_add.first.push_back(new_contact.second); - to_add.second.push_back(std::move(new_contact.first)); + to_add.second.push_back(new_contact.first); } if (to_add.first.empty() && to_delete.empty()) { @@ -6671,16 +6673,16 @@ void ContactsManager::send_get_channel_message_stats_query( ->send(dialog_id.get_channel_id(), full_message_id.get_message_id(), is_dark, dc_id); } -void ContactsManager::load_statistics_graph(DialogId dialog_id, const string &token, int64 x, +void ContactsManager::load_statistics_graph(DialogId dialog_id, string token, int64 x, Promise> &&promise) { - auto dc_id_promise = PromiseCreator::lambda( - [actor_id = actor_id(this), token, x, promise = std::move(promise)](Result r_dc_id) mutable { - if (r_dc_id.is_error()) { - return promise.set_error(r_dc_id.move_as_error()); - } - send_closure(actor_id, &ContactsManager::send_load_async_graph_query, r_dc_id.move_as_ok(), std::move(token), x, - std::move(promise)); - }); + auto dc_id_promise = PromiseCreator::lambda([actor_id = actor_id(this), token = std::move(token), x, + promise = std::move(promise)](Result r_dc_id) mutable { + if (r_dc_id.is_error()) { + return promise.set_error(r_dc_id.move_as_error()); + } + send_closure(actor_id, &ContactsManager::send_load_async_graph_query, r_dc_id.move_as_ok(), std::move(token), x, + std::move(promise)); + }); get_channel_statistics_dc_id(dialog_id, false, std::move(dc_id_promise)); } @@ -6811,8 +6813,8 @@ void ContactsManager::add_chat_participant(ChatId chat_id, UserId user_id, int32 td_->create_handler(std::move(promise))->send(chat_id, std::move(input_user), forward_limit); } -void ContactsManager::add_channel_participant(ChannelId channel_id, UserId user_id, Promise &&promise, - DialogParticipantStatus old_status) { +void ContactsManager::add_channel_participant(ChannelId channel_id, UserId user_id, + const DialogParticipantStatus &old_status, Promise &&promise) { if (td_->auth_manager_->is_bot()) { return promise.set_error(Status::Error(400, "Bots can't add new chat members")); } @@ -6986,8 +6988,8 @@ void ContactsManager::set_channel_participant_status_impl(ChannelId channel_id, if (participant_dialog_id.get_type() != DialogType::User) { return promise.set_error(Status::Error(400, "Can't promote chats to chat administrators")); } - return promote_channel_participant(channel_id, participant_dialog_id.get_user_id(), std::move(status), - std::move(old_status), std::move(promise)); + return promote_channel_participant(channel_id, participant_dialog_id.get_user_id(), status, old_status, + std::move(promise)); } else if (need_restrict) { return restrict_channel_participant(channel_id, participant_dialog_id, std::move(status), std::move(old_status), std::move(promise)); @@ -6996,13 +6998,13 @@ void ContactsManager::set_channel_participant_status_impl(ChannelId channel_id, if (participant_dialog_id.get_type() != DialogType::User) { return promise.set_error(Status::Error(400, "Can't add chats as chat members")); } - return add_channel_participant(channel_id, participant_dialog_id.get_user_id(), std::move(promise), - std::move(old_status)); + return add_channel_participant(channel_id, participant_dialog_id.get_user_id(), old_status, std::move(promise)); } } -void ContactsManager::promote_channel_participant(ChannelId channel_id, UserId user_id, DialogParticipantStatus status, - DialogParticipantStatus old_status, Promise &&promise) { +void ContactsManager::promote_channel_participant(ChannelId channel_id, UserId user_id, + const DialogParticipantStatus &status, + const DialogParticipantStatus &old_status, Promise &&promise) { LOG(INFO) << "Promote " << user_id << " in " << channel_id << " from " << old_status << " to " << status; const Channel *c = get_channel(channel_id); CHECK(c != nullptr); @@ -7459,8 +7461,8 @@ void ContactsManager::delete_chat_participant(ChatId chat_id, UserId user_id, bo } void ContactsManager::restrict_channel_participant(ChannelId channel_id, DialogId participant_dialog_id, - DialogParticipantStatus status, DialogParticipantStatus old_status, - Promise &&promise) { + DialogParticipantStatus &&status, + DialogParticipantStatus &&old_status, Promise &&promise) { TRY_STATUS_PROMISE(promise, G()->close_status()); LOG(INFO) << "Restrict " << participant_dialog_id << " in " << channel_id << " from " << old_status << " to " @@ -7521,22 +7523,23 @@ void ContactsManager::restrict_channel_participant(ChannelId channel_id, DialogI if (old_status.is_member() && !status.is_member() && !status.is_banned()) { // we can't make participant Left without kicking it first auto on_result_promise = PromiseCreator::lambda([actor_id = actor_id(this), channel_id, participant_dialog_id, - status, promise = std::move(promise)](Result<> result) mutable { + status = std::move(status), + promise = std::move(promise)](Result<> result) mutable { if (result.is_error()) { return promise.set_error(result.move_as_error()); } - create_actor("RestrictChannelParticipantSleepActor", 1.0, - PromiseCreator::lambda([actor_id, channel_id, participant_dialog_id, status, - promise = std::move(promise)](Result<> result) mutable { - if (result.is_error()) { - return promise.set_error(result.move_as_error()); - } + create_actor( + "RestrictChannelParticipantSleepActor", 1.0, + PromiseCreator::lambda([actor_id, channel_id, participant_dialog_id, status = std::move(status), + promise = std::move(promise)](Result<> result) mutable { + if (result.is_error()) { + return promise.set_error(result.move_as_error()); + } - send_closure(actor_id, &ContactsManager::restrict_channel_participant, channel_id, - participant_dialog_id, status, DialogParticipantStatus::Banned(0), - std::move(promise)); - })) + send_closure(actor_id, &ContactsManager::restrict_channel_participant, channel_id, participant_dialog_id, + std::move(status), DialogParticipantStatus::Banned(0), std::move(promise)); + })) .release(); }); @@ -7606,7 +7609,7 @@ vector ContactsManager::get_dialog_ids(vector ContactsManager::get_created_public_dialogs(PublicDialogType type, Promise &&promise) { - int32 index = static_cast(type); + auto index = static_cast(type); if (created_public_channels_inited_[index]) { promise.set_value(Unit()); return transform(created_public_channels_[index], [&](ChannelId channel_id) { @@ -7622,7 +7625,7 @@ vector ContactsManager::get_created_public_dialogs(PublicDialogType ty void ContactsManager::on_get_created_public_channels(PublicDialogType type, vector> &&chats) { - int32 index = static_cast(type); + auto index = static_cast(type); created_public_channels_[index] = get_channel_ids(std::move(chats), "on_get_created_public_channels"); created_public_channels_inited_[index] = true; } @@ -9643,7 +9646,7 @@ ContactsManager::ChannelFull *ContactsManager::get_channel_full_force(ChannelId return get_channel_full(channel_id, only_local, source); } -void ContactsManager::for_each_secret_chat_with_user(UserId user_id, std::function f) { +void ContactsManager::for_each_secret_chat_with_user(UserId user_id, const std::function &f) { auto it = secret_chats_with_user_.find(user_id); if (it != secret_chats_with_user_.end()) { for (auto secret_chat_id : it->second) { @@ -10225,7 +10228,7 @@ void ContactsManager::on_get_user_full(tl_object_ptr &&u void ContactsManager::on_get_user_photos(UserId user_id, int32 offset, int32 limit, int32 total_count, vector> photos) { - int32 photo_count = narrow_cast(photos.size()); + auto photo_count = narrow_cast(photos.size()); int32 min_total_count = (offset >= 0 && photo_count > 0 ? offset : 0) + photo_count; if (total_count < min_total_count) { LOG(ERROR) << "Wrong photos total_count " << total_count << ". Receive " << photo_count << " photos with offset " @@ -10754,7 +10757,7 @@ void ContactsManager::on_get_chat_full_failed(ChatId chat_id) { return; } - LOG(INFO) << "Failed to get " << chat_id; + LOG(INFO) << "Failed to get full " << chat_id; } void ContactsManager::on_get_channel_full_failed(ChannelId channel_id) { @@ -10762,7 +10765,7 @@ void ContactsManager::on_get_channel_full_failed(ChannelId channel_id) { return; } - LOG(INFO) << "Failed to get " << channel_id; + LOG(INFO) << "Failed to get full " << channel_id; auto channel_full = get_channel_full(channel_id, true, "on_get_channel_full"); if (channel_full != nullptr) { channel_full->repair_request_version = 0; @@ -10886,8 +10889,8 @@ void ContactsManager::do_update_user_photo(User *u, UserId user_id, do_update_user_photo(u, user_id, std::move(new_photo), true, source); } -void ContactsManager::do_update_user_photo(User *u, UserId user_id, ProfilePhoto new_photo, bool invalidate_photo_cache, - const char *source) { +void ContactsManager::do_update_user_photo(User *u, UserId user_id, ProfilePhoto &&new_photo, + bool invalidate_photo_cache, const char *source) { u->is_photo_inited = true; if (new_photo != u->photo) { LOG_IF(ERROR, u->access_hash == -1 && new_photo.small_file_id.is_valid()) @@ -11138,8 +11141,9 @@ void ContactsManager::on_update_user_full_common_chat_count(UserFull *user_full, void ContactsManager::on_update_user_full_commands(UserFull *user_full, UserId user_id, vector> &&bot_commands) { CHECK(user_full != nullptr); - auto commands = - transform(std::move(bot_commands), [](auto &&bot_command) { return BotCommand(std::move(bot_command)); }); + auto commands = transform(std::move(bot_commands), [](tl_object_ptr &&bot_command) { + return BotCommand(std::move(bot_command)); + }); if (user_full->commands != commands) { user_full->commands = std::move(commands); user_full->is_changed = true; @@ -11164,7 +11168,7 @@ void ContactsManager::on_update_user_need_phone_number_privacy_exception(UserId } void ContactsManager::on_update_user_full_need_phone_number_privacy_exception( - UserFull *user_full, UserId user_id, bool need_phone_number_privacy_exception) { + UserFull *user_full, UserId user_id, bool need_phone_number_privacy_exception) const { CHECK(user_full != nullptr); if (need_phone_number_privacy_exception) { const User *u = get_user(user_id); @@ -11238,6 +11242,7 @@ void ContactsManager::add_profile_photo_to_cache(UserId user_id, Photo &&photo) if (user_photos->photos.empty() || user_photos->photos[0].id.get() != photo.id.get()) { user_photos->photos.insert(user_photos->photos.begin(), photo); user_photos->count++; + register_user_photo(u, user_id, user_photos->photos[0]); } } else { user_photos->count++; @@ -11251,6 +11256,7 @@ void ContactsManager::add_profile_photo_to_cache(UserId user_id, Photo &&photo) if (user_full->photo != photo) { user_full->photo = photo; user_full->is_changed = true; + register_user_photo(u, user_id, photo); } update_user_full(user_full, user_id, "add_profile_photo_to_cache"); } @@ -11691,7 +11697,7 @@ void ContactsManager::on_get_channel_participants( on_get_chats(std::move(channel_participants->chats_), "on_get_channel_participants"); int32 total_count = channel_participants->count_; auto participants = std::move(channel_participants->participants_); - LOG(INFO) << "Receive " << participants.size() << " members in " << channel_id; + LOG(INFO) << "Receive " << participants.size() << " " << filter << " members in " << channel_id; bool is_full = offset == 0 && static_cast(participants.size()) < limit && total_count < limit; @@ -11722,11 +11728,12 @@ void ContactsManager::on_get_channel_participants( } if (total_count < narrow_cast(result.size())) { - LOG(ERROR) << "Receive total_count = " << total_count << ", but have at least " << result.size() << " members in " - << channel_id; + LOG(ERROR) << "Receive total_count = " << total_count << ", but have at least " << result.size() << " " << filter + << " members in " << channel_id; total_count = static_cast(result.size()); } else if (is_full && total_count > static_cast(result.size())) { - LOG(ERROR) << "Fix total number of members from " << total_count << " to " << result.size() << " in " << channel_id; + LOG(ERROR) << "Fix total number of " << filter << " members from " << total_count << " to " << result.size() + << " in " << channel_id; total_count = static_cast(result.size()); } @@ -12006,8 +12013,8 @@ void ContactsManager::speculative_add_channel_participant_count(ChannelId channe } void ContactsManager::speculative_add_channel_user(ChannelId channel_id, UserId user_id, - DialogParticipantStatus new_status, - DialogParticipantStatus old_status) { + const DialogParticipantStatus &new_status, + const DialogParticipantStatus &old_status) { auto c = get_channel_force(channel_id); // channel full must be loaded before c->participant_count is updated, because on_load_channel_full_from_database // must copy the initial c->participant_count before it is speculatibely updated @@ -12176,7 +12183,7 @@ void ContactsManager::on_update_chat_full_photo(ChatFull *chat_full, ChatId chat drop_chat_photos(chat_id, true, false, "on_update_chat_full_photo"); } - auto photo_file_ids = photo_get_file_ids(photo); + auto photo_file_ids = photo_get_file_ids(chat_full->photo); if (chat_full->registered_photo_file_ids == photo_file_ids) { return; } @@ -12213,7 +12220,7 @@ void ContactsManager::on_update_channel_full_photo(ChannelFull *channel_full, Ch drop_channel_photos(channel_id, true, false, "on_update_channel_full_photo"); } - auto photo_file_ids = photo_get_file_ids(photo); + auto photo_file_ids = photo_get_file_ids(channel_full->photo); if (channel_full->registered_photo_file_ids == photo_file_ids) { return; } @@ -12812,7 +12819,7 @@ void ContactsManager::on_update_chat_status(Chat *c, ChatId chat_id, DialogParti bool need_reload_group_call = c->status.can_manage_calls() != status.can_manage_calls(); bool need_drop_invite_link = c->status.can_manage_invite_links() && !status.can_manage_invite_links(); - c->status = status; + c->status = std::move(status); if (c->status.is_left()) { c->participant_count = 0; @@ -13389,7 +13396,7 @@ void ContactsManager::on_update_channel_default_permissions(ChannelId channel_id } void ContactsManager::send_update_chat_member(DialogId dialog_id, UserId agent_user_id, int32 date, - DialogInviteLink invite_link, + const DialogInviteLink &invite_link, const DialogParticipant &old_dialog_participant, const DialogParticipant &new_dialog_participant) { CHECK(td_->auth_manager_->is_bot()); @@ -14634,8 +14641,8 @@ void ContactsManager::add_dialog_participant(DialogId dialog_id, UserId user_id, case DialogType::Chat: return add_chat_participant(dialog_id.get_chat_id(), user_id, forward_limit, std::move(promise)); case DialogType::Channel: - return add_channel_participant(dialog_id.get_channel_id(), user_id, std::move(promise), - DialogParticipantStatus::Left()); + return add_channel_participant(dialog_id.get_channel_id(), user_id, DialogParticipantStatus::Left(), + std::move(promise)); case DialogType::SecretChat: return promise.set_error(Status::Error(400, "Can't add members to a secret chat")); case DialogType::None: @@ -15104,7 +15111,7 @@ void ContactsManager::get_channel_participants(ChannelId channel_id, } }); td_->create_handler(std::move(get_channel_participants_promise)) - ->send(channel_id, std::move(participants_filter), offset, limit); + ->send(channel_id, participants_filter, offset, limit); } vector ContactsManager::get_dialog_administrators(DialogId dialog_id, int left_tries, @@ -15163,12 +15170,13 @@ string ContactsManager::get_dialog_administrators_database_key(DialogId dialog_i void ContactsManager::load_dialog_administrators(DialogId dialog_id, Promise &&promise) { if (G()->parameters().use_chat_info_db) { LOG(INFO) << "Load administrators of " << dialog_id << " from database"; - G()->td_db()->get_sqlite_pmc()->get( - get_dialog_administrators_database_key(dialog_id), - PromiseCreator::lambda([dialog_id, promise = std::move(promise)](string value) mutable { - send_closure(G()->contacts_manager(), &ContactsManager::on_load_dialog_administrators_from_database, - dialog_id, std::move(value), std::move(promise)); - })); + G()->td_db()->get_sqlite_pmc()->get(get_dialog_administrators_database_key(dialog_id), + PromiseCreator::lambda([actor_id = actor_id(this), dialog_id, + promise = std::move(promise)](string value) mutable { + send_closure(actor_id, + &ContactsManager::on_load_dialog_administrators_from_database, + dialog_id, std::move(value), std::move(promise)); + })); } else { promise.set_value(Unit()); } @@ -15663,7 +15671,7 @@ void ContactsManager::on_chat_update(telegram_api::channelForbidden &channel, co on_update_channel_status(c, channel_id, DialogParticipantStatus::Banned(unban_date)); // on_update_channel_username(c, channel_id, ""); // don't know if channel username is empty, so don't update it tl_object_ptr banned_rights; // == nullptr - on_update_channel_default_permissions(c, channel_id, get_restricted_rights(banned_rights)); + on_update_channel_default_permissions(c, channel_id, get_restricted_rights(std::move(banned_rights))); td_->messages_manager_->on_update_dialog_group_call(DialogId(channel_id), false, false, "receive channelForbidden"); bool sign_messages = false; @@ -15982,7 +15990,7 @@ tl_object_ptr ContactsManager::get_supergroup_object(Channel return get_supergroup_object(channel_id, get_channel(channel_id)); } -tl_object_ptr ContactsManager::get_supergroup_object(ChannelId channel_id, const Channel *c) const { +tl_object_ptr ContactsManager::get_supergroup_object(ChannelId channel_id, const Channel *c) { if (c == nullptr) { return nullptr; } diff --git a/td/telegram/ContactsManager.h b/td/telegram/ContactsManager.h index ceaed1ccd..c776acb2e 100644 --- a/td/telegram/ContactsManager.h +++ b/td/telegram/ContactsManager.h @@ -113,7 +113,7 @@ class ContactsManager final : public Actor { bool is_update_about_username_change_received(UserId user_id) const; - void for_each_secret_chat_with_user(UserId user_id, std::function f); + void for_each_secret_chat_with_user(UserId user_id, const std::function &f); string get_user_username(UserId user_id) const; string get_channel_username(ChannelId channel_id) const; @@ -280,14 +280,14 @@ class ContactsManager final : public Actor { static td_api::object_ptr convert_authorization_object( tl_object_ptr &&authorization); - void confirm_qr_code_authentication(string link, Promise> &&promise); + void confirm_qr_code_authentication(const string &link, Promise> &&promise); void get_active_sessions(Promise> &&promise) const; void terminate_session(int64 session_id, Promise &&promise) const; void terminate_all_other_sessions(Promise &&promise) const; void get_connected_websites(Promise> &&promise) const; - void disconnect_website(int64 authorizations_id, Promise &&promise) const; + void disconnect_website(int64 website_id, Promise &&promise) const; void disconnect_all_websites(Promise &&promise) const; void add_contact(Contact contact, bool share_phone_number, Promise &&promise); @@ -297,7 +297,7 @@ class ContactsManager final : public Actor { std::pair> search_contacts(const string &query, int32 limit, Promise &&promise); - void remove_contacts(vector user_ids, Promise &&promise); + void remove_contacts(const vector &user_ids, Promise &&promise); void remove_contacts_by_phone_number(vector user_phone_numbers, vector user_ids, Promise &&promise); @@ -369,7 +369,7 @@ class ContactsManager final : public Actor { void get_channel_message_statistics(FullMessageId full_message_id, bool is_dark, Promise> &&promise); - void load_statistics_graph(DialogId dialog_id, const string &token, int64 x, + void load_statistics_graph(DialogId dialog_id, string token, int64 x, Promise> &&promise); struct CanTransferOwnershipResult { @@ -478,7 +478,7 @@ class ContactsManager final : public Actor { FileSourceId get_chat_full_file_source_id(ChatId chat_id); void reload_chat_full(ChatId chat_id, Promise &&promise); - int32 get_chat_participant_count(ChatId channel_id) const; + int32 get_chat_participant_count(ChatId chat_id) const; bool get_chat_is_active(ChatId chat_id) const; ChannelId get_chat_migrated_to_channel_id(ChatId chat_id) const; DialogParticipantStatus get_chat_status(ChatId chat_id) const; @@ -489,7 +489,7 @@ class ContactsManager final : public Actor { bool have_min_channel(ChannelId channel_id) const; bool have_channel_force(ChannelId channel_id); bool get_channel(ChannelId channel_id, int left_tries, Promise &&promise); - void reload_channel(ChannelId chnanel_id, Promise &&promise); + void reload_channel(ChannelId channel_id, Promise &&promise); void load_channel_full(ChannelId channel_id, bool force, Promise &&promise, const char *source); FileSourceId get_channel_full_file_source_id(ChannelId channel_id); void reload_channel_full(ChannelId channel_id, Promise &&promise, const char *source); @@ -583,7 +583,7 @@ class ContactsManager final : public Actor { static tl_object_ptr convert_stats_graph(tl_object_ptr obj); - static double get_percentage_value(double new_value, double old_value); + static double get_percentage_value(double part, double total); static tl_object_ptr convert_stats_absolute_value( const tl_object_ptr &obj); @@ -1164,7 +1164,7 @@ class ContactsManager final : public Actor { static bool is_valid_username(const string &username); void on_update_user_name(User *u, UserId user_id, string &&first_name, string &&last_name, string &&username); - void on_update_user_phone_number(User *u, UserId user_id, string &&phone_number); + static void on_update_user_phone_number(User *u, UserId user_id, string &&phone_number); void on_update_user_photo(User *u, UserId user_id, tl_object_ptr &&photo, const char *source); void on_update_user_is_contact(User *u, UserId user_id, bool is_contact, bool is_mutual_contact); @@ -1173,7 +1173,7 @@ class ContactsManager final : public Actor { void do_update_user_photo(User *u, UserId user_id, tl_object_ptr &&photo, const char *source); - void do_update_user_photo(User *u, UserId user_id, ProfilePhoto new_photo, bool invalidate_photo_cache, + void do_update_user_photo(User *u, UserId user_id, ProfilePhoto &&new_photo, bool invalidate_photo_cache, const char *source); void upload_profile_photo(FileId file_id, bool is_animation, double main_frame_timestamp, Promise &&promise, @@ -1184,12 +1184,12 @@ class ContactsManager final : public Actor { void register_user_photo(User *u, UserId user_id, const Photo &photo); - void on_update_user_full_is_blocked(UserFull *user_full, UserId user_id, bool is_blocked); - void on_update_user_full_common_chat_count(UserFull *user_full, UserId user_id, int32 common_chat_count); - void on_update_user_full_commands(UserFull *user_full, UserId user_id, - vector> &&bot_commands); + static void on_update_user_full_is_blocked(UserFull *user_full, UserId user_id, bool is_blocked); + static void on_update_user_full_common_chat_count(UserFull *user_full, UserId user_id, int32 common_chat_count); + static void on_update_user_full_commands(UserFull *user_full, UserId user_id, + vector> &&bot_commands); void on_update_user_full_need_phone_number_privacy_exception(UserFull *user_full, UserId user_id, - bool need_phone_number_privacy_exception); + bool need_phone_number_privacy_exception) const; void add_profile_photo_to_cache(UserId user_id, Photo &&photo); bool delete_profile_photo_from_cache(UserId user_id, int64 profile_photo_id, bool send_updates); @@ -1197,13 +1197,14 @@ class ContactsManager final : public Actor { void drop_user_full(UserId user_id); void on_update_chat_status(Chat *c, ChatId chat_id, DialogParticipantStatus status); - void on_update_chat_default_permissions(Chat *c, ChatId chat_id, RestrictedRights default_permissions, int32 version); + static void on_update_chat_default_permissions(Chat *c, ChatId chat_id, RestrictedRights default_permissions, + int32 version); void on_update_chat_participant_count(Chat *c, ChatId chat_id, int32 participant_count, int32 version, const string &debug_str); void on_update_chat_photo(Chat *c, ChatId chat_id, tl_object_ptr &&chat_photo_ptr); - void on_update_chat_title(Chat *c, ChatId chat_id, string &&title); - void on_update_chat_active(Chat *c, ChatId chat_id, bool is_active); - void on_update_chat_migrated_to_channel_id(Chat *c, ChatId chat_id, ChannelId migrated_to_channel_id); + static void on_update_chat_title(Chat *c, ChatId chat_id, string &&title); + static void on_update_chat_active(Chat *c, ChatId chat_id, bool is_active); + static void on_update_chat_migrated_to_channel_id(Chat *c, ChatId chat_id, ChannelId migrated_to_channel_id); void on_update_chat_full_photo(ChatFull *chat_full, ChatId chat_id, Photo photo); bool on_update_chat_full_participants_short(ChatFull *chat_full, ChatId chat_id, int32 version); @@ -1214,10 +1215,11 @@ class ContactsManager final : public Actor { void on_update_channel_photo(Channel *c, ChannelId channel_id, tl_object_ptr &&chat_photo_ptr); - void on_update_channel_title(Channel *c, ChannelId channel_id, string &&title); + static void on_update_channel_title(Channel *c, ChannelId channel_id, string &&title); void on_update_channel_username(Channel *c, ChannelId channel_id, string &&username); void on_update_channel_status(Channel *c, ChannelId channel_id, DialogParticipantStatus &&status); - void on_update_channel_default_permissions(Channel *c, ChannelId channel_id, RestrictedRights default_permissions); + static void on_update_channel_default_permissions(Channel *c, ChannelId channel_id, + RestrictedRights default_permissions); void on_update_channel_bot_user_ids(ChannelId channel_id, vector &&bot_user_ids); @@ -1229,9 +1231,10 @@ class ContactsManager final : public Actor { void on_update_channel_full_location(ChannelFull *channel_full, ChannelId channel_id, const DialogLocation &location); void on_update_channel_full_slow_mode_delay(ChannelFull *channel_full, ChannelId channel_id, int32 slow_mode_delay, int32 slow_mode_next_send_date); - void on_update_channel_full_slow_mode_next_send_date(ChannelFull *channel_full, int32 slow_mode_next_send_date); - void on_update_channel_full_bot_user_ids(ChannelFull *channel_full, ChannelId channel_id, - vector &&bot_user_ids); + static void on_update_channel_full_slow_mode_next_send_date(ChannelFull *channel_full, + int32 slow_mode_next_send_date); + static void on_update_channel_full_bot_user_ids(ChannelFull *channel_full, ChannelId channel_id, + vector &&bot_user_ids); void on_channel_status_changed(const Channel *c, ChannelId channel_id, const DialogParticipantStatus &old_status, const DialogParticipantStatus &new_status); @@ -1245,15 +1248,15 @@ class ContactsManager final : public Actor { void speculative_add_channel_participant_count(ChannelId channel_id, int32 delta_participant_count, bool by_me); - void speculative_add_channel_user(ChannelId channel_id, UserId user_id, DialogParticipantStatus new_status, - DialogParticipantStatus old_status); + void speculative_add_channel_user(ChannelId channel_id, UserId user_id, const DialogParticipantStatus &new_status, + const DialogParticipantStatus &old_status); void drop_chat_photos(ChatId chat_id, bool is_empty, bool drop_chat_full_photo, const char *source); void drop_chat_full(ChatId chat_id); void drop_channel_photos(ChannelId channel_id, bool is_empty, bool drop_channel_full_photo, const char *source); - void do_invalidate_channel_full(ChannelFull *channel_full, bool need_drop_slow_mode_delay); + static void do_invalidate_channel_full(ChannelFull *channel_full, bool need_drop_slow_mode_delay); void update_user_online_member_count(User *u); void update_chat_online_member_count(const ChatFull *chat_full, ChatId chat_id, bool is_from_server); @@ -1333,7 +1336,7 @@ class ContactsManager final : public Actor { void update_channel_full(ChannelFull *channel_full, ChannelId channel_id, const char *source, bool from_database = false); - bool is_chat_full_outdated(const ChatFull *chat_full, const Chat *c, ChatId chat_id); + static bool is_chat_full_outdated(const ChatFull *chat_full, const Chat *c, ChatId chat_id); bool is_user_contact(const User *u, UserId user_id, bool is_mutual) const; @@ -1362,8 +1365,8 @@ class ContactsManager final : public Actor { void on_clear_imported_contacts(vector &&contacts, vector contacts_unique_id, std::pair, vector> &&to_add, Promise &&promise); - void send_update_chat_member(DialogId dialog_id, UserId agent_user_id, int32 date, DialogInviteLink invite_link, - const DialogParticipant &old_dialog_participant, + void send_update_chat_member(DialogId dialog_id, UserId agent_user_id, int32 date, + const DialogInviteLink &invite_link, const DialogParticipant &old_dialog_participant, const DialogParticipant &new_dialog_participant); static vector> get_chats_nearby_object( @@ -1397,8 +1400,8 @@ class ContactsManager final : public Actor { void add_chat_participant(ChatId chat_id, UserId user_id, int32 forward_limit, Promise &&promise); - void add_channel_participant(ChannelId channel_id, UserId user_id, Promise &&promise, - DialogParticipantStatus old_status); + void add_channel_participant(ChannelId channel_id, UserId user_id, const DialogParticipantStatus &old_status, + Promise &&promise); void add_channel_participants(ChannelId channel_id, const vector &user_ids, Promise &&promise); @@ -1467,7 +1470,7 @@ class ContactsManager final : public Actor { static td_api::object_ptr get_update_unknown_supergroup_object(ChannelId channel_id); - tl_object_ptr get_supergroup_object(ChannelId channel_id, const Channel *c) const; + static tl_object_ptr get_supergroup_object(ChannelId channel_id, const Channel *c); tl_object_ptr get_supergroup_full_info_object(const ChannelFull *channel_full, ChannelId channel_id) const; @@ -1520,11 +1523,11 @@ class ContactsManager final : public Actor { DialogParticipantStatus status, DialogParticipantStatus old_status, Promise &&promise); - void promote_channel_participant(ChannelId channel_id, UserId user_id, DialogParticipantStatus status, - DialogParticipantStatus old_status, Promise &&promise); + void promote_channel_participant(ChannelId channel_id, UserId user_id, const DialogParticipantStatus &status, + const DialogParticipantStatus &old_status, Promise &&promise); void restrict_channel_participant(ChannelId channel_id, DialogId participant_dialog_id, - DialogParticipantStatus status, DialogParticipantStatus old_status, + DialogParticipantStatus &&status, DialogParticipantStatus &&old_status, Promise &&promise); void transfer_channel_ownership(ChannelId channel_id, UserId user_id, diff --git a/td/telegram/CountryInfoManager.cpp b/td/telegram/CountryInfoManager.cpp index f876926f4..e9efe9dea 100644 --- a/td/telegram/CountryInfoManager.cpp +++ b/td/telegram/CountryInfoManager.cpp @@ -214,9 +214,9 @@ void CountryInfoManager::do_get_phone_number_info(string phone_number_prefix, st })); } -td_api::object_ptr CountryInfoManager::get_phone_number_info_sync(string language_code, +td_api::object_ptr CountryInfoManager::get_phone_number_info_sync(const string &language_code, string phone_number_prefix) { - td::remove_if(phone_number_prefix, [](char c) { return c < '0' || c > '9'; }); + td::remove_if(phone_number_prefix, [](char c) { return !is_digit(c); }); if (phone_number_prefix.empty()) { return td_api::make_object(nullptr, string(), string()); } @@ -401,7 +401,7 @@ void CountryInfoManager::on_get_country_list_impl(const string &language_code, info.country_code = std::move(c->iso2_); info.default_name = std::move(c->default_name_); info.name = std::move(c->name_); - info.is_hidden = std::move(c->hidden_); + info.is_hidden = c->hidden_; for (auto &code : c->country_codes_) { auto r_calling_code = to_integer_safe(code->country_code_); if (r_calling_code.is_error() || r_calling_code.ok() <= 0) { diff --git a/td/telegram/CountryInfoManager.h b/td/telegram/CountryInfoManager.h index 3b4f83a1d..e3c6eb62f 100644 --- a/td/telegram/CountryInfoManager.h +++ b/td/telegram/CountryInfoManager.h @@ -34,7 +34,7 @@ class CountryInfoManager final : public Actor { void get_phone_number_info(string phone_number_prefix, Promise> &&promise); - static td_api::object_ptr get_phone_number_info_sync(string language_code, + static td_api::object_ptr get_phone_number_info_sync(const string &language_code, string phone_number_prefix); CountryInfoManager(const CountryInfoManager &) = delete; diff --git a/td/telegram/DeviceTokenManager.cpp b/td/telegram/DeviceTokenManager.cpp index dbdb8532c..91993e728 100644 --- a/td/telegram/DeviceTokenManager.cpp +++ b/td/telegram/DeviceTokenManager.cpp @@ -129,7 +129,7 @@ StringBuilder &operator<<(StringBuilder &string_builder, const DeviceTokenManage } void DeviceTokenManager::register_device(tl_object_ptr device_token_ptr, - vector other_user_ids, + const vector &other_user_ids, Promise> promise) { CHECK(device_token_ptr != nullptr); TokenType token_type; @@ -259,7 +259,7 @@ void DeviceTokenManager::register_device(tl_object_ptr devi if (encrypt != info.encrypt) { if (encrypt) { constexpr size_t ENCRYPTION_KEY_LENGTH = 256; - constexpr int64 MIN_ENCRYPTION_KEY_ID = static_cast(10000000000000ll); + constexpr auto MIN_ENCRYPTION_KEY_ID = static_cast(10000000000000ll); info.encryption_key.resize(ENCRYPTION_KEY_LENGTH); while (true) { Random::secure_bytes(info.encryption_key); diff --git a/td/telegram/DeviceTokenManager.h b/td/telegram/DeviceTokenManager.h index 59399f345..bce1ae5a8 100644 --- a/td/telegram/DeviceTokenManager.h +++ b/td/telegram/DeviceTokenManager.h @@ -26,7 +26,7 @@ class DeviceTokenManager final : public NetQueryCallback { public: explicit DeviceTokenManager(ActorShared<> parent) : parent_(std::move(parent)) { } - void register_device(tl_object_ptr device_token_ptr, vector other_user_ids, + void register_device(tl_object_ptr device_token_ptr, const vector &other_user_ids, Promise> promise); void reregister_device(); diff --git a/td/telegram/DhCache.cpp b/td/telegram/DhCache.cpp index 8689e666c..ac262ae7f 100644 --- a/td/telegram/DhCache.cpp +++ b/td/telegram/DhCache.cpp @@ -27,7 +27,7 @@ int DhCache::is_good_prime(Slice prime_str) const { if (value == "bad") { return 0; } - CHECK(value == ""); + CHECK(value.empty()); return -1; } diff --git a/td/telegram/DialogAction.cpp b/td/telegram/DialogAction.cpp index 250366d64..bbafaecc5 100644 --- a/td/telegram/DialogAction.cpp +++ b/td/telegram/DialogAction.cpp @@ -46,7 +46,7 @@ void DialogAction::init(Type type, string emoji) { } } -void DialogAction::init(Type type, int32 message_id, string emoji, string data) { +void DialogAction::init(Type type, int32 message_id, string emoji, const string &data) { if (ServerMessageId(message_id).is_valid() && is_valid_emoji(emoji) && check_utf8(data)) { type_ = type; progress_ = message_id; @@ -199,7 +199,7 @@ DialogAction::DialogAction(telegram_api::object_ptr(action); init(Type::ClickingAnimatedEmoji, emoji_interaction_action->msg_id_, - std::move(emoji_interaction_action->emoticon_), std::move(emoji_interaction_action->interaction_->data_)); + std::move(emoji_interaction_action->emoticon_), emoji_interaction_action->interaction_->data_); break; } default: diff --git a/td/telegram/DialogAction.h b/td/telegram/DialogAction.h index d56a32c83..bfae5f1b7 100644 --- a/td/telegram/DialogAction.h +++ b/td/telegram/DialogAction.h @@ -49,7 +49,7 @@ class DialogAction { void init(Type type, string emoji); - void init(Type type, int32 message_id, string emoji, string data); + void init(Type type, int32 message_id, string emoji, const string &data); static bool is_valid_emoji(string &emoji); diff --git a/td/telegram/DialogParticipant.cpp b/td/telegram/DialogParticipant.cpp index 52e540999..77818dace 100644 --- a/td/telegram/DialogParticipant.cpp +++ b/td/telegram/DialogParticipant.cpp @@ -458,7 +458,7 @@ DialogParticipantStatus get_dialog_participant_status(const tl_object_ptr &admin_rights, + tl_object_ptr &&admin_rights, string rank) { bool can_change_info = (admin_rights->flags_ & telegram_api::chatAdminRights::CHANGE_INFO_MASK) != 0; bool can_post_messages = (admin_rights->flags_ & telegram_api::chatAdminRights::POST_MESSAGES_MASK) != 0; @@ -480,8 +480,8 @@ DialogParticipantStatus get_dialog_participant_status(bool can_be_edited, can_pin_messages, can_promote_members, can_manage_calls); } -DialogParticipantStatus get_dialog_participant_status( - bool is_member, const tl_object_ptr &banned_rights) { +DialogParticipantStatus get_dialog_participant_status(bool is_member, + tl_object_ptr &&banned_rights) { bool can_view_messages = (banned_rights->flags_ & telegram_api::chatBannedRights::VIEW_MESSAGES_MASK) == 0; if (!can_view_messages) { return DialogParticipantStatus::Banned(banned_rights->until_date_); @@ -616,7 +616,7 @@ StringBuilder &operator<<(StringBuilder &string_builder, const RestrictedRights return string_builder; } -RestrictedRights get_restricted_rights(const tl_object_ptr &banned_rights) { +RestrictedRights get_restricted_rights(tl_object_ptr &&banned_rights) { if (banned_rights == nullptr) { return RestrictedRights(false, false, false, false, false, false, false, false, false, false, false); } @@ -657,14 +657,14 @@ RestrictedRights get_restricted_rights(const td_api::object_ptrinviter_user_id = UserId(); } if (joined_date < 0) { LOG(ERROR) << "Receive date " << joined_date; - joined_date = 0; + this->joined_date = 0; } } diff --git a/td/telegram/DialogParticipant.h b/td/telegram/DialogParticipant.h index f3665d8e1..f746f450f 100644 --- a/td/telegram/DialogParticipant.h +++ b/td/telegram/DialogParticipant.h @@ -397,7 +397,7 @@ struct DialogParticipant { DialogParticipant() = default; - DialogParticipant(DialogId user_id, UserId inviter_user_id, int32 joined_date, DialogParticipantStatus status); + DialogParticipant(DialogId dialog_id, UserId inviter_user_id, int32 joined_date, DialogParticipantStatus status); DialogParticipant(tl_object_ptr &&participant_ptr, int32 chat_creation_date, bool is_creator); @@ -508,13 +508,13 @@ DialogParticipantsFilter get_dialog_participants_filter(const tl_object_ptr &status); DialogParticipantStatus get_dialog_participant_status(bool can_be_edited, - const tl_object_ptr &admin_rights, + tl_object_ptr &&admin_rights, string rank); -DialogParticipantStatus get_dialog_participant_status( - bool is_member, const tl_object_ptr &banned_rights); +DialogParticipantStatus get_dialog_participant_status(bool is_member, + tl_object_ptr &&banned_rights); -RestrictedRights get_restricted_rights(const tl_object_ptr &banned_rights); +RestrictedRights get_restricted_rights(tl_object_ptr &&banned_rights); RestrictedRights get_restricted_rights(const td_api::object_ptr &permissions); diff --git a/td/telegram/DocumentsManager.cpp b/td/telegram/DocumentsManager.cpp index 3e1aa5dc9..40aa050ee 100644 --- a/td/telegram/DocumentsManager.cpp +++ b/td/telegram/DocumentsManager.cpp @@ -573,7 +573,7 @@ SecretInputMedia DocumentsManager::get_secret_input_media(FileId document_file_i return SecretInputMedia{}; } vector> attributes; - if (document->file_name.size()) { + if (!document->file_name.empty()) { attributes.push_back(make_tl_object(document->file_name)); } return SecretInputMedia{ @@ -604,7 +604,7 @@ tl_object_ptr DocumentsManager::get_input_media( CHECK(document != nullptr); vector> attributes; - if (document->file_name.size()) { + if (!document->file_name.empty()) { attributes.push_back(make_tl_object(document->file_name)); } int32 flags = 0; diff --git a/td/telegram/FileReferenceManager.h b/td/telegram/FileReferenceManager.h index f5d8a061c..939b6db2e 100644 --- a/td/telegram/FileReferenceManager.h +++ b/td/telegram/FileReferenceManager.h @@ -54,7 +54,8 @@ class FileReferenceManager final : public Actor { using NodeId = FileId; void repair_file_reference(NodeId node_id, Promise<> promise); - void reload_photo(PhotoSizeSource source, Promise promise); + + static void reload_photo(PhotoSizeSource source, Promise promise); bool add_file_source(NodeId node_id, FileSourceId file_source_id); diff --git a/td/telegram/Global.h b/td/telegram/Global.h index ba0543d7a..c80a91fb5 100644 --- a/td/telegram/Global.h +++ b/td/telegram/Global.h @@ -377,7 +377,7 @@ class Global final : public ActorContext { void set_dh_config(std::shared_ptr new_dh_config) { #if !TD_HAVE_ATOMIC_SHARED_PTR std::lock_guard guard(dh_config_mutex_); - dh_config_ = new_dh_config; + dh_config_ = std::move(new_dh_config); #else atomic_store(&dh_config_, std::move(new_dh_config)); #endif diff --git a/td/telegram/GroupCallManager.cpp b/td/telegram/GroupCallManager.cpp index 71f425016..c98c731c9 100644 --- a/td/telegram/GroupCallManager.cpp +++ b/td/telegram/GroupCallManager.cpp @@ -1764,6 +1764,7 @@ void GroupCallManager::on_update_group_call_participants( }); td_->create_handler(std::move(query_promise)) ->send(input_group_call_id, std::move(input_peers), {}); + return; } } @@ -1976,8 +1977,9 @@ void GroupCallManager::on_sync_group_call_participants(InputGroupCallId input_gr } } -GroupCallParticipantOrder GroupCallManager::get_real_participant_order( - bool can_self_unmute, const GroupCallParticipant &participant, const GroupCallParticipants *participants) const { +GroupCallParticipantOrder GroupCallManager::get_real_participant_order(bool can_self_unmute, + const GroupCallParticipant &participant, + const GroupCallParticipants *participants) { auto real_order = participant.get_real_order(can_self_unmute, participants->joined_date_asc, false); if (real_order >= participants->min_order) { return real_order; @@ -2273,7 +2275,7 @@ std::pair GroupCallManager::process_group_call_participant(InputGr } on_add_group_call_participant(input_group_call_id, participants->participants.back().dialog_id); on_participant_speaking_in_group_call(input_group_call_id, participants->participants.back()); - return {diff, participant.video_diff}; + return {diff, participants->participants.back().video_diff}; } void GroupCallManager::on_add_group_call_participant(InputGroupCallId input_group_call_id, @@ -4106,7 +4108,7 @@ InputGroupCallId GroupCallManager::update_group_call(const tl_object_ptr(group_call_ptr.get()); input_group_call_id = InputGroupCallId(group_call->id_, group_call->access_hash_); call.is_active = true; - call.title = std::move(group_call->title_); + call.title = group_call->title_; call.start_subscribed = group_call->schedule_start_subscribed_; call.mute_new_participants = group_call->join_muted_; call.joined_date_asc = group_call->join_date_asc_; @@ -4480,8 +4482,10 @@ void GroupCallManager::remove_recent_group_call_speaker(InputGroupCallId input_g void GroupCallManager::on_group_call_recent_speakers_updated(const GroupCall *group_call, GroupCallRecentSpeakers *recent_speakers) { if (group_call == nullptr || !group_call->is_inited || recent_speakers->is_changed) { - LOG(INFO) << "Don't need to send update of recent speakers in " << group_call->group_call_id << " from " - << group_call->dialog_id; + if (group_call != nullptr) { + LOG(INFO) << "Don't need to send update of recent speakers in " << group_call->group_call_id << " from " + << group_call->dialog_id; + } return; } @@ -4677,12 +4681,12 @@ vector> GroupCallManager::get } tl_object_ptr GroupCallManager::get_group_call_object( - const GroupCall *group_call, vector> recent_speakers) const { + const GroupCall *group_call, vector> recent_speakers) { CHECK(group_call != nullptr); CHECK(group_call->is_inited); int32 scheduled_start_date = group_call->scheduled_start_date; - bool is_active = scheduled_start_date == 0 ? group_call->is_active : 0; + bool is_active = scheduled_start_date == 0 ? group_call->is_active : false; bool is_joined = group_call->is_joined && !group_call->is_being_left; bool start_subscribed = get_group_call_start_subscribed(group_call); bool is_my_video_enabled = get_group_call_is_my_video_enabled(group_call); @@ -4703,7 +4707,7 @@ tl_object_ptr GroupCallManager::get_group_call_object( } tl_object_ptr GroupCallManager::get_update_group_call_object( - const GroupCall *group_call, vector> recent_speakers) const { + const GroupCall *group_call, vector> recent_speakers) { return td_api::make_object(get_group_call_object(group_call, std::move(recent_speakers))); } diff --git a/td/telegram/GroupCallManager.h b/td/telegram/GroupCallManager.h index 16386514b..fed2c5632 100644 --- a/td/telegram/GroupCallManager.h +++ b/td/telegram/GroupCallManager.h @@ -235,8 +235,9 @@ class GroupCallManager final : public Actor { void on_sync_group_call_participants(InputGroupCallId input_group_call_id, Result> &&result); - GroupCallParticipantOrder get_real_participant_order(bool can_self_unmute, const GroupCallParticipant &participant, - const GroupCallParticipants *participants) const; + static GroupCallParticipantOrder get_real_participant_order(bool can_self_unmute, + const GroupCallParticipant &participant, + const GroupCallParticipants *participants); void process_my_group_call_participant(InputGroupCallId input_group_call_id, GroupCallParticipant &&participant); @@ -244,8 +245,8 @@ class GroupCallManager final : public Actor { vector> &&participants, int32 version, const string &offset, bool is_load, bool is_sync); - bool update_group_call_participant_can_be_muted(bool can_manage, const GroupCallParticipants *participants, - GroupCallParticipant &participant); + static bool update_group_call_participant_can_be_muted(bool can_manage, const GroupCallParticipants *participants, + GroupCallParticipant &participant); void update_group_call_participants_can_be_muted(InputGroupCallId input_group_call_id, bool can_manage, GroupCallParticipants *participants); @@ -360,11 +361,11 @@ class GroupCallManager final : public Actor { vector> get_recent_speakers(const GroupCall *group_call, bool for_update); - tl_object_ptr get_update_group_call_object( - const GroupCall *group_call, vector> recent_speakers) const; + static tl_object_ptr get_update_group_call_object( + const GroupCall *group_call, vector> recent_speakers); - tl_object_ptr get_group_call_object( - const GroupCall *group_call, vector> recent_speakers) const; + static tl_object_ptr get_group_call_object( + const GroupCall *group_call, vector> recent_speakers); tl_object_ptr get_update_group_call_participant_object( GroupCallId group_call_id, const GroupCallParticipant &participant); diff --git a/td/telegram/GroupCallParticipant.cpp b/td/telegram/GroupCallParticipant.cpp index 8f1c9270c..d9fee5ab5 100644 --- a/td/telegram/GroupCallParticipant.cpp +++ b/td/telegram/GroupCallParticipant.cpp @@ -20,7 +20,7 @@ GroupCallParticipant::GroupCallParticipant(const tl_object_ptrpeer_); - about = std::move(participant->about_); + about = participant->about_; audio_source = participant->source_; server_is_muted_by_themselves = participant->can_self_unmute_; server_is_muted_by_admin = participant->muted_ && !participant->can_self_unmute_; diff --git a/td/telegram/InlineQueriesManager.cpp b/td/telegram/InlineQueriesManager.cpp index 276ec31b2..174a4cfa8 100644 --- a/td/telegram/InlineQueriesManager.cpp +++ b/td/telegram/InlineQueriesManager.cpp @@ -488,7 +488,11 @@ void InlineQueriesManager::answer_inline_query(int64 inline_query_id, bool is_pe if (first_name.empty()) { return promise.set_error(Status::Error(400, "Field \"first_name\" must be non-empty")); } - title = last_name.empty() ? first_name : first_name + " " + last_name; + if (last_name.empty()) { + title = std::move(first_name); + } else { + title = PSTRING() << first_name << ' ' << last_name; + } description = std::move(phone_number); thumbnail_url = std::move(contact->thumbnail_url_); if (!thumbnail_url.empty()) { @@ -1460,7 +1464,7 @@ void InlineQueriesManager::on_get_inline_query_results(DialogId dialog_id, UserI if (result->type_ == "article") { auto article = make_tl_object(); article->id_ = std::move(result->id_); - article->url_ = get_web_document_url(std::move(result->content_)); + article->url_ = get_web_document_url(result->content_); if (result->url_.empty()) { article->hide_url_ = true; } else { diff --git a/td/telegram/JsonValue.cpp b/td/telegram/JsonValue.cpp index 254d6990b..110bf35e7 100644 --- a/td/telegram/JsonValue.cpp +++ b/td/telegram/JsonValue.cpp @@ -220,7 +220,7 @@ int32 get_json_value_int(telegram_api::object_ptr &&jso string get_json_value_string(telegram_api::object_ptr &&json_value, Slice name) { CHECK(json_value != nullptr); if (json_value->get_id() == telegram_api::jsonString::ID) { - return std::move(static_cast(json_value.get())->value_); + return std::move(static_cast(json_value.get())->value_); } LOG(ERROR) << "Expected String as " << name << ", but found " << to_string(json_value); return string(); diff --git a/td/telegram/LanguagePackManager.cpp b/td/telegram/LanguagePackManager.cpp index 812070a1b..32d3a66be 100644 --- a/td/telegram/LanguagePackManager.cpp +++ b/td/telegram/LanguagePackManager.cpp @@ -170,7 +170,7 @@ static string load_database_language_base_language_code(SqliteKeyValue *kv) { return kv->get("!base_language_code"); } -LanguagePackManager::LanguageDatabase *LanguagePackManager::add_language_database(const string &path) { +LanguagePackManager::LanguageDatabase *LanguagePackManager::add_language_database(string path) { auto it = language_databases_.find(path); if (it != language_databases_.end()) { return it->second.get(); @@ -395,11 +395,11 @@ void LanguagePackManager::on_language_pack_version_changed(bool is_base, int32 n LOG(INFO) << (is_base ? "Base" : "Main") << " language pack " << language_code << " vesrion has changed to " << new_version; - send_language_get_difference_query(language, language_code, version, Auto()); + send_language_get_difference_query(language, std::move(language_code), version, Auto()); } -void LanguagePackManager::send_language_get_difference_query(Language *language, const string &language_code, - int32 version, Promise &&promise) { +void LanguagePackManager::send_language_get_difference_query(Language *language, string language_code, int32 version, + Promise &&promise) { std::lock_guard lock(language->mutex_); language->get_difference_queries_.push_back(std::move(promise)); if (language->has_get_difference_query_) { @@ -1179,7 +1179,7 @@ void LanguagePackManager::synchronize_language_pack(string language_code, Promis if (version == -1) { version = 0; } - send_language_get_difference_query(language, language_code, version, std::move(promise)); + send_language_get_difference_query(language, std::move(language_code), version, std::move(promise)); } static td_api::object_ptr copy_language_pack_string_value( @@ -1294,7 +1294,7 @@ bool LanguagePackManager::is_valid_key(Slice key) { } void LanguagePackManager::save_strings_to_database(SqliteKeyValue *kv, int32 new_version, bool new_is_full, - int32 new_key_count, vector> strings) { + int32 new_key_count, vector> &&strings) { LOG(DEBUG) << "Save to database a language pack with new version " << new_version << " and " << strings.size() << " new strings"; if (new_version == -1 && strings.empty()) { @@ -1314,7 +1314,7 @@ void LanguagePackManager::save_strings_to_database(SqliteKeyValue *kv, int32 new } kv->begin_write_transaction().ensure(); - for (auto str : strings) { + for (const auto &str : strings) { if (!is_valid_key(str.first)) { LOG(ERROR) << "Have invalid key \"" << str.first << '"'; continue; @@ -1339,7 +1339,7 @@ void LanguagePackManager::save_strings_to_database(SqliteKeyValue *kv, int32 new } void LanguagePackManager::on_get_language_pack_strings( - string language_pack, string language_code, int32 version, bool is_diff, vector keys, + string language_pack, string language_code, int32 version, bool is_diff, vector &&keys, vector> results, Promise> promise) { Language *language = get_language(database_, language_pack, language_code); @@ -1370,7 +1370,7 @@ void LanguagePackManager::on_get_language_pack_strings( CHECK(result != nullptr); switch (result->get_id()) { case telegram_api::langPackString::ID: { - auto str = static_cast(result.get()); + auto str = telegram_api::move_object_as(result); auto it = language->ordinary_strings_.find(str->key_); if (it == language->ordinary_strings_.end()) { key_count_delta++; @@ -1383,11 +1383,11 @@ void LanguagePackManager::on_get_language_pack_strings( if (is_diff) { strings.push_back(get_language_pack_string_object(*it)); } - database_strings.emplace_back(str->key_, PSTRING() << '1' << it->second); + database_strings.emplace_back(std::move(str->key_), PSTRING() << '1' << it->second); break; } case telegram_api::langPackStringPluralized::ID: { - auto str = static_cast(result.get()); + auto str = telegram_api::move_object_as(result); PluralizedString value{std::move(str->zero_value_), std::move(str->one_value_), std::move(str->two_value_), std::move(str->few_value_), std::move(str->many_value_), std::move(str->other_value_)}; @@ -1404,20 +1404,21 @@ void LanguagePackManager::on_get_language_pack_strings( strings.push_back(get_language_pack_string_object(*it)); } database_strings.emplace_back( - str->key_, PSTRING() << '2' << it->second.zero_value_ << '\x00' << it->second.one_value_ << '\x00' - << it->second.two_value_ << '\x00' << it->second.few_value_ << '\x00' - << it->second.many_value_ << '\x00' << it->second.other_value_); + std::move(str->key_), PSTRING() + << '2' << it->second.zero_value_ << '\x00' << it->second.one_value_ << '\x00' + << it->second.two_value_ << '\x00' << it->second.few_value_ << '\x00' + << it->second.many_value_ << '\x00' << it->second.other_value_); break; } case telegram_api::langPackStringDeleted::ID: { - auto str = static_cast(result.get()); + auto str = telegram_api::move_object_as(result); key_count_delta -= static_cast(language->ordinary_strings_.erase(str->key_)); key_count_delta -= static_cast(language->pluralized_strings_.erase(str->key_)); - language->deleted_strings_.insert(std::move(str->key_)); + language->deleted_strings_.insert(str->key_); if (is_diff) { strings.push_back(get_language_pack_string_object(str->key_)); } - database_strings.emplace_back(str->key_, "3"); + database_strings.emplace_back(std::move(str->key_), "3"); break; } default: @@ -1426,7 +1427,7 @@ void LanguagePackManager::on_get_language_pack_strings( } } if (!language->is_full_) { - for (auto &key : keys) { + for (const auto &key : keys) { if (!language_has_string_unsafe(language, key)) { LOG(ERROR) << "Doesn't receive key " << key << " from server"; language->deleted_strings_.insert(key); @@ -1822,7 +1823,7 @@ void LanguagePackManager::delete_language(string language_code, Promise && } } -Status LanguagePackManager::do_delete_language(string language_code) { +Status LanguagePackManager::do_delete_language(const string &language_code) { add_language(database_, language_pack_, language_code); std::lock_guard packs_lock(database_->mutex_); diff --git a/td/telegram/LanguagePackManager.h b/td/telegram/LanguagePackManager.h index 6630b3cb2..9fb45e49d 100644 --- a/td/telegram/LanguagePackManager.h +++ b/td/telegram/LanguagePackManager.h @@ -108,7 +108,7 @@ class LanguagePackManager final : public NetQueryCallback { static std::mutex language_database_mutex_; static std::unordered_map> language_databases_; - static LanguageDatabase *add_language_database(const string &path); + static LanguageDatabase *add_language_database(string path); static Language *get_language(LanguageDatabase *database, const string &language_pack, const string &language_code); static Language *get_language(LanguagePack *language_pack, const string &language_code); @@ -160,25 +160,25 @@ class LanguagePackManager final : public NetQueryCallback { static bool is_valid_key(Slice key); void save_strings_to_database(SqliteKeyValue *kv, int32 new_version, bool new_is_full, int32 new_key_count, - vector> strings); + vector> &&strings); void load_empty_language_pack(const string &language_code); void on_get_language_pack_strings(string language_pack, string language_code, int32 version, bool is_diff, - vector keys, vector> results, + vector &&keys, vector> results, Promise> promise); void on_get_all_language_pack_strings(string language_pack, string language_code, Result> r_strings); - void send_language_get_difference_query(Language *language, const string &language_code, int32 version, + void send_language_get_difference_query(Language *language, string language_code, int32 version, Promise &&promise); void on_failed_get_difference(string language_pack, string language_code, Status error); void on_get_language_info(const string &language_pack, td_api::languagePackInfo *language_pack_info); - void save_server_language_pack_infos(LanguagePack *pack); + static void save_server_language_pack_infos(LanguagePack *pack); void on_get_languages(vector> languages, string language_pack, bool only_local, Promise> promise); @@ -186,7 +186,7 @@ class LanguagePackManager final : public NetQueryCallback { void on_get_language(tl_object_ptr lang_pack_language, string language_pack, string language_code, Promise> promise); - Status do_delete_language(string language_code); + Status do_delete_language(const string &language_code); void on_result(NetQueryPtr query) final; diff --git a/td/telegram/LinkManager.cpp b/td/telegram/LinkManager.cpp index 1edff8d6a..8aea83355 100644 --- a/td/telegram/LinkManager.cpp +++ b/td/telegram/LinkManager.cpp @@ -77,7 +77,7 @@ static string get_url_query_hash(bool is_tg, const HttpUrlQuery &url_query) { // /joinchat/ return path[1]; } - if (path.size() >= 1 && path[0].size() >= 2 && (path[0][0] == ' ' || path[0][0] == '+')) { + if (!path.empty() && path[0].size() >= 2 && (path[0][0] == ' ' || path[0][0] == '+')) { // /+ return path[0].substr(1); } @@ -811,7 +811,7 @@ unique_ptr LinkManager::parse_tg_link_query(Slice que } else if (path.size() == 1 && path[0] == "passport") { // passport?bot_id=&scope=&public_key=&nonce= return get_internal_link_passport(query, url_query.args_); - } else if (path.size() >= 1 && path[0] == "settings") { + } else if (!path.empty() && path[0] == "settings") { if (path.size() == 2 && path[1] == "change_number") { // settings/change_number return td::make_unique(); diff --git a/td/telegram/Location.h b/td/telegram/Location.h index afca9abd7..04432130b 100644 --- a/td/telegram/Location.h +++ b/td/telegram/Location.h @@ -34,7 +34,7 @@ class Location { void init(double latitude, double longitude, double horizontal_accuracy, int64 access_hash); - double fix_accuracy(double accuracy); + static double fix_accuracy(double accuracy); public: Location() = default; diff --git a/td/telegram/MessageContent.cpp b/td/telegram/MessageContent.cpp index 52df6bb85..97e4b1144 100644 --- a/td/telegram/MessageContent.cpp +++ b/td/telegram/MessageContent.cpp @@ -566,14 +566,14 @@ class MessageLiveLocation final : public MessageContent { , heading(heading) , proximity_alert_radius(proximity_alert_radius) { if (period < 0) { - period = 0; + this->period = 0; } if (heading < 0 || heading > 360) { LOG(ERROR) << "Receive wrong heading " << heading; - heading = 0; + this->heading = 0; } if (proximity_alert_radius < 0) { - proximity_alert_radius = 0; + this->proximity_alert_radius = 0; } } @@ -750,41 +750,41 @@ static void store(const MessageContent *content, StorerT &storer) { switch (content_type) { case MessageContentType::Animation: { - auto m = static_cast(content); + const auto *m = static_cast(content); td->animations_manager_->store_animation(m->file_id, storer); store(m->caption, storer); break; } case MessageContentType::Audio: { - auto m = static_cast(content); + const auto *m = static_cast(content); td->audios_manager_->store_audio(m->file_id, storer); store(m->caption, storer); store(true, storer); break; } case MessageContentType::Contact: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->contact, storer); break; } case MessageContentType::Document: { - auto m = static_cast(content); + const auto *m = static_cast(content); td->documents_manager_->store_document(m->file_id, storer); store(m->caption, storer); break; } case MessageContentType::Game: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->game, storer); break; } case MessageContentType::Invoice: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->input_invoice, storer); break; } case MessageContentType::LiveLocation: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->location, storer); store(m->period, storer); store(m->heading, storer); @@ -792,69 +792,69 @@ static void store(const MessageContent *content, StorerT &storer) { break; } case MessageContentType::Location: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->location, storer); break; } case MessageContentType::Photo: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->photo, storer); store(m->caption, storer); break; } case MessageContentType::Sticker: { - auto m = static_cast(content); + const auto *m = static_cast(content); td->stickers_manager_->store_sticker(m->file_id, false, storer, "MessageSticker"); break; } case MessageContentType::Text: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->text, storer); store(m->web_page_id, storer); break; } case MessageContentType::Unsupported: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->version, storer); break; } case MessageContentType::Venue: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->venue, storer); break; } case MessageContentType::Video: { - auto m = static_cast(content); + const auto *m = static_cast(content); td->videos_manager_->store_video(m->file_id, storer); store(m->caption, storer); break; } case MessageContentType::VideoNote: { - auto m = static_cast(content); + const auto *m = static_cast(content); td->video_notes_manager_->store_video_note(m->file_id, storer); store(m->is_viewed, storer); break; } case MessageContentType::VoiceNote: { - auto m = static_cast(content); + const auto *m = static_cast(content); td->voice_notes_manager_->store_voice_note(m->file_id, storer); store(m->caption, storer); store(m->is_listened, storer); break; } case MessageContentType::ChatCreate: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->title, storer); store(m->participant_user_ids, storer); break; } case MessageContentType::ChatChangeTitle: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->title, storer); break; } case MessageContentType::ChatChangePhoto: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->photo, storer); break; } @@ -862,40 +862,40 @@ static void store(const MessageContent *content, StorerT &storer) { case MessageContentType::ChatDeleteHistory: break; case MessageContentType::ChatAddUsers: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->user_ids, storer); break; } case MessageContentType::ChatJoinedByLink: break; case MessageContentType::ChatDeleteUser: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->user_id, storer); break; } case MessageContentType::ChatMigrateTo: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->migrated_to_channel_id, storer); break; } case MessageContentType::ChannelCreate: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->title, storer); break; } case MessageContentType::ChannelMigrateFrom: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->title, storer); store(m->migrated_from_chat_id, storer); break; } case MessageContentType::PinMessage: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->message_id, storer); break; } case MessageContentType::GameScore: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->game_message_id, storer); store(m->game_id, storer); store(m->score, storer); @@ -904,12 +904,12 @@ static void store(const MessageContent *content, StorerT &storer) { case MessageContentType::ScreenshotTaken: break; case MessageContentType::ChatSetTtl: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->ttl, storer); break; } case MessageContentType::Call: { - auto m = static_cast(content); + const auto *m = static_cast(content); BEGIN_STORE_FLAGS(); STORE_FLAG(m->is_video); END_STORE_FLAGS(); @@ -919,7 +919,7 @@ static void store(const MessageContent *content, StorerT &storer) { break; } case MessageContentType::PaymentSuccessful: { - auto m = static_cast(content); + const auto *m = static_cast(content); bool has_payload = !m->invoice_payload.empty(); bool has_shipping_option_id = !m->shipping_option_id.empty(); bool has_order_info = m->order_info != nullptr; @@ -970,46 +970,46 @@ static void store(const MessageContent *content, StorerT &storer) { case MessageContentType::ExpiredVideo: break; case MessageContentType::CustomServiceAction: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->message, storer); break; } case MessageContentType::WebsiteConnected: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->domain_name, storer); break; } case MessageContentType::PassportDataSent: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->types, storer); break; } case MessageContentType::PassportDataReceived: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->values, storer); store(m->credentials, storer); break; } case MessageContentType::Poll: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->poll_id, storer); break; } case MessageContentType::Dice: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->emoji, storer); store(m->dice_value, storer); break; } case MessageContentType::ProximityAlertTriggered: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->traveler_dialog_id, storer); store(m->watcher_dialog_id, storer); store(m->distance, storer); break; } case MessageContentType::GroupCall: { - auto m = static_cast(content); + const auto *m = static_cast(content); bool has_duration = m->duration >= 0; bool has_schedule_date = m->schedule_date > 0; BEGIN_STORE_FLAGS(); @@ -1026,13 +1026,13 @@ static void store(const MessageContent *content, StorerT &storer) { break; } case MessageContentType::InviteToGroupCall: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->input_group_call_id, storer); store(m->user_ids, storer); break; } case MessageContentType::ChatSetTheme: { - auto m = static_cast(content); + const auto *m = static_cast(content); store(m->emoji, storer); break; } @@ -2088,58 +2088,58 @@ SecretInputMedia get_secret_input_media(const MessageContent *content, Td *td, BufferSlice thumbnail) { switch (content->get_type()) { case MessageContentType::Animation: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->animations_manager_->get_secret_input_media(m->file_id, std::move(input_file), m->caption.text, std::move(thumbnail)); } case MessageContentType::Audio: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->audios_manager_->get_secret_input_media(m->file_id, std::move(input_file), m->caption.text, std::move(thumbnail)); } case MessageContentType::Contact: { - auto m = static_cast(content); + const auto *m = static_cast(content); return m->contact.get_secret_input_media_contact(); } case MessageContentType::Document: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->documents_manager_->get_secret_input_media(m->file_id, std::move(input_file), m->caption.text, std::move(thumbnail)); } case MessageContentType::Location: { - auto m = static_cast(content); + const auto *m = static_cast(content); return m->location.get_secret_input_media_geo_point(); } case MessageContentType::Photo: { - auto m = static_cast(content); + const auto *m = static_cast(content); return photo_get_secret_input_media(td->file_manager_.get(), m->photo, std::move(input_file), m->caption.text, std::move(thumbnail)); } case MessageContentType::Sticker: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->stickers_manager_->get_secret_input_media(m->file_id, std::move(input_file), std::move(thumbnail)); } case MessageContentType::Text: { CHECK(input_file == nullptr); CHECK(thumbnail.empty()); - auto m = static_cast(content); + const auto *m = static_cast(content); return td->web_pages_manager_->get_secret_input_media(m->web_page_id); } case MessageContentType::Venue: { - auto m = static_cast(content); + const auto *m = static_cast(content); return m->venue.get_secret_input_media_venue(); } case MessageContentType::Video: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->videos_manager_->get_secret_input_media(m->file_id, std::move(input_file), m->caption.text, std::move(thumbnail)); } case MessageContentType::VideoNote: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->video_notes_manager_->get_secret_input_media(m->file_id, std::move(input_file), std::move(thumbnail)); } case MessageContentType::VoiceNote: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->voice_notes_manager_->get_secret_input_media(m->file_id, std::move(input_file), m->caption.text); } case MessageContentType::Call: @@ -2191,35 +2191,35 @@ static tl_object_ptr get_input_media_impl( } switch (content->get_type()) { case MessageContentType::Animation: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->animations_manager_->get_input_media(m->file_id, std::move(input_file), std::move(input_thumbnail)); } case MessageContentType::Audio: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->audios_manager_->get_input_media(m->file_id, std::move(input_file), std::move(input_thumbnail)); } case MessageContentType::Contact: { - auto m = static_cast(content); + const auto *m = static_cast(content); return m->contact.get_input_media_contact(); } case MessageContentType::Dice: { - auto m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->emoji); } case MessageContentType::Document: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->documents_manager_->get_input_media(m->file_id, std::move(input_file), std::move(input_thumbnail)); } case MessageContentType::Game: { - auto m = static_cast(content); + const auto *m = static_cast(content); return m->game.get_input_media_game(td); } case MessageContentType::Invoice: { - auto m = static_cast(content); + const auto *m = static_cast(content); return get_input_media_invoice(m->input_invoice, td); } case MessageContentType::LiveLocation: { - auto m = static_cast(content); + const auto *m = static_cast(content); int32 flags = telegram_api::inputMediaGeoLive::PERIOD_MASK; if (m->heading != 0) { flags |= telegram_api::inputMediaGeoLive::HEADING_MASK; @@ -2230,36 +2230,36 @@ static tl_object_ptr get_input_media_impl( m->proximity_alert_radius); } case MessageContentType::Location: { - auto m = static_cast(content); + const auto *m = static_cast(content); return m->location.get_input_media_geo_point(); } case MessageContentType::Photo: { - auto m = static_cast(content); + const auto *m = static_cast(content); return photo_get_input_media(td->file_manager_.get(), m->photo, std::move(input_file), ttl); } case MessageContentType::Poll: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->poll_manager_->get_input_media(m->poll_id); } case MessageContentType::Sticker: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->stickers_manager_->get_input_media(m->file_id, std::move(input_file), std::move(input_thumbnail), emoji); } case MessageContentType::Venue: { - auto m = static_cast(content); + const auto *m = static_cast(content); return m->venue.get_input_media_venue(); } case MessageContentType::Video: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->videos_manager_->get_input_media(m->file_id, std::move(input_file), std::move(input_thumbnail), ttl); } case MessageContentType::VideoNote: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->video_notes_manager_->get_input_media(m->file_id, std::move(input_file), std::move(input_thumbnail)); } case MessageContentType::VoiceNote: { - auto m = static_cast(content); + const auto *m = static_cast(content); return td->voice_notes_manager_->get_input_media(m->file_id, std::move(input_file)); } case MessageContentType::Text: @@ -2390,31 +2390,31 @@ tl_object_ptr get_fake_input_media(Td *td, tl_object_p void delete_message_content_thumbnail(MessageContent *content, Td *td) { switch (content->get_type()) { case MessageContentType::Animation: { - auto m = static_cast(content); + auto *m = static_cast(content); return td->animations_manager_->delete_animation_thumbnail(m->file_id); } case MessageContentType::Audio: { - auto m = static_cast(content); + auto *m = static_cast(content); return td->audios_manager_->delete_audio_thumbnail(m->file_id); } case MessageContentType::Document: { - auto m = static_cast(content); + auto *m = static_cast(content); return td->documents_manager_->delete_document_thumbnail(m->file_id); } case MessageContentType::Photo: { - auto m = static_cast(content); + auto *m = static_cast(content); return photo_delete_thumbnail(m->photo); } case MessageContentType::Sticker: { - auto m = static_cast(content); + auto *m = static_cast(content); return td->stickers_manager_->delete_sticker_thumbnail(m->file_id); } case MessageContentType::Video: { - auto m = static_cast(content); + auto *m = static_cast(content); return td->videos_manager_->delete_video_thumbnail(m->file_id); } case MessageContentType::VideoNote: { - auto m = static_cast(content); + auto *m = static_cast(content); return td->video_notes_manager_->delete_video_note_thumbnail(m->file_id); } case MessageContentType::Contact: @@ -2706,9 +2706,9 @@ static int32 get_message_content_media_index_mask(const MessageContent *content, return message_search_filter_index_mask(MessageSearchFilter::ChatPhoto); case MessageContentType::Call: { int32 index_mask = message_search_filter_index_mask(MessageSearchFilter::Call); - auto message_call = static_cast(content); - if (!is_outgoing && (message_call->discard_reason == CallDiscardReason::Declined || - message_call->discard_reason == CallDiscardReason::Missed)) { + const auto *m = static_cast(content); + if (!is_outgoing && + (m->discard_reason == CallDiscardReason::Declined || m->discard_reason == CallDiscardReason::Missed)) { index_mask |= message_search_filter_index_mask(MessageSearchFilter::MissedCall); } return index_mask; @@ -2802,8 +2802,8 @@ FullMessageId get_message_content_replied_message_id(DialogId dialog_id, const M std::pair get_message_content_group_call_info(const MessageContent *content) { CHECK(content->get_type() == MessageContentType::GroupCall); - auto message_group_call = static_cast(content); - return {message_group_call->input_group_call_id, message_group_call->duration >= 0}; + const auto *m = static_cast(content); + return {m->input_group_call_id, m->duration >= 0}; } vector get_message_content_added_user_ids(const MessageContent *content) { @@ -2949,8 +2949,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo switch (content_type) { case MessageContentType::Text: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); auto get_content_object = [td, dialog_id](const MessageContent *content) { return to_string( get_message_content_object(content, td, dialog_id, -1, false, false, std::numeric_limits::max())); @@ -2981,8 +2981,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::Animation: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (new_->file_id != old_->file_id) { if (need_merge_files) { td->animations_manager_->merge_animations(new_->file_id, old_->file_id, false); @@ -2995,8 +2995,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::Audio: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (new_->file_id != old_->file_id) { if (need_merge_files) { td->audios_manager_->merge_audios(new_->file_id, old_->file_id, false); @@ -3009,16 +3009,16 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::Contact: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->contact != new_->contact) { need_update = true; } break; } case MessageContentType::Document: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (new_->file_id != old_->file_id) { if (need_merge_files) { td->documents_manager_->merge_documents(new_->file_id, old_->file_id, false); @@ -3031,24 +3031,24 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::Game: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->game != new_->game) { need_update = true; } break; } case MessageContentType::Invoice: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->input_invoice != new_->input_invoice) { need_update = true; } break; } case MessageContentType::LiveLocation: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->location != new_->location) { need_update = true; } @@ -3063,8 +3063,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::Location: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->location != new_->location) { need_update = true; } @@ -3075,8 +3075,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::Photo: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + auto *new_ = static_cast(new_content); const Photo *old_photo = &old_->photo; Photo *new_photo = &new_->photo; if (old_photo->date != new_photo->date) { @@ -3152,8 +3152,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::Sticker: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (new_->file_id != old_->file_id) { if (need_merge_files) { td->stickers_manager_->merge_stickers(new_->file_id, old_->file_id, false); @@ -3163,8 +3163,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::Venue: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->venue != new_->venue) { need_update = true; } @@ -3175,8 +3175,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::Video: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (new_->file_id != old_->file_id) { if (need_merge_files) { td->videos_manager_->merge_videos(new_->file_id, old_->file_id, false); @@ -3189,8 +3189,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::VideoNote: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (new_->file_id != old_->file_id) { if (need_merge_files) { td->video_notes_manager_->merge_video_notes(new_->file_id, old_->file_id, false); @@ -3203,8 +3203,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::VoiceNote: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (new_->file_id != old_->file_id) { if (need_merge_files) { td->voice_notes_manager_->merge_voice_notes(new_->file_id, old_->file_id, false); @@ -3220,24 +3220,24 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::ChatCreate: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->title != new_->title || old_->participant_user_ids != new_->participant_user_ids) { need_update = true; } break; } case MessageContentType::ChatChangeTitle: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->title != new_->title) { need_update = true; } break; } case MessageContentType::ChatChangePhoto: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->photo != new_->photo) { need_update = true; } @@ -3248,8 +3248,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo case MessageContentType::ChatDeleteHistory: break; case MessageContentType::ChatAddUsers: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->user_ids != new_->user_ids) { need_update = true; } @@ -3258,48 +3258,48 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo case MessageContentType::ChatJoinedByLink: break; case MessageContentType::ChatDeleteUser: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->user_id != new_->user_id) { need_update = true; } break; } case MessageContentType::ChatMigrateTo: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->migrated_to_channel_id != new_->migrated_to_channel_id) { need_update = true; } break; } case MessageContentType::ChannelCreate: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->title != new_->title) { need_update = true; } break; } case MessageContentType::ChannelMigrateFrom: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->title != new_->title || old_->migrated_from_chat_id != new_->migrated_from_chat_id) { need_update = true; } break; } case MessageContentType::PinMessage: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->message_id != new_->message_id) { need_update = true; } break; } case MessageContentType::GameScore: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->game_message_id != new_->game_message_id || old_->game_id != new_->game_id || old_->score != new_->score) { need_update = true; @@ -3309,8 +3309,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo case MessageContentType::ScreenshotTaken: break; case MessageContentType::ChatSetTtl: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->ttl != new_->ttl) { LOG(ERROR) << "Ttl has changed from " << old_->ttl << " to " << new_->ttl; need_update = true; @@ -3318,8 +3318,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::Call: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->call_id != new_->call_id || old_->is_video != new_->is_video) { is_content_changed = true; } @@ -3329,8 +3329,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::PaymentSuccessful: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->invoice_dialog_id != new_->invoice_dialog_id || old_->invoice_message_id != new_->invoice_message_id || old_->currency != new_->currency || old_->total_amount != new_->total_amount || old_->invoice_payload != new_->invoice_payload || old_->shipping_option_id != new_->shipping_option_id || @@ -3349,32 +3349,32 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo case MessageContentType::ExpiredVideo: break; case MessageContentType::CustomServiceAction: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->message != new_->message) { need_update = true; } break; } case MessageContentType::WebsiteConnected: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->domain_name != new_->domain_name) { need_update = true; } break; } case MessageContentType::PassportDataSent: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->types != new_->types) { need_update = true; } break; } case MessageContentType::PassportDataReceived: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->values != new_->values) { need_update = true; } @@ -3384,24 +3384,24 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::Poll: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->poll_id != new_->poll_id) { need_update = true; } break; } case MessageContentType::Dice: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->emoji != new_->emoji || old_->dice_value != new_->dice_value) { need_update = true; } break; } case MessageContentType::ProximityAlertTriggered: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->traveler_dialog_id != new_->traveler_dialog_id || old_->watcher_dialog_id != new_->watcher_dialog_id || old_->distance != new_->distance) { need_update = true; @@ -3409,8 +3409,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::GroupCall: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->input_group_call_id != new_->input_group_call_id || old_->duration != new_->duration || old_->schedule_date != new_->schedule_date) { need_update = true; @@ -3421,8 +3421,8 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::InviteToGroupCall: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->input_group_call_id != new_->input_group_call_id || old_->user_ids != new_->user_ids) { need_update = true; } @@ -3432,16 +3432,16 @@ void merge_message_contents(Td *td, const MessageContent *old_content, MessageCo break; } case MessageContentType::ChatSetTheme: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->emoji != new_->emoji) { need_update = true; } break; } case MessageContentType::Unsupported: { - auto old_ = static_cast(old_content); - auto new_ = static_cast(new_content); + const auto *old_ = static_cast(old_content); + const auto *new_ = static_cast(new_content); if (old_->version != new_->version) { is_content_changed = true; } @@ -3761,7 +3761,7 @@ static auto telegram_documentAttributeAudio(bool is_voice_note, int duration, st if (!performer.empty()) { flags |= telegram_api::documentAttributeAudio::PERFORMER_MASK; } - if (waveform.size()) { + if (!waveform.empty()) { flags |= telegram_api::documentAttributeAudio::WAVEFORM_MASK; } return make_tl_object(flags, is_voice_note, duration, std::move(title), @@ -3912,6 +3912,8 @@ unique_ptr get_secret_message_content( constructor_id = secret_api::decryptedMessageMediaDocument::ID; break; } + default: + break; } bool is_media_empty = false; @@ -3925,7 +3927,7 @@ unique_ptr get_secret_message_content( case secret_api::decryptedMessageMediaGeoPoint::ID: { auto message_geo_point = move_tl_object_as(media); - auto m = make_unique(Location(std::move(message_geo_point))); + auto m = make_unique(Location(message_geo_point)); if (m->location.empty()) { is_media_empty = true; break; @@ -4099,7 +4101,7 @@ unique_ptr get_message_content(Td *td, FormattedText message, case telegram_api::messageMediaGeo::ID: { auto message_geo_point = move_tl_object_as(media); - auto m = make_unique(Location(std::move(message_geo_point->geo_))); + auto m = make_unique(Location(message_geo_point->geo_)); if (m->location.empty()) { break; } @@ -4108,7 +4110,7 @@ unique_ptr get_message_content(Td *td, FormattedText message, } case telegram_api::messageMediaGeoLive::ID: { auto message_geo_point_live = move_tl_object_as(media); - auto location = Location(std::move(message_geo_point_live->geo_)); + auto location = Location(message_geo_point_live->geo_); if (location.empty()) { break; } @@ -4346,7 +4348,8 @@ unique_ptr dup_message_content(Td *td, DialogId dialog_id, const } result->photo.photos.clear(); - if (thumbnail.type != 0) { + bool has_thumbnail = thumbnail.type != 0; + if (has_thumbnail) { thumbnail.type = 't'; result->photo.photos.push_back(std::move(thumbnail)); } @@ -4358,7 +4361,7 @@ unique_ptr dup_message_content(Td *td, DialogId dialog_id, const } result->photo.photos.back().file_id = fix_file_id(result->photo.photos.back().file_id); - if (thumbnail.type != 0) { + if (has_thumbnail) { result->photo.photos[0].file_id = td->file_manager_->dup_file_id(result->photo.photos[0].file_id); } return std::move(result); @@ -4724,37 +4727,37 @@ tl_object_ptr get_message_content_object(const MessageCo CHECK(content != nullptr); switch (content->get_type()) { case MessageContentType::Animation: { - const MessageAnimation *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( td->animations_manager_->get_animation_object(m->file_id), get_formatted_text_object(m->caption, skip_bot_commands, max_media_timestamp), is_content_secret); } case MessageContentType::Audio: { - const MessageAudio *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( td->audios_manager_->get_audio_object(m->file_id), get_formatted_text_object(m->caption, skip_bot_commands, max_media_timestamp)); } case MessageContentType::Contact: { - const MessageContact *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->contact.get_contact_object()); } case MessageContentType::Document: { - const MessageDocument *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( td->documents_manager_->get_document_object(m->file_id, PhotoFormat::Jpeg), get_formatted_text_object(m->caption, skip_bot_commands, max_media_timestamp)); } case MessageContentType::Game: { - const MessageGame *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->game.get_game_object(td, skip_bot_commands)); } case MessageContentType::Invoice: { - const MessageInvoice *m = static_cast(content); + const auto *m = static_cast(content); return get_message_invoice_object(m->input_invoice, td); } case MessageContentType::LiveLocation: { - const MessageLiveLocation *m = static_cast(content); + const auto *m = static_cast(content); auto passed = max(G()->unix_time_cached() - message_date, 0); auto expires_in = max(0, m->period - passed); auto heading = expires_in == 0 ? 0 : m->heading; @@ -4763,21 +4766,21 @@ tl_object_ptr get_message_content_object(const MessageCo proximity_alert_radius); } case MessageContentType::Location: { - const MessageLocation *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->location.get_location_object(), 0, 0, 0, 0); } case MessageContentType::Photo: { - const MessagePhoto *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( get_photo_object(td->file_manager_.get(), m->photo), get_formatted_text_object(m->caption, skip_bot_commands, max_media_timestamp), is_content_secret); } case MessageContentType::Sticker: { - const MessageSticker *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(td->stickers_manager_->get_sticker_object(m->file_id)); } case MessageContentType::Text: { - const MessageText *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( get_formatted_text_object(m->text, skip_bot_commands, max_media_timestamp), td->web_pages_manager_->get_web_page_object(m->web_page_id)); @@ -4785,37 +4788,37 @@ tl_object_ptr get_message_content_object(const MessageCo case MessageContentType::Unsupported: return make_tl_object(); case MessageContentType::Venue: { - const MessageVenue *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->venue.get_venue_object()); } case MessageContentType::Video: { - const MessageVideo *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( td->videos_manager_->get_video_object(m->file_id), get_formatted_text_object(m->caption, skip_bot_commands, max_media_timestamp), is_content_secret); } case MessageContentType::VideoNote: { - const MessageVideoNote *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(td->video_notes_manager_->get_video_note_object(m->file_id), m->is_viewed, is_content_secret); } case MessageContentType::VoiceNote: { - const MessageVoiceNote *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( td->voice_notes_manager_->get_voice_note_object(m->file_id), get_formatted_text_object(m->caption, skip_bot_commands, max_media_timestamp), m->is_listened); } case MessageContentType::ChatCreate: { - const MessageChatCreate *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( m->title, td->contacts_manager_->get_user_ids_object(m->participant_user_ids, "MessageChatCreate")); } case MessageContentType::ChatChangeTitle: { - const MessageChatChangeTitle *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->title); } case MessageContentType::ChatChangePhoto: { - const MessageChatChangePhoto *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(get_chat_photo_object(td->file_manager_.get(), m->photo)); } case MessageContentType::ChatDeletePhoto: @@ -4823,53 +4826,53 @@ tl_object_ptr get_message_content_object(const MessageCo case MessageContentType::ChatDeleteHistory: return make_tl_object(); case MessageContentType::ChatAddUsers: { - const MessageChatAddUsers *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( td->contacts_manager_->get_user_ids_object(m->user_ids, "MessageChatAddUsers")); } case MessageContentType::ChatJoinedByLink: return make_tl_object(); case MessageContentType::ChatDeleteUser: { - const MessageChatDeleteUser *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( td->contacts_manager_->get_user_id_object(m->user_id, "MessageChatDeleteMember")); } case MessageContentType::ChatMigrateTo: { - const MessageChatMigrateTo *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( td->contacts_manager_->get_supergroup_id_object(m->migrated_to_channel_id, "MessageChatUpgradeTo")); } case MessageContentType::ChannelCreate: { - const MessageChannelCreate *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->title); } case MessageContentType::ChannelMigrateFrom: { - const MessageChannelMigrateFrom *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( m->title, td->contacts_manager_->get_basic_group_id_object(m->migrated_from_chat_id, "MessageChatUpgradeFrom")); } case MessageContentType::PinMessage: { - const MessagePinMessage *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->message_id.get()); } case MessageContentType::GameScore: { - const MessageGameScore *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->game_message_id.get(), m->game_id, m->score); } case MessageContentType::ScreenshotTaken: return make_tl_object(); case MessageContentType::ChatSetTtl: { - const MessageChatSetTtl *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->ttl); } case MessageContentType::Call: { - const MessageCall *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->is_video, get_call_discard_reason_object(m->discard_reason), m->duration); } case MessageContentType::PaymentSuccessful: { - const MessagePaymentSuccessful *m = static_cast(content); + const auto *m = static_cast(content); if (td->auth_manager_->is_bot()) { return make_tl_object( m->currency, m->total_amount, m->invoice_payload, m->shipping_option_id, @@ -4887,29 +4890,29 @@ tl_object_ptr get_message_content_object(const MessageCo case MessageContentType::ExpiredVideo: return make_tl_object(); case MessageContentType::CustomServiceAction: { - const MessageCustomServiceAction *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->message); } case MessageContentType::WebsiteConnected: { - const MessageWebsiteConnected *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->domain_name); } case MessageContentType::PassportDataSent: { - const MessagePassportDataSent *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(get_passport_element_types_object(m->types)); } case MessageContentType::PassportDataReceived: { - const MessagePassportDataReceived *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( get_encrypted_passport_element_object(td->file_manager_.get(), m->values), get_encrypted_credentials_object(m->credentials)); } case MessageContentType::Poll: { - const MessagePoll *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(td->poll_manager_->get_poll_object(m->poll_id)); } case MessageContentType::Dice: { - const MessageDice *m = static_cast(content); + const auto *m = static_cast(content); auto initial_state = td->stickers_manager_->get_dice_stickers_object(m->emoji, 0); auto final_state = m->dice_value == 0 ? nullptr : td->stickers_manager_->get_dice_stickers_object(m->emoji, m->dice_value); @@ -4919,14 +4922,14 @@ tl_object_ptr get_message_content_object(const MessageCo m->dice_value, success_animation_frame_number); } case MessageContentType::ProximityAlertTriggered: { - const MessageProximityAlertTriggered *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( td->messages_manager_->get_message_sender_object(m->traveler_dialog_id, "messageProximityAlertTriggered 1"), td->messages_manager_->get_message_sender_object(m->watcher_dialog_id, "messageProximityAlertTriggered 2"), m->distance); } case MessageContentType::GroupCall: { - auto *m = static_cast(content); + const auto *m = static_cast(content); if (m->duration >= 0) { return make_tl_object(m->duration); } else { @@ -4939,13 +4942,13 @@ tl_object_ptr get_message_content_object(const MessageCo } } case MessageContentType::InviteToGroupCall: { - auto *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object( td->group_call_manager_->get_group_call_id(m->input_group_call_id, DialogId()).get(), td->contacts_manager_->get_user_ids_object(m->user_ids, "MessageInviteToGroupCall")); } case MessageContentType::ChatSetTheme: { - const MessageChatSetTheme *m = static_cast(content); + const auto *m = static_cast(content); return make_tl_object(m->emoji); } default: @@ -5226,36 +5229,36 @@ vector get_message_content_file_ids(const MessageContent *content, const string get_message_content_search_text(const Td *td, const MessageContent *content) { switch (content->get_type()) { case MessageContentType::Text: { - auto *text = static_cast(content); + const auto *text = static_cast(content); if (!text->web_page_id.is_valid()) { return text->text.text; } return PSTRING() << text->text.text << " " << td->web_pages_manager_->get_web_page_search_text(text->web_page_id); } case MessageContentType::Animation: { - auto animation = static_cast(content); + const auto *animation = static_cast(content); return PSTRING() << td->animations_manager_->get_animation_search_text(animation->file_id) << " " << animation->caption.text; } case MessageContentType::Audio: { - auto audio = static_cast(content); + const auto *audio = static_cast(content); return PSTRING() << td->audios_manager_->get_audio_search_text(audio->file_id) << " " << audio->caption.text; } case MessageContentType::Document: { - auto document = static_cast(content); + const auto *document = static_cast(content); return PSTRING() << td->documents_manager_->get_document_search_text(document->file_id) << " " << document->caption.text; } case MessageContentType::Photo: { - auto photo = static_cast(content); + const auto *photo = static_cast(content); return photo->caption.text; } case MessageContentType::Video: { - auto video = static_cast(content); + const auto *video = static_cast(content); return PSTRING() << td->videos_manager_->get_video_search_text(video->file_id) << " " << video->caption.text; } case MessageContentType::Poll: { - auto poll = static_cast(content); + const auto *poll = static_cast(content); return td->poll_manager_->get_poll_search_text(poll->poll_id); } case MessageContentType::Contact: @@ -5338,8 +5341,8 @@ bool need_reget_message_content(const MessageContent *content) { CHECK(content != nullptr); switch (content->get_type()) { case MessageContentType::Unsupported: { - auto message_unsupported = static_cast(content); - return message_unsupported->version != MessageUnsupported::CURRENT_VERSION; + const auto *m = static_cast(content); + return m->version != MessageUnsupported::CURRENT_VERSION; } default: return false; @@ -5397,7 +5400,7 @@ void update_failed_to_send_message_content(Td *td, unique_ptr &c // do not forget about failed to send message forwards switch (content->get_type()) { case MessageContentType::Poll: { - const MessagePoll *message_poll = static_cast(content.get()); + const auto *message_poll = static_cast(content.get()); if (PollManager::is_local_poll_id(message_poll->poll_id)) { td->poll_manager_->stop_local_poll(message_poll->poll_id); } @@ -5412,7 +5415,7 @@ void update_failed_to_send_message_content(Td *td, unique_ptr &c void add_message_content_dependencies(Dependencies &dependencies, const MessageContent *message_content) { switch (message_content->get_type()) { case MessageContentType::Text: { - auto content = static_cast(message_content); + const auto *content = static_cast(message_content); dependencies.web_page_ids.insert(content->web_page_id); break; } @@ -5421,14 +5424,14 @@ void add_message_content_dependencies(Dependencies &dependencies, const MessageC case MessageContentType::Audio: break; case MessageContentType::Contact: { - auto content = static_cast(message_content); + const auto *content = static_cast(message_content); dependencies.user_ids.insert(content->contact.get_user_id()); break; } case MessageContentType::Document: break; case MessageContentType::Game: { - auto content = static_cast(message_content); + const auto *content = static_cast(message_content); dependencies.user_ids.insert(content->game.get_bot_user_id()); break; } @@ -5451,7 +5454,7 @@ void add_message_content_dependencies(Dependencies &dependencies, const MessageC case MessageContentType::VoiceNote: break; case MessageContentType::ChatCreate: { - auto content = static_cast(message_content); + const auto *content = static_cast(message_content); dependencies.user_ids.insert(content->participant_user_ids.begin(), content->participant_user_ids.end()); break; } @@ -5464,26 +5467,26 @@ void add_message_content_dependencies(Dependencies &dependencies, const MessageC case MessageContentType::ChatDeleteHistory: break; case MessageContentType::ChatAddUsers: { - auto content = static_cast(message_content); + const auto *content = static_cast(message_content); dependencies.user_ids.insert(content->user_ids.begin(), content->user_ids.end()); break; } case MessageContentType::ChatJoinedByLink: break; case MessageContentType::ChatDeleteUser: { - auto content = static_cast(message_content); + const auto *content = static_cast(message_content); dependencies.user_ids.insert(content->user_id); break; } case MessageContentType::ChatMigrateTo: { - auto content = static_cast(message_content); + const auto *content = static_cast(message_content); dependencies.channel_ids.insert(content->migrated_to_channel_id); break; } case MessageContentType::ChannelCreate: break; case MessageContentType::ChannelMigrateFrom: { - auto content = static_cast(message_content); + const auto *content = static_cast(message_content); dependencies.chat_ids.insert(content->migrated_from_chat_id); break; } @@ -5500,7 +5503,7 @@ void add_message_content_dependencies(Dependencies &dependencies, const MessageC case MessageContentType::Call: break; case MessageContentType::PaymentSuccessful: { - auto content = static_cast(message_content); + const auto *content = static_cast(message_content); add_dialog_and_dependencies(dependencies, content->invoice_dialog_id); break; } @@ -5524,7 +5527,7 @@ void add_message_content_dependencies(Dependencies &dependencies, const MessageC case MessageContentType::Dice: break; case MessageContentType::ProximityAlertTriggered: { - auto content = static_cast(message_content); + const auto *content = static_cast(message_content); add_message_sender_dependencies(dependencies, content->traveler_dialog_id); add_message_sender_dependencies(dependencies, content->watcher_dialog_id); break; @@ -5532,7 +5535,7 @@ void add_message_content_dependencies(Dependencies &dependencies, const MessageC case MessageContentType::GroupCall: break; case MessageContentType::InviteToGroupCall: { - auto content = static_cast(message_content); + const auto *content = static_cast(message_content); dependencies.user_ids.insert(content->user_ids.begin(), content->user_ids.end()); break; } diff --git a/td/telegram/MessageEntity.cpp b/td/telegram/MessageEntity.cpp index 8e1b7a68f..0a4203f0c 100644 --- a/td/telegram/MessageEntity.cpp +++ b/td/telegram/MessageEntity.cpp @@ -1595,7 +1595,7 @@ static void fix_entity_offsets(Slice text, vector &entities) { auto entity_begin = entity.offset; auto entity_end = entity.offset + entity.length; - int32 pos = static_cast(ptr - begin); + auto pos = static_cast(ptr - begin); if (entity_begin == pos) { cnt--; entity.offset = utf16_pos; @@ -3010,8 +3010,8 @@ static Result> do_parse_html(CSlice text, string &result) if (tag_name == "a" && attribute_name == Slice("href")) { argument = std::move(attribute_value); - } - if (tag_name == "code" && attribute_name == Slice("class") && begins_with(attribute_value, "language-")) { + } else if (tag_name == "code" && attribute_name == Slice("class") && + begins_with(attribute_value, "language-")) { argument = attribute_value.substr(9); } } @@ -3631,7 +3631,7 @@ static Result clean_input_string_with_entities(const string &text, vecto utf16_offset += 1 + (c >= 0xf0); // >= 4 bytes in symbol => surrogate pair } if (c == 0xe2 && pos + 2 < text_size) { - unsigned char next = static_cast(text[pos + 1]); + auto next = static_cast(text[pos + 1]); if (next == 0x80) { next = static_cast(text[pos + 2]); if (0xa8 <= next && next <= 0xae) { @@ -3642,7 +3642,7 @@ static Result clean_input_string_with_entities(const string &text, vecto } } if (c == 0xcc && pos + 1 < text_size) { - unsigned char next = static_cast(text[pos + 1]); + auto next = static_cast(text[pos + 1]); // remove vertical lines if (next == 0xb3 || next == 0xbf || next == 0x8a) { pos++; @@ -4010,7 +4010,7 @@ Status fix_formatted_text(string &text, vector &entities, bool al first_non_whitespaces_pos++; } if (first_non_whitespaces_pos > 0) { - int32 offset = narrow_cast(first_non_whitespaces_pos); + auto offset = narrow_cast(first_non_whitespaces_pos); text = result.substr(first_non_whitespaces_pos); for (auto &entity : entities) { entity.offset -= offset; diff --git a/td/telegram/MessagesDb.cpp b/td/telegram/MessagesDb.cpp index f15dc3d3b..5a300197b 100644 --- a/td/telegram/MessagesDb.cpp +++ b/td/telegram/MessagesDb.cpp @@ -902,8 +902,8 @@ class MessagesDbImpl final : public MessagesDbSyncInterface { return std::move(right); } - Result> get_messages_inner(SqliteStatement &stmt, DialogId dialog_id, - int64 from_message_id, int32 limit) { + static Result> get_messages_inner(SqliteStatement &stmt, DialogId dialog_id, + int64 from_message_id, int32 limit) { SCOPE_EXIT { stmt.reset(); }; diff --git a/td/telegram/MessagesManager.cpp b/td/telegram/MessagesManager.cpp index 9f79837be..28c8f3b59 100644 --- a/td/telegram/MessagesManager.cpp +++ b/td/telegram/MessagesManager.cpp @@ -151,7 +151,7 @@ class UpdateDialogFiltersOrderQuery final : public Td::ResultHandler { explicit UpdateDialogFiltersOrderQuery(Promise &&promise) : promise_(std::move(promise)) { } - void send(vector dialog_filter_ids) { + void send(const vector &dialog_filter_ids) { send_query(G()->net_query_creator().create(telegram_api::messages_updateDialogFiltersOrder( transform(dialog_filter_ids, [](auto dialog_filter_id) { return dialog_filter_id.get(); })))); } @@ -496,7 +496,7 @@ class GetChannelMessagesQuery final : public Td::ResultHandler { } } } - td->messages_manager_->on_get_empty_messages(DialogId(channel_id_), std::move(empty_message_ids)); + td->messages_manager_->on_get_empty_messages(DialogId(channel_id_), empty_message_ids); } td->messages_manager_->get_channel_difference_if_needed( DialogId(channel_id_), std::move(info), @@ -1529,7 +1529,7 @@ class SaveDraftMessageQuery final : public Td::ResultHandler { if (draft_message->input_message_text.disable_web_page_preview) { flags |= MessagesManager::SEND_MESSAGE_FLAG_DISABLE_WEB_PAGE_PREVIEW; } - if (draft_message->input_message_text.text.entities.size()) { + if (!draft_message->input_message_text.text.entities.empty()) { flags |= MessagesManager::SEND_MESSAGE_FLAG_HAS_ENTITIES; } } @@ -2190,9 +2190,7 @@ class SearchMessagesQuery final : public Td::ResultHandler { int32 limit, MessageSearchFilter filter, MessageId top_thread_message_id, int64 random_id) { auto input_peer = dialog_id.is_valid() ? td->messages_manager_->get_input_peer(dialog_id, AccessRights::Read) : make_tl_object(); - if (input_peer == nullptr) { - return promise_.set_error(Status::Error(400, "Can't access the chat")); - } + CHECK(input_peer != nullptr); dialog_id_ = dialog_id; query_ = query; @@ -6265,8 +6263,6 @@ void MessagesManager::memory_stats(vector &output) { output.push_back(","); output.push_back("\"message_id_to_dialog_id_\":"); output.push_back(std::to_string(this->message_id_to_dialog_id_.size())); output.push_back(","); - output.push_back("\"message_random_ids_\":"); output.push_back(std::to_string(this->message_random_ids_.size())); - output.push_back(","); output.push_back("\"notification_group_id_to_dialog_id_\":"); output.push_back(std::to_string(this->notification_group_id_to_dialog_id_.size())); output.push_back(","); output.push_back("\"previous_repaired_read_inbox_max_message_id_\":"); output.push_back(std::to_string(this->previous_repaired_read_inbox_max_message_id_.size())); @@ -9209,9 +9205,9 @@ void MessagesManager::after_get_difference() { } } -void MessagesManager::on_get_empty_messages(DialogId dialog_id, vector empty_message_ids) { +void MessagesManager::on_get_empty_messages(DialogId dialog_id, const vector &empty_message_ids) { if (!empty_message_ids.empty()) { - delete_dialog_messages(dialog_id, std::move(empty_message_ids), true, true, "on_get_empty_messages"); + delete_dialog_messages(dialog_id, empty_message_ids, true, true, "on_get_empty_messages"); } } @@ -9749,7 +9745,7 @@ void MessagesManager::on_get_dialog_messages_search_result( CHECK(d != nullptr); for (auto &message : messages) { auto new_full_message_id = on_get_message(std::move(message), false, dialog_id.get_type() == DialogType::Channel, - false, false, false, "SearchMessagesQuery"); + false, false, false, "on_get_dialog_messages_search_result"); if (new_full_message_id == FullMessageId()) { total_count--; continue; @@ -10232,7 +10228,7 @@ bool MessagesManager::can_get_message_statistics(DialogId dialog_id, const Messa return td_->contacts_manager_->can_get_channel_message_statistics(dialog_id); } -bool MessagesManager::can_delete_channel_message(DialogParticipantStatus status, const Message *m, bool is_bot) { +bool MessagesManager::can_delete_channel_message(const DialogParticipantStatus &status, const Message *m, bool is_bot) { if (m == nullptr) { return true; } @@ -16128,14 +16124,13 @@ void MessagesManager::reload_pinned_dialogs(DialogListId dialog_list_id, Promise if (dialog_list_id.is_folder()) { send_closure(td_->create_net_actor(std::move(promise)), &GetPinnedDialogsActor::send, dialog_list_id.get_folder_id(), get_sequence_dispatcher_id(DialogId(), MessageContentType::None)); - } - if (dialog_list_id.is_filter()) { + } else if (dialog_list_id.is_filter()) { schedule_dialog_filters_reload(0.0); dialog_filter_reload_queries_.push_back(std::move(promise)); } } -double MessagesManager::get_dialog_filters_cache_time() const { +double MessagesManager::get_dialog_filters_cache_time() { return DIALOG_FILTERS_CACHE_TIME * 0.0001 * Random::fast(9000, 11000); } @@ -16489,7 +16484,7 @@ std::pair> MessagesManager::get_recently_opened_dialogs( vector MessagesManager::sort_dialogs_by_order(const vector &dialog_ids, int32 limit) const { CHECK(!td_->auth_manager_->is_bot()); - int64 fake_order = static_cast(dialog_ids.size()) + 1; + auto fake_order = static_cast(dialog_ids.size()) + 1; auto dialog_dates = transform(dialog_ids, [this, &fake_order](DialogId dialog_id) { const Dialog *d = get_dialog(dialog_id); CHECK(d != nullptr); @@ -16718,7 +16713,7 @@ void MessagesManager::on_get_common_dialogs(UserId user_id, int64 offset_chat_id td_->contacts_manager_->on_update_user_common_chat_count(user_id, total_count); } - result.push_back(DialogId()); + result.emplace_back(); } common_dialogs.total_count = total_count; } @@ -17379,15 +17374,15 @@ void MessagesManager::on_get_message_viewers(DialogId dialog_id, vector void MessagesManager::get_dialog_info_full(DialogId dialog_id, Promise &&promise, const char *source) { switch (dialog_id.get_type()) { case DialogType::User: - send_closure_later(G()->contacts_manager(), &ContactsManager::load_user_full, dialog_id.get_user_id(), false, + send_closure_later(td_->contacts_manager_actor_, &ContactsManager::load_user_full, dialog_id.get_user_id(), false, std::move(promise), source); return; case DialogType::Chat: - send_closure_later(G()->contacts_manager(), &ContactsManager::load_chat_full, dialog_id.get_chat_id(), false, + send_closure_later(td_->contacts_manager_actor_, &ContactsManager::load_chat_full, dialog_id.get_chat_id(), false, std::move(promise), source); return; case DialogType::Channel: - send_closure_later(G()->contacts_manager(), &ContactsManager::load_channel_full, dialog_id.get_channel_id(), + send_closure_later(td_->contacts_manager_actor_, &ContactsManager::load_channel_full, dialog_id.get_channel_id(), false, std::move(promise), source); return; case DialogType::SecretChat: @@ -17406,15 +17401,15 @@ void MessagesManager::reload_dialog_info_full(DialogId dialog_id) { switch (dialog_id.get_type()) { case DialogType::User: - send_closure_later(G()->contacts_manager(), &ContactsManager::reload_user_full, dialog_id.get_user_id()); + send_closure_later(td_->contacts_manager_actor_, &ContactsManager::reload_user_full, dialog_id.get_user_id()); return; case DialogType::Chat: - send_closure_later(G()->contacts_manager(), &ContactsManager::reload_chat_full, dialog_id.get_chat_id(), + send_closure_later(td_->contacts_manager_actor_, &ContactsManager::reload_chat_full, dialog_id.get_chat_id(), Promise()); return; case DialogType::Channel: - send_closure_later(G()->contacts_manager(), &ContactsManager::reload_channel_full, dialog_id.get_channel_id(), - Promise(), "reload_dialog_info_full"); + send_closure_later(td_->contacts_manager_actor_, &ContactsManager::reload_channel_full, + dialog_id.get_channel_id(), Promise(), "reload_dialog_info_full"); return; case DialogType::SecretChat: return; @@ -18259,7 +18254,7 @@ void MessagesManager::reorder_dialog_filters_on_server(vector di send_closure(actor_id, &MessagesManager::on_reorder_dialog_filters, std::move(dialog_filter_ids), result.is_error() ? result.move_as_error() : Status::OK()); }); - td_->create_handler(std::move(promise))->send(std::move(dialog_filter_ids)); + td_->create_handler(std::move(promise))->send(dialog_filter_ids); } void MessagesManager::on_reorder_dialog_filters(vector dialog_filter_ids, Status result) { @@ -19978,7 +19973,7 @@ void MessagesManager::open_dialog(Dialog *d) { d->is_has_scheduled_database_messages_checked = true; G()->td_db()->get_messages_db_async()->get_scheduled_messages( dialog_id, 1, - PromiseCreator::lambda([dialog_id, actor_id = actor_id(this)](vector messages) { + PromiseCreator::lambda([actor_id = actor_id(this), dialog_id](vector messages) { if (messages.empty()) { send_closure(actor_id, &MessagesManager::set_dialog_has_scheduled_database_messages, dialog_id, false); } @@ -20712,7 +20707,7 @@ tl_object_ptr MessagesManager::get_dialog_history(DialogId dia } } - if (messages.size()) { + if (!messages.empty()) { // maybe need some messages CHECK(offset == 0); preload_newer_messages(d, MessageId(messages[0]->id_)); @@ -21238,6 +21233,10 @@ std::pair> MessagesManager::search_dialog_messages( promise.set_error(Status::Error(400, "Chat not found")); return result; } + if (!have_input_peer(dialog_id, AccessRights::Read)) { + promise.set_error(Status::Error(400, "Can't access the chat")); + return {}; + } DialogId sender_dialog_id; if (sender != nullptr) { @@ -21895,7 +21894,7 @@ void MessagesManager::on_search_dialog_messages_db_result(int64 random_id, Dialo } auto &message_count = d->message_count_by_index[message_search_filter_index(filter)]; - int32 result_size = narrow_cast(res.size()); + auto result_size = narrow_cast(res.size()); bool from_the_end = from_message_id == MessageId::max() || (offset < 0 && (result_size == 0 || res[0] < from_message_id)); if ((message_count != -1 && message_count < result_size) || @@ -21939,7 +21938,7 @@ td_api::object_ptr MessagesManager::get_found_messages_ob } MessagesManager::FoundMessages MessagesManager::offline_search_messages(DialogId dialog_id, const string &query, - const string &offset, int32 limit, + string offset, int32 limit, MessageSearchFilter filter, int64 &random_id, Promise<> &&promise) { if (!G()->parameters().use_message_db) { @@ -21993,8 +21992,9 @@ MessagesManager::FoundMessages MessagesManager::offline_search_messages(DialogId found_fts_messages_[random_id]; // reserve place for result G()->td_db()->get_messages_db_async()->get_messages_fts( - std::move(fts_query), PromiseCreator::lambda([random_id, offset, limit, promise = std::move(promise)]( - Result fts_result) mutable { + std::move(fts_query), + PromiseCreator::lambda([random_id, offset = std::move(offset), limit, + promise = std::move(promise)](Result fts_result) mutable { send_closure(G()->messages_manager(), &MessagesManager::on_messages_db_fts_result, std::move(fts_result), std::move(offset), limit, random_id, std::move(promise)); })); @@ -22021,7 +22021,7 @@ void MessagesManager::on_messages_db_fts_result(Result resu for (auto &message : fts_result.messages) { auto m = on_get_message_from_database(message, false, "on_messages_db_fts_result"); if (m != nullptr) { - res.push_back(FullMessageId(message.dialog_id, m->message_id)); + res.emplace_back(message.dialog_id, m->message_id); } } @@ -22055,7 +22055,7 @@ void MessagesManager::on_messages_db_calls_result(Result auto m = on_get_message_from_database(message, false, "on_messages_db_calls_result"); if (m != nullptr && first_db_message_id <= m->message_id) { - res.push_back(FullMessageId(message.dialog_id, m->message_id)); + res.emplace_back(message.dialog_id, m->message_id); } } it->second.first = calls_db_state_.message_count_by_index[call_message_search_filter_index(filter)]; @@ -23249,6 +23249,14 @@ bool MessagesManager::is_anonymous_administrator(DialogId dialog_id, string *aut return true; } +int64 MessagesManager::generate_new_random_id() { + int64 random_id; + do { + random_id = Random::secure_int64(); + } while (random_id == 0 || being_sent_messages_.find(random_id) != being_sent_messages_.end()); + return random_id; +} + unique_ptr MessagesManager::create_message_to_send( Dialog *d, MessageId top_thread_message_id, MessageId reply_to_message_id, const MessageSendOptions &options, unique_ptr &&content, bool suppress_reply_info, unique_ptr forward_info, @@ -23324,7 +23332,7 @@ unique_ptr MessagesManager::create_message_to_send( } m->content = std::move(content); m->forward_info = std::move(forward_info); - m->is_copy = is_copy || forward_info != nullptr; + m->is_copy = is_copy || m->forward_info != nullptr; if (td_->auth_manager_->is_bot() || options.disable_notification || G()->shared_config().get_option_boolean("ignore_default_disable_notification")) { @@ -23369,10 +23377,7 @@ MessagesManager::Message *MessagesManager::get_message_to_send( message->have_previous = true; message->have_next = true; - do { - message->random_id = Random::secure_int64(); - } while (message->random_id == 0 || message_random_ids_.find(message->random_id) != message_random_ids_.end()); - message_random_ids_.insert(message->random_id); + message->random_id = generate_new_random_id(); bool need_update = false; CHECK(have_input_peer(d->dialog_id, AccessRights::Read)); @@ -23423,7 +23428,7 @@ Status MessagesManager::can_send_message(DialogId dialog_id) const { return Status::OK(); } -MessageId MessagesManager::get_persistent_message_id(const Dialog *d, MessageId message_id) const { +MessageId MessagesManager::get_persistent_message_id(const Dialog *d, MessageId message_id) { if (!message_id.is_valid() && !message_id.is_valid_scheduled()) { return MessageId(); } @@ -25788,18 +25793,14 @@ void MessagesManager::update_message_max_reply_media_timestamp(const Dialog *d, return; } - auto new_max_reply_media_timestamp = m->max_reply_media_timestamp; - if (!m->reply_to_message_id.is_valid()) { - new_max_reply_media_timestamp = -1; - } else { + auto new_max_reply_media_timestamp = -1; + if (m->reply_to_message_id.is_valid()) { auto replied_m = get_message(d, m->reply_to_message_id); if (replied_m != nullptr) { new_max_reply_media_timestamp = get_message_own_max_media_timestamp(replied_m); - } else if (d->deleted_message_ids.count(m->reply_to_message_id) || - m->reply_to_message_id <= d->last_clear_history_message_id || - m->reply_to_message_id <= d->max_unavailable_message_id) { - new_max_reply_media_timestamp = -1; - } else { + } else if (!d->deleted_message_ids.count(m->reply_to_message_id) && + m->reply_to_message_id > d->last_clear_history_message_id && + m->reply_to_message_id > d->max_unavailable_message_id) { // replied message isn't deleted and isn't loaded yet return; } @@ -28988,7 +28989,7 @@ void MessagesManager::send_update_chat_has_scheduled_messages(Dialog *d, bool fr } void MessagesManager::send_update_user_chat_action(DialogId dialog_id, MessageId top_thread_message_id, UserId user_id, - DialogAction action) { + const DialogAction &action) { if (td_->auth_manager_->is_bot()) { return; } @@ -29189,10 +29190,7 @@ void MessagesManager::on_send_message_file_part_missing(int64 random_id, int bad CHECK(d != nullptr); // need to change message random_id before resending - do { - m->random_id = Random::secure_int64(); - } while (m->random_id == 0 || message_random_ids_.find(m->random_id) != message_random_ids_.end()); - message_random_ids_.insert(m->random_id); + m->random_id = generate_new_random_id(); delete_random_id_to_message_id_correspondence(d, random_id, m->message_id); add_random_id_to_message_id_correspondence(d, m->random_id, m->message_id); @@ -29241,10 +29239,7 @@ void MessagesManager::on_send_message_file_reference_error(int64 random_id) { CHECK(d != nullptr); // need to change message random_id before resending - do { - m->random_id = Random::secure_int64(); - } while (m->random_id == 0 || message_random_ids_.find(m->random_id) != message_random_ids_.end()); - message_random_ids_.insert(m->random_id); + m->random_id = generate_new_random_id(); delete_random_id_to_message_id_correspondence(d, random_id, m->message_id); add_random_id_to_message_id_correspondence(d, m->random_id, m->message_id); @@ -32037,7 +32032,7 @@ tl_object_ptr MessagesManager::get_chat_event_action_ob } case telegram_api::channelAdminLogEventActionParticipantMute::ID: { auto action = move_tl_object_as(action_ptr); - GroupCallParticipant participant(std::move(action->participant_), 0); + GroupCallParticipant participant(action->participant_, 0); if (!participant.is_valid()) { return nullptr; } @@ -32046,7 +32041,7 @@ tl_object_ptr MessagesManager::get_chat_event_action_ob } case telegram_api::channelAdminLogEventActionParticipantUnmute::ID: { auto action = move_tl_object_as(action_ptr); - GroupCallParticipant participant(std::move(action->participant_), 0); + GroupCallParticipant participant(action->participant_, 0); if (!participant.is_valid()) { return nullptr; } @@ -32055,7 +32050,7 @@ tl_object_ptr MessagesManager::get_chat_event_action_ob } case telegram_api::channelAdminLogEventActionParticipantVolume::ID: { auto action = move_tl_object_as(action_ptr); - GroupCallParticipant participant(std::move(action->participant_), 0); + GroupCallParticipant participant(action->participant_, 0); if (!participant.is_valid()) { return nullptr; } @@ -33580,10 +33575,6 @@ void MessagesManager::delete_message_from_database(Dialog *d, MessageId message_ } } - if (m != nullptr && m->random_id != 0 && (m->is_outgoing || d->dialog_id == get_my_dialog_id())) { - message_random_ids_.erase(m->random_id); - } - if (m != nullptr && m->notification_id.is_valid()) { CHECK(!message_id.is_scheduled()); auto from_mentions = is_from_mention_notification_group(d, m); @@ -35565,7 +35556,7 @@ unique_ptr MessagesManager::parse_dialog(DialogId dialo return d; } -MessagesManager::Dialog *MessagesManager::on_load_dialog_from_database(DialogId dialog_id, const BufferSlice &value, +MessagesManager::Dialog *MessagesManager::on_load_dialog_from_database(DialogId dialog_id, BufferSlice &&value, const char *source) { CHECK(G()->parameters().use_message_db); @@ -35664,17 +35655,17 @@ bool MessagesManager::has_dialogs_from_folder(const DialogList &list, const Dial return false; } -bool MessagesManager::is_dialog_in_list(const Dialog *d, DialogListId dialog_list_id) const { +bool MessagesManager::is_dialog_in_list(const Dialog *d, DialogListId dialog_list_id) { return td::contains(d->dialog_list_ids, dialog_list_id); } -void MessagesManager::add_dialog_to_list(Dialog *d, DialogListId dialog_list_id) const { +void MessagesManager::add_dialog_to_list(Dialog *d, DialogListId dialog_list_id) { LOG(INFO) << "Add " << d->dialog_id << " to " << dialog_list_id; CHECK(!is_dialog_in_list(d, dialog_list_id)); d->dialog_list_ids.push_back(dialog_list_id); } -void MessagesManager::remove_dialog_from_list(Dialog *d, DialogListId dialog_list_id) const { +void MessagesManager::remove_dialog_from_list(Dialog *d, DialogListId dialog_list_id) { LOG(INFO) << "Remove " << d->dialog_id << " from " << dialog_list_id; bool is_removed = td::remove(d->dialog_list_ids, dialog_list_id); CHECK(is_removed); @@ -35811,7 +35802,7 @@ MessagesManager::get_dialog_positions(const Dialog *d) const { return positions; } -vector MessagesManager::get_dialog_list_ids(const Dialog *d) const { +vector MessagesManager::get_dialog_list_ids(const Dialog *d) { return d->dialog_list_ids; } @@ -36957,8 +36948,6 @@ MessagesManager::Message *MessagesManager::continue_send_message(DialogId dialog m->have_previous = true; m->have_next = true; - message_random_ids_.insert(m->random_id); - bool need_update = false; bool need_update_dialog_pos = false; auto result_message = @@ -37182,7 +37171,6 @@ void MessagesManager::on_binlog_events(vector &&events) { m->have_previous = true; m->have_next = true; - message_random_ids_.insert(m->random_id); forwarded_messages.push_back(add_message_to_dialog(to_dialog, std::move(m), true, &need_update, &need_update_dialog_pos, "forward message again")); send_update_new_message(to_dialog, forwarded_messages.back()); diff --git a/td/telegram/MessagesManager.h b/td/telegram/MessagesManager.h index db8805173..55248e981 100644 --- a/td/telegram/MessagesManager.h +++ b/td/telegram/MessagesManager.h @@ -182,7 +182,7 @@ class MessagesManager final : public Actor { bool have_input_peer(DialogId dialog_id, AccessRights access_rights) const; - void on_get_empty_messages(DialogId dialog_id, vector empty_message_ids); + void on_get_empty_messages(DialogId dialog_id, const vector &empty_message_ids); struct MessagesInfo { vector> messages; @@ -522,7 +522,7 @@ class MessagesManager final : public Actor { void load_dialogs(vector dialog_ids, Promise> &&promise); - void load_dialog_filter(DialogFilterId dialog_id, bool force, Promise &&promise); + void load_dialog_filter(DialogFilterId dialog_filter_id, bool force, Promise &&promise); void get_recommended_dialog_filters(Promise> &&promise); @@ -707,7 +707,7 @@ class MessagesManager final : public Actor { td_api::object_ptr get_found_messages_object(const FoundMessages &found_messages, const char *source); - FoundMessages offline_search_messages(DialogId dialog_id, const string &query, const string &offset, int32 limit, + FoundMessages offline_search_messages(DialogId dialog_id, const string &query, string offset, int32 limit, MessageSearchFilter filter, int64 &random_id, Promise<> &&promise); std::pair> search_messages(FolderId folder_id, bool ignore_folder_id, @@ -986,7 +986,7 @@ class MessagesManager final : public Actor { , sender_name(std::move(sender_name)) , from_dialog_id(from_dialog_id) , from_message_id(from_message_id) - , psa_type(psa_type) + , psa_type(std::move(psa_type)) , is_imported(is_imported) { } @@ -1162,8 +1162,8 @@ class MessagesManager final : public Actor { int32 server_unread_count = 0; int32 local_unread_count = 0; int32 unread_mention_count = 0; - MessageId last_read_inbox_message_id; int32 last_read_inbox_message_date = 0; // secret chats only + MessageId last_read_inbox_message_id; MessageId last_read_outbox_message_id; MessageId last_pinned_message_id; MessageId reply_markup_message_id; @@ -1188,11 +1188,13 @@ class MessagesManager final : public Actor { MessageId max_unavailable_message_id; // maximum unavailable message identifier for dialogs with cleared/unavailable history + int32 distance = -1; // distance to the peer + int32 last_clear_history_date = 0; MessageId last_clear_history_message_id; int64 order = DEFAULT_ORDER; - int32 delete_last_message_date = 0; MessageId deleted_last_message_id; + int32 delete_last_message_date = 0; int32 pending_last_message_date = 0; MessageId pending_last_message_id; MessageId max_notification_message_id; @@ -1211,8 +1213,6 @@ class MessagesManager final : public Actor { NotificationId new_secret_chat_notification_id; // secret chats only MessageId pinned_message_notification_message_id; - int32 distance = -1; // distance to the peer - bool has_contact_registered_message = false; bool is_last_message_deleted_locally = false; @@ -1266,10 +1266,13 @@ class MessagesManager final : public Actor { bool has_unload_timeout = false; bool is_channel_difference_finished = false; + bool suffix_load_done_ = false; + bool suffix_load_has_query_ = false; + int32 pts = 0; // for channels only int32 pending_read_channel_inbox_pts = 0; // for channels only - MessageId pending_read_channel_inbox_max_message_id; // for channels only int32 pending_read_channel_inbox_server_unread_count = 0; // for channels only + MessageId pending_read_channel_inbox_max_message_id; // for channels only std::unordered_map random_id_to_message_id; // for secret chats only MessageId last_assigned_message_id; // identifier of the last local or yet unsent message, assigned after @@ -1300,8 +1303,6 @@ class MessagesManager final : public Actor { // [suffix_load_first_message_id_, last_message_id] are loaded MessageId suffix_load_query_message_id_; std::vector, std::function>> suffix_load_queries_; - bool suffix_load_done_ = false; - bool suffix_load_has_query_ = false; std::unordered_map pending_viewed_live_locations; // message_id -> task_id std::unordered_set pending_viewed_message_ids; @@ -1781,6 +1782,8 @@ class MessagesManager final : public Actor { bool is_anonymous_administrator(DialogId dialog_id, string *author_signature) const; + int64 generate_new_random_id(); + unique_ptr create_message_to_send(Dialog *d, MessageId top_thread_message_id, MessageId reply_to_message_id, const MessageSendOptions &options, unique_ptr &&content, bool suppress_reply_info, unique_ptr forward_info, @@ -1817,7 +1820,7 @@ class MessagesManager final : public Actor { bool was_uploaded, bool was_thumbnail_uploaded, string file_reference, int32 scheduled_date, uint64 generation, Result &&result); - MessageId get_persistent_message_id(const Dialog *d, MessageId message_id) const; + static MessageId get_persistent_message_id(const Dialog *d, MessageId message_id); static FullMessageId get_replied_message_id(DialogId dialog_id, const Message *m); @@ -1916,18 +1919,18 @@ class MessagesManager final : public Actor { void on_yet_unsent_media_queue_updated(DialogId dialog_id); - void save_send_bot_start_message_log_event(UserId bot_user_id, DialogId dialog_id, const string ¶meter, - const Message *m); + static void save_send_bot_start_message_log_event(UserId bot_user_id, DialogId dialog_id, const string ¶meter, + const Message *m); void do_send_bot_start_message(UserId bot_user_id, DialogId dialog_id, const string ¶meter, const Message *m); - void save_send_inline_query_result_message_log_event(DialogId dialog_id, const Message *m, int64 query_id, - const string &result_id); + static void save_send_inline_query_result_message_log_event(DialogId dialog_id, const Message *m, int64 query_id, + const string &result_id); void do_send_inline_query_result_message(DialogId dialog_id, const Message *m, int64 query_id, const string &result_id); - uint64 save_send_screenshot_taken_notification_message_log_event(DialogId dialog_id, const Message *m); + static uint64 save_send_screenshot_taken_notification_message_log_event(DialogId dialog_id, const Message *m); void do_send_screenshot_taken_notification_message(DialogId dialog_id, const Message *m, uint64 log_event_id); @@ -1941,7 +1944,7 @@ class MessagesManager final : public Actor { bool can_get_message_statistics(DialogId dialog_id, const Message *m) const; - static bool can_delete_channel_message(DialogParticipantStatus status, const Message *m, bool is_bot); + static bool can_delete_channel_message(const DialogParticipantStatus &status, const Message *m, bool is_bot); bool can_delete_message(DialogId dialog_id, const Message *m) const; @@ -2123,7 +2126,7 @@ class MessagesManager final : public Actor { void on_dialog_updated(DialogId dialog_id, const char *source); - BufferSlice get_dialog_database_value(const Dialog *d); + static BufferSlice get_dialog_database_value(const Dialog *d); void save_dialog_to_database(DialogId dialog_id); @@ -2206,9 +2209,9 @@ class MessagesManager final : public Actor { void do_delete_message_log_event(const DeleteMessageLogEvent &log_event) const; - void attach_message_to_previous(Dialog *d, MessageId message_id, const char *source); + static void attach_message_to_previous(Dialog *d, MessageId message_id, const char *source); - void attach_message_to_next(Dialog *d, MessageId message_id, const char *source); + static void attach_message_to_next(Dialog *d, MessageId message_id, const char *source); bool update_message(Dialog *d, Message *old_message, unique_ptr new_message, bool *need_update_dialog_pos, bool is_message_in_dialog); @@ -2247,7 +2250,7 @@ class MessagesManager final : public Actor { vector get_message_notifications_from_database_force(Dialog *d, bool from_mentions, int32 limit); - Result> do_get_message_notifications_from_database_force( + static Result> do_get_message_notifications_from_database_force( Dialog *d, bool from_mentions, NotificationId from_notification_id, MessageId from_message_id, int32 limit); void do_get_message_notifications_from_database(Dialog *d, bool from_mentions, @@ -2341,7 +2344,7 @@ class MessagesManager final : public Actor { void send_update_chat_has_scheduled_messages(Dialog *d, bool from_deletion); void send_update_user_chat_action(DialogId dialog_id, MessageId top_thread_message_id, UserId user_id, - DialogAction action); + const DialogAction &action); void repair_dialog_action_bar(Dialog *d, const char *source); @@ -2387,7 +2390,7 @@ class MessagesManager final : public Actor { td_api::object_ptr get_update_unread_chat_count_object(const DialogList &list) const; - void save_unread_chat_count(const DialogList &list); + static void save_unread_chat_count(const DialogList &list); void set_dialog_last_read_inbox_message_id(Dialog *d, MessageId message_id, int32 server_unread_count, int32 local_unread_count, bool force_update, const char *source); @@ -2468,7 +2471,8 @@ class MessagesManager final : public Actor { static string get_notification_settings_scope_database_key(NotificationSettingsScope scope); - void save_scope_notification_settings(NotificationSettingsScope scope, const ScopeNotificationSettings &new_settings); + static void save_scope_notification_settings(NotificationSettingsScope scope, + const ScopeNotificationSettings &new_settings); bool update_dialog_notification_settings(DialogId dialog_id, DialogNotificationSettings *current_settings, const DialogNotificationSettings &new_settings); @@ -2533,7 +2537,7 @@ class MessagesManager final : public Actor { Dialog *get_dialog_force(DialogId dialog_id, const char *source = "get_dialog_force"); - Dialog *on_load_dialog_from_database(DialogId dialog_id, const BufferSlice &value, const char *source); + Dialog *on_load_dialog_from_database(DialogId dialog_id, BufferSlice &&value, const char *source); void on_get_dialogs_from_database(FolderId folder_id, int32 limit, DialogDbGetDialogsResult &&dialogs, Promise &&promise); @@ -2546,7 +2550,7 @@ class MessagesManager final : public Actor { void reload_pinned_dialogs(DialogListId dialog_list_id, Promise &&promise); - double get_dialog_filters_cache_time() const; + static double get_dialog_filters_cache_time(); void schedule_dialog_filters_reload(double timeout); @@ -2616,11 +2620,11 @@ class MessagesManager final : public Actor { bool has_dialogs_from_folder(const DialogList &list, const DialogFolder &folder) const; - bool is_dialog_in_list(const Dialog *d, DialogListId dialog_list_id) const; + static bool is_dialog_in_list(const Dialog *d, DialogListId dialog_list_id); - void add_dialog_to_list(Dialog *d, DialogListId dialog_list_id) const; + static void add_dialog_to_list(Dialog *d, DialogListId dialog_list_id); - void remove_dialog_from_list(Dialog *d, DialogListId dialog_list_id) const; + static void remove_dialog_from_list(Dialog *d, DialogListId dialog_list_id); bool need_dialog_in_filter(const Dialog *d, const DialogFilter *filter) const; @@ -2633,7 +2637,8 @@ class MessagesManager final : public Actor { std::unordered_map get_dialog_positions(const Dialog *d) const; - vector get_dialog_list_ids(const Dialog *d) const; + static vector get_dialog_list_ids(const Dialog *d); + DialogListView get_dialog_lists(const Dialog *d); DialogList &add_dialog_list(DialogListId dialog_list_id); @@ -3033,50 +3038,54 @@ class MessagesManager final : public Actor { static void add_message_dependencies(Dependencies &dependencies, const Message *m); - void save_send_message_log_event(DialogId dialog_id, const Message *m); + static void save_send_message_log_event(DialogId dialog_id, const Message *m); - uint64 save_toggle_dialog_report_spam_state_on_server_log_event(DialogId dialog_id, bool is_spam_dialog); + static uint64 save_toggle_dialog_report_spam_state_on_server_log_event(DialogId dialog_id, bool is_spam_dialog); - uint64 save_delete_messages_from_server_log_event(DialogId dialog_id, const vector &message_ids, - bool revoke); + static uint64 save_delete_messages_from_server_log_event(DialogId dialog_id, const vector &message_ids, + bool revoke); - uint64 save_delete_scheduled_messages_from_server_log_event(DialogId dialog_id, const vector &message_ids); + static uint64 save_delete_scheduled_messages_from_server_log_event(DialogId dialog_id, + const vector &message_ids); - uint64 save_delete_dialog_history_from_server_log_event(DialogId dialog_id, MessageId max_message_id, - bool remove_from_dialog_list, bool revoke); + static uint64 save_delete_dialog_history_from_server_log_event(DialogId dialog_id, MessageId max_message_id, + bool remove_from_dialog_list, bool revoke); - uint64 save_delete_all_call_messages_from_server_log_event(bool revoke); + static uint64 save_delete_all_call_messages_from_server_log_event(bool revoke); - uint64 save_block_message_sender_from_replies_on_server_log_event(MessageId message_id, bool delete_message, - bool delete_all_messages, bool report_spam); + static uint64 save_block_message_sender_from_replies_on_server_log_event(MessageId message_id, bool delete_message, + bool delete_all_messages, bool report_spam); - uint64 save_delete_all_channel_messages_from_user_on_server_log_event(ChannelId channel_id, UserId user_id); + static uint64 save_delete_all_channel_messages_from_user_on_server_log_event(ChannelId channel_id, UserId user_id); - uint64 save_read_all_dialog_mentions_on_server_log_event(DialogId dialog_id); + static uint64 save_read_all_dialog_mentions_on_server_log_event(DialogId dialog_id); - uint64 save_toggle_dialog_is_pinned_on_server_log_event(DialogId dialog_id, bool is_pinned); + static uint64 save_toggle_dialog_is_pinned_on_server_log_event(DialogId dialog_id, bool is_pinned); - uint64 save_reorder_pinned_dialogs_on_server_log_event(FolderId folder_id, const vector &dialog_ids); + static uint64 save_reorder_pinned_dialogs_on_server_log_event(FolderId folder_id, const vector &dialog_ids); - uint64 save_toggle_dialog_is_marked_as_unread_on_server_log_event(DialogId dialog_id, bool is_marked_as_unread); + static uint64 save_toggle_dialog_is_marked_as_unread_on_server_log_event(DialogId dialog_id, + bool is_marked_as_unread); - uint64 save_toggle_dialog_is_blocked_on_server_log_event(DialogId dialog_id, bool is_blocked); + static uint64 save_toggle_dialog_is_blocked_on_server_log_event(DialogId dialog_id, bool is_blocked); - uint64 save_read_message_contents_on_server_log_event(DialogId dialog_id, const vector &message_ids); + static uint64 save_read_message_contents_on_server_log_event(DialogId dialog_id, + const vector &message_ids); - uint64 save_update_scope_notification_settings_on_server_log_event(NotificationSettingsScope scope); + static uint64 save_update_scope_notification_settings_on_server_log_event(NotificationSettingsScope scope); - uint64 save_reset_all_notification_settings_on_server_log_event(); + static uint64 save_reset_all_notification_settings_on_server_log_event(); - uint64 save_get_dialog_from_server_log_event(DialogId dialog_id); + static uint64 save_get_dialog_from_server_log_event(DialogId dialog_id); - uint64 save_forward_messages_log_event(DialogId to_dialog_id, DialogId from_dialog_id, - const vector &messages, const vector &message_ids); + static uint64 save_forward_messages_log_event(DialogId to_dialog_id, DialogId from_dialog_id, + const vector &messages, + const vector &message_ids); - uint64 save_unpin_all_dialog_messages_on_server_log_event(DialogId dialog_id); + static uint64 save_unpin_all_dialog_messages_on_server_log_event(DialogId dialog_id); void suffix_load_loop(Dialog *d); - void suffix_load_update_first_message_id(Dialog *d); + static void suffix_load_update_first_message_id(Dialog *d); void suffix_load_query_ready(DialogId dialog_id); void suffix_load_add_query(Dialog *d, std::pair, std::function> query); void suffix_load_till_date(Dialog *d, int32 date, Promise<> promise); @@ -3161,7 +3170,6 @@ class MessagesManager final : public Actor { bool ttl_db_has_query_; Slot ttl_db_slot_; - std::unordered_set message_random_ids_; std::unordered_map being_sent_messages_; // message_random_id -> message std::unordered_map @@ -3312,7 +3320,10 @@ class MessagesManager final : public Actor { double start_time; ActiveDialogAction(MessageId top_thread_message_id, UserId user_id, DialogAction action, double start_time) - : top_thread_message_id(top_thread_message_id), user_id(user_id), action(action), start_time(start_time) { + : top_thread_message_id(top_thread_message_id) + , user_id(user_id) + , action(std::move(action)) + , start_time(start_time) { } }; diff --git a/td/telegram/NotificationManager.cpp b/td/telegram/NotificationManager.cpp index 4518cabc1..2aad75c56 100644 --- a/td/telegram/NotificationManager.cpp +++ b/td/telegram/NotificationManager.cpp @@ -241,7 +241,7 @@ void NotificationManager::init() { last_loaded_notification_group_key_.last_notification_date = std::numeric_limits::max(); if (max_notification_group_count_ != 0) { int32 loaded_groups = 0; - int32 needed_groups = static_cast(max_notification_group_count_); + auto needed_groups = static_cast(max_notification_group_count_); do { loaded_groups += load_message_notification_groups_from_database(needed_groups, false); } while (loaded_groups < needed_groups && last_loaded_notification_group_key_.last_notification_date != 0); @@ -1769,7 +1769,7 @@ void NotificationManager::on_notifications_removed( void NotificationManager::remove_added_notifications_from_pending_updates( NotificationGroupId group_id, - std::function ¬ification)> is_removed) { + const std::function ¬ification)> &is_removed) { auto it = pending_updates_.find(group_id.get()); if (it == pending_updates_.end()) { return; diff --git a/td/telegram/NotificationManager.h b/td/telegram/NotificationManager.h index 0f5f251e5..12688e427 100644 --- a/td/telegram/NotificationManager.h +++ b/td/telegram/NotificationManager.h @@ -111,7 +111,7 @@ class NotificationManager final : public Actor { void process_push_notification(string payload, Promise &&user_promise); - static Result get_push_receiver_id(string push); + static Result get_push_receiver_id(string payload); static Result decrypt_push(int64 encryption_key_id, string encryption_key, string push); // public for tests @@ -290,7 +290,7 @@ class NotificationManager final : public Actor { void remove_added_notifications_from_pending_updates( NotificationGroupId group_id, - std::function ¬ification)> is_removed); + const std::function ¬ification)> &is_removed); void flush_pending_updates(int32 group_id, const char *source); diff --git a/td/telegram/PasswordManager.cpp b/td/telegram/PasswordManager.cpp index 0e3cf7203..ee0dbbc47 100644 --- a/td/telegram/PasswordManager.cpp +++ b/td/telegram/PasswordManager.cpp @@ -656,7 +656,7 @@ Result PasswordManager::get_password_inp new_password_hash = new_hash.move_as_ok(); new_algo = make_tl_object( std::move(new_client_salt), BufferSlice(state.server_salt), state.srp_g, BufferSlice(state.srp_p)); - new_hint = std::move(update_settings.new_hint); + new_hint = update_settings.new_hint; if (have_secret) { update_secure_secret = true; } diff --git a/td/telegram/Payments.cpp b/td/telegram/Payments.cpp index 6607ff7e1..12b763529 100644 --- a/td/telegram/Payments.cpp +++ b/td/telegram/Payments.cpp @@ -1228,7 +1228,7 @@ void send_payment_form(Td *td, FullMessageId full_message_id, int64 payment_form if (!clean_input_string(credentials_id)) { return promise.set_error(Status::Error(400, "Credentials identifier must be encoded in UTF-8")); } - auto temp_password_state = td->password_manager_->get_actor_unsafe()->get_temp_password_state_sync(); + auto temp_password_state = PasswordManager::get_temp_password_state_sync(); if (!temp_password_state.has_temp_password) { return promise.set_error(Status::Error(400, "Temporary password required to use saved credentials")); } diff --git a/td/telegram/PhoneNumberManager.h b/td/telegram/PhoneNumberManager.h index da71ce238..e9e721357 100644 --- a/td/telegram/PhoneNumberManager.h +++ b/td/telegram/PhoneNumberManager.h @@ -47,7 +47,7 @@ class PhoneNumberManager final : public NetActor { void on_new_query(uint64 query_id); void on_query_error(Status status); - void on_query_error(uint64 id, Status status); + static void on_query_error(uint64 id, Status status); void on_query_ok(); void start_net_query(NetQueryType net_query_type, NetQueryPtr net_query); diff --git a/td/telegram/Photo.cpp b/td/telegram/Photo.cpp index 4de1b6b49..d72cf5334 100644 --- a/td/telegram/Photo.cpp +++ b/td/telegram/Photo.cpp @@ -448,8 +448,8 @@ Variant get_photo_size(FileManager *file_manager, PhotoSizeSo source.thumbnail().thumbnail_type = res.type; } - res.file_id = - register_photo(file_manager, source, id, access_hash, file_reference, owner_dialog_id, res.size, dc_id, format); + res.file_id = register_photo(file_manager, source, id, access_hash, std::move(file_reference), owner_dialog_id, + res.size, dc_id, format); if (!content.empty()) { file_manager->set_content(res.file_id, std::move(content)); @@ -481,8 +481,8 @@ AnimationSize get_animation_size(FileManager *file_manager, PhotoSizeSource sour source.thumbnail().thumbnail_type = res.type; } - res.file_id = register_photo(file_manager, source, id, access_hash, file_reference, owner_dialog_id, res.size, dc_id, - PhotoFormat::Mpeg4); + res.file_id = register_photo(file_manager, source, id, access_hash, std::move(file_reference), owner_dialog_id, + res.size, dc_id, PhotoFormat::Mpeg4); return res; } diff --git a/td/telegram/PhotoSizeSource.cpp b/td/telegram/PhotoSizeSource.cpp index 655f59321..a3923a2fe 100644 --- a/td/telegram/PhotoSizeSource.cpp +++ b/td/telegram/PhotoSizeSource.cpp @@ -150,7 +150,7 @@ string PhotoSizeSource::get_unique_name(int64 photo_id) const { UNREACHABLE(); break; } - return 0; + return string(); } static bool operator==(const PhotoSizeSource::Legacy &lhs, const PhotoSizeSource::Legacy &rhs) { diff --git a/td/telegram/PollManager.cpp b/td/telegram/PollManager.cpp index 939d2f5bf..94a54c1ad 100644 --- a/td/telegram/PollManager.cpp +++ b/td/telegram/PollManager.cpp @@ -617,7 +617,6 @@ PollId PollManager::create_poll(string &&question, vector &&options, boo CHECK(is_local_poll_id(poll_id)); bool is_inserted = polls_.emplace(poll_id, std::move(poll)).second; CHECK(is_inserted); - LOG(INFO) << "Created " << poll_id << " with question \"" << oneline(question) << '"'; return poll_id; } @@ -979,7 +978,7 @@ void PollManager::get_poll_voters(PollId poll_id, FullMessageId full_message_id, auto query_promise = PromiseCreator::lambda([actor_id = actor_id(this), poll_id, option_id, offset = voters.next_offset, - limit](Result> &&result) { + limit](Result> &&result) mutable { send_closure(actor_id, &PollManager::on_get_poll_voters, poll_id, option_id, std::move(offset), limit, std::move(result)); }); diff --git a/td/telegram/PollManager.h b/td/telegram/PollManager.h index 15b27e70f..247214843 100644 --- a/td/telegram/PollManager.h +++ b/td/telegram/PollManager.h @@ -167,7 +167,7 @@ class PollManager final : public Actor { static string get_poll_database_key(PollId poll_id); - void save_poll(const Poll *poll, PollId poll_id); + static void save_poll(const Poll *poll, PollId poll_id); void on_load_poll_from_database(PollId poll_id, string value); diff --git a/td/telegram/RecentDialogList.cpp b/td/telegram/RecentDialogList.cpp index 9006385bb..0a5121da4 100644 --- a/td/telegram/RecentDialogList.cpp +++ b/td/telegram/RecentDialogList.cpp @@ -259,7 +259,7 @@ std::pair> RecentDialogList::get_dialogs(int32 limit, Pr update_dialogs(); CHECK(limit >= 0); - int32 total_count = narrow_cast(dialog_ids_.size()); + auto total_count = narrow_cast(dialog_ids_.size()); return {total_count, vector(dialog_ids_.begin(), dialog_ids_.begin() + min(limit, total_count))}; } diff --git a/td/telegram/SecretChatActor.cpp b/td/telegram/SecretChatActor.cpp index 74ea528c8..12bd20ae6 100644 --- a/td/telegram/SecretChatActor.cpp +++ b/td/telegram/SecretChatActor.cpp @@ -132,8 +132,10 @@ void SecretChatActor::on_result_resendable(NetQueryPtr net_query, Promise(QueryType::Ignore): return Status::OK(); + default: + UNREACHABLE(); + return Status::OK(); } - UNREACHABLE(); }()); loop(); @@ -963,8 +965,8 @@ Status SecretChatActor::do_inbound_message_decrypted_unchecked(unique_ptr(decrypted_message_service->action_.get()); - uint32 start_seq_no = static_cast(action_resend->start_seq_no_ / 2); - uint32 finish_seq_no = static_cast(action_resend->end_seq_no_ / 2); + auto start_seq_no = static_cast(action_resend->start_seq_no_ / 2); + auto finish_seq_no = static_cast(action_resend->end_seq_no_ / 2); if (start_seq_no + MAX_RESEND_COUNT < finish_seq_no) { message->promise.set_value(Unit()); return Status::Error(PSLICE() << "Won't resend more than " << MAX_RESEND_COUNT << " messages"); @@ -1976,29 +1978,36 @@ void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionSetMe context_->secret_chat_db()->set_value(config_state_); send_update_secret_chat(); } + void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionReadMessages &read_messages) { // TODO } + void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionDeleteMessages &delete_messages) { // Corresponding log event won't be deleted before promise returned by add_changes is set. on_delete_messages(delete_messages.random_ids_).ensure(); } + void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionScreenshotMessages &screenshot) { - // noting to do + // nothing to do } + void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionFlushHistory &flush_history) { on_flush_history(pfs_state_.message_id).ensure(); } + void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionResend &resend) { if (seq_no_state_.resend_end_seq_no < resend.end_seq_no_ / 2) { // replay protection seq_no_state_.resend_end_seq_no = resend.end_seq_no_ / 2; on_seq_no_state_changed(); } } + void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionNotifyLayer ¬ify_layer) { config_state_.my_layer = notify_layer.layer_; context_->secret_chat_db()->set_value(config_state_); } + void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionTyping &typing) { // noop } @@ -2009,23 +2018,29 @@ Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionSetM send_update_secret_chat(); return Status::OK(); } + Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionReadMessages &read_messages) { // TODO return Status::OK(); } + Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionDeleteMessages &delete_messages) { return on_delete_messages(delete_messages.random_ids_); } + Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionScreenshotMessages &screenshot) { // TODO return Status::OK(); } + Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionFlushHistory &screenshot) { return on_flush_history(pfs_state_.message_id); } + Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionResend &resend) { return Status::OK(); } + Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionNotifyLayer ¬ify_layer) { if (notify_layer.layer_ > config_state_.his_layer) { config_state_.his_layer = notify_layer.layer_; @@ -2034,6 +2049,7 @@ Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionNoti } return Status::OK(); } + Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionTyping &typing) { // noop return Status::OK(); @@ -2045,16 +2061,19 @@ void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionReque pfs_state_.state = PfsState::WaitRequestResponse; on_pfs_state_changed(); } + void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionAcceptKey &accept_key) { CHECK(pfs_state_.state == PfsState::WaitSendAccept || pfs_state_.state == PfsState::SendAccept); pfs_state_.state = PfsState::WaitAcceptResponse; pfs_state_.handshake = mtproto::DhHandshake(); on_pfs_state_changed(); } + void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionAbortKey &abort_key) { // TODO LOG(FATAL) << "TODO"; } + void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionCommitKey &commit_key) { CHECK(pfs_state_.state == PfsState::WaitSendCommit || pfs_state_.state == PfsState::SendCommit); @@ -2069,11 +2088,11 @@ void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionCommi on_pfs_state_changed(); } + void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionNoop &noop) { // noop } -// decryptedMessageActionRequestKey#f3c9611b exchange_id:long g_a:bytes = DecryptedMessageAction; Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionRequestKey &request_key) { if (pfs_state_.state == PfsState::WaitRequestResponse || pfs_state_.state == PfsState::SendRequest) { if (pfs_state_.exchange_id > request_key.exchange_id_) { @@ -2112,7 +2131,6 @@ Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionRequ return Status::OK(); } -// decryptedMessageActionAcceptKey#6fe1735b exchange_id:long g_b:bytes key_fingerprint:long = DecryptedMessageAction; Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionAcceptKey &accept_key) { if (pfs_state_.state != PfsState::WaitRequestResponse) { return Status::Error("AcceptKey: unexpected"); @@ -2136,6 +2154,7 @@ Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionAcce on_pfs_state_changed(); return Status::OK(); } + Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionAbortKey &abort_key) { if (pfs_state_.exchange_id != abort_key.exchange_id_) { LOG(INFO) << "AbortKey: exchange_id mismatch: " << tag("my exchange_id", pfs_state_.exchange_id) @@ -2151,6 +2170,7 @@ Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionAbor on_pfs_state_changed(); return Status::OK(); } + Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionCommitKey &commit_key) { if (pfs_state_.state != PfsState::WaitAcceptResponse) { return Status::Error("CommitKey: unexpected"); @@ -2174,6 +2194,7 @@ Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionComm on_pfs_state_changed(); return Status::OK(); } + Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionNoop &noop) { // noop return Status::OK(); @@ -2224,7 +2245,6 @@ void SecretChatActor::on_outbound_action(secret_api::DecryptedMessageAction &act downcast_call(action, [&](auto &obj) { this->on_outbound_action(obj); }); } -// decryptedMessageActionRequestKey#f3c9611b exchange_id:long g_a:bytes = DecryptedMessageAction; void SecretChatActor::request_new_key() { CHECK(!auth_state_.dh_config.empty()); diff --git a/td/telegram/SecretChatActor.h b/td/telegram/SecretChatActor.h index 34ec1d24f..fb1311a1f 100644 --- a/td/telegram/SecretChatActor.h +++ b/td/telegram/SecretChatActor.h @@ -645,7 +645,7 @@ class SecretChatActor final : public NetQueryCallback { Status save_common_info(T &update); int32 current_layer() const { - int32 layer = static_cast(SecretChatLayer::Current); + auto layer = static_cast(SecretChatLayer::Current); if (config_state_.his_layer < layer) { layer = config_state_.his_layer; } diff --git a/td/telegram/SecretChatsManager.cpp b/td/telegram/SecretChatsManager.cpp index 92475d5c1..c22893731 100644 --- a/td/telegram/SecretChatsManager.cpp +++ b/td/telegram/SecretChatsManager.cpp @@ -169,7 +169,7 @@ void SecretChatsManager::on_update_chat(tl_object_ptrchat_->get_id() == telegram_api::encryptedChatRequested::ID; - pending_chat_updates_.push_back({Timestamp::in(chat_requested ? 1 : 0), std::move(update)}); + pending_chat_updates_.emplace_back(Timestamp::in(chat_requested ? 1 : 0), std::move(update)); flush_pending_chat_updates(); } diff --git a/td/telegram/SecureManager.cpp b/td/telegram/SecureManager.cpp index 47cbb5d89..b4fda1289 100644 --- a/td/telegram/SecureManager.cpp +++ b/td/telegram/SecureManager.cpp @@ -104,11 +104,11 @@ class SetSecureValue final : public NetQueryCallback { void on_upload_ok(FileId file_id, tl_object_ptr input_file) final; void on_upload_encrypted_ok(FileId file_id, tl_object_ptr input_file) final; void on_upload_secure_ok(FileId file_id, tl_object_ptr input_file) final; - void on_upload_error(FileId file_id, Status status) final; + void on_upload_error(FileId file_id, Status error) final; }; void on_upload_ok(FileId file_id, tl_object_ptr input_file, uint32 upload_generation); - void on_upload_error(FileId file_id, Status status, uint32 upload_generation); + void on_upload_error(FileId file_id, Status error, uint32 upload_generation); void on_error(Status error); @@ -125,7 +125,7 @@ class SetSecureValue final : public NetQueryCallback { void cancel_upload(); void start_upload_all(); void start_upload(FileManager *file_manager, FileId &file_id, SecureInputFile &info); - void merge(FileManager *file_manager, FileId file_id, EncryptedSecureFile &encrypted_file); + static void merge(FileManager *file_manager, FileId file_id, EncryptedSecureFile &encrypted_file); }; class SetSecureValueErrorsQuery final : public Td::ResultHandler { @@ -285,7 +285,7 @@ void GetAllSecureValues::loop() { auto secure_values = transform(r_secure_values.move_as_ok(), [](SecureValueWithCredentials &&value) { return std::move(value.value); }); - promise_.set_value(get_passport_elements_object(file_manager, std::move(secure_values))); + promise_.set_value(get_passport_elements_object(file_manager, secure_values)); stop(); } @@ -959,7 +959,7 @@ void SecureManager::get_passport_authorization_form(UserId bot_user_id, string s form.bot_user_id = bot_user_id; form.scope = scope; form.public_key = public_key; - form.nonce = nonce; + form.nonce = std::move(nonce); auto new_promise = PromiseCreator::lambda( [actor_id = actor_id(this), authorization_form_id, promise = std::move(promise)]( Result> r_authorization_form) mutable { @@ -1100,7 +1100,7 @@ void SecureManager::on_get_passport_authorization_form_secret(int32 authorizatio on_get_secure_value(r_secure_value.ok()); auto secure_value = r_secure_value.move_as_ok(); - auto r_passport_element = get_passport_element_object(file_manager, std::move(secure_value.value)); + auto r_passport_element = get_passport_element_object(file_manager, secure_value.value); if (r_passport_element.is_error()) { LOG(ERROR) << "Failed to get passport element object: " << r_passport_element.error(); break; diff --git a/td/telegram/SecureManager.h b/td/telegram/SecureManager.h index 3ac79bb3c..b26766fd9 100644 --- a/td/telegram/SecureManager.h +++ b/td/telegram/SecureManager.h @@ -39,9 +39,13 @@ class SecureManager final : public NetQueryCallback { explicit SecureManager(ActorShared<> parent); void get_secure_value(std::string password, SecureValueType type, Promise promise); + void get_all_secure_values(std::string password, Promise promise); + void set_secure_value(string password, SecureValue secure_value, Promise promise); + void delete_secure_value(SecureValueType type, Promise promise); + void set_secure_value_errors(Td *td, tl_object_ptr input_user, vector> errors, Promise promise); diff --git a/td/telegram/SecureStorage.cpp b/td/telegram/SecureStorage.cpp index 74d25dedb..2fad7139d 100644 --- a/td/telegram/SecureStorage.cpp +++ b/td/telegram/SecureStorage.cpp @@ -208,7 +208,7 @@ Secret Secret::create_new() { auto secret_slice = ::td::as_slice(secret); Random::secure_bytes(secret_slice); auto checksum_diff = secret_checksum(secret_slice); - uint8 new_byte = static_cast((static_cast(secret_slice.ubegin()[0]) + checksum_diff) % 255); + auto new_byte = static_cast((static_cast(secret_slice.ubegin()[0]) + checksum_diff) % 255); secret_slice.ubegin()[0] = new_byte; return create(secret_slice).move_as_ok(); } @@ -364,7 +364,7 @@ Result decrypt_value(const Secret &secret, const ValueHash &hash, S return std::move(decrypted_value); } -Result encrypt_file(const Secret &secret, std::string src, std::string dest) { +Result encrypt_file(const Secret &secret, const string &src, const string &dest) { TRY_RESULT(src_file, FileFd::open(src, FileFd::Flags::Read)); TRY_RESULT(dest_file, FileFd::open(dest, FileFd::Flags::Truncate | FileFd::Flags::Write | FileFd::Create)); TRY_RESULT(src_file_size, src_file.get_size()); @@ -382,7 +382,7 @@ Result encrypt_file(const Secret &secret, std::string src, std::strin return std::move(hash); } -Status decrypt_file(const Secret &secret, const ValueHash &hash, std::string src, std::string dest) { +Status decrypt_file(const Secret &secret, const ValueHash &hash, const string &src, const string &dest) { TRY_RESULT(src_file, FileFd::open(src, FileFd::Flags::Read)); TRY_RESULT(dest_file, FileFd::open(dest, FileFd::Flags::Truncate | FileFd::Flags::Write | FileFd::Create)); TRY_RESULT(src_file_size, src_file.get_size()); diff --git a/td/telegram/SecureStorage.h b/td/telegram/SecureStorage.h index 768f47ed9..d42c824ac 100644 --- a/td/telegram/SecureStorage.h +++ b/td/telegram/SecureStorage.h @@ -184,10 +184,12 @@ struct EncryptedValue { }; Result encrypt_value(const Secret &secret, Slice data); -Result encrypt_file(const Secret &secret, std::string src, std::string dest); Result decrypt_value(const Secret &secret, const ValueHash &hash, Slice data); -Status decrypt_file(const Secret &secret, const ValueHash &hash, std::string src, std::string dest); + +Result encrypt_file(const Secret &secret, const string &src, const string &dest); + +Status decrypt_file(const Secret &secret, const ValueHash &hash, const string &src, const string &dest); } // namespace secure_storage } // namespace td diff --git a/td/telegram/SecureValue.cpp b/td/telegram/SecureValue.cpp index 55c8a97ab..ccc09867f 100644 --- a/td/telegram/SecureValue.cpp +++ b/td/telegram/SecureValue.cpp @@ -517,7 +517,6 @@ static bool check_encrypted_secure_value(const EncryptedSecureValue &value) { case SecureValueType::TemporaryRegistration: return !has_encrypted_data && !has_plain_data && has_files && !has_front_side && !has_reverse_side && !has_selfie; case SecureValueType::PhoneNumber: - return has_plain_data && !has_files && !has_front_side && !has_reverse_side && !has_selfie && !has_translations; case SecureValueType::EmailAddress: return has_plain_data && !has_files && !has_front_side && !has_reverse_side && !has_selfie && !has_translations; case SecureValueType::None: @@ -848,8 +847,7 @@ static Status check_document_number(string &number) { } static Result get_secure_file(FileManager *file_manager, td_api::object_ptr &&file) { - TRY_RESULT(file_id, - file_manager->get_input_file_id(FileType::Secure, std::move(file), DialogId(), false, false, false, true)); + TRY_RESULT(file_id, file_manager->get_input_file_id(FileType::Secure, file, DialogId(), false, false, false, true)); DatedFile result; result.file_id = file_id; result.date = G()->unix_time(); @@ -1294,7 +1292,7 @@ static EncryptedSecureFile encrypt_secure_file(FileManager *file_manager, const static vector encrypt_secure_files(FileManager *file_manager, const secure_storage::Secret &master_secret, - vector files, string &to_hash) { + const vector &files, string &to_hash) { return transform( files, [&](auto dated_file) { return encrypt_secure_file(file_manager, master_secret, dated_file, to_hash); }); /* diff --git a/td/telegram/SendCodeHelper.cpp b/td/telegram/SendCodeHelper.cpp index d6e403fce..5a30c46d2 100644 --- a/td/telegram/SendCodeHelper.cpp +++ b/td/telegram/SendCodeHelper.cpp @@ -53,9 +53,9 @@ telegram_api::object_ptr SendCodeHelper::get_input_c false /*ignored*/); } -telegram_api::auth_sendCode SendCodeHelper::send_code(Slice phone_number, const Settings &settings, int32 api_id, +telegram_api::auth_sendCode SendCodeHelper::send_code(string phone_number, const Settings &settings, int32 api_id, const string &api_hash) { - phone_number_ = phone_number.str(); + phone_number_ = std::move(phone_number); return telegram_api::auth_sendCode(phone_number_, api_id, api_hash, get_input_code_settings(settings)); } @@ -86,11 +86,11 @@ SendCodeHelper::AuthenticationCodeInfo SendCodeHelper::get_authentication_code_i switch (code_type_ptr->get_id()) { case telegram_api::auth_codeTypeSms::ID: - return {AuthenticationCodeInfo::Type::Sms, 0, ""}; + return {AuthenticationCodeInfo::Type::Sms, 0, string()}; case telegram_api::auth_codeTypeCall::ID: - return {AuthenticationCodeInfo::Type::Call, 0, ""}; + return {AuthenticationCodeInfo::Type::Call, 0, string()}; case telegram_api::auth_codeTypeFlashCall::ID: - return {AuthenticationCodeInfo::Type::FlashCall, 0, ""}; + return {AuthenticationCodeInfo::Type::FlashCall, 0, string()}; default: UNREACHABLE(); return AuthenticationCodeInfo(); diff --git a/td/telegram/SendCodeHelper.h b/td/telegram/SendCodeHelper.h index c47daab6c..e223c2d14 100644 --- a/td/telegram/SendCodeHelper.h +++ b/td/telegram/SendCodeHelper.h @@ -25,7 +25,7 @@ class SendCodeHelper { using Settings = td_api::object_ptr; - telegram_api::auth_sendCode send_code(Slice phone_number, const Settings &settings, int32 api_id, + telegram_api::auth_sendCode send_code(string phone_number, const Settings &settings, int32 api_id, const string &api_hash); telegram_api::account_sendChangePhoneCode send_change_phone_code(Slice phone_number, const Settings &settings); diff --git a/td/telegram/StickersManager.cpp b/td/telegram/StickersManager.cpp index 7c8a3f8c0..ec4994076 100644 --- a/td/telegram/StickersManager.cpp +++ b/td/telegram/StickersManager.cpp @@ -624,7 +624,7 @@ class ReorderStickerSetsQuery final : public Td::ResultHandler { bool is_masks_; public: - void send(bool is_masks, vector sticker_set_ids) { + void send(bool is_masks, const vector &sticker_set_ids) { is_masks_ = is_masks; int32 flags = 0; if (is_masks) { @@ -833,7 +833,7 @@ class UninstallStickerSetQuery final : public Td::ResultHandler { class ReadFeaturedStickerSetsQuery final : public Td::ResultHandler { public: - void send(vector sticker_set_ids) { + void send(const vector &sticker_set_ids) { LOG(INFO) << "Read trending sticker sets " << format::as_array(sticker_set_ids); send_query(G()->net_query_creator().create( telegram_api::messages_readFeaturedStickers(StickersManager::convert_sticker_set_ids(sticker_set_ids)))); @@ -1636,6 +1636,7 @@ vector> StickersManager::get_sticke } if (!commands.empty()) { result.push_back(td_api::make_object(std::move(commands))); + commands.clear(); } is_closed = true; break; @@ -2339,11 +2340,11 @@ void StickersManager::add_sticker_thumbnail(Sticker *s, PhotoSize thumbnail) { return; } if (thumbnail.type == 'm') { - s->m_thumbnail = thumbnail; + s->m_thumbnail = std::move(thumbnail); return; } if (thumbnail.type == 's' || thumbnail.type == 't') { - s->s_thumbnail = thumbnail; + s->s_thumbnail = std::move(thumbnail); return; } LOG(ERROR) << "Receive sticker thumbnail of unsupported type " << thumbnail.type; @@ -2363,7 +2364,7 @@ void StickersManager::create_sticker(FileId file_id, string minithumbnail, Photo if (!td_->auth_manager_->is_bot()) { s->minithumbnail = std::move(minithumbnail); } - add_sticker_thumbnail(s.get(), thumbnail); + add_sticker_thumbnail(s.get(), std::move(thumbnail)); if (sticker != nullptr) { s->set_id = on_get_input_sticker_set(file_id, std::move(sticker->stickerset_), load_data_multipromise_ptr); s->alt = std::move(sticker->alt_); @@ -4342,15 +4343,15 @@ void StickersManager::schedule_update_animated_emoji_clicked(const StickerSet *s auto now = Time::now(); auto start_time = max(now, next_update_animated_emoji_clicked_time_); - for (size_t i = 0; i < clicks.size(); i++) { - auto index = clicks[i].first; + for (const auto &click : clicks) { + auto index = click.first; auto sticker_id = sticker_ids[index]; if (!sticker_id.is_valid()) { LOG(INFO) << "Failed to find sticker for " << emoji << " with index " << index; return; } create_actor( - "SendUpdateAnimatedEmojiClicked", start_time + clicks[i].second - now, + "SendUpdateAnimatedEmojiClicked", start_time + click.second - now, PromiseCreator::lambda([actor_id = actor_id(this), full_message_id, sticker_id](Result result) { send_closure(actor_id, &StickersManager::send_update_animated_emoji_clicked, full_message_id, sticker_id); })) @@ -5481,7 +5482,7 @@ void StickersManager::on_new_stickers_uploaded(int64 random_id, Result res td_->create_handler(std::move(pending_new_sticker_set->promise)) ->send(std::move(input_user), pending_new_sticker_set->title, pending_new_sticker_set->short_name, is_masks, - is_animated, std::move(input_stickers), std::move(pending_new_sticker_set->software)); + is_animated, std::move(input_stickers), pending_new_sticker_set->software); } void StickersManager::add_sticker_to_set(UserId user_id, string &short_name, @@ -6630,7 +6631,7 @@ double StickersManager::get_emoji_language_code_last_difference_time(const strin return it->second; } auto &result = emoji_language_code_last_difference_times_[language_code]; - int32 old_unix_time = to_integer(G()->td_db()->get_sqlite_sync_pmc()->get( + auto old_unix_time = to_integer(G()->td_db()->get_sqlite_sync_pmc()->get( get_emoji_language_code_last_difference_time_database_key(language_code))); int32 passed_time = max(static_cast(0), G()->unix_time() - old_unix_time); result = Time::now_cached() - passed_time; diff --git a/td/telegram/StickersManager.h b/td/telegram/StickersManager.h index 6e43ed83d..f09daca41 100644 --- a/td/telegram/StickersManager.h +++ b/td/telegram/StickersManager.h @@ -175,7 +175,7 @@ class StickersManager final : public Actor { FileId upload_sticker_file(UserId user_id, tl_object_ptr &&sticker, Promise &&promise); - void get_suggested_sticker_set_name(string short_name, Promise &&promise); + void get_suggested_sticker_set_name(string title, Promise &&promise); enum class CheckStickerSetNameResult : uint8 { Ok, Invalid, Occupied }; void check_sticker_set_name(const string &name, Promise &&promise); @@ -284,7 +284,7 @@ class StickersManager final : public Actor { void on_uploaded_sticker_file(FileId file_id, tl_object_ptr media, Promise &&promise); - void on_find_stickers_success(const string &emoji, tl_object_ptr &&sticker_sets); + void on_find_stickers_success(const string &emoji, tl_object_ptr &&stickers); void on_find_stickers_fail(const string &emoji, Status &&error); diff --git a/td/telegram/StickersManager.hpp b/td/telegram/StickersManager.hpp index 9c7a7e154..ec60f7e07 100644 --- a/td/telegram/StickersManager.hpp +++ b/td/telegram/StickersManager.hpp @@ -165,7 +165,7 @@ void StickersManager::store_sticker_set(const StickerSet *sticker_set, bool with store(sticker_set->minithumbnail, storer); } - uint32 stored_sticker_count = narrow_cast(is_full ? sticker_set->sticker_ids.size() : stickers_limit); + auto stored_sticker_count = narrow_cast(is_full ? sticker_set->sticker_ids.size() : stickers_limit); store(stored_sticker_count, storer); for (uint32 i = 0; i < stored_sticker_count; i++) { auto sticker_id = sticker_set->sticker_ids[i]; diff --git a/td/telegram/StorageManager.cpp b/td/telegram/StorageManager.cpp index 184ed6036..492c321b1 100644 --- a/td/telegram/StorageManager.cpp +++ b/td/telegram/StorageManager.cpp @@ -65,7 +65,7 @@ void StorageManager::get_storage_stats(bool need_all_files, int32 dialog_limit, if (is_closed_) { return promise.set_error(Global::request_aborted_error()); } - if (pending_storage_stats_.size() != 0) { + if (!pending_storage_stats_.empty()) { if (stats_dialog_limit_ == dialog_limit && need_all_files == stats_need_all_files_) { pending_storage_stats_.emplace_back(std::move(promise)); return; @@ -118,12 +118,12 @@ void StorageManager::run_gc(FileGcParameters parameters, bool return_deleted_fil bool split_by_owner_dialog_id = !parameters.owner_dialog_ids.empty() || !parameters.exclude_owner_dialog_ids.empty() || parameters.dialog_limit != 0; - get_storage_stats(true /*need_all_files*/, split_by_owner_dialog_id, - PromiseCreator::lambda( - [actor_id = actor_id(this), parameters = std::move(parameters)](Result file_stats) { - send_closure(actor_id, &StorageManager::on_all_files, std::move(parameters), - std::move(file_stats)); - })); + get_storage_stats( + true /*need_all_files*/, split_by_owner_dialog_id, + PromiseCreator::lambda( + [actor_id = actor_id(this), parameters = std::move(parameters)](Result file_stats) mutable { + send_closure(actor_id, &StorageManager::on_all_files, std::move(parameters), std::move(file_stats)); + })); //NB: get_storage_stats will cancel all garbage collection queries, so promise needs to be added after the call pending_run_gc_[return_deleted_file_statistics].push_back(std::move(promise)); diff --git a/td/telegram/StorageManager.h b/td/telegram/StorageManager.h index f7de8d725..9afe8ddc8 100644 --- a/td/telegram/StorageManager.h +++ b/td/telegram/StorageManager.h @@ -24,7 +24,7 @@ namespace td { struct DatabaseStats { string debug; DatabaseStats() = default; - explicit DatabaseStats(string debug) : debug(debug) { + explicit DatabaseStats(string debug) : debug(std::move(debug)) { } tl_object_ptr get_database_statistics_object() const; }; @@ -64,7 +64,7 @@ class StorageManager final : public Actor { void on_file_stats(Result r_file_stats, uint32 generation); void create_stats_worker(); void update_fast_stats(const FileStats &stats); - void send_stats(FileStats &&stats, int32 dialog_limit, std::vector> &&promises); + static void send_stats(FileStats &&stats, int32 dialog_limit, std::vector> &&promises); void save_fast_stat(); void load_fast_stat(); diff --git a/td/telegram/SuggestedAction.cpp b/td/telegram/SuggestedAction.cpp index 2aa3026fd..97251965a 100644 --- a/td/telegram/SuggestedAction.cpp +++ b/td/telegram/SuggestedAction.cpp @@ -142,8 +142,7 @@ void update_suggested_actions(vector &suggested_actions, } CHECK(!added_actions.empty() || !removed_actions.empty()); suggested_actions = std::move(new_suggested_actions); - send_closure(G()->td(), &Td::send_update, - get_update_suggested_actions_object(std::move(added_actions), std::move(removed_actions))); + send_closure(G()->td(), &Td::send_update, get_update_suggested_actions_object(added_actions, removed_actions)); } void remove_suggested_action(vector &suggested_actions, SuggestedAction suggested_action) { diff --git a/td/telegram/Td.cpp b/td/telegram/Td.cpp index 3ea788a6b..b17f56fa1 100644 --- a/td/telegram/Td.cpp +++ b/td/telegram/Td.cpp @@ -802,8 +802,8 @@ class LoadChatsRequest final : public RequestActor<> { // 1 for database + 1 for server request + 1 for server request at the end + 1 for return + 1 just in case set_tries(5); - if (limit > 100) { - limit = 100; + if (limit_ > 100) { + limit_ = 100; } } }; @@ -2827,10 +2827,11 @@ void Td::on_get_terms_of_service(Result> result if (result.is_error()) { expires_in = Random::fast(10, 60); } else { - pending_terms_of_service_ = std::move(result.ok().second); + auto terms = result.move_as_ok(); + pending_terms_of_service_ = std::move(terms.second); auto update = get_update_terms_of_service_object(); if (update == nullptr) { - expires_in = min(max(result.ok().first, G()->unix_time() + 3600) - G()->unix_time(), 86400); + expires_in = min(max(terms.first, G()->unix_time() + 3600) - G()->unix_time(), 86400); } else { send_update(std::move(update)); } @@ -4115,7 +4116,7 @@ void Td::init_file_manager() { } void reload_photo(PhotoSizeSource source, Promise promise) final { - send_closure(G()->file_reference_manager(), &FileReferenceManager::reload_photo, source, std::move(promise)); + FileReferenceManager::reload_photo(std::move(source), std::move(promise)); } ActorShared<> create_reference() final { @@ -4557,7 +4558,7 @@ void Td::on_request(uint64 id, td_api::checkAuthenticationBotToken &request) { void Td::on_request(uint64 id, td_api::confirmQrCodeAuthentication &request) { CLEAN_INPUT_STRING(request.link_); CREATE_REQUEST_PROMISE(); - contacts_manager_->confirm_qr_code_authentication(std::move(request.link_), std::move(promise)); + contacts_manager_->confirm_qr_code_authentication(request.link_, std::move(promise)); } void Td::on_request(uint64 id, const td_api::getCurrentState &request) { @@ -4653,7 +4654,7 @@ void Td::on_request(uint64 id, td_api::checkRecoveryEmailAddressCode &request) { CHECK_IS_USER(); CLEAN_INPUT_STRING(request.code_); CREATE_REQUEST_PROMISE(); - send_closure(password_manager_, &PasswordManager::check_recovery_email_address_code, request.code_, + send_closure(password_manager_, &PasswordManager::check_recovery_email_address_code, std::move(request.code_), std::move(promise)); } @@ -5574,7 +5575,7 @@ void Td::on_request(uint64 id, td_api::editInlineMessageText &request) { CHECK_IS_BOT(); CLEAN_INPUT_STRING(request.inline_message_id_); CREATE_OK_REQUEST_PROMISE(); - messages_manager_->edit_inline_message_text(std::move(request.inline_message_id_), std::move(request.reply_markup_), + messages_manager_->edit_inline_message_text(request.inline_message_id_, std::move(request.reply_markup_), std::move(request.input_message_content_), std::move(promise)); } @@ -5582,16 +5583,16 @@ void Td::on_request(uint64 id, td_api::editInlineMessageLiveLocation &request) { CHECK_IS_BOT(); CLEAN_INPUT_STRING(request.inline_message_id_); CREATE_OK_REQUEST_PROMISE(); - messages_manager_->edit_inline_message_live_location( - std::move(request.inline_message_id_), std::move(request.reply_markup_), std::move(request.location_), - request.heading_, request.proximity_alert_radius_, std::move(promise)); + messages_manager_->edit_inline_message_live_location(request.inline_message_id_, std::move(request.reply_markup_), + std::move(request.location_), request.heading_, + request.proximity_alert_radius_, std::move(promise)); } void Td::on_request(uint64 id, td_api::editInlineMessageMedia &request) { CHECK_IS_BOT(); CLEAN_INPUT_STRING(request.inline_message_id_); CREATE_OK_REQUEST_PROMISE(); - messages_manager_->edit_inline_message_media(std::move(request.inline_message_id_), std::move(request.reply_markup_), + messages_manager_->edit_inline_message_media(request.inline_message_id_, std::move(request.reply_markup_), std::move(request.input_message_content_), std::move(promise)); } @@ -5599,17 +5600,16 @@ void Td::on_request(uint64 id, td_api::editInlineMessageCaption &request) { CHECK_IS_BOT(); CLEAN_INPUT_STRING(request.inline_message_id_); CREATE_OK_REQUEST_PROMISE(); - messages_manager_->edit_inline_message_caption(std::move(request.inline_message_id_), - std::move(request.reply_markup_), std::move(request.caption_), - std::move(promise)); + messages_manager_->edit_inline_message_caption(request.inline_message_id_, std::move(request.reply_markup_), + std::move(request.caption_), std::move(promise)); } void Td::on_request(uint64 id, td_api::editInlineMessageReplyMarkup &request) { CHECK_IS_BOT(); CLEAN_INPUT_STRING(request.inline_message_id_); CREATE_OK_REQUEST_PROMISE(); - messages_manager_->edit_inline_message_reply_markup(std::move(request.inline_message_id_), - std::move(request.reply_markup_), std::move(promise)); + messages_manager_->edit_inline_message_reply_markup(request.inline_message_id_, std::move(request.reply_markup_), + std::move(promise)); } void Td::on_request(uint64 id, td_api::editMessageSchedulingState &request) { @@ -5630,8 +5630,8 @@ void Td::on_request(uint64 id, td_api::setInlineGameScore &request) { CHECK_IS_BOT(); CLEAN_INPUT_STRING(request.inline_message_id_); CREATE_OK_REQUEST_PROMISE(); - game_manager_->set_inline_game_score(std::move(request.inline_message_id_), request.edit_message_, - UserId(request.user_id_), request.score_, request.force_, std::move(promise)); + game_manager_->set_inline_game_score(request.inline_message_id_, request.edit_message_, UserId(request.user_id_), + request.score_, request.force_, std::move(promise)); } void Td::on_request(uint64 id, td_api::getGameHighScores &request) { @@ -6243,8 +6243,8 @@ void Td::on_request(uint64 id, const td_api::leaveChat &request) { } } contacts_manager_->set_dialog_participant_status( - dialog_id, td_api::make_object(contacts_manager_->get_my_id().get()), - std::move(new_status), std::move(promise)); + dialog_id, td_api::make_object(contacts_manager_->get_my_id().get()), new_status, + std::move(promise)); } void Td::on_request(uint64 id, const td_api::addChatMember &request) { @@ -6263,8 +6263,8 @@ void Td::on_request(uint64 id, const td_api::addChatMembers &request) { void Td::on_request(uint64 id, td_api::setChatMemberStatus &request) { CREATE_OK_REQUEST_PROMISE(); - contacts_manager_->set_dialog_participant_status(DialogId(request.chat_id_), std::move(request.member_id_), - request.status_, std::move(promise)); + contacts_manager_->set_dialog_participant_status(DialogId(request.chat_id_), request.member_id_, request.status_, + std::move(promise)); } void Td::on_request(uint64 id, const td_api::banChatMember &request) { @@ -6297,8 +6297,7 @@ void Td::on_request(uint64 id, td_api::transferChatOwnership &request) { void Td::on_request(uint64 id, td_api::getChatMember &request) { CREATE_REQUEST_PROMISE(); - contacts_manager_->get_dialog_participant(DialogId(request.chat_id_), std::move(request.member_id_), - std::move(promise)); + contacts_manager_->get_dialog_participant(DialogId(request.chat_id_), request.member_id_, std::move(promise)); } void Td::on_request(uint64 id, td_api::searchChatMembers &request) { @@ -7085,7 +7084,8 @@ void Td::on_request(uint64 id, td_api::getStatisticalGraph &request) { CHECK_IS_USER(); CLEAN_INPUT_STRING(request.token_); CREATE_REQUEST_PROMISE(); - contacts_manager_->load_statistics_graph(DialogId(request.chat_id_), request.token_, request.x_, std::move(promise)); + contacts_manager_->load_statistics_graph(DialogId(request.chat_id_), std::move(request.token_), request.x_, + std::move(promise)); } void Td::on_request(uint64 id, td_api::setChatNotificationSettings &request) { @@ -7838,8 +7838,8 @@ void Td::on_request(uint64 id, td_api::sendEmailAddressVerificationCode &request CHECK_IS_USER(); CLEAN_INPUT_STRING(request.email_address_); CREATE_REQUEST_PROMISE(); - send_closure(password_manager_, &PasswordManager::send_email_address_verification_code, request.email_address_, - std::move(promise)); + send_closure(password_manager_, &PasswordManager::send_email_address_verification_code, + std::move(request.email_address_), std::move(promise)); } void Td::on_request(uint64 id, const td_api::resendEmailAddressVerificationCode &request) { @@ -7852,7 +7852,7 @@ void Td::on_request(uint64 id, td_api::checkEmailAddressVerificationCode &reques CHECK_IS_USER(); CLEAN_INPUT_STRING(request.code_); CREATE_OK_REQUEST_PROMISE(); - send_closure(password_manager_, &PasswordManager::check_email_address_verification_code, request.code_, + send_closure(password_manager_, &PasswordManager::check_email_address_verification_code, std::move(request.code_), std::move(promise)); } @@ -8341,7 +8341,8 @@ td_api::object_ptr Td::do_static_request(const td_api::getLangua td_api::object_ptr Td::do_static_request(const td_api::getPhoneNumberInfoSync &request) { // don't check language_code/phone number UTF-8 correctness - return CountryInfoManager::get_phone_number_info_sync(request.language_code_, request.phone_number_prefix_); + return CountryInfoManager::get_phone_number_info_sync(request.language_code_, + std::move(request.phone_number_prefix_)); } td_api::object_ptr Td::do_static_request(const td_api::getPushReceiverId &request) { diff --git a/td/telegram/Td.h b/td/telegram/Td.h index bd67fdafe..60d45c2a6 100644 --- a/td/telegram/Td.h +++ b/td/telegram/Td.h @@ -337,7 +337,7 @@ class Td final : public Actor { void on_get_terms_of_service(Result> result, bool dummy); - void on_get_promo_data(Result> result, bool dummy); + void on_get_promo_data(Result> r_promo_data, bool dummy); template friend class RequestActor; // uses send_result/send_error @@ -355,7 +355,7 @@ class Td final : public Actor { void on_config_option_updated(const string &name); - void send(NetQueryPtr &&query); + static void send(NetQueryPtr &&query); class OnRequest; diff --git a/td/telegram/TdDb.cpp b/td/telegram/TdDb.cpp index 027667285..6449ba5e8 100644 --- a/td/telegram/TdDb.cpp +++ b/td/telegram/TdDb.cpp @@ -52,7 +52,7 @@ std::string get_sqlite_path(const TdParameters ¶meters) { Result check_encryption(string path) { Binlog binlog; - auto status = binlog.init(path, Binlog::Callback()); + auto status = binlog.init(std::move(path), Binlog::Callback()); if (status.is_error() && status.code() != Binlog::Error::WrongPassword) { LOG(WARNING) << "Failed to check binlog: " << status; return Status::Error(400, status.message()); @@ -281,7 +281,7 @@ void TdDb::do_close(Promise<> on_finished, bool destroy_flag) { lock.set_value(Unit()); } -Status TdDb::init_sqlite(int32 scheduler_id, const TdParameters ¶meters, DbKey key, DbKey old_key, +Status TdDb::init_sqlite(int32 scheduler_id, const TdParameters ¶meters, const DbKey &key, const DbKey &old_key, BinlogKeyValue &binlog_pmc) { CHECK(!parameters.use_message_db || parameters.use_chat_info_db); CHECK(!parameters.use_chat_info_db || parameters.use_file_db); @@ -489,7 +489,7 @@ Status TdDb::destroy(const TdParameters ¶meters) { return Status::OK(); } -void TdDb::with_db_path(std::function callback) { +void TdDb::with_db_path(const std::function &callback) { SqliteDb::with_db_path(sqlite_path(), callback); callback(binlog_path()); } diff --git a/td/telegram/TdDb.h b/td/telegram/TdDb.h index 4608c2718..b3ac7e978 100644 --- a/td/telegram/TdDb.h +++ b/td/telegram/TdDb.h @@ -97,7 +97,7 @@ class TdDb { void change_key(DbKey key, Promise<> promise); - void with_db_path(std::function callback); + void with_db_path(const std::function &callback); Result get_stats(); @@ -121,7 +121,7 @@ class TdDb { std::shared_ptr binlog_; Status init(int32 scheduler_id, const TdParameters ¶meters, DbKey key, Events &events); - Status init_sqlite(int32 scheduler_id, const TdParameters ¶meters, DbKey key, DbKey old_key, + Status init_sqlite(int32 scheduler_id, const TdParameters ¶meters, const DbKey &key, const DbKey &old_key, BinlogKeyValue &binlog_pmc); void do_close(Promise<> on_finished, bool destroy_flag); diff --git a/td/telegram/TermsOfService.cpp b/td/telegram/TermsOfService.cpp index c4d792c67..75c4dd61a 100644 --- a/td/telegram/TermsOfService.cpp +++ b/td/telegram/TermsOfService.cpp @@ -65,9 +65,9 @@ class AcceptTermsOfServiceQuery final : public Td::ResultHandler { explicit AcceptTermsOfServiceQuery(Promise &&promise) : promise_(std::move(promise)) { } - void send(string terms_of_service_id) { + void send(const string &terms_of_service_id) { send_query(G()->net_query_creator().create(telegram_api::help_acceptTermsOfService( - telegram_api::make_object(std::move(terms_of_service_id))))); + telegram_api::make_object(terms_of_service_id)))); } void on_result(uint64 id, BufferSlice packet) final { @@ -116,7 +116,7 @@ void get_terms_of_service(Td *td, Promise> prom } void accept_terms_of_service(Td *td, string &&terms_of_service_id, Promise &&promise) { - td->create_handler(std::move(promise))->send(std::move(terms_of_service_id)); + td->create_handler(std::move(promise))->send(terms_of_service_id); } } // namespace td diff --git a/td/telegram/UpdatesManager.cpp b/td/telegram/UpdatesManager.cpp index 477477711..2ce4d7fdd 100644 --- a/td/telegram/UpdatesManager.cpp +++ b/td/telegram/UpdatesManager.cpp @@ -1877,30 +1877,29 @@ void UpdatesManager::process_updates(vector> } } if (force_apply) { - // forcely process pts updates for (auto &update : updates) { - if (update != nullptr && is_pts_update(update.get())) { - auto constructor_id = update->get_id(); - if (constructor_id == telegram_api::updateWebPage::ID) { - auto update_web_page = move_tl_object_as(update); - td_->web_pages_manager_->on_get_web_page(std::move(update_web_page->webpage_), DialogId()); - continue; + if (update != nullptr) { + if (is_pts_update(update.get())) { + auto constructor_id = update->get_id(); + if (constructor_id == telegram_api::updateWebPage::ID) { + auto update_web_page = move_tl_object_as(update); + td_->web_pages_manager_->on_get_web_page(std::move(update_web_page->webpage_), DialogId()); + continue; + } + + CHECK(constructor_id != telegram_api::updateFolderPeers::ID); + + if (constructor_id == telegram_api::updateReadHistoryInbox::ID) { + static_cast(update.get())->still_unread_count_ = -1; + } + + process_pts_update(std::move(update)); + } else if (is_qts_update(update.get())) { + process_qts_update(std::move(update), 0, mpas.get_promise()); + } else if (update->get_id() == telegram_api::updateChannelTooLong::ID) { + td_->messages_manager_->on_update_channel_too_long( + move_tl_object_as(update), true); } - - CHECK(constructor_id != telegram_api::updateFolderPeers::ID); - - if (constructor_id == telegram_api::updateReadHistoryInbox::ID) { - static_cast(update.get())->still_unread_count_ = -1; - } - - process_pts_update(std::move(update)); - } - if (update != nullptr && is_qts_update(update.get())) { - process_qts_update(std::move(update), 0, mpas.get_promise()); - } - if (update != nullptr && update->get_id() == telegram_api::updateChannelTooLong::ID) { - td_->messages_manager_->on_update_channel_too_long( - move_tl_object_as(update), true); } } } @@ -2102,8 +2101,7 @@ void UpdatesManager::process_qts_update(tl_object_ptr &&up } case telegram_api::updateBotStopped::ID: { auto update = move_tl_object_as(update_ptr); - td_->contacts_manager_->on_update_bot_stopped(UserId(update->user_id_), update->date_, - std::move(update->stopped_)); + td_->contacts_manager_->on_update_bot_stopped(UserId(update->user_id_), update->date_, update->stopped_); add_qts(qts).set_value(Unit()); break; } diff --git a/td/telegram/WebPageBlock.cpp b/td/telegram/WebPageBlock.cpp index 03965be9e..36b483bdf 100644 --- a/td/telegram/WebPageBlock.cpp +++ b/td/telegram/WebPageBlock.cpp @@ -2228,7 +2228,7 @@ unique_ptr get_web_page_block(Td *td, tl_object_ptr(page_block_ptr); - Location location(std::move(page_block->geo_)); + Location location(page_block->geo_); auto zoom = page_block->zoom_; Dimensions dimensions = get_dimensions(page_block->w_, page_block->h_, "pageBlockMap"); if (location.empty()) { diff --git a/td/telegram/WebPagesManager.cpp b/td/telegram/WebPagesManager.cpp index b2d39e69d..bd795bbba 100644 --- a/td/telegram/WebPagesManager.cpp +++ b/td/telegram/WebPagesManager.cpp @@ -1055,18 +1055,19 @@ void WebPagesManager::get_web_page_by_url(const string &url, Promise load_web_page_by_url(url, std::move(promise)); } -void WebPagesManager::load_web_page_by_url(const string &url, Promise &&promise) { +void WebPagesManager::load_web_page_by_url(string url, Promise &&promise) { if (!G()->parameters().use_message_db) { return reload_web_page_by_url(url, std::move(promise)); } LOG(INFO) << "Load \"" << url << '"'; - G()->td_db()->get_sqlite_pmc()->get( - get_web_page_url_database_key(url), - PromiseCreator::lambda([actor_id = actor_id(this), url, promise = std::move(promise)](string value) mutable { - send_closure(actor_id, &WebPagesManager::on_load_web_page_id_by_url_from_database, std::move(url), - std::move(value), std::move(promise)); - })); + auto key = get_web_page_url_database_key(url); + G()->td_db()->get_sqlite_pmc()->get(key, PromiseCreator::lambda([actor_id = actor_id(this), url = std::move(url), + promise = std::move(promise)](string value) mutable { + send_closure(actor_id, + &WebPagesManager::on_load_web_page_id_by_url_from_database, + std::move(url), std::move(value), std::move(promise)); + })); } void WebPagesManager::on_load_web_page_id_by_url_from_database(string url, string value, Promise &&promise) { diff --git a/td/telegram/WebPagesManager.h b/td/telegram/WebPagesManager.h index cfb06626a..d63c73128 100644 --- a/td/telegram/WebPagesManager.h +++ b/td/telegram/WebPagesManager.h @@ -164,7 +164,7 @@ class WebPagesManager final : public Actor { static string get_web_page_url_database_key(const string &url); - void load_web_page_by_url(const string &url, Promise &&promise); + void load_web_page_by_url(string url, Promise &&promise); void on_load_web_page_id_by_url_from_database(string url, string value, Promise &&promise); diff --git a/td/telegram/cli.cpp b/td/telegram/cli.cpp index 4bf0dd868..1dccb9833 100644 --- a/td/telegram/cli.cpp +++ b/td/telegram/cli.cpp @@ -216,7 +216,7 @@ class CliClient final : public Actor { , get_chat_list_(get_chat_list) , disable_network_(disable_network) , api_id_(api_id) - , api_hash_(api_hash) { + , api_hash_(std::move(api_hash)) { } static void quit_instance() { @@ -564,7 +564,7 @@ class CliClient final : public Actor { return it->second; } auto result = to_integer(str); - int64 shift = static_cast(-1000000000000ll); + auto shift = static_cast(-1000000000000ll); if (result <= shift) { return shift - result; } @@ -574,7 +574,7 @@ class CliClient final : public Actor { static int32 as_secret_chat_id(Slice str) { str = trim(str); auto result = to_integer(str); - int64 shift = static_cast(-2000000000000ll); + auto shift = static_cast(-2000000000000ll); if (result <= shift + std::numeric_limits::max()) { return static_cast(result - shift); } @@ -599,7 +599,8 @@ class CliClient final : public Actor { static td_api::object_ptr as_generated_file(string original_path, string conversion, int32 expected_size = 0) { - return td_api::make_object(trim(original_path), trim(conversion), expected_size); + return td_api::make_object(trim(std::move(original_path)), trim(std::move(conversion)), + expected_size); } static td_api::object_ptr as_input_file(string str) { @@ -646,7 +647,8 @@ class CliClient final : public Actor { return to_integer(trim(std::move(str))); } - static td_api::object_ptr as_location(string latitude, string longitude, string accuracy = "") { + static td_api::object_ptr as_location(const string &latitude, const string &longitude, + const string &accuracy) { if (trim(latitude).empty() && trim(longitude).empty()) { return nullptr; } @@ -837,6 +839,8 @@ class CliClient final : public Actor { case td_api::updateConnectionState::ID: LOG(WARNING) << result_str; break; + default: + break; } } @@ -1028,7 +1032,7 @@ class CliClient final : public Actor { #endif static td_api::object_ptr as_formatted_text( - string text, vector> entities = {}) { + const string &text, vector> entities = {}) { if (entities.empty() && !text.empty()) { auto parsed_text = execute( td_api::make_object(text, td_api::make_object(2))); @@ -1040,7 +1044,7 @@ class CliClient final : public Actor { } static td_api::object_ptr as_caption( - string caption, vector> entities = {}) { + const string &caption, vector> entities = {}) { return as_formatted_text(caption, std::move(entities)); } @@ -1199,7 +1203,7 @@ class CliClient final : public Actor { } static td_api::object_ptr get_supergroup_members_filter(MutableSlice filter, - string query, + const string &query, Slice message_thread_id) { filter = trim(filter); to_lower_inplace(filter); @@ -1435,8 +1439,9 @@ class CliClient final : public Actor { return transform(full_split(types, get_delimiter(types)), [](Slice str) { return as_passport_element_type(str); }); } - static td_api::object_ptr as_input_passport_element(string passport_element_type, - string arg, bool with_selfie) { + static td_api::object_ptr as_input_passport_element(const string &passport_element_type, + const string &arg, + bool with_selfie) { vector> input_files; td_api::object_ptr selfie; if (!arg.empty()) { @@ -1446,7 +1451,7 @@ class CliClient final : public Actor { selfie = as_input_file(files.back()); files.pop_back(); } - for (auto file : files) { + for (const auto &file : files) { input_files.push_back(as_input_file(file)); } } @@ -1485,7 +1490,7 @@ class CliClient final : public Actor { std::move(input_files))); } } else if (passport_element_type == "internal_passport" || passport_element_type == "ip") { - if (input_files.size() >= 1) { + if (!input_files.empty()) { auto front_side = std::move(input_files[0]); input_files.erase(input_files.begin()); return td_api::make_object( @@ -1591,7 +1596,7 @@ class CliClient final : public Actor { } } - static int32 get_log_tag_verbosity_level(string name) { + static int32 get_log_tag_verbosity_level(const string &name) { auto level = ClientActor::execute(td_api::make_object(name)); if (level->get_id() == td_api::error::ID) { return -1; @@ -1782,11 +1787,14 @@ class CliClient final : public Actor { } else if (op == "rreac") { send_request(td_api::make_object()); } else if (op == "spncc") { - send_request(td_api::make_object(args, nullptr)); + string hash; + string phone_number; + get_args(args, hash, phone_number); + send_request(td_api::make_object(hash, phone_number, nullptr)); } else if (op == "cpncc") { - send_request(td_api::make_object(args)); + send_request(td_api::make_object(args)); } else if (op == "rpncc") { - send_request(td_api::make_object()); + send_request(td_api::make_object()); } else if (op == "rpr") { send_request(td_api::make_object()); } else if (op == "cprc") { @@ -1823,7 +1831,7 @@ class CliClient final : public Actor { send_request(td_api::make_object( as_input_passport_element(passport_element_type, arg, op == "spes"), password)); } else if (op == "dpe") { - string passport_element_type = args; + string passport_element_type = std::move(args); send_request(td_api::make_object(as_passport_element_type(passport_element_type))); } else if (op == "ppn") { send_request(td_api::make_object(args)); @@ -1943,7 +1951,7 @@ class CliClient final : public Actor { send_request(td_api::make_object( td_api::make_object(string(), first_name, last_name, string(), as_user_id(user_id)), false)); } else if (op == "spn") { - string user_id = args; + string user_id = std::move(args); send_request(td_api::make_object(as_user_id(user_id))); } else if (op == "ImportContacts" || op == "cic") { vector contacts_str = full_split(args, ';'); @@ -2005,7 +2013,7 @@ class CliClient final : public Actor { offset, as_limit(limit), op == "ghl")); } } else if (op == "gcsm") { - string chat_id = args; + string chat_id = std::move(args); send_request(td_api::make_object(as_chat_id(chat_id))); } else if (op == "gmpf") { string chat_id; @@ -2134,10 +2142,10 @@ class CliClient final : public Actor { send_request(td_api::make_object(language_database_path, language_pack, language_code, key)); } else if (op == "synclp") { - string language_code = args; + string language_code = std::move(args); send_request(td_api::make_object(language_code)); } else if (op == "acslp") { - string language_code = args; + string language_code = std::move(args); send_request(td_api::make_object(language_code)); } else if (op == "sclp") { string language_code; @@ -2374,24 +2382,24 @@ class CliClient final : public Actor { send_request(td_api::make_object()); } else if (op == "clean_photos") { std::vector> types; - types.push_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); send_request(td_api::make_object(0, 0, 0, 0, std::move(types), as_chat_ids(""), as_chat_ids(""), true, 20)); } else if (op == "clean_storage") { std::vector> types; - types.push_back(td_api::make_object()); - types.push_back(td_api::make_object()); - types.push_back(td_api::make_object()); - types.push_back(td_api::make_object()); - types.push_back(td_api::make_object()); - types.push_back(td_api::make_object()); - types.push_back(td_api::make_object()); - types.push_back(td_api::make_object()); - types.push_back(td_api::make_object()); - types.push_back(td_api::make_object()); - types.push_back(td_api::make_object()); - types.push_back(td_api::make_object()); - types.push_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); + types.emplace_back(td_api::make_object()); send_request(td_api::make_object(0, -1, -1, 0, std::move(types), as_chat_ids(args), as_chat_ids(""), true, 20)); } else if (op == "network") { @@ -2433,10 +2441,10 @@ class CliClient final : public Actor { get_args(args, chat_id, category); send_request(td_api::make_object(get_top_chat_category(category), as_chat_id(chat_id))); } else if (op == "gsssn") { - string title = args; + string title = std::move(args); send_request(td_api::make_object(title)); } else if (op == "cssn") { - string name = args; + string name = std::move(args); send_request(td_api::make_object(name)); } else if (op == "usf" || op == "usfa") { td_api::object_ptr input_sticker; @@ -2453,7 +2461,7 @@ class CliClient final : public Actor { get_args(args, title, name, stickers); auto input_stickers = transform(full_split(stickers, get_delimiter(stickers)), - [op](string sticker) -> td_api::object_ptr { + [op](const string &sticker) -> td_api::object_ptr { if (op == "cnssa") { return td_api::make_object(as_input_file(sticker), "😀"); } else { @@ -2546,7 +2554,7 @@ class CliClient final : public Actor { get_args(args, chat_id, member_id); send_request(td_api::make_object(as_chat_id(chat_id), as_message_sender(member_id))); } else if (op == "GetChatAdministrators") { - string chat_id = args; + string chat_id = std::move(args); send_request(td_api::make_object(as_chat_id(chat_id))); } else if (op == "GetSupergroupAdministrators" || op == "GetSupergroupBanned" || op == "GetSupergroupBots" || op == "GetSupergroupContacts" || op == "GetSupergroupMembers" || op == "GetSupergroupRestricted" || @@ -2602,7 +2610,7 @@ class CliClient final : public Actor { get_args(args, chat_id, message_id); send_request(td_api::make_object(as_chat_id(chat_id), as_message_id(message_id))); } else if (op == "gcpm") { - string chat_id = args; + string chat_id = std::move(args); send_request(td_api::make_object(as_chat_id(chat_id))); } else if (op == "gms") { string chat_id; @@ -2664,8 +2672,8 @@ class CliClient final : public Actor { int32 scale; string chat_id; get_args(args, latitude, longitude, zoom, width, height, scale, chat_id); - send_request(td_api::make_object(as_location(latitude, longitude), zoom, width, - height, scale, as_chat_id(chat_id))); + send_request(td_api::make_object(as_location(latitude, longitude, string()), zoom, + width, height, scale, as_chat_id(chat_id))); } else if (op == "df" || op == "DownloadFile" || op == "dff" || op == "dfs") { string file_id; int32 priority; @@ -2712,7 +2720,7 @@ class CliClient final : public Actor { } else if (op == "cuf") { send_request(td_api::make_object(as_file_id(args))); } else if (op == "delf" || op == "DeleteFile") { - string file_id = args; + string file_id = std::move(args); send_request(td_api::make_object(as_file_id(file_id))); } else if (op == "dm" || op == "dmr") { string chat_id; @@ -2842,7 +2850,7 @@ class CliClient final : public Actor { send_request(td_api::make_object(as_group_call_id(group_call_id), is_paused)); } else if (op == "egcss") { - string group_call_id = args; + string group_call_id = std::move(args); send_request(td_api::make_object(as_group_call_id(group_call_id))); } else if (op == "sgct") { string chat_id; @@ -2894,7 +2902,7 @@ class CliClient final : public Actor { send_request(td_api::make_object(as_group_call_id(chat_id), title, record_video, use_portrait_orientation)); } else if (op == "egcr") { - string chat_id = args; + string chat_id = std::move(args); send_request(td_api::make_object(as_group_call_id(chat_id))); } else if (op == "tgcpim") { string group_call_id; @@ -2928,7 +2936,7 @@ class CliClient final : public Actor { } else if (op == "dgc") { send_request(td_api::make_object(as_group_call_id(args))); } else if (op == "rpcil") { - string chat_id = args; + string chat_id = std::move(args); send_request(td_api::make_object(as_chat_id(chat_id))); } else if (op == "ccilt") { string chat_id; @@ -2950,7 +2958,7 @@ class CliClient final : public Actor { get_args(args, chat_id, invite_link); send_request(td_api::make_object(as_chat_id(chat_id), invite_link)); } else if (op == "gcilc") { - string chat_id = args; + string chat_id = std::move(args); send_request(td_api::make_object(as_chat_id(chat_id))); } else if (op == "gcil") { string chat_id; @@ -3023,7 +3031,7 @@ class CliClient final : public Actor { execute(td_api::make_object("\"\\u0080\"")); execute(td_api::make_object("\"\\uD800\"")); } else if (op == "gjs") { - auto test_get_json_string = [&](auto &&json_value) { + auto test_get_json_string = [&](td_api::object_ptr &&json_value) { execute(td_api::make_object(std::move(json_value))); }; @@ -3035,21 +3043,21 @@ class CliClient final : public Actor { test_get_json_string(td_api::make_object("aba\200caba")); auto inner_array = td_api::make_object(); - inner_array->values_.push_back(td_api::make_object(false)); + inner_array->values_.emplace_back(td_api::make_object(false)); auto array = td_api::make_object(); - array->values_.push_back(nullptr); - array->values_.push_back(std::move(inner_array)); - array->values_.push_back(td_api::make_object()); - array->values_.push_back(td_api::make_object(-1)); + array->values_.emplace_back(nullptr); + array->values_.emplace_back(std::move(inner_array)); + array->values_.emplace_back(td_api::make_object()); + array->values_.emplace_back(td_api::make_object(-1)); test_get_json_string(std::move(array)); auto object = td_api::make_object(); - object->members_.push_back( + object->members_.emplace_back( td_api::make_object("", td_api::make_object("test"))); - object->members_.push_back(td_api::make_object("a", nullptr)); - object->members_.push_back(td_api::make_object("\x80", nullptr)); - object->members_.push_back(nullptr); - object->members_.push_back( + object->members_.emplace_back(td_api::make_object("a", nullptr)); + object->members_.emplace_back(td_api::make_object("\x80", nullptr)); + object->members_.emplace_back(nullptr); + object->members_.emplace_back( td_api::make_object("a", td_api::make_object())); test_get_json_string(std::move(object)); } else if (op == "gac") { @@ -3159,9 +3167,9 @@ class CliClient final : public Actor { send_request(td_api::make_object(as_chat_id(chat_id), query.query, offset, query.limit, as_search_messages_filter(filter))); } else if (op == "ssd") { - schedule_date_ = args; + schedule_date_ = std::move(args); } else if (op == "smti") { - message_thread_id_ = args; + message_thread_id_ = std::move(args); } else if (op == "sm" || op == "sms" || op == "smr" || op == "smf") { string chat_id; string reply_to_message_id; @@ -3332,8 +3340,8 @@ class CliClient final : public Actor { string bot_id; string query; get_args(args, bot_id, query); - send_request(td_api::make_object(as_user_id(bot_id), 0, as_location("1.1", "2.2"), - query, "")); + send_request(td_api::make_object(as_user_id(bot_id), 0, + as_location("1.1", "2.2", ""), query, "")); } else if (op == "siqr" || op == "siqrh") { string chat_id; int64 query_id; @@ -3688,8 +3696,8 @@ class CliClient final : public Actor { send_request(td_api::make_object(args, false, "Description", nullptr, false)); } else if (op == "cnsgcloc") { send_request(td_api::make_object( - args, false, "Description", td_api::make_object(as_location("40.0", "60.0"), "address"), - false)); + args, false, "Description", + td_api::make_object(as_location("40.0", "60.0", ""), "address"), false)); } else if (op == "cnsgcimport") { send_request(td_api::make_object(args, false, "Description", nullptr, true)); } else if (op == "UpgradeBasicGroupChatToSupergroupChat") { @@ -3726,10 +3734,10 @@ class CliClient final : public Actor { get_args(args, supergroup_id, force); send_request(td_api::make_object(as_supergroup_id(supergroup_id), force)); } else if (op == "gcltac") { - string chat_id = args; + string chat_id = std::move(args); send_request(td_api::make_object(as_chat_id(chat_id))); } else if (op == "actl" || op == "actla" || begins_with(op, "actl-")) { - string chat_id = args; + string chat_id = std::move(args); send_request(td_api::make_object(as_chat_id(chat_id), as_chat_list(op))); } else if (op == "gcf") { send_request(td_api::make_object(as_chat_filter_id(args))); @@ -3760,7 +3768,7 @@ class CliClient final : public Actor { get_args(args, chat_id, title); send_request(td_api::make_object(as_chat_id(chat_id), title)); } else if (op == "scpe") { - string chat_id = args; + string chat_id = std::move(args); send_request(td_api::make_object(as_chat_id(chat_id), nullptr)); } else if (op == "scpp") { string chat_id; @@ -4006,7 +4014,8 @@ class CliClient final : public Actor { string longitude; get_args(args, chat_id, latitude, longitude); send_request(td_api::make_object( - as_chat_id(chat_id), td_api::make_object(as_location(latitude, longitude), "address"))); + as_chat_id(chat_id), + td_api::make_object(as_location(latitude, longitude, string()), "address"))); } else if (op == "scsmd") { string chat_id; int32 slow_mode_delay; @@ -4024,7 +4033,7 @@ class CliClient final : public Actor { get_args(args, chat_id, message_id); send_request(td_api::make_object(as_chat_id(chat_id), as_message_id(message_id))); } else if (op == "uacm") { - string chat_id = args; + string chat_id = std::move(args); send_request(td_api::make_object(as_chat_id(chat_id))); } else if (op == "grib") { send_request(td_api::make_object()); @@ -4044,12 +4053,12 @@ class CliClient final : public Actor { string latitude; string longitude; get_args(args, latitude, longitude); - send_request(td_api::make_object(as_location(latitude, longitude))); + send_request(td_api::make_object(as_location(latitude, longitude, string()))); } else if (op == "sloc") { string latitude; string longitude; get_args(args, latitude, longitude); - send_request(td_api::make_object(as_location(latitude, longitude))); + send_request(td_api::make_object(as_location(latitude, longitude, string()))); } else if (op == "sco") { SearchQuery query; get_args(args, query); @@ -4109,16 +4118,16 @@ class CliClient final : public Actor { send_request( td_api::make_object(as_chat_id(chat_id), as_message_id(message_id))); } else if (op == "gilt") { - string link = args; + string link = std::move(args); send_request(td_api::make_object(link)); } else if (op == "geli") { - string link = args; + string link = std::move(args); send_request(td_api::make_object(link)); } else if (op == "gel" || op == "gelw") { - string link = args; + string link = std::move(args); send_request(td_api::make_object(link, op == "gelw")); } else if (op == "racm") { - string chat_id = args; + string chat_id = std::move(args); send_request(td_api::make_object(as_chat_id(chat_id))); } else if (op == "tre") { send_request(td_api::make_object( @@ -4169,7 +4178,7 @@ class CliClient final : public Actor { get_args(args, group_id, max_notification_id); send_request(td_api::make_object(group_id, max_notification_id)); } else if (op == "rcab") { - string chat_id = args; + string chat_id = std::move(args); send_request(td_api::make_object(as_chat_id(chat_id))); } else if (op == "rc") { string chat_id; @@ -4308,7 +4317,7 @@ class CliClient final : public Actor { << stats.virtual_size_ << ", peak VSZ = " << stats.virtual_size_peak_; } } else if (op == "cpu") { - uint32 inc_count = to_integer(args); + auto inc_count = to_integer(args); while (inc_count-- > 0) { cpu_counter_++; } @@ -4348,7 +4357,7 @@ class CliClient final : public Actor { execute(std::move(request)); } } else if (op == "gltvl" || op == "gltvle" || op == "gtag") { - string tag = args; + string tag = std::move(args); auto request = td_api::make_object(tag); if (op == "gltvl") { send_request(std::move(request)); @@ -4480,7 +4489,7 @@ class CliClient final : public Actor { if (slice.empty()) { return EOF; } - int res = slice[0]; + int res = static_cast(slice[0]); stdin_.input_buffer().confirm_read(1); return res; } diff --git a/td/telegram/files/FileBitmask.cpp b/td/telegram/files/FileBitmask.cpp index 98209403a..3b6b5f014 100644 --- a/td/telegram/files/FileBitmask.cpp +++ b/td/telegram/files/FileBitmask.cpp @@ -106,11 +106,11 @@ int64 Bitmask::get_total_size(int64 part_size, int64 file_size) const { bool Bitmask::get(int64 offset_part) const { if (offset_part < 0) { - return 0; + return false; } auto index = narrow_cast(offset_part / 8); if (index >= data_.size()) { - return 0; + return false; } return (static_cast(data_[index]) & (1 << static_cast(offset_part % 8))) != 0; } @@ -148,7 +148,7 @@ int64 Bitmask::size() const { } StringBuilder &operator<<(StringBuilder &sb, const Bitmask &mask) { - bool prev = 0; + bool prev = false; int32 cnt = 0; for (int64 i = 0; i <= mask.size(); i++) { bool cur = mask.get(i); diff --git a/td/telegram/files/FileDownloader.cpp b/td/telegram/files/FileDownloader.cpp index 2a6b7633c..41e8ee766 100644 --- a/td/telegram/files/FileDownloader.cpp +++ b/td/telegram/files/FileDownloader.cpp @@ -446,7 +446,7 @@ Result FileDownloader::check_loop(int64 checked_prefix_si } end_offset = ready_prefix_size; } - size_t size = narrow_cast(end_offset - begin_offset); + auto size = narrow_cast(end_offset - begin_offset); auto slice = BufferSlice(size); TRY_STATUS(acquire_fd()); TRY_RESULT(read_size, fd_.pread(slice.as_slice(), begin_offset)); diff --git a/td/telegram/files/FileDownloader.h b/td/telegram/files/FileDownloader.h index bb03cab18..cb3f215e3 100644 --- a/td/telegram/files/FileDownloader.h +++ b/td/telegram/files/FileDownloader.h @@ -28,8 +28,8 @@ class FileDownloader final : public FileLoader { class Callback : public FileLoader::Callback { public: virtual void on_start_download() = 0; - virtual void on_partial_download(const PartialLocalFileLocation &partial_local, int64 ready_size, int64 size) = 0; - virtual void on_ok(const FullLocalFileLocation &full_local, int64 size, bool is_new) = 0; + virtual void on_partial_download(PartialLocalFileLocation partial_local, int64 ready_size, int64 size) = 0; + virtual void on_ok(FullLocalFileLocation full_local, int64 size, bool is_new) = 0; virtual void on_error(Status status) = 0; }; diff --git a/td/telegram/files/FileFromBytes.cpp b/td/telegram/files/FileFromBytes.cpp index a1fd5a9ea..28a932ba3 100644 --- a/td/telegram/files/FileFromBytes.cpp +++ b/td/telegram/files/FileFromBytes.cpp @@ -18,8 +18,8 @@ FileFromBytes::FileFromBytes(FileType type, BufferSlice bytes, string name, uniq } void FileFromBytes::wakeup() { - int64 size = narrow_cast(bytes_.size()); - auto r_result = save_file_bytes(type_, std::move(bytes_), std::move(name_)); + auto size = narrow_cast(bytes_.size()); + auto r_result = save_file_bytes(type_, std::move(bytes_), name_); if (r_result.is_error()) { callback_->on_error(r_result.move_as_error()); } else { diff --git a/td/telegram/files/FileGcWorker.cpp b/td/telegram/files/FileGcWorker.cpp index d9486e63c..e1f782f37 100644 --- a/td/telegram/files/FileGcWorker.cpp +++ b/td/telegram/files/FileGcWorker.cpp @@ -55,7 +55,7 @@ void FileGcWorker::run_gc(const FileGcParameters ¶meters, std::vector(get_main_file_type(static_cast(i))); - if (immune_types[main_file_type] == false) { + if (!immune_types[main_file_type]) { immune_types[i] = false; } } diff --git a/td/telegram/files/FileGenerateManager.cpp b/td/telegram/files/FileGenerateManager.cpp index ccdc2dc6d..9845f0706 100644 --- a/td/telegram/files/FileGenerateManager.cpp +++ b/td/telegram/files/FileGenerateManager.cpp @@ -99,7 +99,7 @@ class FileDownloadGenerateActor final : public FileGenerateActor { if (file_view.has_local_location()) { auto location = file_view.local_location(); location.file_type_ = file_type; - callback->on_ok(location); + callback->on_ok(std::move(location)); } else { LOG(ERROR) << "Expected to have local location"; callback->on_error(Status::Error(500, "Unknown")); @@ -365,8 +365,8 @@ class FileExternalGenerateActor final : public FileGenerateActor { }; FileGenerateManager::Query::~Query() = default; -FileGenerateManager::Query::Query(Query &&other) = default; -FileGenerateManager::Query &FileGenerateManager::Query::operator=(Query &&other) = default; +FileGenerateManager::Query::Query(Query &&other) noexcept = default; +FileGenerateManager::Query &FileGenerateManager::Query::operator=(Query &&other) noexcept = default; static Status check_mtime(std::string &conversion, CSlice original_path) { if (original_path.empty()) { diff --git a/td/telegram/files/FileGenerateManager.h b/td/telegram/files/FileGenerateManager.h index 089288672..741855554 100644 --- a/td/telegram/files/FileGenerateManager.h +++ b/td/telegram/files/FileGenerateManager.h @@ -26,8 +26,8 @@ class FileGenerateCallback { FileGenerateCallback &operator=(const FileGenerateCallback &) = delete; virtual ~FileGenerateCallback() = default; - virtual void on_partial_generate(const PartialLocalFileLocation &partial_local, int32 expected_size) = 0; - virtual void on_ok(const FullLocalFileLocation &local) = 0; + virtual void on_partial_generate(PartialLocalFileLocation partial_local, int32 expected_size) = 0; + virtual void on_ok(FullLocalFileLocation local) = 0; virtual void on_error(Status error) = 0; }; @@ -51,8 +51,8 @@ class FileGenerateManager final : public Actor { Query() = default; Query(const Query &other) = delete; Query &operator=(const Query &other) = delete; - Query(Query &&other); - Query &operator=(Query &&other); + Query(Query &&other) noexcept; + Query &operator=(Query &&other) noexcept; ~Query(); ActorOwn worker_; diff --git a/td/telegram/files/FileHashUploader.h b/td/telegram/files/FileHashUploader.h index 3652cfd2b..8bd1b36cc 100644 --- a/td/telegram/files/FileHashUploader.h +++ b/td/telegram/files/FileHashUploader.h @@ -27,7 +27,8 @@ class FileHashUploader final : public FileLoaderActor { Callback(const Callback &) = delete; Callback &operator=(const Callback &) = delete; virtual ~Callback() = default; - virtual void on_ok(const FullRemoteFileLocation &locatioin) = 0; + + virtual void on_ok(FullRemoteFileLocation location) = 0; virtual void on_error(Status status) = 0; }; diff --git a/td/telegram/files/FileLoadManager.cpp b/td/telegram/files/FileLoadManager.cpp index 7d7b69f12..38eacd3e8 100644 --- a/td/telegram/files/FileLoadManager.cpp +++ b/td/telegram/files/FileLoadManager.cpp @@ -192,14 +192,15 @@ void FileLoadManager::on_start_download() { } } -void FileLoadManager::on_partial_download(const PartialLocalFileLocation &partial_local, int64 ready_size, int64 size) { +void FileLoadManager::on_partial_download(PartialLocalFileLocation partial_local, int64 ready_size, int64 size) { auto node_id = get_link_token(); auto node = nodes_container_.get(node_id); if (node == nullptr) { return; } if (!stop_flag_) { - send_closure(callback_, &Callback::on_partial_download, node->query_id_, partial_local, ready_size, size); + send_closure(callback_, &Callback::on_partial_download, node->query_id_, std::move(partial_local), ready_size, + size); } } @@ -214,51 +215,51 @@ void FileLoadManager::on_hash(string hash) { } } -void FileLoadManager::on_partial_upload(const PartialRemoteFileLocation &partial_remote, int64 ready_size) { +void FileLoadManager::on_partial_upload(PartialRemoteFileLocation partial_remote, int64 ready_size) { auto node_id = get_link_token(); auto node = nodes_container_.get(node_id); if (node == nullptr) { return; } if (!stop_flag_) { - send_closure(callback_, &Callback::on_partial_upload, node->query_id_, partial_remote, ready_size); + send_closure(callback_, &Callback::on_partial_upload, node->query_id_, std::move(partial_remote), ready_size); } } -void FileLoadManager::on_ok_download(const FullLocalFileLocation &local, int64 size, bool is_new) { +void FileLoadManager::on_ok_download(FullLocalFileLocation local, int64 size, bool is_new) { auto node_id = get_link_token(); auto node = nodes_container_.get(node_id); if (node == nullptr) { return; } if (!stop_flag_) { - send_closure(callback_, &Callback::on_download_ok, node->query_id_, local, size, is_new); + send_closure(callback_, &Callback::on_download_ok, node->query_id_, std::move(local), size, is_new); } close_node(node_id); loop(); } -void FileLoadManager::on_ok_upload(FileType file_type, const PartialRemoteFileLocation &remote, int64 size) { +void FileLoadManager::on_ok_upload(FileType file_type, PartialRemoteFileLocation remote, int64 size) { auto node_id = get_link_token(); auto node = nodes_container_.get(node_id); if (node == nullptr) { return; } if (!stop_flag_) { - send_closure(callback_, &Callback::on_upload_ok, node->query_id_, file_type, remote, size); + send_closure(callback_, &Callback::on_upload_ok, node->query_id_, file_type, std::move(remote), size); } close_node(node_id); loop(); } -void FileLoadManager::on_ok_upload_full(const FullRemoteFileLocation &remote) { +void FileLoadManager::on_ok_upload_full(FullRemoteFileLocation remote) { auto node_id = get_link_token(); auto node = nodes_container_.get(node_id); if (node == nullptr) { return; } if (!stop_flag_) { - send_closure(callback_, &Callback::on_upload_full_ok, node->query_id_, remote); + send_closure(callback_, &Callback::on_upload_full_ok, node->query_id_, std::move(remote)); } close_node(node_id); loop(); diff --git a/td/telegram/files/FileLoadManager.h b/td/telegram/files/FileLoadManager.h index 2066e068c..e1ed7c1df 100644 --- a/td/telegram/files/FileLoadManager.h +++ b/td/telegram/files/FileLoadManager.h @@ -33,17 +33,18 @@ class FileLoadManager final : public Actor { class Callback : public Actor { public: virtual void on_start_download(QueryId id) = 0; - virtual void on_partial_download(QueryId id, const PartialLocalFileLocation &partial_local, int64 ready_size, + virtual void on_partial_download(QueryId id, PartialLocalFileLocation partial_local, int64 ready_size, int64 size) = 0; - virtual void on_partial_upload(QueryId id, const PartialRemoteFileLocation &partial_remote, int64 ready_size) = 0; + virtual void on_partial_upload(QueryId id, PartialRemoteFileLocation partial_remote, int64 ready_size) = 0; virtual void on_hash(QueryId id, string hash) = 0; - virtual void on_upload_ok(QueryId id, FileType file_type, const PartialRemoteFileLocation &remtoe, int64 size) = 0; - virtual void on_upload_full_ok(QueryId id, const FullRemoteFileLocation &remote) = 0; - virtual void on_download_ok(QueryId id, const FullLocalFileLocation &local, int64 size, bool is_new) = 0; + virtual void on_upload_ok(QueryId id, FileType file_type, PartialRemoteFileLocation remtoe, int64 size) = 0; + virtual void on_upload_full_ok(QueryId id, FullRemoteFileLocation remote) = 0; + virtual void on_download_ok(QueryId id, FullLocalFileLocation local, int64 size, bool is_new) = 0; virtual void on_error(QueryId id, Status status) = 0; }; explicit FileLoadManager(ActorShared callback, ActorShared<> parent); + void download(QueryId id, const FullRemoteFileLocation &remote_location, const LocalFileLocation &local, int64 size, string name, const FileEncryptionKey &encryption_key, bool search_file, int64 offset, int64 limit, int8 priority); @@ -55,6 +56,7 @@ class FileLoadManager final : public Actor { void cancel(QueryId id); void update_local_file_location(QueryId id, const LocalFileLocation &local); void update_downloaded_part(QueryId id, int64 offset, int64 limit); + void get_content(const FullLocalFileLocation &local_location, Promise promise); private: @@ -84,12 +86,12 @@ class FileLoadManager final : public Actor { ActorOwn &get_download_resource_manager(bool is_small, DcId dc_id); void on_start_download(); - void on_partial_download(const PartialLocalFileLocation &partial_local, int64 ready_size, int64 size); - void on_partial_upload(const PartialRemoteFileLocation &partial_remote, int64 ready_size); + void on_partial_download(PartialLocalFileLocation partial_local, int64 ready_size, int64 size); + void on_partial_upload(PartialRemoteFileLocation partial_remote, int64 ready_size); void on_hash(string hash); - void on_ok_download(const FullLocalFileLocation &local, int64 size, bool is_new); - void on_ok_upload(FileType file_type, const PartialRemoteFileLocation &remote, int64 size); - void on_ok_upload_full(const FullRemoteFileLocation &remote); + void on_ok_download(FullLocalFileLocation local, int64 size, bool is_new); + void on_ok_upload(FileType file_type, PartialRemoteFileLocation remote, int64 size); + void on_ok_upload_full(FullRemoteFileLocation remote); void on_error(Status status); void on_error_impl(NodeId node_id, Status status); @@ -104,11 +106,11 @@ class FileLoadManager final : public Actor { void on_start_download() final { send_closure(actor_id_, &FileLoadManager::on_start_download); } - void on_partial_download(const PartialLocalFileLocation &partial_local, int64 ready_size, int64 size) final { - send_closure(actor_id_, &FileLoadManager::on_partial_download, partial_local, ready_size, size); + void on_partial_download(PartialLocalFileLocation partial_local, int64 ready_size, int64 size) final { + send_closure(actor_id_, &FileLoadManager::on_partial_download, std::move(partial_local), ready_size, size); } - void on_ok(const FullLocalFileLocation &full_local, int64 size, bool is_new) final { - send_closure(std::move(actor_id_), &FileLoadManager::on_ok_download, full_local, size, is_new); + void on_ok(FullLocalFileLocation full_local, int64 size, bool is_new) final { + send_closure(std::move(actor_id_), &FileLoadManager::on_ok_download, std::move(full_local), size, is_new); } void on_error(Status status) final { send_closure(std::move(actor_id_), &FileLoadManager::on_error, std::move(status)); @@ -126,11 +128,11 @@ class FileLoadManager final : public Actor { void on_hash(string hash) final { send_closure(actor_id_, &FileLoadManager::on_hash, std::move(hash)); } - void on_partial_upload(const PartialRemoteFileLocation &partial_remote, int64 ready_size) final { - send_closure(actor_id_, &FileLoadManager::on_partial_upload, partial_remote, ready_size); + void on_partial_upload(PartialRemoteFileLocation partial_remote, int64 ready_size) final { + send_closure(actor_id_, &FileLoadManager::on_partial_upload, std::move(partial_remote), ready_size); } - void on_ok(FileType file_type, const PartialRemoteFileLocation &partial_remote, int64 size) final { - send_closure(std::move(actor_id_), &FileLoadManager::on_ok_upload, file_type, partial_remote, size); + void on_ok(FileType file_type, PartialRemoteFileLocation partial_remote, int64 size) final { + send_closure(std::move(actor_id_), &FileLoadManager::on_ok_upload, file_type, std::move(partial_remote), size); } void on_error(Status status) final { send_closure(std::move(actor_id_), &FileLoadManager::on_error, std::move(status)); @@ -144,8 +146,8 @@ class FileLoadManager final : public Actor { private: ActorShared actor_id_; - void on_ok(const FullRemoteFileLocation &remote) final { - send_closure(std::move(actor_id_), &FileLoadManager::on_ok_upload_full, remote); + void on_ok(FullRemoteFileLocation remote) final { + send_closure(std::move(actor_id_), &FileLoadManager::on_ok_upload_full, std::move(remote)); } void on_error(Status status) final { send_closure(std::move(actor_id_), &FileLoadManager::on_error, std::move(status)); diff --git a/td/telegram/files/FileLoaderUtils.cpp b/td/telegram/files/FileLoaderUtils.cpp index 4556909a1..a3631a3e7 100644 --- a/td/telegram/files/FileLoaderUtils.cpp +++ b/td/telegram/files/FileLoaderUtils.cpp @@ -66,7 +66,7 @@ StringBuilder &operator<<(StringBuilder &sb, const Ext &ext) { Result> open_temp_file(FileType file_type) { auto pmc = G()->td_db()->get_binlog_pmc(); // TODO: CAS? - int32 file_id = to_integer(pmc->get("tmp_file_id")); + auto file_id = to_integer(pmc->get("tmp_file_id")); pmc->set("tmp_file_id", to_string(file_id + 1)); auto temp_dir = get_files_temp_dir(file_type); @@ -94,7 +94,7 @@ bool for_suggested_file_name(CSlice name, bool use_pmc, bool use_random, F &&cal } } else if (use_pmc) { auto pmc = G()->td_db()->get_binlog_pmc(); - int32 file_id = to_integer(pmc->get("perm_file_id")); + auto file_id = to_integer(pmc->get("perm_file_id")); pmc->set("perm_file_id", to_string(file_id + 1)); active = callback(PSLICE() << "file_" << file_id << Ext{ext}); if (active) { diff --git a/td/telegram/files/FileLocation.h b/td/telegram/files/FileLocation.h index b93abb235..03f44129a 100644 --- a/td/telegram/files/FileLocation.h +++ b/td/telegram/files/FileLocation.h @@ -630,9 +630,9 @@ class RemoteFileLocation { RemoteFileLocation() : variant_{EmptyRemoteFileLocation{}} { } - explicit RemoteFileLocation(const FullRemoteFileLocation &full) : variant_(full) { + explicit RemoteFileLocation(FullRemoteFileLocation full) : variant_(std::move(full)) { } - explicit RemoteFileLocation(const PartialRemoteFileLocation &partial) : variant_(partial) { + explicit RemoteFileLocation(PartialRemoteFileLocation partial) : variant_(std::move(partial)) { } private: @@ -771,19 +771,21 @@ struct PartialLocalFileLocationPtr { PartialLocalFileLocationPtr() : location_(make_unique()) { } explicit PartialLocalFileLocationPtr(PartialLocalFileLocation location) - : location_(make_unique(location)) { + : location_(make_unique(std::move(location))) { } PartialLocalFileLocationPtr(const PartialLocalFileLocationPtr &other) : location_(make_unique(*other.location_)) { } PartialLocalFileLocationPtr &operator=(const PartialLocalFileLocationPtr &other) { - *location_ = *other.location_; + if (this != &other) { + *location_ = *other.location_; + } return *this; } - PartialLocalFileLocationPtr(PartialLocalFileLocationPtr &&other) + PartialLocalFileLocationPtr(PartialLocalFileLocationPtr &&other) noexcept : location_(make_unique(std::move(*other.location_))) { } - PartialLocalFileLocationPtr &operator=(PartialLocalFileLocationPtr &&other) { + PartialLocalFileLocationPtr &operator=(PartialLocalFileLocationPtr &&other) noexcept { *location_ = std::move(*other.location_); return *this; } @@ -839,9 +841,10 @@ class LocalFileLocation { LocalFileLocation() : variant_{EmptyLocalFileLocation()} { } - explicit LocalFileLocation(const PartialLocalFileLocation &partial) : variant_(PartialLocalFileLocationPtr(partial)) { + explicit LocalFileLocation(PartialLocalFileLocation partial) + : variant_(PartialLocalFileLocationPtr(std::move(partial))) { } - explicit LocalFileLocation(const FullLocalFileLocation &full) : variant_(full) { + explicit LocalFileLocation(FullLocalFileLocation full) : variant_(std::move(full)) { } LocalFileLocation(FileType file_type, string path, uint64 mtime_nsec) : variant_(FullLocalFileLocation{file_type, std::move(path), mtime_nsec}) { diff --git a/td/telegram/files/FileManager.cpp b/td/telegram/files/FileManager.cpp index 7821a92b6..fc0297ee3 100644 --- a/td/telegram/files/FileManager.cpp +++ b/td/telegram/files/FileManager.cpp @@ -271,7 +271,7 @@ void FileNode::delete_partial_remote_location() { } } -void FileNode::set_partial_remote_location(const PartialRemoteFileLocation &remote, int64 ready_size) { +void FileNode::set_partial_remote_location(PartialRemoteFileLocation remote, int64 ready_size) { if (remote_.is_full_alive) { VLOG(update_file) << "File " << main_file_id_ << " remote is still alive, so there is NO reason to update partial"; return; @@ -294,7 +294,7 @@ void FileNode::set_partial_remote_location(const PartialRemoteFileLocation &remo } VLOG(update_file) << "File " << main_file_id_ << " partial location has changed to " << remote; - remote_.partial = make_unique(remote); + remote_.partial = make_unique(std::move(remote)); on_changed(); } @@ -1037,7 +1037,7 @@ bool FileManager::try_fix_partial_local_location(FileNodePtr node) { partial.ready_bitmask_ = new_mask.encode(); auto ready_size = new_mask.get_total_size(partial.part_size_, node->size_); - node->set_local_location(LocalFileLocation(partial), ready_size, -1, -1); + node->set_local_location(LocalFileLocation(std::move(partial)), ready_size, -1, -1); LOG(INFO) << " ok: increase part_size " << old_part_size << "->" << new_part_size; return true; } @@ -1110,17 +1110,17 @@ Result FileManager::register_local(FullLocalFileLocation location, Dialo skip_file_size_checks); } -FileId FileManager::register_remote(const FullRemoteFileLocation &location, FileLocationSource file_location_source, +FileId FileManager::register_remote(FullRemoteFileLocation location, FileLocationSource file_location_source, DialogId owner_dialog_id, int64 size, int64 expected_size, string remote_name) { FileData data; - data.remote_ = RemoteFileLocation(location); + auto url = location.get_url(); + data.remote_ = RemoteFileLocation(std::move(location)); data.owner_dialog_id_ = owner_dialog_id; data.size_ = size; data.expected_size_ = expected_size; data.remote_name_ = std::move(remote_name); auto file_id = register_file(std::move(data), file_location_source, "register_remote", false).move_as_ok(); - auto url = location.get_url(); if (!url.empty()) { auto file_node = get_file_node(file_id); CHECK(file_node); @@ -1274,8 +1274,8 @@ Result FileManager::register_file(FileData &&data, FileLocationSource fi // 1 -- choose y // 2 -- choose any static int merge_choose_local_location(const LocalFileLocation &x, const LocalFileLocation &y) { - int32 x_type = static_cast(x.type()); - int32 y_type = static_cast(y.type()); + auto x_type = static_cast(x.type()); + auto y_type = static_cast(y.type()); if (x_type != y_type) { return x_type < y_type; } @@ -2383,7 +2383,7 @@ class FileManager::ForceUploadActor final : public Actor { void on_upload_error(FileId file_id, Status error) final { send_closure(std::move(callback_), &ForceUploadActor::on_upload_error, std::move(error)); } - ~UploadCallback() { + ~UploadCallback() final { if (callback_.empty()) { return; } @@ -2595,7 +2595,7 @@ bool FileManager::delete_partial_remote_location(FileId file_id) { return true; } -void FileManager::delete_file_reference(FileId file_id, string file_reference) { +void FileManager::delete_file_reference(FileId file_id, Slice file_reference) { VLOG(file_references) << "Delete file reference of file " << file_id << " " << tag("reference_base64", base64_encode(file_reference)); auto node = get_sync_file_node(file_id); @@ -2698,11 +2698,12 @@ void FileManager::run_generate(FileNodePtr node) { public: Callback(ActorId actor, QueryId id) : actor_(std::move(actor)), query_id_(id) { } - void on_partial_generate(const PartialLocalFileLocation &partial_local, int32 expected_size) final { - send_closure(actor_, &FileManager::on_partial_generate, query_id_, partial_local, expected_size); + void on_partial_generate(PartialLocalFileLocation partial_local, int32 expected_size) final { + send_closure(actor_, &FileManager::on_partial_generate, query_id_, std::move(partial_local), + expected_size); } - void on_ok(const FullLocalFileLocation &local) final { - send_closure(actor_, &FileManager::on_generate_ok, query_id_, local); + void on_ok(FullLocalFileLocation local) final { + send_closure(actor_, &FileManager::on_generate_ok, query_id_, std::move(local)); } void on_error(Status error) final { send_closure(actor_, &FileManager::on_error, query_id_, std::move(error)); @@ -2973,12 +2974,12 @@ td_api::object_ptr FileManager::get_file_object(FileId file_id, bo string persistent_file_id = file_view.get_persistent_file_id(); string unique_file_id = file_view.get_unique_file_id(); bool is_uploading_completed = !persistent_file_id.empty(); - int32 size = narrow_cast(file_view.size()); - int32 expected_size = narrow_cast(file_view.expected_size()); - int32 download_offset = narrow_cast(file_view.download_offset()); - int32 local_prefix_size = narrow_cast(file_view.local_prefix_size()); - int32 local_total_size = narrow_cast(file_view.local_total_size()); - int32 remote_size = narrow_cast(file_view.remote_size()); + auto size = narrow_cast(file_view.size()); + auto expected_size = narrow_cast(file_view.expected_size()); + auto download_offset = narrow_cast(file_view.download_offset()); + auto local_prefix_size = narrow_cast(file_view.local_prefix_size()); + auto local_total_size = narrow_cast(file_view.local_total_size()); + auto remote_size = narrow_cast(file_view.remote_size()); string path = file_view.path(); bool can_be_downloaded = file_view.can_download_from_server() || file_view.can_generate(); bool can_be_deleted = file_view.can_delete(); @@ -3190,8 +3191,8 @@ Result FileManager::get_map_thumbnail_file_id(Location location, int32 z const double PI = 3.14159265358979323846; double sin_latitude = std::sin(location.get_latitude() * PI / 180); int32 size = 256 * (1 << zoom); - int32 x = static_cast((location.get_longitude() + 180) / 360 * size); - int32 y = static_cast((0.5 - std::log((1 + sin_latitude) / (1 - sin_latitude)) / (4 * PI)) * size); + auto x = static_cast((location.get_longitude() + 180) / 360 * size); + auto y = static_cast((0.5 - std::log((1 + sin_latitude) / (1 - sin_latitude)) / (4 * PI)) * size); x = clamp(x, 0, size - 1); // just in case y = clamp(y, 0, size - 1); // just in case @@ -3353,7 +3354,7 @@ FileId FileManager::next_file_id() { } FileManager::FileNodeId FileManager::next_file_node_id() { - FileNodeId res = static_cast(file_nodes_.size()); + auto res = static_cast(file_nodes_.size()); file_nodes_.emplace_back(nullptr); return res; } @@ -3380,7 +3381,7 @@ void FileManager::on_start_download(QueryId query_id) { file_node->is_download_started_ = true; } -void FileManager::on_partial_download(QueryId query_id, const PartialLocalFileLocation &partial_local, int64 ready_size, +void FileManager::on_partial_download(QueryId query_id, PartialLocalFileLocation partial_local, int64 ready_size, int64 size) { if (is_closed_) { return; @@ -3406,7 +3407,7 @@ void FileManager::on_partial_download(QueryId query_id, const PartialLocalFileLo file_node->set_size(size); } } - file_node->set_local_location(LocalFileLocation(partial_local), ready_size, -1, -1 /* TODO */); + file_node->set_local_location(LocalFileLocation(std::move(partial_local)), ready_size, -1, -1 /* TODO */); try_flush_node(file_node, "on_partial_download"); } @@ -3432,8 +3433,7 @@ void FileManager::on_hash(QueryId query_id, string hash) { file_node->encryption_key_.set_value_hash(secure_storage::ValueHash::create(hash).move_as_ok()); } -void FileManager::on_partial_upload(QueryId query_id, const PartialRemoteFileLocation &partial_remote, - int64 ready_size) { +void FileManager::on_partial_upload(QueryId query_id, PartialRemoteFileLocation partial_remote, int64 ready_size) { if (is_closed_) { return; } @@ -3452,11 +3452,11 @@ void FileManager::on_partial_upload(QueryId query_id, const PartialRemoteFileLoc return; } - file_node->set_partial_remote_location(partial_remote, ready_size); + file_node->set_partial_remote_location(std::move(partial_remote), ready_size); try_flush_node(file_node, "on_partial_upload"); } -void FileManager::on_download_ok(QueryId query_id, const FullLocalFileLocation &local, int64 size, bool is_new) { +void FileManager::on_download_ok(QueryId query_id, FullLocalFileLocation local, int64 size, bool is_new) { if (is_closed_) { return; } @@ -3466,7 +3466,7 @@ void FileManager::on_download_ok(QueryId query_id, const FullLocalFileLocation & std::tie(query, was_active) = finish_query(query_id); auto file_id = query.file_id_; LOG(INFO) << "ON DOWNLOAD OK of " << (is_new ? "new" : "checked") << " file " << file_id << " of size " << size; - auto r_new_file_id = register_local(local, DialogId(), size, false, false, true); + auto r_new_file_id = register_local(std::move(local), DialogId(), size, false, false, true); Status status = Status::OK(); if (r_new_file_id.is_error()) { status = Status::Error(PSLICE() << "Can't register local file after download: " << r_new_file_id.error().message()); @@ -3485,7 +3485,7 @@ void FileManager::on_download_ok(QueryId query_id, const FullLocalFileLocation & } } -void FileManager::on_upload_ok(QueryId query_id, FileType file_type, const PartialRemoteFileLocation &partial_remote, +void FileManager::on_upload_ok(QueryId query_id, FileType file_type, PartialRemoteFileLocation partial_remote, int64 size) { if (is_closed_) { return; @@ -3562,19 +3562,18 @@ void FileManager::on_upload_ok(QueryId query_id, FileType file_type, const Parti } } -void FileManager::on_upload_full_ok(QueryId query_id, const FullRemoteFileLocation &remote) { +void FileManager::on_upload_full_ok(QueryId query_id, FullRemoteFileLocation remote) { if (is_closed_) { return; } auto file_id = finish_query(query_id).first.file_id_; LOG(INFO) << "ON UPLOAD FULL OK for file " << file_id; - auto new_file_id = register_remote(remote, FileLocationSource::FromServer, DialogId(), 0, 0, ""); + auto new_file_id = register_remote(std::move(remote), FileLocationSource::FromServer, DialogId(), 0, 0, ""); LOG_STATUS(merge(new_file_id, file_id)); } -void FileManager::on_partial_generate(QueryId query_id, const PartialLocalFileLocation &partial_local, - int32 expected_size) { +void FileManager::on_partial_generate(QueryId query_id, PartialLocalFileLocation partial_local, int32 expected_size) { if (is_closed_) { return; } @@ -3604,13 +3603,13 @@ void FileManager::on_partial_generate(QueryId query_id, const PartialLocalFileLo } if (file_node->upload_id_ != 0) { send_closure(file_load_manager_, &FileLoadManager::update_local_file_location, file_node->upload_id_, - LocalFileLocation(partial_local)); + LocalFileLocation(std::move(partial_local))); } try_flush_node(file_node, "on_partial_generate"); } -void FileManager::on_generate_ok(QueryId query_id, const FullLocalFileLocation &local) { +void FileManager::on_generate_ok(QueryId query_id, FullLocalFileLocation local) { if (is_closed_) { return; } @@ -3654,7 +3653,7 @@ void FileManager::on_generate_ok(QueryId query_id, const FullLocalFileLocation & if (was_active) { if (old_upload_id != 0 && old_upload_id == file_node->upload_id_) { send_closure(file_load_manager_, &FileLoadManager::update_local_file_location, file_node->upload_id_, - LocalFileLocation(local)); + LocalFileLocation(std::move(local))); } } } diff --git a/td/telegram/files/FileManager.h b/td/telegram/files/FileManager.h index 1f83b5b0e..c5b4a766d 100644 --- a/td/telegram/files/FileManager.h +++ b/td/telegram/files/FileManager.h @@ -88,7 +88,7 @@ class FileNode { int64 ready_prefix_size); void set_new_remote_location(NewRemoteFileLocation remote); void delete_partial_remote_location(); - void set_partial_remote_location(const PartialRemoteFileLocation &remote, int64 ready_size); + void set_partial_remote_location(PartialRemoteFileLocation remote, int64 ready_size); bool delete_file_reference(Slice file_reference); void set_generate_location(unique_ptr &&generate); @@ -98,7 +98,7 @@ class FileNode { void set_url(string url); void set_owner_dialog_id(DialogId owner_id); void set_encryption_key(FileEncryptionKey key); - void set_upload_pause(FileId file_id); + void set_upload_pause(FileId upload_pause); void set_download_priority(int8 priority); void set_upload_priority(int8 priority); @@ -421,7 +421,7 @@ class FileManager final : public FileLoadManager::Callback { Result register_local(FullLocalFileLocation location, DialogId owner_dialog_id, int64 size, bool get_by_hash = false, bool force = false, bool skip_file_size_checks = false) TD_WARN_UNUSED_RESULT; - FileId register_remote(const FullRemoteFileLocation &location, FileLocationSource file_location_source, + FileId register_remote(FullRemoteFileLocation location, FileLocationSource file_location_source, DialogId owner_dialog_id, int64 size, int64 expected_size, string remote_name) TD_WARN_UNUSED_RESULT; Result register_generate(FileType file_type, FileLocationSource file_location_source, string original_path, @@ -450,7 +450,7 @@ class FileManager final : public FileLoadManager::Callback { int32 new_priority, uint64 upload_order, bool force = false, bool prefer_small = false); void cancel_upload(FileId file_id); bool delete_partial_remote_location(FileId file_id); - void delete_file_reference(FileId file_id, std::string file_reference); + void delete_file_reference(FileId file_id, Slice file_reference); void get_content(FileId file_id, Promise promise); Result get_suggested_file_name(FileId file_id, const string &directory); @@ -470,7 +470,7 @@ class FileManager final : public FileLoadManager::Callback { td_api::object_ptr get_file_object(FileId file_id, bool with_main_file_id = true); vector get_file_ids_object(const vector &file_ids, bool with_main_file_id = true); - Result get_input_thumbnail_file_id(const tl_object_ptr &thumb_input_file, + Result get_input_thumbnail_file_id(const tl_object_ptr &thumbnail_input_file, DialogId owner_dialog_id, bool is_encrypted) TD_WARN_UNUSED_RESULT; Result get_input_file_id(FileType type, const tl_object_ptr &file, DialogId owner_dialog_id, bool allow_zero, bool is_encrypted, @@ -601,7 +601,7 @@ class FileManager final : public FileLoadManager::Callback { FileId register_pmc_file_data(FileData &&data); Status check_local_location(FileNodePtr node); - bool try_fix_partial_local_location(FileNodePtr node); + static bool try_fix_partial_local_location(FileNodePtr node); Status check_local_location(FullLocalFileLocation &location, int64 &size, bool skip_file_size_checks); void try_flush_node_full(FileNodePtr node, bool new_remote, bool new_local, bool new_generate, FileDbId other_pmc_id); void try_flush_node(FileNodePtr node, const char *source); @@ -616,7 +616,7 @@ class FileManager final : public FileLoadManager::Callback { Result from_persistent_id_v3(Slice binary, FileType file_type); Result from_persistent_id_v23(Slice binary, FileType file_type, int32 version); - string fix_file_extension(Slice file_name, Slice file_type, Slice file_extension); + static string fix_file_extension(Slice file_name, Slice file_type, Slice file_extension); string get_file_name(FileType file_type, Slice path); ConstFileNodePtr get_file_node(FileId file_id) const { @@ -640,20 +640,19 @@ class FileManager final : public FileLoadManager::Callback { void run_generate(FileNodePtr node); void on_start_download(QueryId query_id) final; - void on_partial_download(QueryId query_id, const PartialLocalFileLocation &partial_local, int64 ready_size, + void on_partial_download(QueryId query_id, PartialLocalFileLocation partial_local, int64 ready_size, int64 size) final; void on_hash(QueryId query_id, string hash) final; - void on_partial_upload(QueryId query_id, const PartialRemoteFileLocation &partial_remote, int64 ready_size) final; - void on_download_ok(QueryId query_id, const FullLocalFileLocation &local, int64 size, bool is_new) final; - void on_upload_ok(QueryId query_id, FileType file_type, const PartialRemoteFileLocation &partial_remote, - int64 size) final; - void on_upload_full_ok(QueryId query_id, const FullRemoteFileLocation &remote) final; + void on_partial_upload(QueryId query_id, PartialRemoteFileLocation partial_remote, int64 ready_size) final; + void on_download_ok(QueryId query_id, FullLocalFileLocation local, int64 size, bool is_new) final; + void on_upload_ok(QueryId query_id, FileType file_type, PartialRemoteFileLocation partial_remote, int64 size) final; + void on_upload_full_ok(QueryId query_id, FullRemoteFileLocation remote) final; void on_error(QueryId query_id, Status status) final; void on_error_impl(FileNodePtr node, Query::Type type, bool was_active, Status status); - void on_partial_generate(QueryId, const PartialLocalFileLocation &partial_local, int32 expected_size); - void on_generate_ok(QueryId, const FullLocalFileLocation &local); + void on_partial_generate(QueryId, PartialLocalFileLocation partial_local, int32 expected_size); + void on_generate_ok(QueryId, FullLocalFileLocation local); std::pair finish_query(QueryId query_id); diff --git a/td/telegram/files/FileManager.hpp b/td/telegram/files/FileManager.hpp index 23c41ed42..6971c1733 100644 --- a/td/telegram/files/FileManager.hpp +++ b/td/telegram/files/FileManager.hpp @@ -107,9 +107,7 @@ void FileManager::store_file(FileId file_id, StorerT &storer, int32 ttl) const { default: UNREACHABLE(); } - if (has_encryption_key) { - store(file_view.encryption_key(), storer); - } else if (has_secure_key) { + if (has_encryption_key || has_secure_key) { store(file_view.encryption_key(), storer); } } @@ -225,13 +223,10 @@ FileId FileManager::parse_file(ParserT &parser) { return FileId(); }(); - if (has_encryption_key) { + if (has_encryption_key || has_secure_key) { + auto key_type = has_encryption_key ? FileEncryptionKey::Type::Secret : FileEncryptionKey::Type::Secure; FileEncryptionKey encryption_key; - encryption_key.parse(FileEncryptionKey::Type::Secret, parser); - set_encryption_key(file_id, std::move(encryption_key)); - } else if (has_secure_key) { - FileEncryptionKey encryption_key; - encryption_key.parse(FileEncryptionKey::Type::Secure, parser); + encryption_key.parse(key_type, parser); set_encryption_key(file_id, std::move(encryption_key)); } diff --git a/td/telegram/files/FileStats.cpp b/td/telegram/files/FileStats.cpp index 295897472..52b9d4bf7 100644 --- a/td/telegram/files/FileStats.cpp +++ b/td/telegram/files/FileStats.cpp @@ -137,7 +137,7 @@ td_api::object_ptr FileStats::get_storage_stati auto stats = make_tl_object(dialog_id.get(), 0, 0, Auto()); FileStats::StatByType aggregated_stats; for (int32 i = 0; i < MAX_FILE_TYPE; i++) { - size_t file_type = narrow_cast(get_main_file_type(static_cast(i))); + auto file_type = narrow_cast(get_main_file_type(static_cast(i))); aggregated_stats[file_type].size += stat_by_type_[i].size; aggregated_stats[file_type].cnt += stat_by_type_[i].cnt; } @@ -150,7 +150,7 @@ td_api::object_ptr FileStats::get_storage_stati continue; } - FileType file_type = static_cast(i); + auto file_type = static_cast(i); stats->size_ += size; stats->count_ += cnt; stats->by_file_type_.push_back( diff --git a/td/telegram/files/FileUploader.h b/td/telegram/files/FileUploader.h index 81a89e24d..321cb07fb 100644 --- a/td/telegram/files/FileUploader.h +++ b/td/telegram/files/FileUploader.h @@ -24,8 +24,8 @@ class FileUploader final : public FileLoader { class Callback : public FileLoader::Callback { public: virtual void on_hash(string hash) = 0; - virtual void on_partial_upload(const PartialRemoteFileLocation &partial_remote, int64 ready_size) = 0; - virtual void on_ok(FileType file_type, const PartialRemoteFileLocation &partial_remote, int64 size) = 0; + virtual void on_partial_upload(PartialRemoteFileLocation partial_remote, int64 ready_size) = 0; + virtual void on_ok(FileType file_type, PartialRemoteFileLocation partial_remote, int64 size) = 0; virtual void on_error(Status status) = 0; }; diff --git a/td/telegram/files/PartsManager.cpp b/td/telegram/files/PartsManager.cpp index 69b7d2760..988a7ba05 100644 --- a/td/telegram/files/PartsManager.cpp +++ b/td/telegram/files/PartsManager.cpp @@ -537,8 +537,8 @@ int64 PartsManager::get_unchecked_ready_prefix_size() { } Part PartsManager::get_part(int id) const { - int64 offset = narrow_cast(part_size_) * id; - int64 size = narrow_cast(part_size_); + auto size = narrow_cast(part_size_); + auto offset = size * id; auto total_size = unknown_size_flag_ ? max_size_ : get_size(); if (total_size < offset) { size = 0; diff --git a/td/telegram/files/PartsManager.h b/td/telegram/files/PartsManager.h index 51700d16c..0efeb27d4 100644 --- a/td/telegram/files/PartsManager.h +++ b/td/telegram/files/PartsManager.h @@ -93,8 +93,9 @@ class PartsManager { const std::vector &ready_parts) TD_WARN_UNUSED_RESULT; Status init_no_size(size_t part_size, const std::vector &ready_parts) TD_WARN_UNUSED_RESULT; + static Part get_empty_part(); + Part get_part(int id) const; - Part get_empty_part(); void on_part_start(int32 id); void update_first_empty_part(); void update_first_not_ready_part(); diff --git a/td/telegram/misc.cpp b/td/telegram/misc.cpp index 2886fa0cc..89147caf2 100644 --- a/td/telegram/misc.cpp +++ b/td/telegram/misc.cpp @@ -74,7 +74,7 @@ bool clean_input_string(string &str) { size_t str_size = str.size(); size_t new_size = 0; for (size_t pos = 0; pos < str_size; pos++) { - unsigned char c = static_cast(str[pos]); + auto c = static_cast(str[pos]); switch (c) { // remove control characters case 0: @@ -118,7 +118,7 @@ bool clean_input_string(string &str) { default: // remove \xe2\x80[\xa8-\xae] if (c == 0xe2 && pos + 2 < str_size) { - unsigned char next = static_cast(str[pos + 1]); + auto next = static_cast(str[pos + 1]); if (next == 0x80) { next = static_cast(str[pos + 2]); if (0xa8 <= next && next <= 0xae) { @@ -129,7 +129,7 @@ bool clean_input_string(string &str) { } // remove vertical lines \xcc[\xb3\xbf\x8a] if (c == 0xcc && pos + 1 < str_size) { - unsigned char next = static_cast(str[pos + 1]); + auto next = static_cast(str[pos + 1]); if (next == 0xb3 || next == 0xbf || next == 0x8a) { pos++; break; diff --git a/td/telegram/net/ConnectionCreator.cpp b/td/telegram/net/ConnectionCreator.cpp index d0de32ace..14700f18e 100644 --- a/td/telegram/net/ConnectionCreator.cpp +++ b/td/telegram/net/ConnectionCreator.cpp @@ -130,7 +130,7 @@ ConnectionCreator::ConnectionCreator(ActorShared<> parent) : parent_(std::move(p ConnectionCreator::ConnectionCreator(ConnectionCreator &&other) = default; -ConnectionCreator &ConnectionCreator::operator=(ConnectionCreator &&other) = default; +ConnectionCreator &ConnectionCreator::operator=(ConnectionCreator &&other) noexcept = default; ConnectionCreator::~ConnectionCreator() = default; @@ -396,7 +396,7 @@ void ConnectionCreator::ping_proxy_socket_fd(IPAddress ip_address, SocketFd sock auto raw_connection = mtproto::RawConnection::create(ip_address, std::move(socket_fd), std::move(transport_type), nullptr); children_[token] = { - false, create_ping_actor(std::move(debug_str), std::move(raw_connection), nullptr, + false, create_ping_actor(debug_str, std::move(raw_connection), nullptr, PromiseCreator::lambda([promise = std::move(promise)]( Result> result) mutable { if (result.is_error()) { @@ -672,7 +672,7 @@ Result ConnectionCreator::get_transport_type(const Proxy if (G()->is_test_dc()) { int_dc_id += 10000; } - int16 raw_dc_id = narrow_cast(info.option->is_media_only() ? -int_dc_id : int_dc_id); + auto raw_dc_id = narrow_cast(info.option->is_media_only() ? -int_dc_id : int_dc_id); if (proxy.use_mtproto_proxy()) { return mtproto::TransportType{mtproto::TransportType::ObfuscatedTcp, raw_dc_id, proxy.secret()}; @@ -736,7 +736,7 @@ Result ConnectionCreator::find_connection(const Proxy &proxy, const IP ActorOwn<> ConnectionCreator::prepare_connection(IPAddress ip_address, SocketFd socket_fd, const Proxy &proxy, const IPAddress &mtproto_ip_address, - mtproto::TransportType transport_type, Slice actor_name_prefix, + const mtproto::TransportType &transport_type, Slice actor_name_prefix, Slice debug_str, unique_ptr stats_callback, ActorShared<> parent, bool use_connection_token, @@ -934,13 +934,13 @@ void ConnectionCreator::client_loop(ClientInfo &client) { client.checking_connections++; } - auto promise = PromiseCreator::lambda( - [actor_id = actor_id(this), check_mode, transport_type = extra.transport_type, hash = client.hash, - debug_str = extra.debug_str, - network_generation = network_generation_](Result r_connection_data) mutable { - send_closure(std::move(actor_id), &ConnectionCreator::client_create_raw_connection, - std::move(r_connection_data), check_mode, transport_type, hash, debug_str, network_generation); - }); + auto promise = PromiseCreator::lambda([actor_id = actor_id(this), check_mode, transport_type = extra.transport_type, + hash = client.hash, debug_str = extra.debug_str, + network_generation = + network_generation_](Result r_connection_data) mutable { + send_closure(std::move(actor_id), &ConnectionCreator::client_create_raw_connection, std::move(r_connection_data), + check_mode, std::move(transport_type), hash, std::move(debug_str), network_generation); + }); auto stats_callback = td::make_unique(client.is_media ? media_net_stats_callback_ : common_net_stats_callback_, @@ -1060,17 +1060,16 @@ void ConnectionCreator::on_dc_options(DcOptions new_dc_options) { } void ConnectionCreator::on_dc_update(DcId dc_id, string ip_port, Promise<> promise) { - promise.set_result([&]() -> Result<> { - if (!dc_id.is_exact()) { - return Status::Error("Invalid dc_id"); - } - IPAddress ip_address; - TRY_STATUS(ip_address.init_host_port(ip_port)); - DcOptions options; - options.dc_options.emplace_back(dc_id, ip_address); - send_closure(G()->config_manager(), &ConfigManager::on_dc_options_update, std::move(options)); - return Unit(); - }()); + if (!dc_id.is_exact()) { + return promise.set_error(Status::Error("Invalid dc_id")); + } + + IPAddress ip_address; + TRY_STATUS_PROMISE(promise, ip_address.init_host_port(ip_port)); + DcOptions options; + options.dc_options.emplace_back(dc_id, ip_address); + send_closure(G()->config_manager(), &ConfigManager::on_dc_options_update, std::move(options)); + promise.set_value(Unit()); } void ConnectionCreator::update_mtproto_header(const Proxy &proxy) { @@ -1129,13 +1128,13 @@ void ConnectionCreator::start_up() { for (auto &info : proxy_info) { if (begins_with(info.first, "_used")) { - int32 proxy_id = to_integer_safe(Slice(info.first).substr(5)).move_as_ok(); - int32 last_used = to_integer_safe(info.second).move_as_ok(); + auto proxy_id = to_integer_safe(Slice(info.first).substr(5)).move_as_ok(); + auto last_used = to_integer_safe(info.second).move_as_ok(); proxy_last_used_date_[proxy_id] = last_used; proxy_last_used_saved_date_[proxy_id] = last_used; } else { LOG_CHECK(!ends_with(info.first, "_max_id")) << info.first; - int32 proxy_id = info.first == "" ? 1 : to_integer_safe(info.first).move_as_ok(); + auto proxy_id = info.first.empty() ? static_cast(1) : to_integer_safe(info.first).move_as_ok(); CHECK(proxies_.count(proxy_id) == 0); log_event_parse(proxies_[proxy_id], info.second).ensure(); if (proxies_[proxy_id].type() == Proxy::Type::None) { diff --git a/td/telegram/net/ConnectionCreator.h b/td/telegram/net/ConnectionCreator.h index db25e09b8..5a5f69086 100644 --- a/td/telegram/net/ConnectionCreator.h +++ b/td/telegram/net/ConnectionCreator.h @@ -54,7 +54,7 @@ class ConnectionCreator final : public NetQueryCallback { public: explicit ConnectionCreator(ActorShared<> parent); ConnectionCreator(ConnectionCreator &&other); - ConnectionCreator &operator=(ConnectionCreator &&other); + ConnectionCreator &operator=(ConnectionCreator &&other) noexcept; ~ConnectionCreator() final; void on_dc_options(DcOptions new_dc_options); @@ -89,8 +89,9 @@ class ConnectionCreator final : public NetQueryCallback { static DcOptions get_default_dc_options(bool is_test); static ActorOwn<> prepare_connection(IPAddress ip_address, SocketFd socket_fd, const Proxy &proxy, - const IPAddress &mtproto_ip_address, mtproto::TransportType transport_type, - Slice actor_name_prefix, Slice debug_str, + const IPAddress &mtproto_ip_address, + const mtproto::TransportType &transport_type, Slice actor_name_prefix, + Slice debug_str, unique_ptr stats_callback, ActorShared<> parent, bool use_connection_token, Promise promise); diff --git a/td/telegram/net/DcAuthManager.cpp b/td/telegram/net/DcAuthManager.cpp index cf3969036..d8f1a4584 100644 --- a/td/telegram/net/DcAuthManager.cpp +++ b/td/telegram/net/DcAuthManager.cpp @@ -93,7 +93,7 @@ DcAuthManager::DcInfo *DcAuthManager::find_dc(int32 dc_id) { } void DcAuthManager::update_auth_key_state() { - int32 dc_id = narrow_cast(get_link_token()); + auto dc_id = narrow_cast(get_link_token()); auto &dc = get_dc(dc_id); dc.auth_key_state = dc.shared_auth_data->get_auth_key_state(); VLOG(dc) << "Update " << dc_id << " auth key state from " << dc.auth_key_state << " to " << dc.auth_key_state; @@ -102,7 +102,7 @@ void DcAuthManager::update_auth_key_state() { } void DcAuthManager::on_result(NetQueryPtr result) { - int32 dc_id = narrow_cast(get_link_token()); + auto dc_id = narrow_cast(get_link_token()); auto &dc = get_dc(dc_id); CHECK(dc.wait_id == result->id()); dc.wait_id = std::numeric_limits::max(); diff --git a/td/telegram/net/MtprotoHeader.h b/td/telegram/net/MtprotoHeader.h index 0494d6b9c..b5b0754c3 100644 --- a/td/telegram/net/MtprotoHeader.h +++ b/td/telegram/net/MtprotoHeader.h @@ -33,7 +33,7 @@ class MtprotoHeader { } void set_proxy(Proxy proxy) { - options_.proxy = proxy; + options_.proxy = std::move(proxy); default_header_ = gen_header(options_, false); } @@ -42,7 +42,7 @@ class MtprotoHeader { return false; } - options_.parameters = parameters; + options_.parameters = std::move(parameters); default_header_ = gen_header(options_, false); return true; } diff --git a/td/telegram/net/NetQuery.h b/td/telegram/net/NetQuery.h index 039d8e2b5..c284b20b0 100644 --- a/td/telegram/net/NetQuery.h +++ b/td/telegram/net/NetQuery.h @@ -300,10 +300,10 @@ class NetQuery final : public TsListNode { movable_atomic() = default; movable_atomic(T &&x) : std::atomic(std::forward(x)) { } - movable_atomic(movable_atomic &&other) { + movable_atomic(movable_atomic &&other) noexcept { this->store(other.load(std::memory_order_relaxed), std::memory_order_relaxed); } - movable_atomic &operator=(movable_atomic &&other) { + movable_atomic &operator=(movable_atomic &&other) noexcept { this->store(other.load(std::memory_order_relaxed), std::memory_order_relaxed); return *this; } diff --git a/td/telegram/net/NetQueryDispatcher.cpp b/td/telegram/net/NetQueryDispatcher.cpp index 17459a9e1..0660af35b 100644 --- a/td/telegram/net/NetQueryDispatcher.cpp +++ b/td/telegram/net/NetQueryDispatcher.cpp @@ -91,7 +91,7 @@ void NetQueryDispatcher::dispatch(NetQueryPtr net_query) { net_query->dispatch_ttl_--; } - size_t dc_pos = static_cast(dest_dc_id.get_raw_id() - 1); + auto dc_pos = static_cast(dest_dc_id.get_raw_id() - 1); CHECK(dc_pos < dcs_.size()); switch (net_query->type()) { case NetQuery::Type::Common: @@ -118,7 +118,7 @@ Status NetQueryDispatcher::wait_dc_init(DcId dc_id, bool force) { if (!dc_id.is_exact()) { return Status::Error("Not exact DC"); } - size_t pos = static_cast(dc_id.get_raw_id() - 1); + auto pos = static_cast(dc_id.get_raw_id() - 1); if (pos >= dcs_.size()) { return Status::Error("Too big DC ID"); } @@ -276,7 +276,7 @@ bool NetQueryDispatcher::get_use_pfs() { return G()->shared_config().get_option_boolean("use_pfs") || get_session_count() > 1; } -NetQueryDispatcher::NetQueryDispatcher(std::function()> create_reference) { +NetQueryDispatcher::NetQueryDispatcher(const std::function()> &create_reference) { auto s_main_dc_id = G()->td_db()->get_binlog_pmc()->get("main_dc_id"); if (!s_main_dc_id.empty()) { main_dc_id_ = to_integer(s_main_dc_id); @@ -298,7 +298,7 @@ void NetQueryDispatcher::try_fix_migrate(NetQueryPtr &net_query) { static constexpr CSlice prefixes[] = {"PHONE_MIGRATE_", "NETWORK_MIGRATE_", "USER_MIGRATE_"}; for (auto &prefix : prefixes) { if (msg.substr(0, prefix.size()) == prefix) { - int32 new_main_dc_id = to_integer(msg.substr(prefix.size())); + auto new_main_dc_id = to_integer(msg.substr(prefix.size())); set_main_dc_id(new_main_dc_id); if (!net_query->dc_id().is_main()) { diff --git a/td/telegram/net/NetQueryDispatcher.h b/td/telegram/net/NetQueryDispatcher.h index f44178a90..e65a9fc32 100644 --- a/td/telegram/net/NetQueryDispatcher.h +++ b/td/telegram/net/NetQueryDispatcher.h @@ -33,7 +33,7 @@ class SessionMultiProxy; // Not just dispatcher. class NetQueryDispatcher { public: - explicit NetQueryDispatcher(std::function()> create_reference); + explicit NetQueryDispatcher(const std::function()> &create_reference); NetQueryDispatcher(); NetQueryDispatcher(const NetQueryDispatcher &) = delete; NetQueryDispatcher &operator=(const NetQueryDispatcher &) = delete; diff --git a/td/telegram/net/NetStatsManager.cpp b/td/telegram/net/NetStatsManager.cpp index 2caa38146..ca30e6b1b 100644 --- a/td/telegram/net/NetStatsManager.cpp +++ b/td/telegram/net/NetStatsManager.cpp @@ -168,7 +168,7 @@ void NetStatsManager::add_network_stats(const NetworkStatsEntry &entry) { return add_network_stats_impl(common_net_stats_, entry); } add_network_stats_impl(media_net_stats_, entry); - size_t file_type_n = static_cast(entry.file_type); + auto file_type_n = static_cast(entry.file_type); CHECK(file_type_n < static_cast(MAX_FILE_TYPE)); add_network_stats_impl(files_stats_[file_type_n], entry); } @@ -256,7 +256,7 @@ std::shared_ptr NetStatsManager::get_media_stats_callback() co std::vector> NetStatsManager::get_file_stats_callbacks() const { auto result = transform(files_stats_, [](auto &stat) { return stat.stats.get_callback(); }); for (int32 i = 0; i < MAX_FILE_TYPE; i++) { - int32 main_file_type = static_cast(get_main_file_type(static_cast(i))); + auto main_file_type = static_cast(get_main_file_type(static_cast(i))); if (main_file_type != i) { result[i] = result[main_file_type]; } diff --git a/td/telegram/net/NetStatsManager.h b/td/telegram/net/NetStatsManager.h index 66bc77e0f..1dad82480 100644 --- a/td/telegram/net/NetStatsManager.h +++ b/td/telegram/net/NetStatsManager.h @@ -136,7 +136,7 @@ class NetStatsManager final : public Actor { void start_up() final; void update(NetStatsInfo &info, bool force_save); - void save_stats(NetStatsInfo &info, NetType net_type); + static void save_stats(NetStatsInfo &info, NetType net_type); void info_loop(NetStatsInfo &info); void on_stats_updated(size_t id); diff --git a/td/telegram/net/Proxy.h b/td/telegram/net/Proxy.h index 3bcf502b7..66ac5d1b9 100644 --- a/td/telegram/net/Proxy.h +++ b/td/telegram/net/Proxy.h @@ -18,7 +18,7 @@ namespace td { namespace td_api { class ProxyType; -} +} // namespace td_api class Proxy { public: @@ -28,7 +28,7 @@ class Proxy { Proxy proxy; proxy.type_ = Type::Socks5; proxy.server_ = std::move(server); - proxy.port_ = std::move(port); + proxy.port_ = port; proxy.user_ = std::move(user); proxy.password_ = std::move(password); return proxy; @@ -38,7 +38,7 @@ class Proxy { Proxy proxy; proxy.type_ = Type::HttpTcp; proxy.server_ = std::move(server); - proxy.port_ = std::move(port); + proxy.port_ = port; proxy.user_ = std::move(user); proxy.password_ = std::move(password); return proxy; @@ -48,7 +48,7 @@ class Proxy { Proxy proxy; proxy.type_ = Type::HttpCaching; proxy.server_ = std::move(server); - proxy.port_ = std::move(port); + proxy.port_ = port; proxy.user_ = std::move(user); proxy.password_ = std::move(password); return proxy; @@ -58,7 +58,7 @@ class Proxy { Proxy proxy; proxy.type_ = Type::Mtproto; proxy.server_ = std::move(server); - proxy.port_ = std::move(port); + proxy.port_ = port; proxy.secret_ = std::move(secret); return proxy; } diff --git a/td/telegram/net/Session.cpp b/td/telegram/net/Session.cpp index 5d411424a..4b6e4c54a 100644 --- a/td/telegram/net/Session.cpp +++ b/td/telegram/net/Session.cpp @@ -143,7 +143,7 @@ bool Session::PriorityQueue::empty() const { Session::Session(unique_ptr callback, std::shared_ptr shared_auth_data, int32 raw_dc_id, int32 dc_id, bool is_main, bool use_pfs, bool is_cdn, bool need_destroy, - const mtproto::AuthKey &tmp_auth_key, std::vector server_salts) + const mtproto::AuthKey &tmp_auth_key, const vector &server_salts) : raw_dc_id_(raw_dc_id), dc_id_(dc_id), is_main_(is_main), is_cdn_(is_cdn) { VLOG(dc) << "Start connection " << tag("need_destroy", need_destroy); need_destroy_ = need_destroy; @@ -160,7 +160,7 @@ Session::Session(unique_ptr callback, std::shared_ptr auth_data_.set_future_salts(shared_auth_data_->get_future_salts(), Time::now()); if (use_pfs && !tmp_auth_key.empty()) { auth_data_.set_tmp_auth_key(tmp_auth_key); - auth_data_.set_future_salts(std::move(server_salts), Time::now()); + auth_data_.set_future_salts(server_salts, Time::now()); } uint64 session_id = 0; do { @@ -515,7 +515,7 @@ void Session::on_closed(Status status) { LOG(WARNING) << "Invalidate CDN tmp_key"; auth_data_.drop_main_auth_key(); on_auth_key_updated(); - on_session_failed(std::move(status)); + on_session_failed(status.clone()); } else if (need_destroy_) { auth_data_.drop_main_auth_key(); on_auth_key_updated(); @@ -1199,7 +1199,7 @@ bool Session::connection_send_bind_key(ConnectionInfo *info) { int64 perm_auth_key_id = auth_data_.get_main_auth_key().id(); int64 nonce = Random::secure_int64(); - int32 expires_at = static_cast(auth_data_.get_server_time(auth_data_.get_tmp_auth_key().expires_at())); + auto expires_at = static_cast(auth_data_.get_server_time(auth_data_.get_tmp_auth_key().expires_at())); int64 message_id; BufferSlice encrypted; std::tie(message_id, encrypted) = info->connection->encrypted_bind(perm_auth_key_id, nonce, expires_at); diff --git a/td/telegram/net/Session.h b/td/telegram/net/Session.h index 0a9c1c0a6..41ccdf234 100644 --- a/td/telegram/net/Session.h +++ b/td/telegram/net/Session.h @@ -61,14 +61,14 @@ class Session final virtual void request_raw_connection(unique_ptr auth_data, Promise>) = 0; virtual void on_tmp_auth_key_updated(mtproto::AuthKey auth_key) = 0; - virtual void on_server_salt_updated(std::vector server_salts) = 0; + virtual void on_server_salt_updated(vector server_salts) = 0; virtual void on_update(BufferSlice &&update) = 0; virtual void on_result(NetQueryPtr net_query) = 0; }; Session(unique_ptr callback, std::shared_ptr shared_auth_data, int32 raw_dc_id, int32 dc_id, bool is_main, bool use_pfs, bool is_cdn, bool need_destroy, const mtproto::AuthKey &tmp_auth_key, - std::vector server_salts); + const vector &server_salts); void send(NetQueryPtr &&query); void on_network(bool network_flag, uint32 network_generation); void on_online(bool online_flag); diff --git a/td/tl/tl_jni_object.cpp b/td/tl/tl_jni_object.cpp index a46ff58c3..5bae3de49 100644 --- a/td/tl/tl_jni_object.cpp +++ b/td/tl/tl_jni_object.cpp @@ -121,10 +121,10 @@ void init_vars(JNIEnv *env, const char *td_api_java_package) { static size_t get_utf8_from_utf16_length(const jchar *p, jsize len) { size_t result = 0; for (jsize i = 0; i < len; i++) { - unsigned int cur = p[i]; + uint32 cur = p[i]; if ((cur & 0xF800) == 0xD800) { if (i < len) { - unsigned int next = p[++i]; + uint32 next = p[++i]; if ((next & 0xFC00) == 0xDC00 && (cur & 0x400) == 0) { result += 4; continue; @@ -141,8 +141,8 @@ static size_t get_utf8_from_utf16_length(const jchar *p, jsize len) { static void utf16_to_utf8(const jchar *p, jsize len, char *res) { for (jsize i = 0; i < len; i++) { - unsigned int cur = p[i]; - // TODO conversion unsigned int -> signed char is implementation defined + uint32 cur = p[i]; + // TODO conversion uint32 -> signed char is implementation defined if (cur <= 0x7f) { *res++ = static_cast(cur); } else if (cur <= 0x7ff) { @@ -154,8 +154,8 @@ static void utf16_to_utf8(const jchar *p, jsize len, char *res) { *res++ = static_cast(0x80 | (cur & 0x3f)); } else { // correctness is already checked - unsigned int next = p[++i]; - unsigned int val = ((cur - 0xD800) << 10) + next - 0xDC00 + 0x10000; + uint32 next = p[++i]; + uint32 val = ((cur - 0xD800) << 10) + next - 0xDC00 + 0x10000; *res++ = static_cast(0xf0 | (val >> 18)); *res++ = static_cast(0x80 | ((val >> 12) & 0x3f)); @@ -178,14 +178,14 @@ static jsize get_utf16_from_utf8_length(const char *p, size_t len, jsize *surrog static void utf8_to_utf16(const char *p, size_t len, jchar *res) { // UTF-8 correctness is supposed for (size_t i = 0; i < len;) { - unsigned int a = static_cast(p[i++]); + uint32 a = static_cast(p[i++]); if (a >= 0x80) { - unsigned int b = static_cast(p[i++]); + uint32 b = static_cast(p[i++]); if (a >= 0xe0) { - unsigned int c = static_cast(p[i++]); + uint32 c = static_cast(p[i++]); if (a >= 0xf0) { - unsigned int d = static_cast(p[i++]); - unsigned int val = ((a & 0x07) << 18) + ((b & 0x3f) << 12) + ((c & 0x3f) << 6) + (d & 0x3f) - 0x10000; + uint32 d = static_cast(p[i++]); + uint32 val = ((a & 0x07) << 18) + ((b & 0x3f) << 12) + ((c & 0x3f) << 6) + (d & 0x3f) - 0x10000; *res++ = static_cast(0xD800 + (val >> 10)); *res++ = static_cast(0xDC00 + (val & 0x3ff)); } else { @@ -213,7 +213,7 @@ std::string fetch_string(JNIEnv *env, jobject o, jfieldID id) { std::string from_jstring(JNIEnv *env, jstring s) { if (!s) { - return ""; + return std::string(); } jsize s_len = env->GetStringLength(s); const jchar *p = env->GetStringChars(s, nullptr); @@ -264,7 +264,7 @@ std::string from_bytes(JNIEnv *env, jbyteArray arr) { jbyteArray to_bytes(JNIEnv *env, const std::string &b) { static_assert(sizeof(char) == sizeof(jbyte), "Mismatched jbyte size"); - jsize length = narrow_cast(b.size()); + auto length = narrow_cast(b.size()); jbyteArray arr = env->NewByteArray(length); if (arr != nullptr && length != 0) { env->SetByteArrayRegion(arr, 0, length, reinterpret_cast(b.data())); @@ -274,7 +274,7 @@ jbyteArray to_bytes(JNIEnv *env, const std::string &b) { jintArray store_vector(JNIEnv *env, const std::vector &v) { static_assert(sizeof(std::int32_t) == sizeof(jint), "Mismatched jint size"); - jsize length = narrow_cast(v.size()); + auto length = narrow_cast(v.size()); jintArray arr = env->NewIntArray(length); if (arr != nullptr && length != 0) { env->SetIntArrayRegion(arr, 0, length, reinterpret_cast(&v[0])); @@ -284,7 +284,7 @@ jintArray store_vector(JNIEnv *env, const std::vector &v) { jlongArray store_vector(JNIEnv *env, const std::vector &v) { static_assert(sizeof(std::int64_t) == sizeof(jlong), "Mismatched jlong size"); - jsize length = narrow_cast(v.size()); + auto length = narrow_cast(v.size()); jlongArray arr = env->NewLongArray(length); if (arr != nullptr && length != 0) { env->SetLongArrayRegion(arr, 0, length, reinterpret_cast(&v[0])); @@ -294,7 +294,7 @@ jlongArray store_vector(JNIEnv *env, const std::vector &v) { jdoubleArray store_vector(JNIEnv *env, const std::vector &v) { static_assert(sizeof(double) == sizeof(jdouble), "Mismatched jdouble size"); - jsize length = narrow_cast(v.size()); + auto length = narrow_cast(v.size()); jdoubleArray arr = env->NewDoubleArray(length); if (arr != nullptr && length != 0) { env->SetDoubleArrayRegion(arr, 0, length, reinterpret_cast(&v[0])); @@ -303,7 +303,7 @@ jdoubleArray store_vector(JNIEnv *env, const std::vector &v) { } jobjectArray store_vector(JNIEnv *env, const std::vector &v) { - jsize length = narrow_cast(v.size()); + auto length = narrow_cast(v.size()); jobjectArray arr = env->NewObjectArray(length, StringClass, 0); if (arr != nullptr) { for (jsize i = 0; i < length; i++) { diff --git a/td/tl/tl_jni_object.h b/td/tl/tl_jni_object.h index d2f81b350..b1e7dde5a 100644 --- a/td/tl/tl_jni_object.h +++ b/td/tl/tl_jni_object.h @@ -107,7 +107,7 @@ jobjectArray store_vector(JNIEnv *env, const std::vector &v); template jobjectArray store_vector(JNIEnv *env, const std::vector &v) { - jint length = static_cast(v.size()); + auto length = static_cast(v.size()); jobjectArray arr = env->NewObjectArray(length, T::element_type::Class, jobject()); if (arr != nullptr) { for (jint i = 0; i < length; i++) { @@ -155,7 +155,7 @@ class get_array_class { template jobjectArray store_vector(JNIEnv *env, const std::vector> &v) { - jint length = static_cast(v.size()); + auto length = static_cast(v.size()); jobjectArray arr = env->NewObjectArray(length, get_array_class::get(), 0); if (arr != nullptr) { for (jint i = 0; i < length; i++) { diff --git a/td/tl/tl_json.h b/td/tl/tl_json.h index be863636c..483dc11b9 100644 --- a/td/tl/tl_json.h +++ b/td/tl/tl_json.h @@ -71,8 +71,9 @@ inline Status from_json(int32 &to, JsonValue from) { } inline Status from_json(bool &to, JsonValue from) { - if (from.type() != JsonValue::Type::Boolean) { - if (from.type() == JsonValue::Type::Null) { + auto from_type = from.type(); + if (from_type != JsonValue::Type::Boolean) { + if (from_type == JsonValue::Type::Null) { return Status::OK(); } int32 x = 0; @@ -81,7 +82,7 @@ inline Status from_json(bool &to, JsonValue from) { to = x != 0; return Status::OK(); } - return Status::Error(PSLICE() << "Expected Boolean, got " << from.type()); + return Status::Error(PSLICE() << "Expected Boolean, got " << from_type); } to = from.get_boolean(); return Status::OK(); diff --git a/tdactor/td/actor/PromiseFuture.h b/tdactor/td/actor/PromiseFuture.h index dde678aaf..ba474cc9e 100644 --- a/tdactor/td/actor/PromiseFuture.h +++ b/tdactor/td/actor/PromiseFuture.h @@ -136,7 +136,7 @@ class LambdaPromise : public PromiseInterface { , has_lambda_(true) { } template - LambdaPromise(FromOkT &&ok) : LambdaPromise(std::move(ok), Ignore(), true) { + LambdaPromise(FromOkT &&ok) : LambdaPromise(std::forward(ok), Ignore(), true) { } private: @@ -184,35 +184,29 @@ class SafePromise; template class Promise; -constexpr std::false_type is_promise_interface(...) { - return {}; -} +constexpr std::false_type is_promise_interface(...); + template -constexpr std::true_type is_promise_interface(const PromiseInterface &promise) { - return {}; -} +constexpr std::true_type is_promise_interface(const PromiseInterface &promise); + template -constexpr std::true_type is_promise_interface(const Promise &promise) { - return {}; -} +constexpr std::true_type is_promise_interface(const Promise &promise); template constexpr bool is_promise_interface() { return decltype(is_promise_interface(std::declval()))::value; } -constexpr std::false_type is_promise_interface_ptr(...) { - return {}; -} +constexpr std::false_type is_promise_interface_ptr(...); + template -constexpr std::true_type is_promise_interface_ptr(const unique_ptr &promise) { - return {}; -} +constexpr std::true_type is_promise_interface_ptr(const unique_ptr &promise); template constexpr bool is_promise_interface_ptr() { return decltype(is_promise_interface_ptr(std::declval()))::value; } + template ::value, bool> has_t = false> auto lambda_promise(F &&f) { return detail::LambdaPromise>>, std::decay_t>( @@ -461,7 +455,7 @@ class SendClosure { template auto promise_send_closure(ArgsT &&... args) { return [t = std::make_tuple(std::forward(args)...)](auto &&res) mutable { - call_tuple(SendClosure(), std::tuple_cat(std::move(t), std::make_tuple(std::move(res)))); + call_tuple(SendClosure(), std::tuple_cat(std::move(t), std::make_tuple(std::forward(res)))); }; } diff --git a/tdactor/td/actor/SignalSlot.h b/tdactor/td/actor/SignalSlot.h index 17f8aa84f..e90f2814c 100644 --- a/tdactor/td/actor/SignalSlot.h +++ b/tdactor/td/actor/SignalSlot.h @@ -16,7 +16,7 @@ class Signal { public: void emit(); - explicit Signal(ActorId slot_id) : slot_id_(slot_id) { + explicit Signal(ActorId slot_id) : slot_id_(std::move(slot_id)) { } private: diff --git a/tdactor/td/actor/impl/Actor-decl.h b/tdactor/td/actor/impl/Actor-decl.h index f8ae5f5ef..bd3bb4e96 100644 --- a/tdactor/td/actor/impl/Actor-decl.h +++ b/tdactor/td/actor/impl/Actor-decl.h @@ -24,8 +24,8 @@ class Actor : public ObserverBase { Actor() = default; Actor(const Actor &) = delete; Actor &operator=(const Actor &) = delete; - Actor(Actor &&other); - Actor &operator=(Actor &&other); + Actor(Actor &&other) noexcept; + Actor &operator=(Actor &&other) noexcept; ~Actor() override { if (!empty()) { do_stop(); diff --git a/tdactor/td/actor/impl/Actor.h b/tdactor/td/actor/impl/Actor.h index b57eeb129..4cf204ffe 100644 --- a/tdactor/td/actor/impl/Actor.h +++ b/tdactor/td/actor/impl/Actor.h @@ -20,14 +20,14 @@ namespace td { -inline Actor::Actor(Actor &&other) { +inline Actor::Actor(Actor &&other) noexcept { CHECK(info_.empty()); info_ = std::move(other.info_); if (!empty()) { info_->on_actor_moved(this); } } -inline Actor &Actor::operator=(Actor &&other) { +inline Actor &Actor::operator=(Actor &&other) noexcept { CHECK(info_.empty()); info_ = std::move(other.info_); if (!empty()) { @@ -52,7 +52,7 @@ inline void Actor::do_stop() { CHECK(empty()); } inline bool Actor::has_timeout() const { - return Scheduler::instance()->has_actor_timeout(this); + return get_info()->get_heap_node()->in_heap(); } inline double Actor::get_timeout() const { return Scheduler::instance()->get_actor_timeout(this); diff --git a/tdactor/td/actor/impl/ActorId-decl.h b/tdactor/td/actor/impl/ActorId-decl.h index 9eadc02ea..61a81fc28 100644 --- a/tdactor/td/actor/impl/ActorId-decl.h +++ b/tdactor/td/actor/impl/ActorId-decl.h @@ -25,10 +25,10 @@ class ActorId { ActorId() = default; ActorId(const ActorId &other) = default; ActorId &operator=(const ActorId &other) = default; - ActorId(ActorId &&other) : ptr_(other.ptr_) { + ActorId(ActorId &&other) noexcept : ptr_(other.ptr_) { other.ptr_.clear(); } - ActorId &operator=(ActorId &&other) { + ActorId &operator=(ActorId &&other) noexcept { if (&other == this) { return *this; } @@ -85,8 +85,8 @@ class ActorOwn { explicit ActorOwn(ActorOwn &&other); template ActorOwn &operator=(ActorOwn &&other); - ActorOwn(ActorOwn &&other); - ActorOwn &operator=(ActorOwn &&other); + ActorOwn(ActorOwn &&other) noexcept; + ActorOwn &operator=(ActorOwn &&other) noexcept; ActorOwn(const ActorOwn &other) = delete; ActorOwn &operator=(const ActorOwn &other) = delete; ~ActorOwn(); @@ -121,8 +121,8 @@ class ActorShared { ActorShared(ActorOwn &&other); template ActorShared &operator=(ActorShared &&other); - ActorShared(ActorShared &&other); - ActorShared &operator=(ActorShared &&other); + ActorShared(ActorShared &&other) noexcept; + ActorShared &operator=(ActorShared &&other) noexcept; ActorShared(const ActorShared &other) = delete; ActorShared &operator=(const ActorShared &other) = delete; ~ActorShared(); diff --git a/tdactor/td/actor/impl/ActorId.h b/tdactor/td/actor/impl/ActorId.h index fb4c85fa3..3f04e028b 100644 --- a/tdactor/td/actor/impl/ActorId.h +++ b/tdactor/td/actor/impl/ActorId.h @@ -62,10 +62,10 @@ ActorOwn &ActorOwn::operator=(ActorOwn &&o } template -ActorOwn::ActorOwn(ActorOwn &&other) : id_(other.release()) { +ActorOwn::ActorOwn(ActorOwn &&other) noexcept : id_(other.release()) { } template -ActorOwn &ActorOwn::operator=(ActorOwn &&other) { +ActorOwn &ActorOwn::operator=(ActorOwn &&other) noexcept { reset(other.release()); return *this; } @@ -127,10 +127,10 @@ ActorShared &ActorShared::operator=(ActorShared -ActorShared::ActorShared(ActorShared &&other) : id_(other.release()), token_(other.token_) { +ActorShared::ActorShared(ActorShared &&other) noexcept : id_(other.release()), token_(other.token_) { } template -ActorShared &ActorShared::operator=(ActorShared &&other) { +ActorShared &ActorShared::operator=(ActorShared &&other) noexcept { reset(other.release()); token_ = other.token_; return *this; diff --git a/tdactor/td/actor/impl/Event.h b/tdactor/td/actor/impl/Event.h index 30d55d6f7..c61598c58 100644 --- a/tdactor/td/actor/impl/Event.h +++ b/tdactor/td/actor/impl/Event.h @@ -166,10 +166,10 @@ class Event { } Event(const Event &other) = delete; Event &operator=(const Event &) = delete; - Event(Event &&other) : type(other.type), link_token(other.link_token), data(other.data) { + Event(Event &&other) noexcept : type(other.type), link_token(other.link_token), data(other.data) { other.type = Type::NoType; } - Event &operator=(Event &&other) { + Event &operator=(Event &&other) noexcept { destroy(); type = other.type; link_token = other.link_token; diff --git a/tdactor/td/actor/impl/EventFull-decl.h b/tdactor/td/actor/impl/EventFull-decl.h index f270ee857..a3d41c3a0 100644 --- a/tdactor/td/actor/impl/EventFull-decl.h +++ b/tdactor/td/actor/impl/EventFull-decl.h @@ -45,7 +45,7 @@ class EventFull { data_.link_token = actor_ref.token(); } template - EventFull(ActorId actor_id, Event &&data) : actor_id_(actor_id), data_(std::move(data)) { + EventFull(ActorId actor_id, Event &&data) : actor_id_(std::move(actor_id)), data_(std::move(data)) { } ActorId<> actor_id_; diff --git a/tdactor/td/actor/impl/Scheduler-decl.h b/tdactor/td/actor/impl/Scheduler-decl.h index 0e3fa3b03..daa988580 100644 --- a/tdactor/td/actor/impl/Scheduler-decl.h +++ b/tdactor/td/actor/impl/Scheduler-decl.h @@ -107,9 +107,6 @@ class Scheduler { template void send(ActorRef actor_ref, Event &&event); - void hack(const ActorId<> &actor_id, Event &&event) { - actor_id.get_actor_unsafe()->raw_event(event.data); - } void before_tail_send(const ActorId<> &actor_id); static void subscribe(PollableFd fd, PollFlags flags = PollFlags::ReadWrite()); @@ -125,7 +122,6 @@ class Scheduler { void start_migrate_actor(Actor *actor, int32 dest_sched_id); void finish_migrate_actor(Actor *actor); - bool has_actor_timeout(const Actor *actor) const; double get_actor_timeout(const Actor *actor) const; void set_actor_timeout_in(Actor *actor, double timeout); void set_actor_timeout_at(Actor *actor, double timeout_at); @@ -176,7 +172,6 @@ class Scheduler { void do_migrate_actor(ActorInfo *actor_info, int32 dest_sched_id); void start_migrate_actor(ActorInfo *actor_info, int32 dest_sched_id); - bool has_actor_timeout(const ActorInfo *actor_info) const; double get_actor_timeout(const ActorInfo *actor_info) const; void set_actor_timeout_in(ActorInfo *actor_info, double timeout); void set_actor_timeout_at(ActorInfo *actor_info, double timeout_at); diff --git a/tdactor/td/actor/impl/Scheduler.cpp b/tdactor/td/actor/impl/Scheduler.cpp index 4e32cb33a..74013ab6c 100644 --- a/tdactor/td/actor/impl/Scheduler.cpp +++ b/tdactor/td/actor/impl/Scheduler.cpp @@ -435,7 +435,7 @@ void Scheduler::set_actor_timeout_at(ActorInfo *actor_info, double timeout_at) { void Scheduler::run_poll(Timestamp timeout) { // we can't wait for less than 1ms - int timeout_ms = static_cast(clamp(timeout.in(), 0.0, 1000000.0) * 1000 + 1); + auto timeout_ms = static_cast(clamp(timeout.in(), 0.0, 1000000.0) * 1000 + 1); #if TD_PORT_WINDOWS CHECK(inbound_queue_); inbound_queue_->reader_get_event_fd().wait(timeout_ms); diff --git a/tdactor/td/actor/impl/Scheduler.h b/tdactor/td/actor/impl/Scheduler.h index 2356f6d1c..47780e760 100644 --- a/tdactor/td/actor/impl/Scheduler.h +++ b/tdactor/td/actor/impl/Scheduler.h @@ -299,9 +299,6 @@ inline void Scheduler::finish_migrate_actor(Actor *actor) { register_migrated_actor(actor->get_info()); } -inline bool Scheduler::has_actor_timeout(const Actor *actor) const { - return has_actor_timeout(actor->get_info()); -} inline double Scheduler::get_actor_timeout(const Actor *actor) const { return get_actor_timeout(actor->get_info()); } @@ -315,11 +312,6 @@ inline void Scheduler::cancel_actor_timeout(Actor *actor) { cancel_actor_timeout(actor->get_info()); } -inline bool Scheduler::has_actor_timeout(const ActorInfo *actor_info) const { - const HeapNode *heap_node = actor_info->get_heap_node(); - return heap_node->in_heap(); -} - inline void Scheduler::cancel_actor_timeout(ActorInfo *actor_info) { HeapNode *heap_node = actor_info->get_heap_node(); if (heap_node->in_heap()) { diff --git a/tdactor/test/actors_simple.cpp b/tdactor/test/actors_simple.cpp index 0a20369f0..96c00186f 100644 --- a/tdactor/test/actors_simple.cpp +++ b/tdactor/test/actors_simple.cpp @@ -71,14 +71,14 @@ class X { X(const X &) { sb << "[cnstr_copy]"; } - X(X &&) { + X(X &&) noexcept { sb << "[cnstr_move]"; } X &operator=(const X &) { sb << "[set_copy]"; return *this; } - X &operator=(X &&) { + X &operator=(X &&) noexcept { sb << "[set_move]"; return *this; } diff --git a/tddb/td/db/SqliteKeyValue.h b/tddb/td/db/SqliteKeyValue.h index b44537d48..1d920aaa0 100644 --- a/tddb/td/db/SqliteKeyValue.h +++ b/tddb/td/db/SqliteKeyValue.h @@ -35,10 +35,6 @@ class SqliteKeyValue { Status init_with_connection(SqliteDb connection, string table_name) TD_WARN_UNUSED_RESULT; - Result try_regenerate_index() TD_WARN_UNUSED_RESULT { - return false; - } - void close() { *this = SqliteKeyValue(); } @@ -118,7 +114,7 @@ class SqliteKeyValue { SqliteStatement get_by_prefix_stmt_; SqliteStatement get_by_prefix_rare_stmt_; - string next_prefix(Slice prefix); + static string next_prefix(Slice prefix); }; } // namespace td diff --git a/tddb/td/db/SqliteKeyValueAsync.cpp b/tddb/td/db/SqliteKeyValueAsync.cpp index 3f59b2b81..796d02282 100644 --- a/tddb/td/db/SqliteKeyValueAsync.cpp +++ b/tddb/td/db/SqliteKeyValueAsync.cpp @@ -44,6 +44,7 @@ class SqliteKeyValueAsync final : public SqliteKeyValueAsyncInterface { public: explicit Impl(std::shared_ptr kv_safe) : kv_safe_(std::move(kv_safe)) { } + void set(string key, string value, Promise<> promise) { auto it = buffer_.find(key); if (it != buffer_.end()) { @@ -57,6 +58,7 @@ class SqliteKeyValueAsync final : public SqliteKeyValueAsyncInterface { cnt_++; do_flush(false /*force*/); } + void erase(string key, Promise<> promise) { auto it = buffer_.find(key); if (it != buffer_.end()) { @@ -70,6 +72,7 @@ class SqliteKeyValueAsync final : public SqliteKeyValueAsyncInterface { cnt_++; do_flush(false /*force*/); } + void erase_by_prefix(string key_prefix, Promise<> promise) { do_flush(true /*force*/); kv_->erase_by_prefix(key_prefix); diff --git a/tddb/td/db/TQueue.cpp b/tddb/td/db/TQueue.cpp index 70095eb93..52335504a 100644 --- a/tddb/td/db/TQueue.cpp +++ b/tddb/td/db/TQueue.cpp @@ -68,7 +68,7 @@ bool EventId::operator<(const EventId &other) const { return id_ < other.id_; } -StringBuilder &operator<<(StringBuilder &string_builder, const EventId id) { +StringBuilder &operator<<(StringBuilder &string_builder, EventId id) { return string_builder << "EventId{" << id.value() << "}"; } diff --git a/tddb/td/db/TQueue.h b/tddb/td/db/TQueue.h index 6301e20ba..8e84ae9a9 100644 --- a/tddb/td/db/TQueue.h +++ b/tddb/td/db/TQueue.h @@ -117,7 +117,7 @@ class TQueue { virtual void close(Promise<> promise) = 0; }; -StringBuilder &operator<<(StringBuilder &string_builder, const TQueue::EventId id); +StringBuilder &operator<<(StringBuilder &string_builder, TQueue::EventId id); struct BinlogEvent; @@ -131,7 +131,7 @@ class TQueueBinlog final : public TQueue::StorageCallback { void set_binlog(std::shared_ptr binlog) { binlog_ = std::move(binlog); } - virtual void close(Promise<> promise) final; + void close(Promise<> promise) final; private: std::shared_ptr binlog_; @@ -143,7 +143,7 @@ class TQueueMemoryStorage final : public TQueue::StorageCallback { uint64 push(QueueId queue_id, const RawEvent &event) final; void pop(uint64 log_event_id) final; void replay(TQueue &q) const; - virtual void close(Promise<> promise) final; + void close(Promise<> promise) final; private: uint64 next_log_event_id_{1}; diff --git a/tddb/td/db/binlog/Binlog.cpp b/tddb/td/db/binlog/Binlog.cpp index fb2e4bcab..873cfd6c8 100644 --- a/tddb/td/db/binlog/Binlog.cpp +++ b/tddb/td/db/binlog/Binlog.cpp @@ -54,7 +54,7 @@ struct AesCtrEncryptionEvent { BufferSlice iv_; BufferSlice key_hash_; - BufferSlice generate_key(const DbKey &db_key) { + BufferSlice generate_key(const DbKey &db_key) const { CHECK(!db_key.is_empty()); BufferSlice key(key_size()); size_t iteration_count = kdf_iteration_count(); @@ -64,7 +64,8 @@ struct AesCtrEncryptionEvent { pbkdf2_sha256(db_key.data(), key_salt_.as_slice(), narrow_cast(iteration_count), key.as_slice()); return key; } - BufferSlice generate_hash(Slice key) { + + static BufferSlice generate_hash(Slice key) { BufferSlice hash(hash_size()); hmac_sha256(key, "cucumbers everywhere", hash.as_slice()); return hash; @@ -354,11 +355,13 @@ void Binlog::do_event(BinlogEvent &&event) { key = encryption_event.generate_key(db_key_); } - if (encryption_event.generate_hash(key.as_slice()).as_slice() != encryption_event.key_hash_.as_slice()) { + if (detail::AesCtrEncryptionEvent::generate_hash(key.as_slice()).as_slice() != + encryption_event.key_hash_.as_slice()) { CHECK(state_ == State::Load); if (!old_db_key_.is_empty()) { key = encryption_event.generate_key(old_db_key_); - if (encryption_event.generate_hash(key.as_slice()).as_slice() != encryption_event.key_hash_.as_slice()) { + if (detail::AesCtrEncryptionEvent::generate_hash(key.as_slice()).as_slice() != + encryption_event.key_hash_.as_slice()) { info_.wrong_password = true; } } else { @@ -610,7 +613,7 @@ void Binlog::reset_encryption() { key = event.generate_key(db_key_); } - event.key_hash_ = event.generate_hash(key.as_slice()); + event.key_hash_ = EncryptionEvent::generate_hash(key.as_slice()); do_event(BinlogEvent( BinlogEvent::create_raw(0, BinlogEvent::ServiceTypes::AesCtrEncryption, 0, create_default_storer(event)), @@ -677,7 +680,7 @@ void Binlog::do_reindex() { << detail::file_size(new_path) << ' ' << fd_events_ << ' ' << path_; } - double ratio = static_cast(start_size) / static_cast(finish_size + 1); + auto ratio = static_cast(start_size) / static_cast(finish_size + 1); [&](Slice msg) { if (start_size > (10 << 20) || finish_time - start_time > 1) { @@ -722,7 +725,7 @@ string Binlog::debug_get_binlog_data(int64 begin_offset, int64 end_offset) { SCOPE_EXIT { fd_.lock(FileFd::LockFlags::Write, path_, 1).ensure(); }; - size_t expected_data_length = narrow_cast(end_offset - begin_offset); + auto expected_data_length = narrow_cast(end_offset - begin_offset); string data(expected_data_length, '\0'); auto r_data_size = fd.pread(data, begin_offset); if (r_data_size.is_error()) { diff --git a/tddb/td/db/binlog/Binlog.h b/tddb/td/db/binlog/Binlog.h index d9ebe1038..1cc50c13e 100644 --- a/tddb/td/db/binlog/Binlog.h +++ b/tddb/td/db/binlog/Binlog.h @@ -154,7 +154,7 @@ class Binlog { bool need_sync_{false}; enum class State { Empty, Load, Reindex, Run } state_{State::Empty}; - Result open_binlog(const string &path, int32 flags); + static Result open_binlog(const string &path, int32 flags); size_t flush_events_buffer(bool force); void do_add_event(BinlogEvent &&event); void do_event(BinlogEvent &&event); diff --git a/tddb/td/db/binlog/BinlogInterface.h b/tddb/td/db/binlog/BinlogInterface.h index 21fe53451..20d156661 100644 --- a/tddb/td/db/binlog/BinlogInterface.h +++ b/tddb/td/db/binlog/BinlogInterface.h @@ -66,7 +66,7 @@ class BinlogInterface { virtual void force_sync(Promise<> promise) = 0; virtual void force_flush() = 0; - virtual void change_key(DbKey db_key, Promise<> promise = Promise<>()) = 0; + virtual void change_key(DbKey db_key, Promise<> promise) = 0; virtual uint64 next_id() = 0; virtual uint64 next_id(int32 shift) = 0; diff --git a/tdnet/td/net/GetHostByNameActor.cpp b/tdnet/td/net/GetHostByNameActor.cpp index 227780287..c966103c9 100644 --- a/tdnet/td/net/GetHostByNameActor.cpp +++ b/tdnet/td/net/GetHostByNameActor.cpp @@ -62,7 +62,7 @@ class GoogleDnsResolver final : public Actor { } TRY_RESULT(answer, get_json_object_field(json_value.get_object(), "Answer", JsonValue::Type::Array, false)); auto &array = answer.get_array(); - if (array.size() == 0) { + if (array.empty()) { return Status::Error("Failed to parse DNS result: Answer is an empty array"); } if (array[0].type() != JsonValue::Type::Object) { diff --git a/tdnet/td/net/HttpChunkedByteFlow.cpp b/tdnet/td/net/HttpChunkedByteFlow.cpp index c56fb2d87..7123c1727 100644 --- a/tdnet/td/net/HttpChunkedByteFlow.cpp +++ b/tdnet/td/net/HttpChunkedByteFlow.cpp @@ -62,7 +62,7 @@ bool HttpChunkedByteFlow::loop() { if (len_ == 0) { if (input_->size() < 2) { - need_size = 2; + set_need_size(2); break; } input_->advance(2); diff --git a/tdnet/td/net/HttpConnectionBase.cpp b/tdnet/td/net/HttpConnectionBase.cpp index c12782b2d..ff61ee9ab 100644 --- a/tdnet/td/net/HttpConnectionBase.cpp +++ b/tdnet/td/net/HttpConnectionBase.cpp @@ -184,7 +184,7 @@ void HttpConnectionBase::loop() { } if (state_ == State::Close) { LOG_IF(INFO, fd_.need_flush_write()) << "Close nonempty connection"; - LOG_IF(INFO, want_read && (fd_.input_buffer().size() > 0 || current_query_->type_ != HttpQuery::Type::Empty)) + LOG_IF(INFO, want_read && (!fd_.input_buffer().empty() || current_query_->type_ != HttpQuery::Type::Empty)) << "Close connection while reading request/response"; return stop(); } diff --git a/tdnet/td/net/HttpReader.cpp b/tdnet/td/net/HttpReader.cpp index 2d2478b27..59d770068 100644 --- a/tdnet/td/net/HttpReader.cpp +++ b/tdnet/td/net/HttpReader.cpp @@ -19,6 +19,7 @@ #include "td/utils/port/path.h" #include "td/utils/SliceBuilder.h" +#include #include namespace td { @@ -114,14 +115,14 @@ Result HttpReader::read_next(HttpQuery *query, bool can_be_slow) { return Status::Error(400, "Bad Request: boundary not found"); } p += 8; - ptrdiff_t offset = p - content_type_lowercased_.c_str(); + std::ptrdiff_t offset = p - content_type_lowercased_.c_str(); p = static_cast( std::memchr(content_type_.begin() + offset, '=', content_type_.size() - offset)); if (p == nullptr) { return Status::Error(400, "Bad Request: boundary value not found"); } p++; - const char *end_p = static_cast(std::memchr(p, ';', content_type_.end() - p)); + auto end_p = static_cast(std::memchr(p, ';', content_type_.end() - p)); if (end_p == nullptr) { end_p = content_type_.end(); } diff --git a/tdnet/td/net/SslStream.cpp b/tdnet/td/net/SslStream.cpp index 84d9e5573..a392afbe1 100644 --- a/tdnet/td/net/SslStream.cpp +++ b/tdnet/td/net/SslStream.cpp @@ -96,7 +96,6 @@ long strm_ctrl(BIO *b, int cmd, long num, void *ptr) { case BIO_CTRL_FLUSH: return 1; case BIO_CTRL_PUSH: - return 0; case BIO_CTRL_POP: return 0; default: @@ -487,7 +486,7 @@ int strm_read(BIO *b, char *buf, int len) { CHECK(stream != nullptr); BIO_clear_retry_flags(b); CHECK(buf != nullptr); - int res = narrow_cast(stream->flow_read(MutableSlice(buf, len))); + auto res = narrow_cast(stream->flow_read(MutableSlice(buf, len))); if (res == 0) { BIO_set_retry_read(b); return -1; @@ -506,8 +505,8 @@ int strm_write(BIO *b, const char *buf, int len) { } // namespace detail SslStream::SslStream() = default; -SslStream::SslStream(SslStream &&) = default; -SslStream &SslStream::operator=(SslStream &&) = default; +SslStream::SslStream(SslStream &&) noexcept = default; +SslStream &SslStream::operator=(SslStream &&) noexcept = default; SslStream::~SslStream() = default; Result SslStream::create(CSlice host, CSlice cert_file, VerifyPeer verify_peer, diff --git a/tdnet/td/net/SslStream.h b/tdnet/td/net/SslStream.h index 6eac2c6d2..5a1a40671 100644 --- a/tdnet/td/net/SslStream.h +++ b/tdnet/td/net/SslStream.h @@ -19,14 +19,14 @@ class SslStreamImpl; class SslStream { public: SslStream(); - SslStream(SslStream &&); - SslStream &operator=(SslStream &&); + SslStream(SslStream &&) noexcept; + SslStream &operator=(SslStream &&) noexcept; ~SslStream(); enum class VerifyPeer { On, Off }; static Result create(CSlice host, CSlice cert_file = CSlice(), VerifyPeer verify_peer = VerifyPeer::On, - bool check_ip_address_as_host = false); + bool use_ip_address_as_host = false); ByteFlowInterface &read_byte_flow(); ByteFlowInterface &write_byte_flow(); diff --git a/tdtl/td/tl/tl_config.cpp b/tdtl/td/tl/tl_config.cpp index c42affd0a..8d2f442c2 100644 --- a/tdtl/td/tl/tl_config.cpp +++ b/tdtl/td/tl/tl_config.cpp @@ -40,7 +40,7 @@ void tl_config::add_type(tl_type *type) { } tl_type *tl_config::get_type(std::int32_t type_id) const { - auto it = id_to_type.find(type_id); + std::map::const_iterator it = id_to_type.find(type_id); assert(it != id_to_type.end()); return it->second; } diff --git a/tdtl/td/tl/tl_generate.cpp b/tdtl/td/tl/tl_generate.cpp index 116cc1073..1747bc5f0 100644 --- a/tdtl/td/tl/tl_generate.cpp +++ b/tdtl/td/tl/tl_generate.cpp @@ -857,7 +857,7 @@ bool write_tl_to_file(const tl_config &config, const std::string &file_name, con tl_string_outputer out; write_tl(config, out, w); - auto old_file_contents = get_file_contents(file_name, "rb"); + std::string old_file_contents = get_file_contents(file_name, "rb"); if (!w.is_documentation_generated()) { old_file_contents = remove_documentation(old_file_contents); } diff --git a/tdtl/td/tl/tl_generate.h b/tdtl/td/tl/tl_generate.h index d33db4077..57cfaa3fe 100644 --- a/tdtl/td/tl/tl_generate.h +++ b/tdtl/td/tl/tl_generate.h @@ -18,6 +18,7 @@ namespace tl { void write_tl(const tl_config &config, tl_outputer &out, const TL_writer &w); tl_config read_tl_config_from_file(const std::string &file_name); + bool write_tl_to_file(const tl_config &config, const std::string &file_name, const TL_writer &w); } // namespace tl diff --git a/tdtl/td/tl/tl_simple.h b/tdtl/td/tl/tl_simple.h index 05024aeb0..67ad2a1aa 100644 --- a/tdtl/td/tl/tl_simple.h +++ b/tdtl/td/tl/tl_simple.h @@ -22,19 +22,19 @@ namespace td { namespace tl { namespace simple { -std::string gen_cpp_name(std::string name) { +inline std::string gen_cpp_name(std::string name) { for (std::size_t i = 0; i < name.size(); i++) { if ((name[i] < '0' || '9' < name[i]) && (name[i] < 'a' || 'z' < name[i]) && (name[i] < 'A' || 'Z' < name[i])) { name[i] = '_'; } } - assert(name.size() > 0); + assert(!name.empty()); assert(name[name.size() - 1] != '_'); return name; } -std::string gen_cpp_field_name(std::string name) { - return gen_cpp_name(name) + "_"; +inline std::string gen_cpp_field_name(std::string name) { + return gen_cpp_name(name) + '_'; } struct CustomType; diff --git a/tdutils/generate/generate_mime_types_gperf.cpp b/tdutils/generate/generate_mime_types_gperf.cpp index 4a424814e..6bb64903b 100644 --- a/tdutils/generate/generate_mime_types_gperf.cpp +++ b/tdutils/generate/generate_mime_types_gperf.cpp @@ -116,7 +116,7 @@ int main(int argc, char *argv[]) { std::vector extensions; while (!extensions_string.empty()) { - extensions.push_back(""); + extensions.emplace_back(); std::tie(extensions.back(), extensions_string) = split(extensions_string); } assert(!extensions.empty()); diff --git a/tdutils/td/utils/BigNum.cpp b/tdutils/td/utils/BigNum.cpp index 4e2e2bf8c..adf70c53c 100644 --- a/tdutils/td/utils/BigNum.cpp +++ b/tdutils/td/utils/BigNum.cpp @@ -40,9 +40,8 @@ class BigNumContext::Impl { BigNumContext::BigNumContext() : impl_(make_unique()) { } -BigNumContext::BigNumContext(BigNumContext &&other) = default; -BigNumContext &BigNumContext::operator=(BigNumContext &&other) = default; - +BigNumContext::BigNumContext(BigNumContext &&other) noexcept = default; +BigNumContext &BigNumContext::operator=(BigNumContext &&other) noexcept = default; BigNumContext::~BigNumContext() = default; class BigNum::Impl { @@ -71,6 +70,9 @@ BigNum::BigNum(const BigNum &other) : BigNum() { } BigNum &BigNum::operator=(const BigNum &other) { + if (this == &other) { + return *this; + } CHECK(impl_ != nullptr); CHECK(other.impl_ != nullptr); BIGNUM *result = BN_copy(impl_->big_num, other.impl_->big_num); @@ -78,10 +80,8 @@ BigNum &BigNum::operator=(const BigNum &other) { return *this; } -BigNum::BigNum(BigNum &&other) = default; - -BigNum &BigNum::operator=(BigNum &&other) = default; - +BigNum::BigNum(BigNum &&other) noexcept = default; +BigNum &BigNum::operator=(BigNum &&other) noexcept = default; BigNum::~BigNum() = default; BigNum BigNum::from_binary(Slice str) { diff --git a/tdutils/td/utils/BigNum.h b/tdutils/td/utils/BigNum.h index 63a4d09bc..1e63efb88 100644 --- a/tdutils/td/utils/BigNum.h +++ b/tdutils/td/utils/BigNum.h @@ -21,8 +21,8 @@ class BigNumContext { BigNumContext(); BigNumContext(const BigNumContext &other) = delete; BigNumContext &operator=(const BigNumContext &other) = delete; - BigNumContext(BigNumContext &&other); - BigNumContext &operator=(BigNumContext &&other); + BigNumContext(BigNumContext &&other) noexcept; + BigNumContext &operator=(BigNumContext &&other) noexcept; ~BigNumContext(); private: @@ -37,8 +37,8 @@ class BigNum { BigNum(); BigNum(const BigNum &other); BigNum &operator=(const BigNum &other); - BigNum(BigNum &&other); - BigNum &operator=(BigNum &&other); + BigNum(BigNum &&other) noexcept; + BigNum &operator=(BigNum &&other) noexcept; ~BigNum(); static BigNum from_binary(Slice str); diff --git a/tdutils/td/utils/BufferedFd.h b/tdutils/td/utils/BufferedFd.h index 12fdbe1d1..ab4720f12 100644 --- a/tdutils/td/utils/BufferedFd.h +++ b/tdutils/td/utils/BufferedFd.h @@ -66,8 +66,8 @@ class BufferedFd final : public BufferedFdBase { public: BufferedFd(); explicit BufferedFd(FdT &&fd_); - BufferedFd(BufferedFd &&); - BufferedFd &operator=(BufferedFd &&); + BufferedFd(BufferedFd &&) noexcept; + BufferedFd &operator=(BufferedFd &&) noexcept; BufferedFd(const BufferedFd &) = delete; BufferedFd &operator=(const BufferedFd &) = delete; ~BufferedFd(); @@ -163,12 +163,12 @@ BufferedFd::BufferedFd(FdT &&fd_) : Parent(std::move(fd_)) { } template -BufferedFd::BufferedFd(BufferedFd &&from) { +BufferedFd::BufferedFd(BufferedFd &&from) noexcept { *this = std::move(from); } template -BufferedFd &BufferedFd::operator=(BufferedFd &&from) { +BufferedFd &BufferedFd::operator=(BufferedFd &&from) noexcept { FdT::operator=(std::move(static_cast(from))); input_reader_ = std::move(from.input_reader_); input_writer_ = std::move(from.input_writer_); diff --git a/tdutils/td/utils/BufferedUdp.h b/tdutils/td/utils/BufferedUdp.h index a4b13446e..6e70b6832 100644 --- a/tdutils/td/utils/BufferedUdp.h +++ b/tdutils/td/utils/BufferedUdp.h @@ -79,8 +79,8 @@ class UdpReader { } } Status read_once(UdpSocketFd &fd, VectorQueue &queue) TD_WARN_UNUSED_RESULT { - for (size_t i = 0; i < messages_.size(); i++) { - CHECK(messages_[i].data.size() == 2048); + for (auto &message : messages_) { + CHECK(message.data.size() == 2048); } size_t cnt = 0; auto status = fd.receive_messages(messages_, cnt); @@ -94,6 +94,7 @@ class UdpReader { } if (status.is_error() && !UdpSocketFd::is_critical_read_error(status)) { queue.push(UdpMessage{{}, {}, std::move(status)}); + status = Status::OK(); } return status; } diff --git a/tdutils/td/utils/ByteFlow.h b/tdutils/td/utils/ByteFlow.h index ec67f13d7..dbb5c49bd 100644 --- a/tdutils/td/utils/ByteFlow.h +++ b/tdutils/td/utils/ByteFlow.h @@ -225,11 +225,11 @@ class ByteFlowSource final : public ByteFlowInterface { ByteFlowSource() = default; explicit ByteFlowSource(ChainBufferReader *buffer) : buffer_(buffer) { } - ByteFlowSource(ByteFlowSource &&other) : buffer_(other.buffer_), parent_(other.parent_) { + ByteFlowSource(ByteFlowSource &&other) noexcept : buffer_(other.buffer_), parent_(other.parent_) { other.buffer_ = nullptr; other.parent_ = nullptr; } - ByteFlowSource &operator=(ByteFlowSource &&other) { + ByteFlowSource &operator=(ByteFlowSource &&other) noexcept { buffer_ = other.buffer_; parent_ = other.parent_; other.buffer_ = nullptr; diff --git a/tdutils/td/utils/CancellationToken.h b/tdutils/td/utils/CancellationToken.h index 1dbd013da..f47a2fc19 100644 --- a/tdutils/td/utils/CancellationToken.h +++ b/tdutils/td/utils/CancellationToken.h @@ -37,9 +37,9 @@ class CancellationToken { class CancellationTokenSource { public: CancellationTokenSource() = default; - CancellationTokenSource(CancellationTokenSource &&other) : token_(std::move(other.token_)) { + CancellationTokenSource(CancellationTokenSource &&other) noexcept : token_(std::move(other.token_)) { } - CancellationTokenSource &operator=(CancellationTokenSource &&other) { + CancellationTokenSource &operator=(CancellationTokenSource &&other) noexcept { cancel(); token_ = std::move(other.token_); return *this; diff --git a/tdutils/td/utils/ConcurrentHashTable.h b/tdutils/td/utils/ConcurrentHashTable.h index fae7a876c..3ecb0ffda 100644 --- a/tdutils/td/utils/ConcurrentHashTable.h +++ b/tdutils/td/utils/ConcurrentHashTable.h @@ -57,8 +57,8 @@ class AtomicHashArray { template bool with_value(KeyT key, bool should_create, F &&f) { DCHECK(key != empty_key()); - size_t pos = static_cast(key) % nodes_.size(); - size_t n = td::min(td::max(static_cast(300), nodes_.size() / 16 + 2), nodes_.size()); + auto pos = static_cast(key) % nodes_.size(); + auto n = td::min(td::max(static_cast(300), nodes_.size() / 16 + 2), nodes_.size()); for (size_t i = 0; i < n; i++) { pos++; diff --git a/tdutils/td/utils/Container.h b/tdutils/td/utils/Container.h index 407145498..d5b4e4281 100644 --- a/tdutils/td/utils/Container.h +++ b/tdutils/td/utils/Container.h @@ -106,8 +106,8 @@ class Container { } int32 decode_id(Id id) const { - int32 slot_id = static_cast(id >> 32); - uint32 generation = static_cast(id); + auto slot_id = static_cast(id >> 32); + auto generation = static_cast(id); if (slot_id < 0 || slot_id >= static_cast(slots_.size())) { return -1; } diff --git a/tdutils/td/utils/Enumerator.h b/tdutils/td/utils/Enumerator.h index 1fb054f51..6b6d31fea 100644 --- a/tdutils/td/utils/Enumerator.h +++ b/tdutils/td/utils/Enumerator.h @@ -11,7 +11,6 @@ #include #include #include -#include namespace td { @@ -20,84 +19,27 @@ class Enumerator { public: using Key = int32; - std::map get_map() const { - return map_; - } - - void clear() { - map_.clear(); - arr_.clear(); - next_id = 1; - } - - void lock_access_mutex() const { - access_mutex.lock(); - } - - void unlock_access_mutex() const { - access_mutex.unlock(); - } - - /** - * - * @return true if the key is new - */ - Key next() { - auto id = next_id++; - - return id; - } - - void erase_unsafe(Key key_y) { - auto find_val = arr_.find(key_y); - if (find_val != arr_.end()) { - // Erase this - map_.erase(find_val->second); - // TODO: Not sure about erasing this, instead - arr_.erase(key_y); - } - } - Key add(ValueT v) { - std::lock_guard writerLock(access_mutex); - - return add_internal(v); - } - - Key add_internal(ValueT v) { - auto id = next(); + CHECK(arr_.size() < static_cast(std::numeric_limits::max() - 1)); + auto next_id = static_cast(arr_.size() + 1); bool was_inserted; decltype(map_.begin()) it; - std::tie(it, was_inserted) = map_.emplace(std::move(v), id); + std::tie(it, was_inserted) = map_.emplace(std::move(v), next_id); if (was_inserted) { - arr_[id] = it->first; + arr_.push_back(&it->first); } return it->second; } const ValueT &get(Key key) const { - std::shared_lock readerLock(access_mutex); - - return get_internal(key); - } - - const ValueT &get_internal(Key key) const { - return arr_.at(key); - } - - std::pair add_and_get(ValueT v) { - std::lock_guard writerLock(access_mutex); - - auto remote_key = add_internal(v); - auto &stored_info = get_internal(remote_key); - return std::make_pair(remote_key, stored_info); + auto pos = static_cast(key - 1); + CHECK(pos < arr_.size()); + return *arr_[pos]; } private: - mutable int32 next_id = 1; std::map map_; - std::unordered_map arr_; - mutable std::shared_timed_mutex access_mutex; + std::vector arr_; }; } // namespace td diff --git a/tdutils/td/utils/EpochBasedMemoryReclamation.h b/tdutils/td/utils/EpochBasedMemoryReclamation.h index 4ca02fe20..7639d80db 100644 --- a/tdutils/td/utils/EpochBasedMemoryReclamation.h +++ b/tdutils/td/utils/EpochBasedMemoryReclamation.h @@ -37,7 +37,7 @@ class EpochBasedMemoryReclamation { if (ebmr_) { retire_sync(); unlock(); - ebmr_.release(); + (void)ebmr_.release(); } } void lock() { diff --git a/tdutils/td/utils/Gzip.cpp b/tdutils/td/utils/Gzip.cpp index 26466f294..a2fc6037d 100644 --- a/tdutils/td/utils/Gzip.cpp +++ b/tdutils/td/utils/Gzip.cpp @@ -130,11 +130,11 @@ void Gzip::clear() { Gzip::Gzip() : impl_(make_unique()) { } -Gzip::Gzip(Gzip &&other) : Gzip() { +Gzip::Gzip(Gzip &&other) noexcept : Gzip() { swap(other); } -Gzip &Gzip::operator=(Gzip &&other) { +Gzip &Gzip::operator=(Gzip &&other) noexcept { CHECK(this != &other); clear(); swap(other); @@ -189,7 +189,7 @@ BufferSlice gzencode(Slice s, double max_compression_ratio) { gzip.init_encode().ensure(); gzip.set_input(s); gzip.close_input(); - size_t max_size = static_cast(static_cast(s.size()) * max_compression_ratio); + auto max_size = static_cast(static_cast(s.size()) * max_compression_ratio); BufferWriter message{max_size}; gzip.set_output(message.prepare_append()); auto r_state = gzip.run(); diff --git a/tdutils/td/utils/Gzip.h b/tdutils/td/utils/Gzip.h index 001401dae..65fed30f9 100644 --- a/tdutils/td/utils/Gzip.h +++ b/tdutils/td/utils/Gzip.h @@ -20,8 +20,8 @@ class Gzip { Gzip(); Gzip(const Gzip &) = delete; Gzip &operator=(const Gzip &) = delete; - Gzip(Gzip &&other); - Gzip &operator=(Gzip &&other); + Gzip(Gzip &&other) noexcept; + Gzip &operator=(Gzip &&other) noexcept; ~Gzip(); enum class Mode { Empty, Encode, Decode }; diff --git a/tdutils/td/utils/Heap.h b/tdutils/td/utils/Heap.h index c9bbbd901..68f557705 100644 --- a/tdutils/td/utils/Heap.h +++ b/tdutils/td/utils/Heap.h @@ -38,7 +38,7 @@ class KHeap { } KeyT get_key(const HeapNode *node) const { - size_t pos = static_cast(node->pos_); + auto pos = static_cast(node->pos_); CHECK(pos < array_.size()); return array_[pos].key_; } @@ -62,7 +62,7 @@ class KHeap { } void fix(KeyT key, HeapNode *node) { - size_t pos = static_cast(node->pos_); + auto pos = static_cast(node->pos_); CHECK(pos < array_.size()); KeyT old_key = array_[pos].key_; array_[pos].key_ = key; @@ -74,7 +74,7 @@ class KHeap { } void erase(HeapNode *node) { - size_t pos = static_cast(node->pos_); + auto pos = static_cast(node->pos_); node->remove(); CHECK(pos < array_.size()); erase(pos); diff --git a/tdutils/td/utils/Hints.cpp b/tdutils/td/utils/Hints.cpp index a583fb483..e5c03954e 100644 --- a/tdutils/td/utils/Hints.cpp +++ b/tdutils/td/utils/Hints.cpp @@ -150,7 +150,7 @@ void Hints::add_search_results(vector &results, const string &word, vector Hints::search_word(const string &word) const { vector results; add_search_results(results, word, translit_word_to_keys_); - for (auto w : get_word_transliterations(word, true)) { + for (const auto &w : get_word_transliterations(word, true)) { add_search_results(results, w, word_to_keys_); } diff --git a/tdutils/td/utils/HttpUrl.cpp b/tdutils/td/utils/HttpUrl.cpp index 0b8f4f21b..f30497257 100644 --- a/tdutils/td/utils/HttpUrl.cpp +++ b/tdutils/td/utils/HttpUrl.cpp @@ -168,7 +168,7 @@ Result parse_url(Slice url, HttpUrl::Protocol default_protocol) { } // all other symbols aren't allowed - unsigned char uc = static_cast(c); + auto uc = static_cast(c); if (uc >= 128) { // but we allow plain UTF-8 symbols continue; diff --git a/tdutils/td/utils/JsonBuilder.cpp b/tdutils/td/utils/JsonBuilder.cpp index c3634795e..2872b50a1 100644 --- a/tdutils/td/utils/JsonBuilder.cpp +++ b/tdutils/td/utils/JsonBuilder.cpp @@ -96,11 +96,11 @@ StringBuilder &operator<<(StringBuilder &sb, const JsonString &val) { break; } if (128 <= ch) { - int a = s[pos]; + uint32 a = ch; CHECK((a & 0x40) != 0); CHECK(pos + 1 < len); - int b = s[++pos]; + uint32 b = static_cast(s[++pos]); CHECK((b & 0xc0) == 0x80); if ((a & 0x20) == 0) { CHECK((a & 0x1e) > 0); @@ -109,7 +109,7 @@ StringBuilder &operator<<(StringBuilder &sb, const JsonString &val) { } CHECK(pos + 1 < len); - int c = s[++pos]; + uint32 c = static_cast(s[++pos]); CHECK((c & 0xc0) == 0x80); if ((a & 0x10) == 0) { CHECK(((a & 0x0f) | (b & 0x20)) > 0); @@ -118,7 +118,7 @@ StringBuilder &operator<<(StringBuilder &sb, const JsonString &val) { } CHECK(pos + 1 < len); - int d = s[++pos]; + uint32 d = static_cast(s[++pos]); CHECK((d & 0xc0) == 0x80); if ((a & 0x08) == 0) { CHECK(((a & 0x07) | (b & 0x30)) > 0); @@ -394,7 +394,7 @@ Result do_json_decode(Parser &parser, int32 max_depth) { case '{': { parser.skip('{'); parser.skip_whitespaces(); - std::vector > res; + std::vector> res; if (parser.try_skip('}')) { return JsonValue::make_object(std::move(res)); } @@ -408,7 +408,7 @@ Result do_json_decode(Parser &parser, int32 max_depth) { return Status::Error("':' expected"); } TRY_RESULT(value, do_json_decode(parser, max_depth - 1)); - res.emplace_back(std::move(key), std::move(value)); + res.emplace_back(key, std::move(value)); parser.skip_whitespaces(); if (parser.try_skip('}')) { diff --git a/tdutils/td/utils/JsonBuilder.h b/tdutils/td/utils/JsonBuilder.h index e740006dc..23954ad46 100644 --- a/tdutils/td/utils/JsonBuilder.h +++ b/tdutils/td/utils/JsonBuilder.h @@ -95,7 +95,7 @@ class JsonFloat { class JsonOneChar { public: - explicit JsonOneChar(unsigned int c) : c_(c) { + explicit JsonOneChar(uint32 c) : c_(c) { } friend StringBuilder &operator<<(StringBuilder &sb, const JsonOneChar &val) { @@ -105,12 +105,12 @@ class JsonOneChar { } private: - unsigned int c_; + uint32 c_; }; class JsonChar { public: - explicit JsonChar(unsigned int c) : c_(c) { + explicit JsonChar(uint32 c) : c_(c) { } friend StringBuilder &operator<<(StringBuilder &sb, const JsonChar &val) { auto c = val.c_; @@ -129,7 +129,7 @@ class JsonChar { } private: - unsigned int c_; + uint32 c_; }; class JsonRaw { @@ -459,10 +459,10 @@ class JsonValue final : private Jsonable { ~JsonValue() { destroy(); } - JsonValue(JsonValue &&other) : JsonValue() { + JsonValue(JsonValue &&other) noexcept : JsonValue() { init(std::move(other)); } - JsonValue &operator=(JsonValue &&other) { + JsonValue &operator=(JsonValue &&other) noexcept { if (&other == this) { return *this; } diff --git a/tdutils/td/utils/List.h b/tdutils/td/utils/List.h index 86422e751..c6af14dd9 100644 --- a/tdutils/td/utils/List.h +++ b/tdutils/td/utils/List.h @@ -24,7 +24,7 @@ struct ListNode { ListNode(const ListNode &) = delete; ListNode &operator=(const ListNode &) = delete; - ListNode(ListNode &&other) { + ListNode(ListNode &&other) noexcept { if (other.empty()) { clear(); } else { @@ -32,7 +32,7 @@ struct ListNode { } } - ListNode &operator=(ListNode &&other) { + ListNode &operator=(ListNode &&other) noexcept { if (this == &other) { return *this; } diff --git a/tdutils/td/utils/MemoryLog.h b/tdutils/td/utils/MemoryLog.h index a634a0955..4e837b769 100644 --- a/tdutils/td/utils/MemoryLog.h +++ b/tdutils/td/utils/MemoryLog.h @@ -47,8 +47,8 @@ class MemoryLog final : public LogInterface { CHECK(slice_size * 3 < buffer_size); size_t pad_size = ((slice_size + 15) & ~15) - slice_size; constexpr size_t MAGIC_SIZE = 16; - uint32 total_size = static_cast(slice_size + pad_size + MAGIC_SIZE); - uint32 real_pos = pos_.fetch_add(total_size, std::memory_order_relaxed); + auto total_size = static_cast(slice_size + pad_size + MAGIC_SIZE); + auto real_pos = pos_.fetch_add(total_size, std::memory_order_relaxed); CHECK((total_size & 15) == 0); uint32 start_pos = real_pos & (buffer_size - 1); diff --git a/tdutils/td/utils/MovableValue.h b/tdutils/td/utils/MovableValue.h index ceadfff49..70e3fd61f 100644 --- a/tdutils/td/utils/MovableValue.h +++ b/tdutils/td/utils/MovableValue.h @@ -14,10 +14,10 @@ class MovableValue { MovableValue() = default; MovableValue(T val) : val_(val) { } - MovableValue(MovableValue &&other) : val_(other.val_) { + MovableValue(MovableValue &&other) noexcept : val_(other.val_) { other.clear(); } - MovableValue &operator=(MovableValue &&other) { + MovableValue &operator=(MovableValue &&other) noexcept { if (this != &other) { val_ = other.val_; other.clear(); diff --git a/tdutils/td/utils/ObjectPool.h b/tdutils/td/utils/ObjectPool.h index 2399e90f9..05a1f4fa4 100644 --- a/tdutils/td/utils/ObjectPool.h +++ b/tdutils/td/utils/ObjectPool.h @@ -84,11 +84,11 @@ class ObjectPool { OwnerPtr() = default; OwnerPtr(const OwnerPtr &) = delete; OwnerPtr &operator=(const OwnerPtr &) = delete; - OwnerPtr(OwnerPtr &&other) : storage_(other.storage_), parent_(other.parent_) { + OwnerPtr(OwnerPtr &&other) noexcept : storage_(other.storage_), parent_(other.parent_) { other.storage_ = nullptr; other.parent_ = nullptr; } - OwnerPtr &operator=(OwnerPtr &&other) { + OwnerPtr &operator=(OwnerPtr &&other) noexcept { if (this != &other) { storage_ = other.storage_; parent_ = other.parent_; diff --git a/tdutils/td/utils/Parser.h b/tdutils/td/utils/Parser.h index 1a0e65c78..862cc65cc 100644 --- a/tdutils/td/utils/Parser.h +++ b/tdutils/td/utils/Parser.h @@ -23,10 +23,10 @@ class ParserImpl { public: explicit ParserImpl(SliceT data) : ptr_(data.begin()), end_(data.end()), status_() { } - ParserImpl(ParserImpl &&other) : ptr_(other.ptr_), end_(other.end_), status_(std::move(other.status_)) { + ParserImpl(ParserImpl &&other) noexcept : ptr_(other.ptr_), end_(other.end_), status_(std::move(other.status_)) { other.clear(); } - ParserImpl &operator=(ParserImpl &&other) { + ParserImpl &operator=(ParserImpl &&other) noexcept { if (&other == this) { return *this; } diff --git a/tdutils/td/utils/ScopeGuard.h b/tdutils/td/utils/ScopeGuard.h index 59b808940..900906b20 100644 --- a/tdutils/td/utils/ScopeGuard.h +++ b/tdutils/td/utils/ScopeGuard.h @@ -42,11 +42,11 @@ class LambdaGuard final : public Guard { } LambdaGuard &operator=(LambdaGuard &&other) = delete; - void dismiss() { + void dismiss() final { dismissed_ = true; } - ~LambdaGuard() { + ~LambdaGuard() final { if (!dismissed_) { func_(); } diff --git a/tdutils/td/utils/SharedObjectPool.h b/tdutils/td/utils/SharedObjectPool.h index cb8c417a0..8cd377950 100644 --- a/tdutils/td/utils/SharedObjectPool.h +++ b/tdutils/td/utils/SharedObjectPool.h @@ -106,16 +106,19 @@ class SharedPtr { SharedPtr(const SharedPtr &other) : SharedPtr(other.raw_) { } SharedPtr &operator=(const SharedPtr &other) { + if (this == &other) { + return *this; + } if (other.raw_) { other.raw_->inc(); } reset(other.raw_); return *this; } - SharedPtr(SharedPtr &&other) : raw_(other.raw_) { + SharedPtr(SharedPtr &&other) noexcept : raw_(other.raw_) { other.raw_ = nullptr; } - SharedPtr &operator=(SharedPtr &&other) { + SharedPtr &operator=(SharedPtr &&other) noexcept { reset(other.raw_); other.raw_ = nullptr; return *this; diff --git a/tdutils/td/utils/Status.h b/tdutils/td/utils/Status.h index 3f5a55420..64f80d551 100644 --- a/tdutils/td/utils/Status.h +++ b/tdutils/td/utils/Status.h @@ -423,14 +423,14 @@ class Result { } Result(const Result &) = delete; Result &operator=(const Result &) = delete; - Result(Result &&other) : status_(std::move(other.status_)) { + Result(Result &&other) noexcept : status_(std::move(other.status_)) { if (status_.is_ok()) { new (&value_) T(std::move(other.value_)); other.value_.~T(); } other.status_ = Status::Error<-2>(); } - Result &operator=(Result &&other) { + Result &operator=(Result &&other) noexcept { CHECK(this != &other); if (status_.is_ok()) { value_.~T(); diff --git a/tdutils/td/utils/StealingQueue.h b/tdutils/td/utils/StealingQueue.h index 219551b36..4e0aace9e 100644 --- a/tdutils/td/utils/StealingQueue.h +++ b/tdutils/td/utils/StealingQueue.h @@ -77,7 +77,7 @@ class StealingQueue { if (other_tail < other_head) { continue; } - size_t n = narrow_cast(other_tail - other_head); + auto n = narrow_cast(other_tail - other_head); if (n > N) { continue; } diff --git a/tdutils/td/utils/StringBuilder.cpp b/tdutils/td/utils/StringBuilder.cpp index 8454f6887..1ffd33e63 100644 --- a/tdutils/td/utils/StringBuilder.cpp +++ b/tdutils/td/utils/StringBuilder.cpp @@ -191,7 +191,7 @@ StringBuilder &StringBuilder::operator<<(FixedDouble x) { ss->precision(x.precision); *ss << x.d; - int len = narrow_cast(static_cast(ss->tellp())); + auto len = narrow_cast(static_cast(ss->tellp())); auto left = end_ptr_ + RESERVED_SIZE - current_ptr_; if (unlikely(len >= left)) { error_flag_ = true; diff --git a/tdutils/td/utils/TsCerr.h b/tdutils/td/utils/TsCerr.h index 8ef4942e3..06416e49a 100644 --- a/tdutils/td/utils/TsCerr.h +++ b/tdutils/td/utils/TsCerr.h @@ -26,8 +26,8 @@ class TsCerr { private: static std::atomic_flag lock_; - void enterCritical(); - void exitCritical(); + static void enterCritical(); + static void exitCritical(); }; } // namespace td diff --git a/tdutils/td/utils/TsFileLog.cpp b/tdutils/td/utils/TsFileLog.cpp index 51ca4d54e..bdb54e5a1 100644 --- a/tdutils/td/utils/TsFileLog.cpp +++ b/tdutils/td/utils/TsFileLog.cpp @@ -99,7 +99,7 @@ class TsFileLog final : public LogInterface { Result> TsFileLog::create(string path, int64 rotate_threshold, bool redirect_stderr) { auto res = make_unique(); - TRY_STATUS(res->init(path, rotate_threshold, redirect_stderr)); + TRY_STATUS(res->init(std::move(path), rotate_threshold, redirect_stderr)); return std::move(res); } diff --git a/tdutils/td/utils/TsList.h b/tdutils/td/utils/TsList.h index 0f4b8943a..6ed083446 100644 --- a/tdutils/td/utils/TsList.h +++ b/tdutils/td/utils/TsList.h @@ -35,7 +35,7 @@ class TsListNode : protected ListNode { TsListNode(const TsListNode &) = delete; TsListNode &operator=(const TsListNode &) = delete; - TsListNode(TsListNode &&other) { + TsListNode(TsListNode &&other) noexcept { other.validate(); if (other.empty()) { data_ = std::move(other.data_); @@ -48,7 +48,7 @@ class TsListNode : protected ListNode { other.validate(); } - TsListNode &operator=(TsListNode &&other) { + TsListNode &operator=(TsListNode &&other) noexcept { validate(); if (this == &other) { return *this; diff --git a/tdutils/td/utils/Variant.h b/tdutils/td/utils/Variant.h index b964d488a..502c7df03 100644 --- a/tdutils/td/utils/Variant.h +++ b/tdutils/td/utils/Variant.h @@ -115,12 +115,15 @@ class Variant { Variant(const Variant &other) { other.visit([&](auto &&value) { this->init_empty(std::forward(value)); }); } - Variant &operator=(Variant &&other) { + Variant &operator=(Variant &&other) noexcept { clear(); other.visit([&](auto &&value) { this->init_empty(std::forward(value)); }); return *this; } Variant &operator=(const Variant &other) { + if (this == &other) { + return *this; + } clear(); other.visit([&](auto &&value) { this->init_empty(std::forward(value)); }); return *this; diff --git a/tdutils/td/utils/base64.cpp b/tdutils/td/utils/base64.cpp index 92f8e1d13..84a28fde3 100644 --- a/tdutils/td/utils/base64.cpp +++ b/tdutils/td/utils/base64.cpp @@ -185,13 +185,13 @@ static bool is_base64_impl(Slice input) { } if ((input.size() & 3) == 2) { - auto value = table[static_cast(input.back())]; + auto value = table[static_cast(input.back())]; if ((value & 15) != 0) { return false; } } if ((input.size() & 3) == 3) { - auto value = table[static_cast(input.back())]; + auto value = table[static_cast(input.back())]; if ((value & 3) != 0) { return false; } diff --git a/tdutils/td/utils/buffer.h b/tdutils/td/utils/buffer.h index b37c67ca3..c159121f1 100644 --- a/tdutils/td/utils/buffer.h +++ b/tdutils/td/utils/buffer.h @@ -118,10 +118,10 @@ class BufferSlice { } BufferSlice(const BufferSlice &other) = delete; BufferSlice &operator=(const BufferSlice &other) = delete; - BufferSlice(BufferSlice &&other) : BufferSlice(std::move(other.buffer_), other.begin_, other.end_) { + BufferSlice(BufferSlice &&other) noexcept : BufferSlice(std::move(other.buffer_), other.begin_, other.end_) { debug_untrack(); // yes, debug_untrack } - BufferSlice &operator=(BufferSlice &&other) { + BufferSlice &operator=(BufferSlice &&other) noexcept { if (this == &other) { return *this; } diff --git a/tdutils/td/utils/crypto.cpp b/tdutils/td/utils/crypto.cpp index 4671acc00..6355c89ef 100644 --- a/tdutils/td/utils/crypto.cpp +++ b/tdutils/td/utils/crypto.cpp @@ -396,8 +396,8 @@ struct AesState::Impl { }; AesState::AesState() = default; -AesState::AesState(AesState &&from) = default; -AesState &AesState::operator=(AesState &&from) = default; +AesState::AesState(AesState &&from) noexcept = default; +AesState &AesState::operator=(AesState &&from) noexcept = default; AesState::~AesState() = default; void AesState::init(Slice key, bool encrypt) { @@ -466,7 +466,7 @@ class AesIgeStateImpl { } evp_.init_iv(encrypted_iv_.as_slice()); - int inlen = static_cast(AES_BLOCK_SIZE * count); + auto inlen = static_cast(AES_BLOCK_SIZE * count); evp_.encrypt(data_xored[0].raw(), data_xored[0].raw(), inlen); data_xored[0] ^= plaintext_iv_; @@ -515,8 +515,8 @@ class AesIgeStateImpl { }; AesIgeState::AesIgeState() = default; -AesIgeState::AesIgeState(AesIgeState &&from) = default; -AesIgeState &AesIgeState::operator=(AesIgeState &&from) = default; +AesIgeState::AesIgeState(AesIgeState &&from) noexcept = default; +AesIgeState &AesIgeState::operator=(AesIgeState &&from) noexcept = default; AesIgeState::~AesIgeState() = default; void AesIgeState::init(Slice key, Slice iv, bool encrypt) { @@ -580,8 +580,8 @@ AesCbcState::AesCbcState(Slice key256, Slice iv128) : raw_{SecureString(key256), CHECK(raw_.iv.size() == 16); } -AesCbcState::AesCbcState(AesCbcState &&from) = default; -AesCbcState &AesCbcState::operator=(AesCbcState &&from) = default; +AesCbcState::AesCbcState(AesCbcState &&from) noexcept = default; +AesCbcState &AesCbcState::operator=(AesCbcState &&from) noexcept = default; AesCbcState::~AesCbcState() = default; void AesCbcState::encrypt(Slice from, MutableSlice to) { @@ -634,8 +634,8 @@ struct AesCtrState::Impl { }; AesCtrState::AesCtrState() = default; -AesCtrState::AesCtrState(AesCtrState &&from) = default; -AesCtrState &AesCtrState::operator=(AesCtrState &&from) = default; +AesCtrState::AesCtrState(AesCtrState &&from) noexcept = default; +AesCtrState &AesCtrState::operator=(AesCtrState &&from) noexcept = default; AesCtrState::~AesCtrState() = default; void AesCtrState::init(Slice key, Slice iv) { @@ -723,6 +723,12 @@ void sha512(Slice data, MutableSlice output) { #endif } +string sha1(Slice data) { + string result(20, '\0'); + sha1(data, MutableSlice(result).ubegin()); + return result; +} + string sha256(Slice data) { string result(32, '\0'); sha256(data, result); @@ -762,13 +768,13 @@ class Sha256State::Impl { Sha256State::Sha256State() = default; -Sha256State::Sha256State(Sha256State &&other) { +Sha256State::Sha256State(Sha256State &&other) noexcept { impl_ = std::move(other.impl_); is_inited_ = other.is_inited_; other.is_inited_ = false; } -Sha256State &Sha256State::operator=(Sha256State &&other) { +Sha256State &Sha256State::operator=(Sha256State &&other) noexcept { Sha256State copy(std::move(other)); using std::swap; swap(impl_, copy.impl_); @@ -844,7 +850,7 @@ static void pbkdf2_impl(Slice password, Slice salt, int iteration_count, Mutable HMAC_CTX ctx; HMAC_CTX_init(&ctx); unsigned char counter[4] = {0, 0, 0, 1}; - int password_len = narrow_cast(password.size()); + auto password_len = narrow_cast(password.size()); HMAC_Init_ex(&ctx, password.data(), password_len, evp_md, nullptr); HMAC_Update(&ctx, salt.ubegin(), narrow_cast(salt.size())); HMAC_Update(&ctx, counter, 4); diff --git a/tdutils/td/utils/crypto.h b/tdutils/td/utils/crypto.h index b6651df53..071c0fc46 100644 --- a/tdutils/td/utils/crypto.h +++ b/tdutils/td/utils/crypto.h @@ -26,8 +26,8 @@ class AesState { AesState(); AesState(const AesState &from) = delete; AesState &operator=(const AesState &from) = delete; - AesState(AesState &&from); - AesState &operator=(AesState &&from); + AesState(AesState &&from) noexcept; + AesState &operator=(AesState &&from) noexcept; ~AesState(); void init(Slice key, bool encrypt); @@ -51,8 +51,8 @@ class AesIgeState { AesIgeState(); AesIgeState(const AesIgeState &from) = delete; AesIgeState &operator=(const AesIgeState &from) = delete; - AesIgeState(AesIgeState &&from); - AesIgeState &operator=(AesIgeState &&from); + AesIgeState(AesIgeState &&from) noexcept; + AesIgeState &operator=(AesIgeState &&from) noexcept; ~AesIgeState(); void init(Slice key, Slice iv, bool encrypt); @@ -73,8 +73,8 @@ class AesCtrState { AesCtrState(); AesCtrState(const AesCtrState &from) = delete; AesCtrState &operator=(const AesCtrState &from) = delete; - AesCtrState(AesCtrState &&from); - AesCtrState &operator=(AesCtrState &&from); + AesCtrState(AesCtrState &&from) noexcept; + AesCtrState &operator=(AesCtrState &&from) noexcept; ~AesCtrState(); void init(Slice key, Slice iv); @@ -93,8 +93,8 @@ class AesCbcState { AesCbcState(Slice key256, Slice iv128); AesCbcState(const AesCbcState &from) = delete; AesCbcState &operator=(const AesCbcState &from) = delete; - AesCbcState(AesCbcState &&from); - AesCbcState &operator=(AesCbcState &&from); + AesCbcState(AesCbcState &&from) noexcept; + AesCbcState &operator=(AesCbcState &&from) noexcept; ~AesCbcState(); void encrypt(Slice from, MutableSlice to); @@ -122,6 +122,8 @@ void sha256(Slice data, MutableSlice output); void sha512(Slice data, MutableSlice output); +string sha1(Slice data) TD_WARN_UNUSED_RESULT; + string sha256(Slice data) TD_WARN_UNUSED_RESULT; string sha512(Slice data) TD_WARN_UNUSED_RESULT; @@ -131,15 +133,15 @@ class Sha256State { Sha256State(); Sha256State(const Sha256State &other) = delete; Sha256State &operator=(const Sha256State &other) = delete; - Sha256State(Sha256State &&other); - Sha256State &operator=(Sha256State &&other); + Sha256State(Sha256State &&other) noexcept; + Sha256State &operator=(Sha256State &&other) noexcept; ~Sha256State(); void init(); void feed(Slice data); - void extract(MutableSlice dest, bool destroy = false); + void extract(MutableSlice output, bool destroy = false); private: class Impl; diff --git a/tdutils/td/utils/find_boundary.cpp b/tdutils/td/utils/find_boundary.cpp index b71755d70..32fbe6bf0 100644 --- a/tdutils/td/utils/find_boundary.cpp +++ b/tdutils/td/utils/find_boundary.cpp @@ -33,7 +33,7 @@ bool find_boundary(ChainBufferReader range, Slice boundary, size_t &already_read range.advance(1); already_read++; } else { - const char *ptr = static_cast(std::memchr(ready.data(), boundary[0], ready.size())); + const auto *ptr = static_cast(std::memchr(ready.data(), boundary[0], ready.size())); size_t shift; if (ptr == nullptr) { shift = ready.size(); diff --git a/tdutils/td/utils/logging.cpp b/tdutils/td/utils/logging.cpp index a716ae617..3268f8da8 100644 --- a/tdutils/td/utils/logging.cpp +++ b/tdutils/td/utils/logging.cpp @@ -73,7 +73,7 @@ Logger::Logger(LogInterface &log, const LogOptions &options, int log_level, Slic // log level sb_ << '['; - if (static_cast(log_level) < 10) { + if (static_cast(log_level) < 10) { sb_ << ' ' << static_cast('0' + log_level); } else { sb_ << log_level; @@ -83,7 +83,7 @@ Logger::Logger(LogInterface &log, const LogOptions &options, int log_level, Slic // thread id auto thread_id = get_thread_id(); sb_ << "[t"; - if (static_cast(thread_id) < 10) { + if (static_cast(thread_id) < 10) { sb_ << ' ' << static_cast('0' + thread_id); } else { sb_ << thread_id; @@ -109,7 +109,7 @@ Logger::Logger(LogInterface &log, const LogOptions &options, int log_level, Slic last_slash_--; } file_name = file_name.substr(last_slash_ + 1); - sb_ << '[' << file_name << ':' << static_cast(line_num) << ']'; + sb_ << '[' << file_name << ':' << static_cast(line_num) << ']'; } // context from tag_ @@ -219,6 +219,9 @@ class DefaultLog final : public LogInterface { case VERBOSITY_NAME(INFO): color = Slice("\x1b[1;36m"); // cyan break; + default: + // no color + break; } Slice no_color("\x1b[0m"); if (!slice.empty() && slice.back() == '\n') { diff --git a/tdutils/td/utils/logging.h b/tdutils/td/utils/logging.h index d388af59b..06232c19c 100644 --- a/tdutils/td/utils/logging.h +++ b/tdutils/td/utils/logging.h @@ -128,6 +128,9 @@ struct LogOptions { } LogOptions &operator=(const LogOptions &other) { + if (this == &other) { + return *this; + } level = other.level.load(); fix_newlines = other.fix_newlines; add_info = other.add_info; diff --git a/tdutils/td/utils/misc.cpp b/tdutils/td/utils/misc.cpp index fc33710f1..98dd015a4 100644 --- a/tdutils/td/utils/misc.cpp +++ b/tdutils/td/utils/misc.cpp @@ -16,7 +16,7 @@ namespace td { char *str_dup(Slice str) { - char *res = static_cast(std::malloc(str.size() + 1)); + auto *res = static_cast(std::malloc(str.size() + 1)); if (res == nullptr) { return nullptr; } diff --git a/tdutils/td/utils/port/FileFd.cpp b/tdutils/td/utils/port/FileFd.cpp index 15be794b2..4c63b6d31 100644 --- a/tdutils/td/utils/port/FileFd.cpp +++ b/tdutils/td/utils/port/FileFd.cpp @@ -108,8 +108,8 @@ class FileFdImpl { } // namespace detail FileFd::FileFd() = default; -FileFd::FileFd(FileFd &&) = default; -FileFd &FileFd::operator=(FileFd &&) = default; +FileFd::FileFd(FileFd &&) noexcept = default; +FileFd &FileFd::operator=(FileFd &&) noexcept = default; FileFd::~FileFd() = default; FileFd::FileFd(unique_ptr impl) : impl_(std::move(impl)) { @@ -407,7 +407,7 @@ static Status create_local_lock(const string &path, int32 &max_tries) { } } -Status FileFd::lock(const LockFlags flags, const string &path, int32 max_tries) { +Status FileFd::lock(LockFlags flags, const string &path, int32 max_tries) { if (max_tries <= 0) { return Status::Error("Can't lock file: wrong max_tries"); } diff --git a/tdutils/td/utils/port/FileFd.h b/tdutils/td/utils/port/FileFd.h index f4c8f0635..6d34c6a8d 100644 --- a/tdutils/td/utils/port/FileFd.h +++ b/tdutils/td/utils/port/FileFd.h @@ -20,13 +20,13 @@ namespace td { namespace detail { class FileFdImpl; -} +} // namespace detail class FileFd { public: FileFd(); - FileFd(FileFd &&); - FileFd &operator=(FileFd &&); + FileFd(FileFd &&) noexcept; + FileFd &operator=(FileFd &&) noexcept; ~FileFd(); FileFd(const FileFd &) = delete; FileFd &operator=(const FileFd &) = delete; @@ -45,7 +45,7 @@ class FileFd { Result pread(MutableSlice slice, int64 offset) const TD_WARN_UNUSED_RESULT; enum class LockFlags { Write, Read, Unlock }; - Status lock(const LockFlags flags, const string &path, int32 max_tries) TD_WARN_UNUSED_RESULT; + Status lock(LockFlags flags, const string &path, int32 max_tries) TD_WARN_UNUSED_RESULT; static void remove_local_lock(const string &path); PollableFdInfo &get_poll_info(); diff --git a/tdutils/td/utils/port/IPAddress.cpp b/tdutils/td/utils/port/IPAddress.cpp index cf4e317b7..38be8ed0c 100644 --- a/tdutils/td/utils/port/IPAddress.cpp +++ b/tdutils/td/utils/port/IPAddress.cpp @@ -86,7 +86,7 @@ static void punycode(string &result, Slice part) { if (code == next_n) { // found next symbol, encode delta - int left = static_cast(delta); + auto left = static_cast(delta); while (true) { bias += 36; auto t = clamp(bias, 1, 26); diff --git a/tdutils/td/utils/port/MemoryMapping.cpp b/tdutils/td/utils/port/MemoryMapping.cpp index 032c0a5f7..870bfd721 100644 --- a/tdutils/td/utils/port/MemoryMapping.cpp +++ b/tdutils/td/utils/port/MemoryMapping.cpp @@ -91,8 +91,8 @@ Result MemoryMapping::create_from_file(const FileFd &file_fd, con #endif } -MemoryMapping::MemoryMapping(MemoryMapping &&other) = default; -MemoryMapping &MemoryMapping::operator=(MemoryMapping &&other) = default; +MemoryMapping::MemoryMapping(MemoryMapping &&other) noexcept = default; +MemoryMapping &MemoryMapping::operator=(MemoryMapping &&other) noexcept = default; MemoryMapping::~MemoryMapping() = default; MemoryMapping::MemoryMapping(unique_ptr impl) : impl_(std::move(impl)) { diff --git a/tdutils/td/utils/port/MemoryMapping.h b/tdutils/td/utils/port/MemoryMapping.h index 93ef45658..a9db9ecff 100644 --- a/tdutils/td/utils/port/MemoryMapping.h +++ b/tdutils/td/utils/port/MemoryMapping.h @@ -39,8 +39,8 @@ class MemoryMapping { MemoryMapping(const MemoryMapping &other) = delete; const MemoryMapping &operator=(const MemoryMapping &other) = delete; - MemoryMapping(MemoryMapping &&other); - MemoryMapping &operator=(MemoryMapping &&other); + MemoryMapping(MemoryMapping &&other) noexcept; + MemoryMapping &operator=(MemoryMapping &&other) noexcept; ~MemoryMapping(); private: diff --git a/tdutils/td/utils/port/RwMutex.h b/tdutils/td/utils/port/RwMutex.h index c6afc9f7f..8c6d6676a 100644 --- a/tdutils/td/utils/port/RwMutex.h +++ b/tdutils/td/utils/port/RwMutex.h @@ -26,11 +26,11 @@ class RwMutex { } RwMutex(const RwMutex &) = delete; RwMutex &operator=(const RwMutex &) = delete; - RwMutex(RwMutex &&other) { + RwMutex(RwMutex &&other) noexcept { init(); other.clear(); } - RwMutex &operator=(RwMutex &&other) { + RwMutex &operator=(RwMutex &&other) noexcept { other.clear(); return *this; } diff --git a/tdutils/td/utils/port/ServerSocketFd.cpp b/tdutils/td/utils/port/ServerSocketFd.cpp index d15874ec7..a362666ef 100644 --- a/tdutils/td/utils/port/ServerSocketFd.cpp +++ b/tdutils/td/utils/port/ServerSocketFd.cpp @@ -282,8 +282,8 @@ void ServerSocketFdImplDeleter::operator()(ServerSocketFdImpl *impl) { } // namespace detail ServerSocketFd::ServerSocketFd() = default; -ServerSocketFd::ServerSocketFd(ServerSocketFd &&) = default; -ServerSocketFd &ServerSocketFd::operator=(ServerSocketFd &&) = default; +ServerSocketFd::ServerSocketFd(ServerSocketFd &&) noexcept = default; +ServerSocketFd &ServerSocketFd::operator=(ServerSocketFd &&) noexcept = default; ServerSocketFd::~ServerSocketFd() = default; ServerSocketFd::ServerSocketFd(unique_ptr impl) : impl_(impl.release()) { } diff --git a/tdutils/td/utils/port/ServerSocketFd.h b/tdutils/td/utils/port/ServerSocketFd.h index 24079f5ae..271cfc2eb 100644 --- a/tdutils/td/utils/port/ServerSocketFd.h +++ b/tdutils/td/utils/port/ServerSocketFd.h @@ -29,8 +29,8 @@ class ServerSocketFd { ServerSocketFd(); ServerSocketFd(const ServerSocketFd &) = delete; ServerSocketFd &operator=(const ServerSocketFd &) = delete; - ServerSocketFd(ServerSocketFd &&); - ServerSocketFd &operator=(ServerSocketFd &&); + ServerSocketFd(ServerSocketFd &&) noexcept; + ServerSocketFd &operator=(ServerSocketFd &&) noexcept; ~ServerSocketFd(); static Result open(int32 port, CSlice addr = CSlice("0.0.0.0")) TD_WARN_UNUSED_RESULT; diff --git a/tdutils/td/utils/port/SocketFd.cpp b/tdutils/td/utils/port/SocketFd.cpp index 61e8ef87a..c54912723 100644 --- a/tdutils/td/utils/port/SocketFd.cpp +++ b/tdutils/td/utils/port/SocketFd.cpp @@ -489,7 +489,7 @@ class SocketFdImpl { TRY_STATUS(get_pending_error()); } int native_fd = get_native_fd().socket(); - CHECK(slice.size() > 0); + CHECK(!slice.empty()); auto read_res = detail::skip_eintr([&] { return ::read(native_fd, slice.begin(), slice.size()); }); auto read_errno = errno; if (read_res >= 0) { @@ -609,8 +609,8 @@ Status init_socket_options(NativeFd &native_fd) { } // namespace detail SocketFd::SocketFd() = default; -SocketFd::SocketFd(SocketFd &&) = default; -SocketFd &SocketFd::operator=(SocketFd &&) = default; +SocketFd::SocketFd(SocketFd &&) noexcept = default; +SocketFd &SocketFd::operator=(SocketFd &&) noexcept = default; SocketFd::~SocketFd() = default; SocketFd::SocketFd(unique_ptr impl) : impl_(impl.release()) { diff --git a/tdutils/td/utils/port/SocketFd.h b/tdutils/td/utils/port/SocketFd.h index 67f8bd512..a82771110 100644 --- a/tdutils/td/utils/port/SocketFd.h +++ b/tdutils/td/utils/port/SocketFd.h @@ -33,8 +33,8 @@ class SocketFd { SocketFd(); SocketFd(const SocketFd &) = delete; SocketFd &operator=(const SocketFd &) = delete; - SocketFd(SocketFd &&); - SocketFd &operator=(SocketFd &&); + SocketFd(SocketFd &&) noexcept; + SocketFd &operator=(SocketFd &&) noexcept; ~SocketFd(); static Result open(const IPAddress &address) TD_WARN_UNUSED_RESULT; diff --git a/tdutils/td/utils/port/StdStreams.cpp b/tdutils/td/utils/port/StdStreams.cpp index a311e04df..f80fc0b6b 100644 --- a/tdutils/td/utils/port/StdStreams.cpp +++ b/tdutils/td/utils/port/StdStreams.cpp @@ -229,8 +229,8 @@ void BufferedStdinImplDeleter::operator()(BufferedStdinImpl *impl) { BufferedStdin::BufferedStdin() : impl_(make_unique().release()) { } -BufferedStdin::BufferedStdin(BufferedStdin &&) = default; -BufferedStdin &BufferedStdin::operator=(BufferedStdin &&) = default; +BufferedStdin::BufferedStdin(BufferedStdin &&) noexcept = default; +BufferedStdin &BufferedStdin::operator=(BufferedStdin &&) noexcept = default; BufferedStdin::~BufferedStdin() = default; ChainBufferReader &BufferedStdin::input_buffer() { diff --git a/tdutils/td/utils/port/StdStreams.h b/tdutils/td/utils/port/StdStreams.h index 687c898b6..e95d0c85c 100644 --- a/tdutils/td/utils/port/StdStreams.h +++ b/tdutils/td/utils/port/StdStreams.h @@ -34,8 +34,8 @@ class BufferedStdin { BufferedStdin(); BufferedStdin(const BufferedStdin &) = delete; BufferedStdin &operator=(const BufferedStdin &) = delete; - BufferedStdin(BufferedStdin &&); - BufferedStdin &operator=(BufferedStdin &&); + BufferedStdin(BufferedStdin &&) noexcept; + BufferedStdin &operator=(BufferedStdin &&) noexcept; ~BufferedStdin(); ChainBufferReader &input_buffer(); PollableFdInfo &get_poll_info(); diff --git a/tdutils/td/utils/port/UdpSocketFd.cpp b/tdutils/td/utils/port/UdpSocketFd.cpp index a8da87664..2c65c459d 100644 --- a/tdutils/td/utils/port/UdpSocketFd.cpp +++ b/tdutils/td/utils/port/UdpSocketFd.cpp @@ -59,7 +59,7 @@ class UdpSocketReceiveHelper { message_header.dwFlags = 0; } - void from_native(WSAMSG &message_header, size_t message_size, UdpMessage &message) { + static void from_native(WSAMSG &message_header, size_t message_size, UdpMessage &message) { message.address.init_sockaddr(reinterpret_cast(message_header.name), message_header.namelen).ignore(); message.error = Status::OK(); @@ -79,6 +79,7 @@ class UdpSocketReceiveHelper { sockaddr_storage addr_; WSABUF buf_; }; + class UdpSocketSendHelper { public: void to_native(const UdpMessage &message, WSAMSG &message_header) { @@ -295,7 +296,7 @@ class UdpSocketFdImpl final : private Iocp::Callback { VLOG(fd) << get_native_fd() << " on receive " << size; CHECK(is_receive_active_); is_receive_active_ = false; - receive_helper_.from_native(receive_message_, size, to_receive_); + UdpSocketReceiveHelper::from_native(receive_message_, size, to_receive_); receive_buffer_.confirm_read((to_receive_.data.size() + 7) & ~7); { auto lock = lock_.lock(); @@ -387,7 +388,7 @@ class UdpSocketReceiveHelper { message_header.msg_flags = 0; } - void from_native(msghdr &message_header, size_t message_size, UdpSocketFd::InboundMessage &message) { + static void from_native(msghdr &message_header, size_t message_size, UdpSocketFd::InboundMessage &message) { #if TD_LINUX cmsghdr *cmsg; sock_extended_err *ee = nullptr; @@ -502,7 +503,7 @@ class UdpSocketFdImpl { auto recvmsg_res = detail::skip_eintr([&] { return recvmsg(native_fd, &message_header, flags); }); auto recvmsg_errno = errno; if (recvmsg_res >= 0) { - helper.from_native(message_header, recvmsg_res, message); + UdpSocketReceiveHelper::from_native(message_header, recvmsg_res, message); is_received = true; return Status::OK(); } @@ -719,7 +720,7 @@ class UdpSocketFdImpl { if (recvmmsg_res >= 0) { cnt = narrow_cast(recvmmsg_res); for (size_t i = 0; i < cnt; i++) { - helpers[i].from_native(headers[i].msg_hdr, headers[i].msg_len, messages[i]); + UdpSocketReceiveHelper::from_native(headers[i].msg_hdr, headers[i].msg_len, messages[i]); } return Status::OK(); } @@ -738,8 +739,8 @@ void UdpSocketFdImplDeleter::operator()(UdpSocketFdImpl *impl) { } // namespace detail UdpSocketFd::UdpSocketFd() = default; -UdpSocketFd::UdpSocketFd(UdpSocketFd &&) = default; -UdpSocketFd &UdpSocketFd::operator=(UdpSocketFd &&) = default; +UdpSocketFd::UdpSocketFd(UdpSocketFd &&) noexcept = default; +UdpSocketFd &UdpSocketFd::operator=(UdpSocketFd &&) noexcept = default; UdpSocketFd::~UdpSocketFd() = default; PollableFdInfo &UdpSocketFd::get_poll_info() { return impl_->get_poll_info(); diff --git a/tdutils/td/utils/port/UdpSocketFd.h b/tdutils/td/utils/port/UdpSocketFd.h index 59f3506c5..ccdcfddfe 100644 --- a/tdutils/td/utils/port/UdpSocketFd.h +++ b/tdutils/td/utils/port/UdpSocketFd.h @@ -38,8 +38,8 @@ struct UdpMessage { class UdpSocketFd { public: UdpSocketFd(); - UdpSocketFd(UdpSocketFd &&); - UdpSocketFd &operator=(UdpSocketFd &&); + UdpSocketFd(UdpSocketFd &&) noexcept; + UdpSocketFd &operator=(UdpSocketFd &&) noexcept; ~UdpSocketFd(); UdpSocketFd(const UdpSocketFd &) = delete; diff --git a/tdutils/td/utils/port/detail/EventFdLinux.cpp b/tdutils/td/utils/port/detail/EventFdLinux.cpp index 96bfcb052..ce87692a8 100644 --- a/tdutils/td/utils/port/detail/EventFdLinux.cpp +++ b/tdutils/td/utils/port/detail/EventFdLinux.cpp @@ -33,8 +33,8 @@ class EventFdLinuxImpl { }; EventFdLinux::EventFdLinux() = default; -EventFdLinux::EventFdLinux(EventFdLinux &&) = default; -EventFdLinux &EventFdLinux::operator=(EventFdLinux &&) = default; +EventFdLinux::EventFdLinux(EventFdLinux &&) noexcept = default; +EventFdLinux &EventFdLinux::operator=(EventFdLinux &&) noexcept = default; EventFdLinux::~EventFdLinux() = default; void EventFdLinux::init() { @@ -96,7 +96,7 @@ void EventFdLinux::acquire() { auto slice = MutableSlice(reinterpret_cast(&res), sizeof(res)); auto native_fd = impl_->info.native_fd().fd(); auto result = [&]() -> Result { - CHECK(slice.size() > 0); + CHECK(!slice.empty()); auto read_res = detail::skip_eintr([&] { return ::read(native_fd, slice.begin(), slice.size()); }); auto read_errno = errno; if (read_res >= 0) { diff --git a/tdutils/td/utils/port/detail/EventFdLinux.h b/tdutils/td/utils/port/detail/EventFdLinux.h index 7e482caa3..87e428949 100644 --- a/tdutils/td/utils/port/detail/EventFdLinux.h +++ b/tdutils/td/utils/port/detail/EventFdLinux.h @@ -24,9 +24,9 @@ class EventFdLinux final : public EventFdBase { public: EventFdLinux(); - EventFdLinux(EventFdLinux &&); - EventFdLinux &operator=(EventFdLinux &&); - ~EventFdLinux(); + EventFdLinux(EventFdLinux &&) noexcept; + EventFdLinux &operator=(EventFdLinux &&) noexcept; + ~EventFdLinux() override; void init() final; diff --git a/tdutils/td/utils/port/detail/NativeFd.cpp b/tdutils/td/utils/port/detail/NativeFd.cpp index c03e0afc1..98f64a4ca 100644 --- a/tdutils/td/utils/port/detail/NativeFd.cpp +++ b/tdutils/td/utils/port/detail/NativeFd.cpp @@ -134,14 +134,14 @@ NativeFd::NativeFd(Socket socket) : fd_(reinterpret_cast(socket)), is_socket } #endif -NativeFd::NativeFd(NativeFd &&other) : fd_(other.fd_) { +NativeFd::NativeFd(NativeFd &&other) noexcept : fd_(other.fd_) { #if TD_PORT_WINDOWS is_socket_ = other.is_socket_; #endif other.fd_ = empty_fd(); } -NativeFd &NativeFd::operator=(NativeFd &&other) { +NativeFd &NativeFd::operator=(NativeFd &&other) noexcept { CHECK(this != &other); close(); fd_ = other.fd_; diff --git a/tdutils/td/utils/port/detail/NativeFd.h b/tdutils/td/utils/port/detail/NativeFd.h index c992c6676..7dd0f9402 100644 --- a/tdutils/td/utils/port/detail/NativeFd.h +++ b/tdutils/td/utils/port/detail/NativeFd.h @@ -34,8 +34,8 @@ class NativeFd { #endif NativeFd(const NativeFd &) = delete; NativeFd &operator=(const NativeFd &) = delete; - NativeFd(NativeFd &&other); - NativeFd &operator=(NativeFd &&other); + NativeFd(NativeFd &&other) noexcept; + NativeFd &operator=(NativeFd &&other) noexcept; ~NativeFd(); explicit operator bool() const; diff --git a/tdutils/td/utils/port/detail/PollableFd.h b/tdutils/td/utils/port/detail/PollableFd.h index dd4e86a1a..5cc197499 100644 --- a/tdutils/td/utils/port/detail/PollableFd.h +++ b/tdutils/td/utils/port/detail/PollableFd.h @@ -151,7 +151,7 @@ class PollableFdInfo final : private ListNode { #if TD_PORT_WINDOWS auto lock = observer_lock_.lock(); #endif - CHECK(!observer_); + CHECK(observer_ == nullptr); observer_ = observer; } void clear_observer() { @@ -165,7 +165,7 @@ class PollableFdInfo final : private ListNode { auto lock = observer_lock_.lock(); #endif VLOG(fd) << native_fd() << " notify " << tag("observer", observer_); - if (observer_) { + if (observer_ != nullptr) { observer_->notify(); } } diff --git a/tdutils/td/utils/port/detail/ThreadPthread.h b/tdutils/td/utils/port/detail/ThreadPthread.h index a9f7166c9..d73ec1083 100644 --- a/tdutils/td/utils/port/detail/ThreadPthread.h +++ b/tdutils/td/utils/port/detail/ThreadPthread.h @@ -33,7 +33,7 @@ class ThreadPthread { ThreadPthread &operator=(const ThreadPthread &other) = delete; ThreadPthread(ThreadPthread &&other) noexcept : is_inited_(std::move(other.is_inited_)), thread_(other.thread_) { } - ThreadPthread &operator=(ThreadPthread &&other) { + ThreadPthread &operator=(ThreadPthread &&other) noexcept { join(); is_inited_ = std::move(other.is_inited_); thread_ = other.thread_; @@ -72,7 +72,8 @@ class ThreadPthread { return std::forward(v); } - int do_pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg); + static int do_pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), + void *arg); static void *run_thread(void *ptr) { ThreadIdGuard thread_id_guard; diff --git a/tdutils/td/utils/port/signals.cpp b/tdutils/td/utils/port/signals.cpp index 25e73a209..1c95a63ba 100644 --- a/tdutils/td/utils/port/signals.cpp +++ b/tdutils/td/utils/port/signals.cpp @@ -74,7 +74,7 @@ static void set_handler(struct sigaction &act, decltype(act.sa_sigaction) handle act.sa_flags |= SA_SIGINFO; } template -static Status set_signal_handler_impl(vector signals, F func) { +static Status set_signal_handler_impl(vector &&signals, F func) { struct sigaction act; std::memset(&act, '\0', sizeof(act)); @@ -123,7 +123,7 @@ static void signal_handler_func(int sig) { handler(sig); } -static Status set_signal_handler_impl(vector signals, void (*func)(int sig)) { +static Status set_signal_handler_impl(vector &&signals, void (*func)(int sig)) { for (auto signal : signals) { CHECK(0 <= signal && signal < NSIG); if (func != SIG_IGN && func != SIG_DFL) { @@ -296,7 +296,7 @@ void signal_safe_write_signal_number(int sig, bool add_header) { } void signal_safe_write_pointer(void *p, bool add_header) { - std::uintptr_t addr = reinterpret_cast(p); + auto addr = reinterpret_cast(p); char buf[100]; char *end = buf + sizeof(buf); char *ptr = end; diff --git a/tdutils/td/utils/port/stacktrace.cpp b/tdutils/td/utils/port/stacktrace.cpp index 52817624d..88c3d96a5 100644 --- a/tdutils/td/utils/port/stacktrace.cpp +++ b/tdutils/td/utils/port/stacktrace.cpp @@ -26,7 +26,7 @@ namespace td { namespace { -void print_backtrace(void) { +void print_backtrace() { #if TD_PORT_WINDOWS void *buffer[128]; USHORT nptrs = CaptureStackBackTrace(0, 128, buffer, nullptr); @@ -48,7 +48,7 @@ void print_backtrace(void) { signal_safe_write("-------------------------------\n", false); } -void print_backtrace_gdb(void) { +void print_backtrace_gdb() { #if TD_LINUX || TD_FREEBSD char pid_buf[30]; char *pid_buf_begin = pid_buf + sizeof(pid_buf); diff --git a/tdutils/td/utils/port/uname.cpp b/tdutils/td/utils/port/uname.cpp index 327632821..34a5c7525 100644 --- a/tdutils/td/utils/port/uname.cpp +++ b/tdutils/td/utils/port/uname.cpp @@ -49,7 +49,7 @@ static string read_os_name(CSlice os_version_file_path, CSlice prefix, CSlice su auto end_pos = r_file.ok().find(suffix.c_str(), begin_pos); if (end_pos != string::npos) { auto os_version = trim(r_file.ok().substr(begin_pos, end_pos - begin_pos)); - if (os_version.find("\n") == string::npos) { + if (os_version.find('\n') == string::npos) { return os_version; } } @@ -254,7 +254,7 @@ Slice get_operating_system_version() { } return "Windows Server 2016"; } - if (os_version_info.dwBuildNumber >= 21900) { // build numbers between 21391 and 21999 aren't used + if (os_version_info.dwBuildNumber >= 21900) { // build numbers between 21391 and 21999 aren't used return "Windows 11"; } return "Windows 10"; diff --git a/tdutils/td/utils/port/wstring_convert.cpp b/tdutils/td/utils/port/wstring_convert.cpp index c81d0695f..1c3257297 100644 --- a/tdutils/td/utils/port/wstring_convert.cpp +++ b/tdutils/td/utils/port/wstring_convert.cpp @@ -29,14 +29,14 @@ Result to_wstring(CSlice slice) { if (wstring_len) { wchar_t *res = &result[0]; for (size_t i = 0; i < slice.size();) { - unsigned int a = static_cast(slice[i++]); + uint32 a = static_cast(slice[i++]); if (a >= 0x80) { - unsigned int b = static_cast(slice[i++]); + uint32 b = static_cast(slice[i++]); if (a >= 0xe0) { - unsigned int c = static_cast(slice[i++]); + uint32 c = static_cast(slice[i++]); if (a >= 0xf0) { - unsigned int d = static_cast(slice[i++]); - unsigned int val = ((a & 0x07) << 18) + ((b & 0x3f) << 12) + ((c & 0x3f) << 6) + (d & 0x3f) - 0x10000; + uint32 d = static_cast(slice[i++]); + uint32 val = ((a & 0x07) << 18) + ((b & 0x3f) << 12) + ((c & 0x3f) << 6) + (d & 0x3f) - 0x10000; *res++ = static_cast(0xD800 + (val >> 10)); *res++ = static_cast(0xDC00 + (val & 0x3ff)); } else { @@ -57,10 +57,10 @@ Result to_wstring(CSlice slice) { Result from_wstring(const wchar_t *begin, size_t size) { size_t result_len = 0; for (size_t i = 0; i < size; i++) { - unsigned int cur = begin[i]; + uint32 cur = begin[i]; if ((cur & 0xF800) == 0xD800) { if (i < size) { - unsigned int next = begin[++i]; + uint32 next = begin[++i]; if ((next & 0xFC00) == 0xDC00 && (cur & 0x400) == 0) { result_len += 4; continue; @@ -76,8 +76,8 @@ Result from_wstring(const wchar_t *begin, size_t size) { if (result_len) { char *res = &result[0]; for (size_t i = 0; i < size; i++) { - unsigned int cur = begin[i]; - // TODO conversion unsigned int -> signed char is implementation defined + uint32 cur = begin[i]; + // TODO conversion uint32 -> signed char is implementation defined if (cur <= 0x7f) { *res++ = static_cast(cur); } else if (cur <= 0x7ff) { @@ -88,8 +88,8 @@ Result from_wstring(const wchar_t *begin, size_t size) { *res++ = static_cast(0x80 | ((cur >> 6) & 0x3f)); *res++ = static_cast(0x80 | (cur & 0x3f)); } else { - unsigned int next = begin[++i]; - unsigned int val = ((cur - 0xD800) << 10) + next - 0xDC00 + 0x10000; + uint32 next = begin[++i]; + uint32 val = ((cur - 0xD800) << 10) + next - 0xDC00 + 0x10000; *res++ = static_cast(0xf0 | (val >> 18)); *res++ = static_cast(0x80 | ((val >> 12) & 0x3f)); diff --git a/tdutils/td/utils/queue.h b/tdutils/td/utils/queue.h index c0f419084..4d3f336eb 100644 --- a/tdutils/td/utils/queue.h +++ b/tdutils/td/utils/queue.h @@ -150,7 +150,7 @@ class SPSCBlockQueue { } }; -template > +template > class SPSCChainQueue { public: using ValueType = T; @@ -308,10 +308,10 @@ class BackoffQueue : public QueueT { } }; -template > +template > using InfBackoffQueue = BackoffQueue; -template > +template > class PollQueue final : public QueueT { public: using ValueType = T; diff --git a/tdutils/td/utils/tests.cpp b/tdutils/td/utils/tests.cpp index ecb14a968..dddad7c75 100644 --- a/tdutils/td/utils/tests.cpp +++ b/tdutils/td/utils/tests.cpp @@ -64,10 +64,11 @@ class RegressionTesterImpl final : public RegressionTester { unlink(db_path).ignore(); } - RegressionTesterImpl(string db_path, string db_cache_dir) : db_path_(db_path), db_cache_dir_(db_cache_dir) { - load_db(db_path).ignore(); + RegressionTesterImpl(string db_path, string db_cache_dir) + : db_path_(std::move(db_path)), db_cache_dir_(std::move(db_cache_dir)) { + load_db(db_path_).ignore(); if (db_cache_dir_.empty()) { - db_cache_dir_ = PathView(db_path).without_extension().str() + ".cache/"; + db_cache_dir_ = PathView(db_path_).without_extension().str() + ".cache/"; } mkdir(db_cache_dir_).ensure(); } @@ -120,7 +121,7 @@ class RegressionTesterImpl final : public RegressionTester { void save_db(StringBuilder &sb) { sb << magic() << "\n"; - for (auto it : tests_) { + for (const auto &it : tests_) { sb << it.second; } } @@ -171,7 +172,7 @@ void TestsRunner::add_test(string name, std::function()> test) LOG(FATAL) << "Test name collision " << name; } } - tests_.emplace_back(name, TestInfo{std::move(test), nullptr}); + tests_.emplace_back(std::move(name), TestInfo{std::move(test), nullptr}); } void TestsRunner::add_substr_filter(string str) { diff --git a/tdutils/td/utils/tests.h b/tdutils/td/utils/tests.h index ec8377db5..10bca6010 100644 --- a/tdutils/td/utils/tests.h +++ b/tdutils/td/utils/tests.h @@ -122,7 +122,7 @@ template class RegisterTest { public: explicit RegisterTest(string name, TestsRunner &runner = TestsRunner::get_default()) { - runner.add_test(name, [] { return make_unique(); }); + runner.add_test(std::move(name), [] { return make_unique(); }); } }; diff --git a/tdutils/td/utils/tl_parsers.h b/tdutils/td/utils/tl_parsers.h index a7141d263..e0fb668f8 100644 --- a/tdutils/td/utils/tl_parsers.h +++ b/tdutils/td/utils/tl_parsers.h @@ -178,7 +178,7 @@ class TlParser { if (!error.empty()) { return T(); } - const char *result = reinterpret_cast(data); + auto result = reinterpret_cast(data); data += size; return T(result, size); } diff --git a/tdutils/td/utils/unicode.cpp b/tdutils/td/utils/unicode.cpp index 42bbf62c4..b5e7892fa 100644 --- a/tdutils/td/utils/unicode.cpp +++ b/tdutils/td/utils/unicode.cpp @@ -1200,8 +1200,9 @@ static uint32 binary_search_ranges(const int32 (&ranges)[N], uint32 code) { return 0; } - int32 code_int = static_cast(code); - size_t l = 0, r = N; + auto code_int = static_cast(code); + size_t l = 0; + size_t r = N; while (l < r) { size_t m = ((l + r + 2) >> 2) << 1; if (ranges[m] <= code_int) { diff --git a/tdutils/td/utils/utf8.cpp b/tdutils/td/utils/utf8.cpp index 819e9d27b..a13abb2d1 100644 --- a/tdutils/td/utils/utf8.cpp +++ b/tdutils/td/utils/utf8.cpp @@ -15,7 +15,7 @@ bool check_utf8(CSlice str) { const char *data = str.data(); const char *data_end = data + str.size(); do { - unsigned int a = static_cast(*data++); + uint32 a = static_cast(*data++); if ((a & 0x80) == 0) { if (data == data_end + 1) { return true; @@ -30,25 +30,25 @@ bool check_utf8(CSlice str) { ENSURE((a & 0x40) != 0); - unsigned int b = static_cast(*data++); + uint32 b = static_cast(*data++); ENSURE((b & 0xc0) == 0x80); if ((a & 0x20) == 0) { ENSURE((a & 0x1e) > 0); continue; } - unsigned int c = static_cast(*data++); + uint32 c = static_cast(*data++); ENSURE((c & 0xc0) == 0x80); if ((a & 0x10) == 0) { - int x = (((a & 0x0f) << 6) | (b & 0x20)); + uint32 x = (((a & 0x0f) << 6) | (b & 0x20)); ENSURE(x != 0 && x != 0x360); // surrogates continue; } - unsigned int d = static_cast(*data++); + uint32 d = static_cast(*data++); ENSURE((d & 0xc0) == 0x80); if ((a & 0x08) == 0) { - int t = (((a & 0x07) << 6) | (b & 0x30)); + uint32 t = (((a & 0x07) << 6) | (b & 0x30)); ENSURE(0 < t && t < 0x110); // end of unicode continue; } diff --git a/tdutils/test/StealingQueue.cpp b/tdutils/test/StealingQueue.cpp index fc878fb58..64fca0e16 100644 --- a/tdutils/test/StealingQueue.cpp +++ b/tdutils/test/StealingQueue.cpp @@ -131,9 +131,9 @@ TEST(StealingQueue, simple) { for (td::uint64 round = 1; round < 1000; round++) { if (id == 0) { sum = 0; - int n = static_cast(rnd() % 5); + auto n = static_cast(rnd() % 5); for (int j = 0; j < n; j++) { - int x = static_cast(rnd() % XN); + auto x = static_cast(rnd() % XN); sum += x_sum[x]; gq.push(x, id); } diff --git a/tdutils/test/bitmask.cpp b/tdutils/test/bitmask.cpp index 1c7a5280b..6ace35354 100644 --- a/tdutils/test/bitmask.cpp +++ b/tdutils/test/bitmask.cpp @@ -78,8 +78,8 @@ class RangeSet { CHECK(it.begin % BIT_SIZE == 0); CHECK(it.end % BIT_SIZE == 0); - uint32 begin = narrow_cast(it.begin / BIT_SIZE); - uint32 end = narrow_cast(it.end / BIT_SIZE); + auto begin = narrow_cast(it.begin / BIT_SIZE); + auto end = narrow_cast(it.end / BIT_SIZE); if (sizes.empty()) { if (begin != 0) { sizes.push_back(0); diff --git a/test/country_info.cpp b/test/country_info.cpp index ca9f2376a..40a08e3cc 100644 --- a/test/country_info.cpp +++ b/test/country_info.cpp @@ -9,9 +9,9 @@ #include "td/utils/common.h" #include "td/utils/tests.h" -static void check_phone_number_info(const td::string &phone_number_prefix, const td::string &country_code, +static void check_phone_number_info(td::string phone_number_prefix, const td::string &country_code, const td::string &calling_code, const td::string &formatted_phone_number) { - auto result = td::CountryInfoManager::get_phone_number_info_sync(td::string(), phone_number_prefix); + auto result = td::CountryInfoManager::get_phone_number_info_sync(td::string(), std::move(phone_number_prefix)); CHECK(result != nullptr); if (result->country_ == nullptr) { CHECK(country_code.empty()); diff --git a/test/db.cpp b/test/db.cpp index 44c4fab68..b3970af62 100644 --- a/test/db.cpp +++ b/test/db.cpp @@ -296,18 +296,18 @@ class QueryHandler { class SqliteKV { public: - string get(string key) { + string get(const string &key) { return kv_->get().get(key); } - SeqNo set(string key, string value) { + SeqNo set(const string &key, const string &value) { kv_->get().set(key, value); return 0; } - SeqNo erase(string key) { + SeqNo erase(const string &key) { kv_->get().erase(key); return 0; } - Status init(string name) { + Status init(const string &name) { auto sql_connection = std::make_shared(name, DbKey::empty()); kv_ = std::make_shared("kv", sql_connection); return Status::OK(); diff --git a/test/link.cpp b/test/link.cpp index f2c5fdae1..5f7d0cb57 100644 --- a/test/link.cpp +++ b/test/link.cpp @@ -98,34 +98,34 @@ TEST(Link, parse_internal_link) { auto active_sessions = [] { return td::td_api::make_object(); }; - auto authentication_code = [](td::string code) { + auto authentication_code = [](const td::string &code) { return td::td_api::make_object(code); }; - auto background = [](td::string background_name) { + auto background = [](const td::string &background_name) { return td::td_api::make_object(background_name); }; - auto bot_start = [](td::string bot_username, td::string start_parameter) { + auto bot_start = [](const td::string &bot_username, const td::string &start_parameter) { return td::td_api::make_object(bot_username, start_parameter); }; - auto bot_start_in_group = [](td::string bot_username, td::string start_parameter) { + auto bot_start_in_group = [](const td::string &bot_username, const td::string &start_parameter) { return td::td_api::make_object(bot_username, start_parameter); }; auto change_phone_number = [] { return td::td_api::make_object(); }; - auto chat_invite = [](td::string hash) { + auto chat_invite = [](const td::string &hash) { return td::td_api::make_object("tg:join?invite=" + hash); }; auto filter_settings = [] { return td::td_api::make_object(); }; - auto game = [](td::string bot_username, td::string game_short_name) { + auto game = [](const td::string &bot_username, const td::string &game_short_name) { return td::td_api::make_object(bot_username, game_short_name); }; - auto language_pack = [](td::string language_pack_name) { + auto language_pack = [](const td::string &language_pack_name) { return td::td_api::make_object(language_pack_name); }; - auto message = [](td::string url) { + auto message = [](const td::string &url) { return td::td_api::make_object(url); }; auto message_draft = [](td::string text, bool contains_url) { @@ -133,23 +133,24 @@ TEST(Link, parse_internal_link) { formatted_text->text_ = std::move(text); return td::td_api::make_object(std::move(formatted_text), contains_url); }; - auto passport_data_request = [](td::int32 bot_user_id, td::string scope, td::string public_key, td::string nonce, - td::string callback_url) { + auto passport_data_request = [](td::int32 bot_user_id, const td::string &scope, const td::string &public_key, + const td::string &nonce, const td::string &callback_url) { return td::td_api::make_object(bot_user_id, scope, public_key, nonce, callback_url); }; - auto phone_number_confirmation = [](td::string hash, td::string phone_number) { + auto phone_number_confirmation = [](const td::string &hash, const td::string &phone_number) { return td::td_api::make_object(hash, phone_number); }; - auto proxy_mtproto = [](td::string server, td::int32 port, td::string secret) { + auto proxy_mtproto = [](const td::string &server, td::int32 port, const td::string &secret) { return td::td_api::make_object( server, port, td::td_api::make_object(secret)); }; - auto proxy_socks = [](td::string server, td::int32 port, td::string username, td::string password) { + auto proxy_socks = [](const td::string &server, td::int32 port, const td::string &username, + const td::string &password) { return td::td_api::make_object( server, port, td::td_api::make_object(username, password)); }; - auto public_chat = [](td::string chat_username) { + auto public_chat = [](const td::string &chat_username) { return td::td_api::make_object(chat_username); }; auto qr_code_authentication = [] { @@ -158,19 +159,19 @@ TEST(Link, parse_internal_link) { auto settings = [] { return td::td_api::make_object(); }; - auto sticker_set = [](td::string sticker_set_name) { + auto sticker_set = [](const td::string &sticker_set_name) { return td::td_api::make_object(sticker_set_name); }; - auto theme = [](td::string theme_name) { + auto theme = [](const td::string &theme_name) { return td::td_api::make_object(theme_name); }; auto theme_settings = [] { return td::td_api::make_object(); }; - auto unknown_deep_link = [](td::string link) { + auto unknown_deep_link = [](const td::string &link) { return td::td_api::make_object(link); }; - auto voice_chat = [](td::string chat_username, td::string invite_hash, bool is_live_stream) { + auto voice_chat = [](const td::string &chat_username, const td::string &invite_hash, bool is_live_stream) { return td::td_api::make_object(chat_username, invite_hash, is_live_stream); }; diff --git a/test/mtproto.cpp b/test/mtproto.cpp index c0b66e126..7bee6b377 100644 --- a/test/mtproto.cpp +++ b/test/mtproto.cpp @@ -612,7 +612,7 @@ class FastPingTestActor final : public Actor { } iteration_++; fast_ping_ = create_ping_actor( - "", std::move(connection_), std::move(auth_data), + td::Slice(), std::move(connection_), std::move(auth_data), PromiseCreator::lambda([self = actor_id(this)](Result> r_raw_connection) { send_closure(self, &FastPingTestActor::got_raw_connection, std::move(r_raw_connection)); }),