From a401f78bc86f7e6ea6a55ad9f453ae31be835b55 Mon Sep 17 00:00:00 2001 From: Xinye Tao Date: Thu, 20 Jan 2022 13:38:30 +0800 Subject: [PATCH] *: update rust toolchain to 2022-01-07 (#11875) * update rust toolchain to 2022-01-17 Signed-off-by: tabokie * address comment: clean up unnecessary `as_ref()` Signed-off-by: tabokie * try fixing the underflow Signed-off-by: tabokie * mute underflow warning for raft metrics Signed-off-by: tabokie * clean up unused data members Signed-off-by: tabokie * format Signed-off-by: tabokie * step back to 2022-01-07 Signed-off-by: tabokie --- components/backup/src/endpoint.rs | 21 +++---------- components/cdc/src/channel.rs | 4 +-- components/cdc/tests/mod.rs | 2 ++ components/encryption/src/file_dict_file.rs | 8 ++--- components/encryption/src/io.rs | 5 +-- components/engine_rocks/src/config.rs | 2 +- components/engine_rocks/src/properties.rs | 14 ++++----- components/engine_traits/src/options.rs | 11 +------ components/engine_traits/src/sst.rs | 5 +++ components/file_system/src/lib.rs | 10 ++---- .../src/coprocessor/split_check/table.rs | 4 +-- components/raftstore/src/lib.rs | 1 - components/raftstore/src/store/fsm/apply.rs | 2 -- components/raftstore/src/store/fsm/peer.rs | 27 +++++++--------- components/raftstore/src/store/fsm/store.rs | 20 +++++++++--- .../raftstore/src/store/local_metrics.rs | 30 ++---------------- components/raftstore/src/store/snap.rs | 3 ++ components/raftstore/src/store/snap/io.rs | 4 +-- .../raftstore/src/store/worker/query_stats.rs | 1 + .../raftstore/src/store/worker/region.rs | 3 +- .../src/store/worker/split_controller.rs | 10 +----- components/resolved_ts/src/cmd.rs | 1 + components/resource_metering/src/lib.rs | 1 - components/resource_metering/src/model.rs | 1 + .../resource_metering/src/recorder/mod.rs | 2 ++ .../resource_metering/tests/summary_test.rs | 6 ++-- components/security/src/lib.rs | 16 +--------- components/test_coprocessor/src/column.rs | 4 +++ components/test_coprocessor/src/dag.rs | 18 +++++++++++ components/test_coprocessor/src/store.rs | 1 + components/test_coprocessor/src/table.rs | 1 + components/test_raftstore/src/cluster.rs | 7 ++--- .../test_raftstore/src/transport_simulate.rs | 7 +++++ components/test_storage/src/sync_storage.rs | 6 ++-- .../src/builder/field_type.rs | 6 ++++ .../src/codec/batch/lazy_column.rs | 1 + .../src/codec/batch/lazy_column_vec.rs | 2 ++ .../src/codec/data_type/chunked_vec_bytes.rs | 5 +-- .../src/codec/data_type/chunked_vec_json.rs | 5 +-- .../src/codec/data_type/vector.rs | 1 + .../src/codec/mysql/duration.rs | 3 ++ .../src/codec/mysql/json/json_modify.rs | 2 +- .../src/codec/mysql/time/mod.rs | 15 +-------- .../src/codec/mysql/time/weekmode.rs | 1 + .../src/codec/row/v2/encoder_for_test.rs | 3 ++ components/tidb_query_executors/src/runner.rs | 17 +++++----- .../src/slow_hash_aggr_executor.rs | 2 +- .../src/top_n_executor.rs | 2 +- components/tidb_query_expr/src/impl_cast.rs | 31 ++++++------------- .../tidb_query_expr/src/impl_encryption.rs | 4 +-- .../tidb_query_expr/src/types/expr_builder.rs | 5 +++ .../tidb_query_expr/src/types/test_util.rs | 6 ++++ components/tikv_kv/src/cursor.rs | 8 +++++ components/tikv_kv/src/lib.rs | 13 +------- components/tikv_kv/src/mock_engine.rs | 6 ++++ components/tikv_util/src/lib.rs | 1 + components/tikv_util/src/lru.rs | 7 +---- components/tikv_util/src/worker/pool.rs | 2 ++ .../tipb_helper/src/expr_def_builder.rs | 1 + components/txn_types/src/lock.rs | 2 ++ components/txn_types/src/timestamp.rs | 2 ++ components/txn_types/src/types.rs | 1 + components/txn_types/src/write.rs | 1 + rust-toolchain | 2 +- scripts/clippy | 2 +- src/config.rs | 20 ++++++------ src/coprocessor/dag/mod.rs | 1 + src/coprocessor/statistics/analyze.rs | 12 +------ src/coprocessor/statistics/cmsketch.rs | 1 + src/coprocessor_v2/config.rs | 10 +----- src/coprocessor_v2/endpoint.rs | 1 + src/lib.rs | 1 - src/server/gc_worker/gc_manager.rs | 4 +-- src/server/lock_manager/client.rs | 2 -- src/server/lock_manager/waiter_manager.rs | 1 + src/server/service/diagnostics/sys.rs | 2 +- src/storage/mod.rs | 1 + src/storage/mvcc/reader/point_getter.rs | 7 +++++ src/storage/mvcc/reader/scanner/backward.rs | 2 +- src/storage/mvcc/reader/scanner/forward.rs | 3 +- src/storage/mvcc/reader/scanner/mod.rs | 10 ++++++ .../txn/commands/acquire_pessimistic_lock.rs | 8 ++--- .../txn/commands/check_secondary_locks.rs | 4 +-- src/storage/txn/commands/check_txn_status.rs | 4 +-- src/storage/txn/commands/cleanup.rs | 4 +-- src/storage/txn/commands/commit.rs | 4 +-- .../txn/commands/pessimistic_rollback.rs | 8 ++--- src/storage/txn/commands/prewrite.rs | 2 +- src/storage/txn/commands/resolve_lock.rs | 8 ++--- src/storage/txn/commands/resolve_lock_lite.rs | 4 +-- src/storage/txn/commands/rollback.rs | 4 +-- src/storage/txn/commands/txn_heart_beat.rs | 4 +-- src/storage/txn/flow_controller.rs | 1 - src/storage/txn/store.rs | 6 ++-- .../raftstore/test_replication_mode.rs | 2 +- 95 files changed, 258 insertions(+), 300 deletions(-) diff --git a/components/backup/src/endpoint.rs b/components/backup/src/endpoint.rs index 35563c596bd..8cffa7190d4 100644 --- a/components/backup/src/endpoint.rs +++ b/components/backup/src/endpoint.rs @@ -85,12 +85,6 @@ impl fmt::Debug for Task { } } -#[derive(Clone)] -struct LimitedStorage { - limiter: Limiter, - storage: Arc, -} - impl Task { /// Create a backup task based on the given backup request. pub fn new( @@ -483,7 +477,7 @@ impl BackupRange { &self, engine: E, db: Arc, - storage: &LimitedStorage, + limiter: &Limiter, file_name: String, cf: CfNameWrap, compression_type: Option, @@ -495,7 +489,7 @@ impl BackupRange { db, &file_name, cf, - storage.limiter.clone(), + limiter.clone(), compression_type, compression_level, cipher, @@ -793,7 +787,7 @@ impl Endpoint { request: Request, saver_tx: async_channel::Sender, resp_tx: UnboundedSender, - backend: Arc, + _backend: Arc, ) { let start_ts = request.start_ts; let backup_ts = request.end_ts; @@ -806,11 +800,6 @@ impl Endpoint { let limit = self.softlimit.limit(); self.pool.borrow_mut().spawn(async move { - let storage = LimitedStorage { - limiter: request.limiter, - storage: backend, - }; - loop { // when get the guard, release it until we finish scanning a batch, // because if we were suspended during scanning, @@ -868,7 +857,7 @@ impl Endpoint { .backup_raw_kv_to_file( engine, db.clone(), - &storage, + &request.limiter, name, cf.into(), ct, @@ -880,7 +869,7 @@ impl Endpoint { } else { let writer_builder = BackupWriterBuilder::new( store_id, - storage.limiter.clone(), + request.limiter.clone(), brange.region.clone(), db.clone(), ct, diff --git a/components/cdc/src/channel.rs b/components/cdc/src/channel.rs index 5b3cefbb090..5afa03c92c1 100644 --- a/components/cdc/src/channel.rs +++ b/components/cdc/src/channel.rs @@ -387,12 +387,12 @@ impl<'a> Drain { }); let (event_bytes, resolved_ts_bytes) = batcher.statistics(); let resps = batcher.build(); - let last_idx = resps.len() - 1; + let resps_len = resps.len(); // Events are about to be sent, free pending events memory counter. memory_quota.free(bytes as _); for (i, e) in resps.into_iter().enumerate() { // Buffer messages and flush them at once. - let write_flags = WriteFlags::default().buffer_hint(i != last_idx); + let write_flags = WriteFlags::default().buffer_hint(i + 1 != resps_len); sink.feed((e, write_flags)).await?; } sink.flush().await?; diff --git a/components/cdc/tests/mod.rs b/components/cdc/tests/mod.rs index 8368c2792d5..9858e246373 100644 --- a/components/cdc/tests/mod.rs +++ b/components/cdc/tests/mod.rs @@ -104,11 +104,13 @@ impl TestSuiteBuilder { } } + #[must_use] pub fn cluster(mut self, cluster: Cluster) -> TestSuiteBuilder { self.cluster = Some(cluster); self } + #[must_use] pub fn memory_quota(mut self, memory_quota: usize) -> TestSuiteBuilder { self.memory_quota = Some(memory_quota); self diff --git a/components/encryption/src/file_dict_file.rs b/components/encryption/src/file_dict_file.rs index 196a860a861..b2553be3344 100644 --- a/components/encryption/src/file_dict_file.rs +++ b/components/encryption/src/file_dict_file.rs @@ -548,14 +548,14 @@ mod tests { ) .unwrap(); - file_dict.insert(&"f1".to_owned(), &info1).unwrap(); - file_dict.insert(&"f2".to_owned(), &info2).unwrap(); - file_dict.insert(&"f3".to_owned(), &info3).unwrap(); + file_dict.insert("f1", &info1).unwrap(); + file_dict.insert("f2", &info2).unwrap(); + file_dict.insert("f3", &info3).unwrap(); file_dict.insert("f4", &info4).unwrap(); file_dict.remove("f3").unwrap(); - file_dict.remove(&"f2".to_owned()).unwrap(); + file_dict.remove("f2").unwrap(); } // Try open as v1 file. Should fail. { diff --git a/components/encryption/src/io.rs b/components/encryption/src/io.rs index 1cdb1b0560f..842257be372 100644 --- a/components/encryption/src/io.rs +++ b/components/encryption/src/io.rs @@ -399,10 +399,7 @@ impl CrypterCore { fn reset_buffer(&mut self, size: usize) { // OCrypter require the output buffer to have block_size extra bytes, or it will panic. - self.buffer.reserve(size + self.block_size); - unsafe { - self.buffer.set_len(size + self.block_size); - } + self.buffer.resize(size + self.block_size, 0); } pub fn reset_crypter(&mut self, offset: u64) -> IoResult<()> { diff --git a/components/engine_rocks/src/config.rs b/components/engine_rocks/src/config.rs index ec9aa6f9348..369c63530c3 100644 --- a/components/engine_rocks/src/config.rs +++ b/components/engine_rocks/src/config.rs @@ -199,7 +199,7 @@ pub mod compression_type_serde { "disable" => DBCompressionType::Disable, _ => { return Err(E::invalid_value( - Unexpected::Other(&"invalid compression type".to_string()), + Unexpected::Other("invalid compression type"), &self, )); } diff --git a/components/engine_rocks/src/properties.rs b/components/engine_rocks/src/properties.rs index eb244908f51..773ae81dc6a 100644 --- a/components/engine_rocks/src/properties.rs +++ b/components/engine_rocks/src/properties.rs @@ -598,19 +598,19 @@ mod tests { assert_eq!(props.get_approximate_keys_in_range(b"", b"k"), 11_u64); assert_eq!(props.offsets.len(), 7); - let a = props.get(b"a".as_ref()); + let a = props.get(b"a"); assert_eq!(a.size, 1); - let e = props.get(b"e".as_ref()); + let e = props.get(b"e"); assert_eq!(e.size, DEFAULT_PROP_SIZE_INDEX_DISTANCE + 5); - let i = props.get(b"i".as_ref()); + let i = props.get(b"i"); assert_eq!(i.size, DEFAULT_PROP_SIZE_INDEX_DISTANCE / 8 * 17 + 9); - let k = props.get(b"k".as_ref()); + let k = props.get(b"k"); assert_eq!(k.size, DEFAULT_PROP_SIZE_INDEX_DISTANCE / 8 * 25 + 11); - let m = props.get(b"m".as_ref()); + let m = props.get(b"m"); assert_eq!(m.keys, 11 + DEFAULT_PROP_KEYS_INDEX_DISTANCE); - let n = props.get(b"n".as_ref()); + let n = props.get(b"n"); assert_eq!(n.keys, 11 + 2 * DEFAULT_PROP_KEYS_INDEX_DISTANCE); - let o = props.get(b"o".as_ref()); + let o = props.get(b"o"); assert_eq!(o.keys, 12 + 2 * DEFAULT_PROP_KEYS_INDEX_DISTANCE); let empty = RangeOffsets::default(); let cases = [ diff --git a/components/engine_traits/src/options.rs b/components/engine_traits/src/options.rs index 19676d6a313..2891872b77f 100644 --- a/components/engine_traits/src/options.rs +++ b/components/engine_traits/src/options.rs @@ -29,7 +29,7 @@ impl Default for ReadOptions { } } -#[derive(Clone)] +#[derive(Clone, Default)] pub struct WriteOptions { sync: bool, no_slowdown: bool, @@ -60,15 +60,6 @@ impl WriteOptions { } } -impl Default for WriteOptions { - fn default() -> WriteOptions { - WriteOptions { - sync: false, - no_slowdown: false, - } - } -} - #[derive(Clone, PartialEq)] pub enum SeekMode { TotalOrder, diff --git a/components/engine_traits/src/sst.rs b/components/engine_traits/src/sst.rs index 033e7eb2ee5..3c88998148b 100644 --- a/components/engine_traits/src/sst.rs +++ b/components/engine_traits/src/sst.rs @@ -66,17 +66,22 @@ where fn new() -> Self; /// Set DB for the builder. The builder may need some config from the DB. + #[must_use] fn set_db(self, db: &E) -> Self; /// Set CF for the builder. The builder may need some config from the CF. + #[must_use] fn set_cf(self, cf: &str) -> Self; /// Set it to true, the builder builds a in-memory SST builder. + #[must_use] fn set_in_memory(self, in_memory: bool) -> Self; /// set other config specified by writer + #[must_use] fn set_compression_type(self, compression: Option) -> Self; + #[must_use] fn set_compression_level(self, level: i32) -> Self; /// Builder a SstWriter. diff --git a/components/file_system/src/lib.rs b/components/file_system/src/lib.rs index 0f06295f756..dd06443cff1 100644 --- a/components/file_system/src/lib.rs +++ b/components/file_system/src/lib.rs @@ -1,7 +1,7 @@ // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. #![feature(test)] -#![feature(duration_consts_2)] +#![feature(duration_consts_float)] #[macro_use] extern crate lazy_static; @@ -108,18 +108,12 @@ impl Drop for WithIOType { } #[repr(C)] -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Copy, Clone, Default)] pub struct IOBytes { read: u64, write: u64, } -impl Default for IOBytes { - fn default() -> Self { - IOBytes { read: 0, write: 0 } - } -} - impl std::ops::Sub for IOBytes { type Output = Self; diff --git a/components/raftstore/src/coprocessor/split_check/table.rs b/components/raftstore/src/coprocessor/split_check/table.rs index e24258ead63..3e6ed691dd4 100644 --- a/components/raftstore/src/coprocessor/split_check/table.rs +++ b/components/raftstore/src/coprocessor/split_check/table.rs @@ -344,8 +344,8 @@ mod tests { type Case = (Option>, Option>, Option); let mut check_cases = |cases: Vec| { for (encoded_start_key, encoded_end_key, table_id) in cases { - region.set_start_key(encoded_start_key.unwrap_or_else(Vec::new)); - region.set_end_key(encoded_end_key.unwrap_or_else(Vec::new)); + region.set_start_key(encoded_start_key.unwrap_or_default()); + region.set_end_key(encoded_end_key.unwrap_or_default()); runnable.run(SplitCheckTask::split_check( region.clone(), true, diff --git a/components/raftstore/src/lib.rs b/components/raftstore/src/lib.rs index 3bfe0990651..844e47e3525 100644 --- a/components/raftstore/src/lib.rs +++ b/components/raftstore/src/lib.rs @@ -2,7 +2,6 @@ #![cfg_attr(test, feature(test))] #![feature(cell_update)] -#![feature(shrink_to)] #![feature(div_duration)] #![feature(min_specialization)] #![feature(box_patterns)] diff --git a/components/raftstore/src/store/fsm/apply.rs b/components/raftstore/src/store/fsm/apply.rs index 53c292c8a1b..1ca6724f17d 100644 --- a/components/raftstore/src/store/fsm/apply.rs +++ b/components/raftstore/src/store/fsm/apply.rs @@ -4794,9 +4794,7 @@ mod tests { #[derive(Clone, Default)] struct ApplyObserver { - pre_admin_count: Arc, pre_query_count: Arc, - post_admin_count: Arc, post_query_count: Arc, cmd_sink: Option>>>, } diff --git a/components/raftstore/src/store/fsm/peer.rs b/components/raftstore/src/store/fsm/peer.rs index 06e1092bff6..378f81a8ac2 100644 --- a/components/raftstore/src/store/fsm/peer.rs +++ b/components/raftstore/src/store/fsm/peer.rs @@ -889,7 +889,7 @@ where // FIXME: should use `bcast_check_stale_peer_message` instead. // Sending a new enum type msg to a old tikv may cause panic during rolling update // we should change the protobuf behavior and check if properly handled in all place - self.fsm.peer.bcast_wake_up_message(&mut self.ctx); + self.fsm.peer.bcast_wake_up_message(self.ctx); } } CasualMessage::SnapshotGenerated => { @@ -920,7 +920,7 @@ where .iter() .any(|p| p.get_id() == self.fsm.peer_id()) { - self.fsm.peer.send_wake_up_message(&mut self.ctx, &leader); + self.fsm.peer.send_wake_up_message(self.ctx, &leader); } } CasualMessage::RejectRaftAppend { peer_id } => { @@ -930,7 +930,7 @@ where msg.from = self.fsm.peer.peer_id(); let raft_msg = self.fsm.peer.build_raft_messages(self.ctx, vec![msg]); - self.fsm.peer.send_raft_messages(&mut self.ctx, raft_msg); + self.fsm.peer.send_raft_messages(self.ctx, raft_msg); } } } @@ -1695,9 +1695,7 @@ where } } - if result.is_err() { - return result; - } + result?; if self.fsm.peer.any_new_peer_catch_up(from_peer_id) { self.fsm.peer.heartbeat_pd(self.ctx); @@ -2289,7 +2287,7 @@ where match self .fsm .peer - .ready_to_transfer_leader(&mut self.ctx, msg.get_index(), &from) + .ready_to_transfer_leader(self.ctx, msg.get_index(), &from) { Some(reason) => { info!( @@ -2337,12 +2335,9 @@ where } } } else { - self.fsm.peer.execute_transfer_leader( - &mut self.ctx, - msg.get_from(), - peer_disk_usage, - false, - ); + self.fsm + .peer + .execute_transfer_leader(self.ctx, msg.get_from(), peer_disk_usage, false); } } @@ -3336,7 +3331,7 @@ where .as_ref() .unwrap() .get_commit(), - &mut self.ctx, + self.ctx, ); } } @@ -4632,7 +4627,7 @@ where "expect" => %self.ctx.cfg.max_leader_missing_duration, ); - self.fsm.peer.bcast_check_stale_peer_message(&mut self.ctx); + self.fsm.peer.bcast_check_stale_peer_message(self.ctx); let task = PdTask::ValidatePeer { peer: self.fsm.peer.peer.clone(), @@ -4736,7 +4731,7 @@ where // As the leader can propose the TransferLeader request successfully, the disk of // the leader is probably not full. self.fsm.peer.execute_transfer_leader( - &mut self.ctx, + self.ctx, self.fsm.peer.leader_id(), DiskUsage::Normal, true, diff --git a/components/raftstore/src/store/fsm/store.rs b/components/raftstore/src/store/fsm/store.rs index e6b44ec3f52..1c68b39053a 100644 --- a/components/raftstore/src/store/fsm/store.rs +++ b/components/raftstore/src/store/fsm/store.rs @@ -859,9 +859,21 @@ impl PollHandler, St self.tag, self.poll_ctx.pending_count, self.poll_ctx.ready_count, - self.poll_ctx.raft_metrics.ready.append - self.previous_metrics.append, - self.poll_ctx.raft_metrics.ready.message - self.previous_metrics.message, - self.poll_ctx.raft_metrics.ready.snapshot - self.previous_metrics.snapshot + self.poll_ctx + .raft_metrics + .ready + .append + .saturating_sub(self.previous_metrics.append), + self.poll_ctx + .raft_metrics + .ready + .message + .saturating_sub(self.previous_metrics.message), + self.poll_ctx + .raft_metrics + .ready + .snapshot + .saturating_sub(self.previous_metrics.snapshot), ); dur } else { @@ -1263,7 +1275,7 @@ impl RaftBatchSystem { } pub fn refresh_config_scheduler(&mut self) -> Scheduler { - assert!(!self.workers.is_none()); + assert!(self.workers.is_some()); self.workers .as_ref() .unwrap() diff --git a/components/raftstore/src/store/local_metrics.rs b/components/raftstore/src/store/local_metrics.rs index 76b9bd6ba1f..9f0544307d8 100644 --- a/components/raftstore/src/store/local_metrics.rs +++ b/components/raftstore/src/store/local_metrics.rs @@ -297,7 +297,7 @@ impl RaftProposeMetrics { } /// The buffered metrics counter for invalid propose -#[derive(Clone)] +#[derive(Clone, Default)] pub struct RaftInvalidProposeMetrics { pub mismatch_store_id: u64, pub region_not_found: u64, @@ -310,22 +310,6 @@ pub struct RaftInvalidProposeMetrics { pub is_applying_snapshot: u64, } -impl Default for RaftInvalidProposeMetrics { - fn default() -> RaftInvalidProposeMetrics { - RaftInvalidProposeMetrics { - mismatch_store_id: 0, - region_not_found: 0, - not_leader: 0, - mismatch_peer_id: 0, - stale_command: 0, - epoch_not_match: 0, - read_index_no_leader: 0, - region_not_initialized: 0, - is_applying_snapshot: 0, - } - } -} - impl RaftInvalidProposeMetrics { fn flush(&mut self) { if self.mismatch_store_id > 0 { @@ -385,23 +369,13 @@ impl RaftInvalidProposeMetrics { } } -#[derive(Clone)] +#[derive(Clone, Default)] pub struct RaftLogGcSkippedMetrics { pub reserve_log: u64, pub threshold_limit: u64, pub compact_idx_too_small: u64, } -impl Default for RaftLogGcSkippedMetrics { - fn default() -> RaftLogGcSkippedMetrics { - RaftLogGcSkippedMetrics { - reserve_log: 0, - threshold_limit: 0, - compact_idx_too_small: 0, - } - } -} - impl RaftLogGcSkippedMetrics { fn flush(&mut self) { if self.reserve_log > 0 { diff --git a/components/raftstore/src/store/snap.rs b/components/raftstore/src/store/snap.rs index 97154d645fa..e7eb56107e4 100644 --- a/components/raftstore/src/store/snap.rs +++ b/components/raftstore/src/store/snap.rs @@ -1490,14 +1490,17 @@ pub struct SnapManagerBuilder { } impl SnapManagerBuilder { + #[must_use] pub fn max_write_bytes_per_sec(mut self, bytes: i64) -> SnapManagerBuilder { self.max_write_bytes_per_sec = bytes; self } + #[must_use] pub fn max_total_size(mut self, bytes: u64) -> SnapManagerBuilder { self.max_total_size = bytes; self } + #[must_use] pub fn encryption_key_manager(mut self, m: Option>) -> SnapManagerBuilder { self.key_manager = m; self diff --git a/components/raftstore/src/store/snap/io.rs b/components/raftstore/src/store/snap/io.rs index 42365db9f85..16c3e8b27b9 100644 --- a/components/raftstore/src/store/snap/io.rs +++ b/components/raftstore/src/store/snap/io.rs @@ -303,8 +303,8 @@ mod tests { cf, 16, |v| { - v.to_owned() - .into_iter() + v.iter() + .cloned() .for_each(|pair| applied_keys.entry(cf).or_default().push(pair)) }, ) diff --git a/components/raftstore/src/store/worker/query_stats.rs b/components/raftstore/src/store/worker/query_stats.rs index 46ea5b37686..01b9ba72c6d 100644 --- a/components/raftstore/src/store/worker/query_stats.rs +++ b/components/raftstore/src/store/worker/query_stats.rs @@ -68,6 +68,7 @@ impl QueryStats { } } + #[must_use] pub fn sub_query_stats(&self, query_stats: &QueryStats) -> QueryStats { let mut res = QueryStats::default(); for kind in QUERY_KINDS { diff --git a/components/raftstore/src/store/worker/region.rs b/components/raftstore/src/store/worker/region.rs index 60000319939..67ee76e70a5 100644 --- a/components/raftstore/src/store/worker/region.rs +++ b/components/raftstore/src/store/worker/region.rs @@ -805,8 +805,7 @@ mod tests { // when we want to insert [g, q), we first extract overlap ranges, // which are [f, i), [m, n), [p, t) let timeout2 = 12; - let overlap_ranges = - pending_delete_ranges.drain_overlap_ranges(&b"g".to_vec(), &b"q".to_vec()); + let overlap_ranges = pending_delete_ranges.drain_overlap_ranges(b"g", b"q"); assert_eq!( overlap_ranges, [ diff --git a/components/raftstore/src/store/worker/split_controller.rs b/components/raftstore/src/store/worker/split_controller.rs index 71c2f2b5c8b..a7f20f42954 100644 --- a/components/raftstore/src/store/worker/split_controller.rs +++ b/components/raftstore/src/store/worker/split_controller.rs @@ -300,7 +300,7 @@ impl Recorder { } } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] pub struct WriteStats { pub region_infos: HashMap, } @@ -319,14 +319,6 @@ impl WriteStats { } } -impl Default for WriteStats { - fn default() -> WriteStats { - WriteStats { - region_infos: HashMap::default(), - } - } -} - #[derive(Clone, Debug)] pub struct ReadStats { pub region_infos: HashMap, diff --git a/components/resolved_ts/src/cmd.rs b/components/resolved_ts/src/cmd.rs index b9c3cfa3d10..70a930fd7ac 100644 --- a/components/resolved_ts/src/cmd.rs +++ b/components/resolved_ts/src/cmd.rs @@ -33,6 +33,7 @@ pub enum ChangeRow { }, } +#[allow(clippy::large_enum_variant)] pub enum ChangeLog { Error(errorpb::Error), Rows { index: u64, rows: Vec }, diff --git a/components/resource_metering/src/lib.rs b/components/resource_metering/src/lib.rs index 4f045714bd7..472771d64a5 100644 --- a/components/resource_metering/src/lib.rs +++ b/components/resource_metering/src/lib.rs @@ -2,7 +2,6 @@ // TODO(mornyx): crate doc. -#![feature(shrink_to)] #![feature(hash_drain_filter)] #![feature(core_intrinsics)] diff --git a/components/resource_metering/src/model.rs b/components/resource_metering/src/model.rs index f4ae1539934..7d8d23ffd36 100644 --- a/components/resource_metering/src/model.rs +++ b/components/resource_metering/src/model.rs @@ -328,6 +328,7 @@ impl SummaryRecord { } /// Gets the value and writes it to zero. + #[must_use] pub fn take_and_reset(&self) -> Self { Self { read_keys: AtomicU32::new(self.read_keys.swap(0, Relaxed)), diff --git a/components/resource_metering/src/recorder/mod.rs b/components/resource_metering/src/recorder/mod.rs index 56cc699132e..d2cc9e67378 100644 --- a/components/resource_metering/src/recorder/mod.rs +++ b/components/resource_metering/src/recorder/mod.rs @@ -238,12 +238,14 @@ impl Default for RecorderBuilder { impl RecorderBuilder { /// Sets the precision_ms parameter of [Recorder]. + #[must_use] pub fn precision_ms(mut self, precision_ms: u64) -> Self { self.precision_ms = precision_ms; self } /// Add a [SubRecorder] for the execution of [Recorder]. + #[must_use] pub fn add_sub_recorder(mut self, r: Box) -> Self { self.recorders.push(r); self diff --git a/components/resource_metering/tests/summary_test.rs b/components/resource_metering/tests/summary_test.rs index b6f42f12090..1186f3a50d8 100644 --- a/components/resource_metering/tests/summary_test.rs +++ b/components/resource_metering/tests/summary_test.rs @@ -69,7 +69,7 @@ fn test_summary() { resource_metering::record_write_keys(456); } thread::sleep(Duration::from_millis(REPORT_INTERVAL_MS + 500)); // wait report - assert!(data_sink.get(&b"TAG-1".to_vec()).is_none()); + assert!(data_sink.get(b"TAG-1").is_none()); data_sink.clear(); }) .join() @@ -95,7 +95,7 @@ fn test_summary() { } thread::sleep(Duration::from_millis(REPORT_INTERVAL_MS + 500)); // wait report - let r = data_sink.get(&b"TAG-1".to_vec()).unwrap(); + let r = data_sink.get(b"TAG-1").unwrap(); assert_eq!( r.get_record() .get_items() @@ -133,7 +133,7 @@ fn test_summary() { resource_metering::record_write_keys(456); } thread::sleep(Duration::from_millis(REPORT_INTERVAL_MS + 500)); // wait report - assert!(data_sink.get(&b"TAG-1".to_vec()).is_none()); + assert!(data_sink.get(b"TAG-1").is_none()); data_sink.clear(); }) .join() diff --git a/components/security/src/lib.rs b/components/security/src/lib.rs index e4cc41f915a..901a9c78b7e 100644 --- a/components/security/src/lib.rs +++ b/components/security/src/lib.rs @@ -17,7 +17,7 @@ use grpcio::{ ServerCredentialsFetcher, }; -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)] #[serde(default)] #[serde(rename_all = "kebab-case")] pub struct SecurityConfig { @@ -33,20 +33,6 @@ pub struct SecurityConfig { pub encryption: EncryptionConfig, } -impl Default for SecurityConfig { - fn default() -> SecurityConfig { - SecurityConfig { - ca_path: String::new(), - cert_path: String::new(), - key_path: String::new(), - override_ssl_target: String::new(), - cert_allowed_cn: HashSet::default(), - redact_info_log: None, - encryption: EncryptionConfig::default(), - } - } -} - /// Checks and opens key file. Returns `Ok(None)` if the path is empty. /// /// # Arguments diff --git a/components/test_coprocessor/src/column.rs b/components/test_coprocessor/src/column.rs index f17de1e84dc..c10cbb7650c 100644 --- a/components/test_coprocessor/src/column.rs +++ b/components/test_coprocessor/src/column.rs @@ -62,11 +62,13 @@ impl ColumnBuilder { } } + #[must_use] pub fn col_type(mut self, t: i32) -> ColumnBuilder { self.col_type = t; self } + #[must_use] pub fn primary_key(mut self, b: bool) -> ColumnBuilder { if b { self.index = 0; @@ -76,11 +78,13 @@ impl ColumnBuilder { self } + #[must_use] pub fn index_key(mut self, idx_id: i64) -> ColumnBuilder { self.index = idx_id; self } + #[must_use] pub fn default(mut self, val: Datum) -> ColumnBuilder { self.default_val = Some(val); self diff --git a/components/test_coprocessor/src/dag.rs b/components/test_coprocessor/src/dag.rs index dd2d74b9034..1b7812efb20 100644 --- a/components/test_coprocessor/src/dag.rs +++ b/components/test_coprocessor/src/dag.rs @@ -78,11 +78,13 @@ impl DAGSelect { } } + #[must_use] pub fn limit(mut self, n: u64) -> DAGSelect { self.limit = Some(n); self } + #[must_use] pub fn order_by(mut self, col: &Column, desc: bool) -> DAGSelect { let col_offset = offset_for_column(&self.cols, col.id); let mut item = ByItem::default(); @@ -96,10 +98,12 @@ impl DAGSelect { self } + #[must_use] pub fn count(self, col: &Column) -> DAGSelect { self.aggr_col(col, ExprType::Count) } + #[must_use] pub fn aggr_col(mut self, col: &Column, aggr_t: ExprType) -> DAGSelect { let col_offset = offset_for_column(&self.cols, col.id); let mut col_expr = Expr::default(); @@ -119,38 +123,47 @@ impl DAGSelect { self } + #[must_use] pub fn first(self, col: &Column) -> DAGSelect { self.aggr_col(col, ExprType::First) } + #[must_use] pub fn sum(self, col: &Column) -> DAGSelect { self.aggr_col(col, ExprType::Sum) } + #[must_use] pub fn avg(self, col: &Column) -> DAGSelect { self.aggr_col(col, ExprType::Avg) } + #[must_use] pub fn max(self, col: &Column) -> DAGSelect { self.aggr_col(col, ExprType::Max) } + #[must_use] pub fn min(self, col: &Column) -> DAGSelect { self.aggr_col(col, ExprType::Min) } + #[must_use] pub fn bit_and(self, col: &Column) -> DAGSelect { self.aggr_col(col, ExprType::AggBitAnd) } + #[must_use] pub fn bit_or(self, col: &Column) -> DAGSelect { self.aggr_col(col, ExprType::AggBitOr) } + #[must_use] pub fn bit_xor(self, col: &Column) -> DAGSelect { self.aggr_col(col, ExprType::AggBitXor) } + #[must_use] pub fn group_by(mut self, cols: &[&Column]) -> DAGSelect { for col in cols { let offset = offset_for_column(&self.cols, col.id); @@ -163,11 +176,13 @@ impl DAGSelect { self } + #[must_use] pub fn output_offsets(mut self, output_offsets: Option>) -> DAGSelect { self.output_offsets = output_offsets; self } + #[must_use] pub fn where_expr(mut self, expr: Expr) -> DAGSelect { let mut exec = Executor::default(); exec.set_tp(ExecType::TypeSelection); @@ -178,17 +193,20 @@ impl DAGSelect { self } + #[must_use] pub fn desc(mut self, desc: bool) -> DAGSelect { self.execs[0].mut_tbl_scan().set_desc(desc); self } + #[must_use] pub fn paging_size(mut self, paging_size: u64) -> DAGSelect { assert_ne!(paging_size, 0); self.paging_size = Some(paging_size); self } + #[must_use] pub fn key_ranges(mut self, key_ranges: Vec) -> DAGSelect { self.key_ranges = key_ranges; self diff --git a/components/test_coprocessor/src/store.rs b/components/test_coprocessor/src/store.rs index cd7ab240309..a8cce9e3022 100644 --- a/components/test_coprocessor/src/store.rs +++ b/components/test_coprocessor/src/store.rs @@ -32,6 +32,7 @@ impl<'a, E: Engine> Insert<'a, E> { } } + #[must_use] pub fn set(mut self, col: &Column, value: Datum) -> Self { assert!(self.table.column_by_id(col.id).is_some()); self.values.insert(col.id, value); diff --git a/components/test_coprocessor/src/table.rs b/components/test_coprocessor/src/table.rs index fa0660cc716..0cf2646e489 100644 --- a/components/test_coprocessor/src/table.rs +++ b/components/test_coprocessor/src/table.rs @@ -138,6 +138,7 @@ impl TableBuilder { } } + #[must_use] pub fn add_col(mut self, name: impl std::borrow::Borrow, col: Column) -> TableBuilder { use std::cmp::Ordering::*; diff --git a/components/test_raftstore/src/cluster.rs b/components/test_raftstore/src/cluster.rs index ef15ddea433..2dc96a2bdc8 100644 --- a/components/test_raftstore/src/cluster.rs +++ b/components/test_raftstore/src/cluster.rs @@ -737,15 +737,14 @@ impl Cluster { pub fn shutdown(&mut self) { debug!("about to shutdown cluster"); - let keys; - match self.sim.read() { - Ok(s) => keys = s.get_node_ids(), + let keys = match self.sim.read() { + Ok(s) => s.get_node_ids(), Err(_) => { safe_panic!("failed to acquire read lock"); // Leave the resource to avoid double panic. return; } - } + }; for id in keys { self.stop_node(id); } diff --git a/components/test_raftstore/src/transport_simulate.rs b/components/test_raftstore/src/transport_simulate.rs index b7c95d75eda..767304f3f02 100644 --- a/components/test_raftstore/src/transport_simulate.rs +++ b/components/test_raftstore/src/transport_simulate.rs @@ -434,37 +434,44 @@ impl RegionPacketFilter { } } + #[must_use] pub fn direction(mut self, direction: Direction) -> RegionPacketFilter { self.direction = direction; self } // TODO: rename it to `drop`. + #[must_use] pub fn msg_type(mut self, m_type: MessageType) -> RegionPacketFilter { self.drop_type.push(m_type); self } + #[must_use] pub fn skip(mut self, m_type: MessageType) -> RegionPacketFilter { self.skip_type.push(m_type); self } + #[must_use] pub fn allow(mut self, number: usize) -> RegionPacketFilter { self.block = Either::Left(Arc::new(AtomicUsize::new(number))); self } + #[must_use] pub fn when(mut self, condition: Arc) -> RegionPacketFilter { self.block = Either::Right(condition); self } + #[must_use] pub fn reserve_dropped(mut self, dropped: Arc>>) -> RegionPacketFilter { self.dropped_messages = Some(dropped); self } + #[must_use] pub fn set_msg_callback( mut self, cb: Arc, diff --git a/components/test_storage/src/sync_storage.rs b/components/test_storage/src/sync_storage.rs index 2bf7b550a05..60c1492015d 100644 --- a/components/test_storage/src/sync_storage.rs +++ b/components/test_storage/src/sync_storage.rs @@ -59,11 +59,13 @@ impl SyncTestStorageBuilder { } } + #[must_use] pub fn config(mut self, config: Config) -> Self { self.config = Some(config); self } + #[must_use] pub fn gc_config(mut self, gc_config: GcConfig) -> Self { self.gc_config = Some(gc_config); self @@ -154,8 +156,8 @@ impl SyncTestStorage { ) -> Result>>> { let mut ids = vec![]; let requests: Vec = keys - .to_owned() - .into_iter() + .iter() + .copied() .map(|key| { let mut req = GetRequest::default(); req.set_context(ctx.clone()); diff --git a/components/tidb_query_datatype/src/builder/field_type.rs b/components/tidb_query_datatype/src/builder/field_type.rs index 663445bc1e5..8b443ef4921 100644 --- a/components/tidb_query_datatype/src/builder/field_type.rs +++ b/components/tidb_query_datatype/src/builder/field_type.rs @@ -13,31 +13,37 @@ impl FieldTypeBuilder { Default::default() } + #[must_use] pub fn tp(mut self, v: crate::FieldTypeTp) -> Self { FieldTypeAccessor::set_tp(&mut self.0, v); self } + #[must_use] pub fn flag(mut self, v: crate::FieldTypeFlag) -> Self { FieldTypeAccessor::set_flag(&mut self.0, v); self } + #[must_use] pub fn flen(mut self, v: isize) -> Self { FieldTypeAccessor::set_flen(&mut self.0, v); self } + #[must_use] pub fn decimal(mut self, v: isize) -> Self { FieldTypeAccessor::set_decimal(&mut self.0, v); self } + #[must_use] pub fn collation(mut self, v: crate::Collation) -> Self { FieldTypeAccessor::set_collation(&mut self.0, v); self } + #[must_use] pub fn charset(mut self, v: &str) -> Self { self.0.set_charset(String::from(v)); self diff --git a/components/tidb_query_datatype/src/codec/batch/lazy_column.rs b/components/tidb_query_datatype/src/codec/batch/lazy_column.rs index a861aac4dc9..ca57b84f36d 100644 --- a/components/tidb_query_datatype/src/codec/batch/lazy_column.rs +++ b/components/tidb_query_datatype/src/codec/batch/lazy_column.rs @@ -54,6 +54,7 @@ impl LazyBatchColumn { /// Creates a new empty `LazyBatchColumn` with the same schema. #[inline] + #[must_use] pub fn clone_empty(&self, capacity: usize) -> Self { match self { LazyBatchColumn::Raw(_) => Self::raw_with_capacity(capacity), diff --git a/components/tidb_query_datatype/src/codec/batch/lazy_column_vec.rs b/components/tidb_query_datatype/src/codec/batch/lazy_column_vec.rs index e180c22e3f3..e492fa32c91 100644 --- a/components/tidb_query_datatype/src/codec/batch/lazy_column_vec.rs +++ b/components/tidb_query_datatype/src/codec/batch/lazy_column_vec.rs @@ -48,6 +48,7 @@ impl LazyBatchColumnVec { /// Creates a new empty `LazyBatchColumnVec` with the same number of columns and schema. #[inline] + #[must_use] pub fn clone_empty(&self, capacity: usize) -> Self { Self { columns: self @@ -60,6 +61,7 @@ impl LazyBatchColumnVec { /// Creates a new `LazyBatchColumnVec`, which contains `columns_count` number of raw columns. #[cfg(test)] + #[must_use] pub fn with_raw_columns(columns_count: usize) -> Self { let mut columns = Vec::with_capacity(columns_count); for _ in 0..columns_count { diff --git a/components/tidb_query_datatype/src/codec/data_type/chunked_vec_bytes.rs b/components/tidb_query_datatype/src/codec/data_type/chunked_vec_bytes.rs index a5d1c909ef0..4ade7a7dc06 100644 --- a/components/tidb_query_datatype/src/codec/data_type/chunked_vec_bytes.rs +++ b/components/tidb_query_datatype/src/codec/data_type/chunked_vec_bytes.rs @@ -238,10 +238,7 @@ mod tests { None, ]; assert_eq!(ChunkedVecBytes::from_slice(test_bytes).to_vec(), test_bytes); - assert_eq!( - ChunkedVecBytes::from_slice(&test_bytes.to_vec()).to_vec(), - test_bytes - ); + assert_eq!(ChunkedVecBytes::from_slice(test_bytes).to_vec(), test_bytes); } #[test] diff --git a/components/tidb_query_datatype/src/codec/data_type/chunked_vec_json.rs b/components/tidb_query_datatype/src/codec/data_type/chunked_vec_json.rs index a092c301e60..fd03420d45f 100644 --- a/components/tidb_query_datatype/src/codec/data_type/chunked_vec_json.rs +++ b/components/tidb_query_datatype/src/codec/data_type/chunked_vec_json.rs @@ -146,10 +146,7 @@ mod tests { None, ]; assert_eq!(ChunkedVecJson::from_slice(test_json).to_vec(), test_json); - assert_eq!( - ChunkedVecJson::from_slice(&test_json.to_vec()).to_vec(), - test_json - ); + assert_eq!(ChunkedVecJson::from_slice(test_json).to_vec(), test_json); } #[test] diff --git a/components/tidb_query_datatype/src/codec/data_type/vector.rs b/components/tidb_query_datatype/src/codec/data_type/vector.rs index 21b5c01b085..3e545bef6be 100644 --- a/components/tidb_query_datatype/src/codec/data_type/vector.rs +++ b/components/tidb_query_datatype/src/codec/data_type/vector.rs @@ -39,6 +39,7 @@ impl VectorValue { /// Creates a new empty `VectorValue` with the same eval type. #[inline] + #[must_use] pub fn clone_empty(&self, capacity: usize) -> Self { match_template_evaltype! { TT, match self { diff --git a/components/tidb_query_datatype/src/codec/mysql/duration.rs b/components/tidb_query_datatype/src/codec/mysql/duration.rs index c68fc3dbb48..eb522b2981f 100644 --- a/components/tidb_query_datatype/src/codec/mysql/duration.rs +++ b/components/tidb_query_datatype/src/codec/mysql/duration.rs @@ -307,6 +307,7 @@ impl Duration { } #[inline] + #[must_use] pub fn minimize_fsp(self) -> Self { Duration { fsp: MIN_FSP as u8, @@ -315,6 +316,7 @@ impl Duration { } #[inline] + #[must_use] pub fn maximize_fsp(self) -> Self { Duration { fsp: MAX_FSP as u8, @@ -366,6 +368,7 @@ impl Duration { /// Returns the absolute value of `Duration` #[inline] + #[must_use] pub fn abs(self) -> Self { Duration { nanos: self.nanos.abs(), diff --git a/components/tidb_query_datatype/src/codec/mysql/json/json_modify.rs b/components/tidb_query_datatype/src/codec/mysql/json/json_modify.rs index 159ca66530f..71881162da2 100644 --- a/components/tidb_query_datatype/src/codec/mysql/json/json_modify.rs +++ b/components/tidb_query_datatype/src/codec/mysql/json/json_modify.rs @@ -220,7 +220,7 @@ mod tests { json, "#{} expect modified json {:?} == {:?}", i, - json.to_string(), + json, expected.to_string() ); } else { diff --git a/components/tidb_query_datatype/src/codec/mysql/time/mod.rs b/components/tidb_query_datatype/src/codec/mysql/time/mod.rs index 0c047acc8f5..2a81d807518 100755 --- a/components/tidb_query_datatype/src/codec/mysql/time/mod.rs +++ b/components/tidb_query_datatype/src/codec/mysql/time/mod.rs @@ -1964,7 +1964,7 @@ mod tests { use std::sync::Arc; - #[derive(Debug)] + #[derive(Debug, Default)] struct TimeEnv { strict_mode: bool, no_zero_in_date: bool, @@ -1974,19 +1974,6 @@ mod tests { time_zone: Option, } - impl Default for TimeEnv { - fn default() -> TimeEnv { - TimeEnv { - strict_mode: false, - no_zero_in_date: false, - no_zero_date: false, - allow_invalid_date: false, - ignore_truncate: false, - time_zone: None, - } - } - } - impl From for EvalContext { fn from(config: TimeEnv) -> EvalContext { let mut eval_config = EvalConfig::new(); diff --git a/components/tidb_query_datatype/src/codec/mysql/time/weekmode.rs b/components/tidb_query_datatype/src/codec/mysql/time/weekmode.rs index 0b97d0b8096..09ddef98e05 100644 --- a/components/tidb_query_datatype/src/codec/mysql/time/weekmode.rs +++ b/components/tidb_query_datatype/src/codec/mysql/time/weekmode.rs @@ -9,6 +9,7 @@ bitflags::bitflags! { } impl WeekMode { + #[must_use] pub fn to_normalized(self) -> WeekMode { let mut mode = self; if !mode.contains(WeekMode::BEHAVIOR_MONDAY_FIRST) { diff --git a/components/tidb_query_datatype/src/codec/row/v2/encoder_for_test.rs b/components/tidb_query_datatype/src/codec/row/v2/encoder_for_test.rs index d82351cd8b2..7c3ddcc16b2 100644 --- a/components/tidb_query_datatype/src/codec/row/v2/encoder_for_test.rs +++ b/components/tidb_query_datatype/src/codec/row/v2/encoder_for_test.rs @@ -62,6 +62,7 @@ impl Column { &self.ft } + #[must_use] pub fn with_tp(mut self, tp: FieldTypeTp) -> Self { self.ft.as_mut_accessor().set_tp(tp); self @@ -71,11 +72,13 @@ impl Column { self.ft.is_unsigned() } + #[must_use] pub fn with_unsigned(mut self) -> Self { self.ft.as_mut_accessor().set_flag(FieldTypeFlag::UNSIGNED); self } + #[must_use] pub fn with_decimal(mut self, decimal: isize) -> Self { self.ft.as_mut_accessor().set_decimal(decimal); self diff --git a/components/tidb_query_executors/src/runner.rs b/components/tidb_query_executors/src/runner.rs index 6e9df1011c7..4f46351f4b9 100644 --- a/components/tidb_query_executors/src/runner.rs +++ b/components/tidb_query_executors/src/runner.rs @@ -162,13 +162,13 @@ pub fn build_executors( .next() .ok_or_else(|| other_err!("No executors"))?; - let mut executor: Box>; let mut summary_slot_index = 0; // Limit executor use this flag to check if its src is table/index scan. // Performance enhancement for plan like: limit 1 -> table/index scan. let mut is_src_scan_executor = true; - match first_ed.get_tp() { + let mut executor: Box> = match first_ed.get_tp() + { ExecType::TypeTableScan => { EXECUTOR_COUNT_METRICS.batch_table_scan.inc(); @@ -177,7 +177,7 @@ pub fn build_executors( let primary_column_ids = descriptor.take_primary_column_ids(); let primary_prefix_column_ids = descriptor.take_primary_prefix_column_ids(); - executor = Box::new( + Box::new( BatchTableScanExecutor::new( storage, config.clone(), @@ -189,7 +189,7 @@ pub fn build_executors( primary_prefix_column_ids, )? .collect_summary(summary_slot_index), - ); + ) } ExecType::TypeIndexScan => { EXECUTOR_COUNT_METRICS.batch_index_scan.inc(); @@ -197,7 +197,7 @@ pub fn build_executors( let mut descriptor = first_ed.take_idx_scan(); let columns_info = descriptor.take_columns().into(); let primary_column_ids_len = descriptor.take_primary_column_ids().len(); - executor = Box::new( + Box::new( BatchIndexScanExecutor::new( storage, config.clone(), @@ -209,7 +209,7 @@ pub fn build_executors( is_scanned_range_aware, )? .collect_summary(summary_slot_index), - ); + ) } _ => { return Err(other_err!( @@ -217,12 +217,12 @@ pub fn build_executors( first_ed.get_tp() )); } - } + }; for mut ed in executor_descriptors { summary_slot_index += 1; - let new_executor: Box> = match ed.get_tp() { + executor = match ed.get_tp() { ExecType::TypeSelection => { EXECUTOR_COUNT_METRICS.batch_selection.inc(); @@ -331,7 +331,6 @@ pub fn build_executors( )); } }; - executor = new_executor; is_src_scan_executor = false; } diff --git a/components/tidb_query_executors/src/slow_hash_aggr_executor.rs b/components/tidb_query_executors/src/slow_hash_aggr_executor.rs index 6cdafb86644..13ecd652790 100644 --- a/components/tidb_query_executors/src/slow_hash_aggr_executor.rs +++ b/components/tidb_query_executors/src/slow_hash_aggr_executor.rs @@ -206,7 +206,7 @@ pub struct SlowHashAggregationImpl { /// element are stored in `group_key_offsets`. /// /// `GroupKeyRefUnsafe` contains a raw pointer to this buffer. - #[allow(clippy::box_vec)] + #[allow(clippy::box_collection)] group_key_buffer: Box>, /// The offsets of encoded keys in `group_key_buffer`. This `Vec` always has a leading `0` diff --git a/components/tidb_query_executors/src/top_n_executor.rs b/components/tidb_query_executors/src/top_n_executor.rs index a13585b0ed1..1c84d25b5e6 100644 --- a/components/tidb_query_executors/src/top_n_executor.rs +++ b/components/tidb_query_executors/src/top_n_executor.rs @@ -41,7 +41,7 @@ pub struct BatchTopNExecutor { /// /// This field is placed before `order_exprs` and `src` because it relies on data in /// those fields and we want this field to be dropped first. - #[allow(clippy::box_vec)] + #[allow(clippy::box_collection)] eval_columns_buffer_unsafe: Box>>, order_exprs: Box<[RpnExpression]>, diff --git a/components/tidb_query_expr/src/impl_cast.rs b/components/tidb_query_expr/src/impl_cast.rs index 4b9710efe09..ecba330cce8 100644 --- a/components/tidb_query_expr/src/impl_cast.rs +++ b/components/tidb_query_expr/src/impl_cast.rs @@ -516,12 +516,11 @@ fn cast_string_as_signed_real( match val { None => Ok(None), Some(val) => { - let r: f64; - if val.is_empty() { - r = 0.0; + let r = if val.is_empty() { + 0.0 } else { - r = val.convert(ctx)?; - } + val.convert(ctx)? + }; let r = produce_float_with_specified_tp(ctx, extra.ret_field_type, r)?; Ok(Real::new(r).ok()) } @@ -1558,6 +1557,7 @@ mod tests { assert!(r.is_none()); } + #[derive(Default)] struct CtxConfig { overflow_as_warning: bool, truncate_as_warning: bool, @@ -1566,18 +1566,6 @@ mod tests { in_update_or_delete_stmt: bool, } - impl Default for CtxConfig { - fn default() -> Self { - CtxConfig { - overflow_as_warning: false, - truncate_as_warning: false, - should_clip_to_zero: false, - in_insert_stmt: false, - in_update_or_delete_stmt: false, - } - } - } - impl From for EvalContext { fn from(config: CtxConfig) -> Self { let mut flag: Flag = Flag::empty(); @@ -6168,12 +6156,11 @@ mod tests { Ok(v) => match v { Some(dur) => { if expect_max { - let max_val_str: &str; - if dur.is_neg() { - max_val_str = "-838:59:59"; + let max_val_str = if dur.is_neg() { + "-838:59:59" } else { - max_val_str = "838:59:59"; - } + "838:59:59" + }; let max_expect = Duration::parse(&mut ctx, max_val_str, fsp); let log = format!( "func_name: {}, input: {}, output: {:?}, output_warn: {:?}, expect: {:?}", diff --git a/components/tidb_query_expr/src/impl_encryption.rs b/components/tidb_query_expr/src/impl_encryption.rs index a8930ea3b65..bac8140d294 100644 --- a/components/tidb_query_expr/src/impl_encryption.rs +++ b/components/tidb_query_expr/src/impl_encryption.rs @@ -304,7 +304,7 @@ mod tests { ]; for (s, exp) in cases { - let s = s.map(|inner| hex::decode(inner.as_bytes().to_vec()).unwrap()); + let s = s.map(|inner| hex::decode(inner.as_bytes()).unwrap()); let output = RpnFnScalarEvaluator::new() .push_param(s) .evaluate(ScalarFuncSig::UncompressedLength) @@ -383,7 +383,7 @@ mod tests { ), ]; for (arg, expect) in test_cases { - let expect = Some(hex::decode(expect.as_bytes().to_vec()).unwrap()); + let expect = Some(hex::decode(expect.as_bytes()).unwrap()); let output = RpnFnScalarEvaluator::new() .push_param(arg) diff --git a/components/tidb_query_expr/src/types/expr_builder.rs b/components/tidb_query_expr/src/types/expr_builder.rs index f2c2a3c44d1..564b5c67534 100644 --- a/components/tidb_query_expr/src/types/expr_builder.rs +++ b/components/tidb_query_expr/src/types/expr_builder.rs @@ -116,6 +116,7 @@ impl RpnExpressionBuilder { } /// Pushes a `FnCall` node. + #[must_use] pub fn push_fn_call_for_test( mut self, func_meta: RpnFnMeta, @@ -133,6 +134,7 @@ impl RpnExpressionBuilder { } #[cfg(test)] + #[must_use] pub fn push_fn_call_with_metadata( mut self, func_meta: RpnFnMeta, @@ -152,6 +154,7 @@ impl RpnExpressionBuilder { /// Pushes a `Constant` node. The field type will be auto inferred by choosing an arbitrary /// field type that matches the field type of the given value. + #[must_use] pub fn push_constant_for_test(mut self, value: impl Into) -> Self { let value = value.into(); let field_type = value @@ -165,6 +168,7 @@ impl RpnExpressionBuilder { /// Pushes a `Constant` node. #[cfg(test)] + #[must_use] pub fn push_constant_with_field_type( mut self, value: impl Into, @@ -179,6 +183,7 @@ impl RpnExpressionBuilder { } /// Pushes a `ColumnRef` node. + #[must_use] pub fn push_column_ref_for_test(mut self, offset: usize) -> Self { let node = RpnExpressionNode::ColumnRef { offset }; self.0.push(node); diff --git a/components/tidb_query_expr/src/types/test_util.rs b/components/tidb_query_expr/src/types/test_util.rs index 90884276053..0c2ecab2f12 100644 --- a/components/tidb_query_expr/src/types/test_util.rs +++ b/components/tidb_query_expr/src/types/test_util.rs @@ -35,11 +35,13 @@ impl RpnFnScalarEvaluator { /// Pushes a parameter as the value of an argument for evaluation. The field type will be auto /// inferred by choosing an arbitrary field type that matches the field type of the given /// value. + #[must_use] pub fn push_param(mut self, value: impl Into) -> Self { self.rpn_expr_builder = self.rpn_expr_builder.push_constant_for_test(value); self } + #[must_use] pub fn push_params(mut self, values: impl IntoIterator>) -> Self { for value in values { self.rpn_expr_builder = self.rpn_expr_builder.push_constant_for_test(value); @@ -48,6 +50,7 @@ impl RpnFnScalarEvaluator { } /// Pushes a parameter as the value of an argument for evaluation using a specified field type. + #[must_use] pub fn push_param_with_field_type( mut self, value: impl Into, @@ -63,6 +66,7 @@ impl RpnFnScalarEvaluator { /// /// If not set, the evaluation will use an inferred return field type by choosing an arbitrary /// field type that matches the field type of the generic type `T` when calling `evaluate()`. + #[must_use] pub fn return_field_type(mut self, field_type: impl Into) -> Self { self.return_field_type = Some(field_type.into()); self @@ -71,12 +75,14 @@ impl RpnFnScalarEvaluator { /// Sets the context to use during evaluation. /// /// If not set, a default `EvalContext` will be used. + #[must_use] pub fn context(mut self, context: impl Into) -> Self { self.context = Some(context.into()); self } /// Sets the metadata to use during evaluation. + #[must_use] pub fn metadata(mut self, metadata: Box) -> Self { self.metadata = Some(metadata); self diff --git a/components/tikv_kv/src/cursor.rs b/components/tikv_kv/src/cursor.rs index 41916ec144f..55cd35162d1 100644 --- a/components/tikv_kv/src/cursor.rs +++ b/components/tikv_kv/src/cursor.rs @@ -459,6 +459,7 @@ impl<'a, S: 'a + Snapshot> CursorBuilder<'a, S> { /// /// Defaults to `true`. #[inline] + #[must_use] pub fn fill_cache(mut self, fill_cache: bool) -> Self { self.fill_cache = fill_cache; self @@ -468,6 +469,7 @@ impl<'a, S: 'a + Snapshot> CursorBuilder<'a, S> { /// /// Defaults to `false`, it means use total order seek. #[inline] + #[must_use] pub fn prefix_seek(mut self, prefix_seek: bool) -> Self { self.prefix_seek = prefix_seek; self @@ -477,6 +479,7 @@ impl<'a, S: 'a + Snapshot> CursorBuilder<'a, S> { /// /// Defaults to `ScanMode::Forward`. #[inline] + #[must_use] pub fn scan_mode(mut self, scan_mode: ScanMode) -> Self { self.scan_mode = scan_mode; self @@ -487,6 +490,7 @@ impl<'a, S: 'a + Snapshot> CursorBuilder<'a, S> { /// /// Both default to `None`. #[inline] + #[must_use] pub fn range(mut self, lower: Option, upper: Option) -> Self { self.lower_bound = lower; self.upper_bound = upper; @@ -497,6 +501,7 @@ impl<'a, S: 'a + Snapshot> CursorBuilder<'a, S> { /// /// Default is empty. #[inline] + #[must_use] pub fn hint_min_ts(mut self, min_ts: Option) -> Self { self.hint_min_ts = min_ts; self @@ -506,18 +511,21 @@ impl<'a, S: 'a + Snapshot> CursorBuilder<'a, S> { /// /// Default is empty. #[inline] + #[must_use] pub fn hint_max_ts(mut self, max_ts: Option) -> Self { self.hint_max_ts = max_ts; self } #[inline] + #[must_use] pub fn key_only(mut self, key_only: bool) -> Self { self.key_only = key_only; self } #[inline] + #[must_use] pub fn max_skippable_internal_keys(mut self, count: u64) -> Self { self.max_skippable_internal_keys = count; self diff --git a/components/tikv_kv/src/lib.rs b/components/tikv_kv/src/lib.rs index 6ebb45f7b22..291e83ebc35 100644 --- a/components/tikv_kv/src/lib.rs +++ b/components/tikv_kv/src/lib.rs @@ -147,7 +147,7 @@ impl WriteData { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Default)] pub struct SnapContext<'a> { pub pb_ctx: &'a Context, pub read_id: Option, @@ -157,17 +157,6 @@ pub struct SnapContext<'a> { pub key_ranges: Vec, } -impl<'a> Default for SnapContext<'a> { - fn default() -> Self { - SnapContext { - pb_ctx: Default::default(), - read_id: None, - start_ts: Default::default(), - key_ranges: Default::default(), - } - } -} - /// Engine defines the common behaviour for a storage engine type. pub trait Engine: Send + Clone + 'static { type Snap: Snapshot; diff --git a/components/tikv_kv/src/mock_engine.rs b/components/tikv_kv/src/mock_engine.rs index 555f1955bd2..ea343dfa9e9 100644 --- a/components/tikv_kv/src/mock_engine.rs +++ b/components/tikv_kv/src/mock_engine.rs @@ -36,6 +36,7 @@ impl ExpectedWrite { pub fn new() -> Self { Default::default() } + #[must_use] pub fn expect_modify(self, modify: Modify) -> Self { Self { modify: Some(modify), @@ -43,6 +44,7 @@ impl ExpectedWrite { use_committed_cb: self.use_committed_cb, } } + #[must_use] pub fn expect_proposed_cb(self) -> Self { Self { modify: self.modify, @@ -50,6 +52,7 @@ impl ExpectedWrite { use_committed_cb: self.use_committed_cb, } } + #[must_use] pub fn expect_no_proposed_cb(self) -> Self { Self { modify: self.modify, @@ -57,6 +60,7 @@ impl ExpectedWrite { use_committed_cb: self.use_committed_cb, } } + #[must_use] pub fn expect_committed_cb(self) -> Self { Self { modify: self.modify, @@ -64,6 +68,7 @@ impl ExpectedWrite { use_committed_cb: Some(true), } } + #[must_use] pub fn expect_no_committed_cb(self) -> Self { Self { modify: self.modify, @@ -196,6 +201,7 @@ impl MockEngineBuilder { } } + #[must_use] pub fn add_expected_write(mut self, write: ExpectedWrite) -> Self { match self.expected_modifies.as_mut() { Some(expected_modifies) => expected_modifies.push_back(write), diff --git a/components/tikv_util/src/lib.rs b/components/tikv_util/src/lib.rs index b1991663d28..b0d8dc7f739 100644 --- a/components/tikv_util/src/lib.rs +++ b/components/tikv_util/src/lib.rs @@ -395,6 +395,7 @@ impl MustConsumeVec { } } + #[must_use] pub fn take(&mut self) -> Self { MustConsumeVec { tag: self.tag, diff --git a/components/tikv_util/src/lru.rs b/components/tikv_util/src/lru.rs index b457e0f4c75..c4976261464 100644 --- a/components/tikv_util/src/lru.rs +++ b/components/tikv_util/src/lru.rs @@ -139,6 +139,7 @@ pub trait SizePolicy { fn on_reset(&mut self, val: usize); } +#[derive(Default)] pub struct CountTracker(usize); impl SizePolicy for CountTracker { @@ -159,12 +160,6 @@ impl SizePolicy for CountTracker { } } -impl Default for CountTracker { - fn default() -> Self { - Self(0) - } -} - pub struct LruCache where T: SizePolicy, diff --git a/components/tikv_util/src/worker/pool.rs b/components/tikv_util/src/worker/pool.rs index 01182382a22..66f1926bbb4 100644 --- a/components/tikv_util/src/worker/pool.rs +++ b/components/tikv_util/src/worker/pool.rs @@ -270,11 +270,13 @@ impl> Builder { } /// Pending tasks won't exceed `pending_capacity`. + #[must_use] pub fn pending_capacity(mut self, pending_capacity: usize) -> Self { self.pending_capacity = pending_capacity; self } + #[must_use] pub fn thread_count(mut self, thread_count: usize) -> Self { self.thread_count = thread_count; self diff --git a/components/tipb_helper/src/expr_def_builder.rs b/components/tipb_helper/src/expr_def_builder.rs index 020d8f3dd39..589ee1afbd6 100644 --- a/components/tipb_helper/src/expr_def_builder.rs +++ b/components/tipb_helper/src/expr_def_builder.rs @@ -79,6 +79,7 @@ impl ExprDefBuilder { Self(expr) } + #[must_use] pub fn push_child(mut self, child: impl Into) -> Self { self.0.mut_children().push(child.into()); self diff --git a/components/txn_types/src/lock.rs b/components/txn_types/src/lock.rs index d4955f3d229..67b70e2c9b1 100644 --- a/components/txn_types/src/lock.rs +++ b/components/txn_types/src/lock.rs @@ -132,12 +132,14 @@ impl Lock { } } + #[must_use] pub fn use_async_commit(mut self, secondaries: Vec>) -> Self { self.use_async_commit = true; self.secondaries = secondaries; self } + #[must_use] pub fn with_rollback_ts(mut self, rollback_ts: Vec) -> Self { self.rollback_ts = rollback_ts; self diff --git a/components/txn_types/src/timestamp.rs b/components/txn_types/src/timestamp.rs index 9f29516b901..1c2079a889f 100644 --- a/components/txn_types/src/timestamp.rs +++ b/components/txn_types/src/timestamp.rs @@ -33,11 +33,13 @@ impl TimeStamp { self.0 >> TSO_PHYSICAL_SHIFT_BITS } + #[must_use] pub fn next(self) -> TimeStamp { assert!(self.0 < u64::MAX); TimeStamp(self.0 + 1) } + #[must_use] pub fn prev(self) -> TimeStamp { assert!(self.0 > 0); TimeStamp(self.0 - 1) diff --git a/components/txn_types/src/types.rs b/components/txn_types/src/types.rs index bc00c5eb9a4..411866788d0 100644 --- a/components/txn_types/src/types.rs +++ b/components/txn_types/src/types.rs @@ -105,6 +105,7 @@ impl Key { /// Creates a new key by appending a `u64` timestamp to this key. #[inline] + #[must_use] pub fn append_ts(mut self, ts: TimeStamp) -> Key { self.0.encode_u64_desc(ts.into_inner()).unwrap(); self diff --git a/components/txn_types/src/write.rs b/components/txn_types/src/write.rs index 7e59157f4ee..844fc27df95 100644 --- a/components/txn_types/src/write.rs +++ b/components/txn_types/src/write.rs @@ -190,6 +190,7 @@ impl Write { } #[inline] + #[must_use] pub fn set_overlapped_rollback( mut self, has_overlapped_rollback: bool, diff --git a/rust-toolchain b/rust-toolchain index 08c09fbcd18..324e4c96b46 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1 +1 @@ -nightly-2021-07-28 +nightly-2022-01-07 diff --git a/scripts/clippy b/scripts/clippy index d21c8dbf8bd..f0f46fccfa6 100755 --- a/scripts/clippy +++ b/scripts/clippy @@ -29,7 +29,7 @@ CLIPPY_LINTS=(-A clippy::module_inception \ -A clippy::unnecessary_sort_by \ -A clippy::unnecessary_wraps \ -A clippy::bool_assert_comparison \ - -A clippy::self_named_constructor \ + -A clippy::self_named_constructors \ -A clippy::enum_variant_names \ -W clippy::dbg_macro \ -W clippy::todo \ diff --git a/src/config.rs b/src/config.rs index 3fcb467c096..a5812fd3fbd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -2964,12 +2964,12 @@ impl TiKvConfig { // as the shared cache size. let cache_cfg = &mut self.storage.block_cache; if cache_cfg.shared && cache_cfg.capacity.0.is_none() { - cache_cfg.capacity.0 = Some(ReadableSize { - 0: self.rocksdb.defaultcf.block_cache_size.0 + cache_cfg.capacity.0 = Some(ReadableSize( + self.rocksdb.defaultcf.block_cache_size.0 + self.rocksdb.writecf.block_cache_size.0 + self.rocksdb.lockcf.block_cache_size.0 + self.raftdb.defaultcf.block_cache_size.0, - }); + )); } if self.backup.sst_max_size.0 < default_coprocessor.region_max_size.0 / 10 { warn!( @@ -3240,7 +3240,7 @@ fn serde_to_online_config(name: String) -> String { "raftstore.apply_pool_size", "raft_store.apply_batch_system.pool_size", ), - _ => name.replace("raftstore", "raft_store").replace("-", "_"), + _ => name.replace("raftstore", "raft_store").replace('-', "_"), } } @@ -3363,9 +3363,9 @@ fn to_toml_encode(change: HashMap) -> CfgResult DagHandlerBuilder { } } + #[must_use] pub fn data_version(mut self, data_version: Option) -> Self { self.data_version = data_version; self diff --git a/src/coprocessor/statistics/analyze.rs b/src/coprocessor/statistics/analyze.rs index 9fe5be03b7f..d2a7e5943c4 100644 --- a/src/coprocessor/statistics/analyze.rs +++ b/src/coprocessor/statistics/analyze.rs @@ -650,23 +650,13 @@ impl RowSampleCollector for BernoulliRowSampleCollector { } } -#[derive(Clone)] +#[derive(Clone, Default)] struct ReservoirRowSampleCollector { base: BaseRowSampleCollector, samples: BinaryHeap>)>>, max_sample_size: usize, } -impl Default for ReservoirRowSampleCollector { - fn default() -> Self { - ReservoirRowSampleCollector { - base: Default::default(), - samples: BinaryHeap::new(), - max_sample_size: 0, - } - } -} - impl ReservoirRowSampleCollector { fn new( max_sample_size: usize, diff --git a/src/coprocessor/statistics/cmsketch.rs b/src/coprocessor/statistics/cmsketch.rs index 123f3019e95..c809b34c807 100644 --- a/src/coprocessor/statistics/cmsketch.rs +++ b/src/coprocessor/statistics/cmsketch.rs @@ -6,6 +6,7 @@ use murmur3::murmur3_x64_128; /// Refer:[Count-Min Sketch](https://en.wikipedia.org/wiki/Count-min_sketch) #[derive(Clone)] pub struct CmSketch { + #[allow(dead_code)] depth: usize, width: usize, count: u32, diff --git a/src/coprocessor_v2/config.rs b/src/coprocessor_v2/config.rs index 2574856f8c8..aeb92784e50 100644 --- a/src/coprocessor_v2/config.rs +++ b/src/coprocessor_v2/config.rs @@ -2,17 +2,9 @@ use std::path::PathBuf; -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)] #[serde(default)] #[serde(rename_all = "kebab-case")] pub struct Config { pub coprocessor_plugin_directory: Option, } - -impl Default for Config { - fn default() -> Config { - Config { - coprocessor_plugin_directory: None, - } - } -} diff --git a/src/coprocessor_v2/endpoint.rs b/src/coprocessor_v2/endpoint.rs index a00ff39eab5..761facbde3f 100644 --- a/src/coprocessor_v2/endpoint.rs +++ b/src/coprocessor_v2/endpoint.rs @@ -11,6 +11,7 @@ use super::plugin_registry::PluginRegistry; use super::raw_storage_impl::RawStorageImpl; use crate::storage::{self, lock_manager::LockManager, Engine, Storage}; +#[allow(clippy::large_enum_variant)] enum CoprocessorError { RegionError(kvproto::errorpb::Error), Other(String), diff --git a/src/lib.rs b/src/lib.rs index 37d310011eb..b0cf7549efa 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,7 +23,6 @@ #![feature(proc_macro_hygiene)] #![feature(min_specialization)] #![feature(box_patterns)] -#![feature(shrink_to)] #![feature(drain_filter)] #![feature(negative_impls)] #![feature(deadline_api)] diff --git a/src/server/gc_worker/gc_manager.rs b/src/server/gc_worker/gc_manager.rs index 5450a5d843b..637368318e7 100644 --- a/src/server/gc_worker/gc_manager.rs +++ b/src/server/gc_worker/gc_manager.rs @@ -206,9 +206,7 @@ impl GcManagerHandle { .stop_signal_sender .send(()) .map_err(|e| box_err!("failed to send stop signal to gc worker thread: {:?}", e)); - if res.is_err() { - return res; - } + res?; self.join_handle .join() .map_err(|e| box_err!("failed to join gc worker thread: {:?}", e)) diff --git a/src/server/lock_manager/client.rs b/src/server/lock_manager/client.rs index bc068a4d929..5b9dda7e006 100644 --- a/src/server/lock_manager/client.rs +++ b/src/server/lock_manager/client.rs @@ -30,7 +30,6 @@ pub fn env() -> Arc { #[derive(Clone)] pub struct Client { - addr: String, client: DeadlockClient, sender: Option>, } @@ -43,7 +42,6 @@ impl Client { let channel = security_mgr.connect(cb, addr); let client = DeadlockClient::new(channel); Self { - addr: addr.to_owned(), client, sender: None, } diff --git a/src/server/lock_manager/waiter_manager.rs b/src/server/lock_manager/waiter_manager.rs index 9bfa443b7f2..ce4f48fcc38 100644 --- a/src/server/lock_manager/waiter_manager.rs +++ b/src/server/lock_manager/waiter_manager.rs @@ -95,6 +95,7 @@ impl Future for Delay { pub type Callback = Box) + Send>; +#[allow(clippy::large_enum_variant)] pub enum Task { WaitFor { // which txn waits for the lock diff --git a/src/server/service/diagnostics/sys.rs b/src/server/service/diagnostics/sys.rs index 399101a9a06..f33394ffb43 100644 --- a/src/server/service/diagnostics/sys.rs +++ b/src/server/service/diagnostics/sys.rs @@ -485,7 +485,7 @@ fn get_sysctl_list() -> HashMap { let content = std::fs::read_to_string(entry.path()).ok()?; let path = entry.path().to_str()?; - let name = path.trim_start_matches(DIR).replace("/", "."); + let name = path.trim_start_matches(DIR).replace('/', "."); Some((name, content.trim().to_string())) }) .collect() diff --git a/src/storage/mod.rs b/src/storage/mod.rs index 34a06b9b24a..bc6796cae73 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -6495,6 +6495,7 @@ mod tests { test_pessimistic_lock_impl(true); } + #[allow(clippy::large_enum_variant)] pub enum Msg { WaitFor { start_ts: TimeStamp, diff --git a/src/storage/mvcc/reader/point_getter.rs b/src/storage/mvcc/reader/point_getter.rs index a651b1b256c..2cf3727e197 100644 --- a/src/storage/mvcc/reader/point_getter.rs +++ b/src/storage/mvcc/reader/point_getter.rs @@ -43,6 +43,7 @@ impl PointGetterBuilder { /// /// Defaults to `true`. #[inline] + #[must_use] pub fn multi(mut self, multi: bool) -> Self { self.multi = multi; self @@ -52,6 +53,7 @@ impl PointGetterBuilder { /// /// Defaults to `true`. #[inline] + #[must_use] pub fn fill_cache(mut self, fill_cache: bool) -> Self { self.fill_cache = fill_cache; self @@ -64,6 +66,7 @@ impl PointGetterBuilder { /// /// Defaults to `false`. #[inline] + #[must_use] pub fn omit_value(mut self, omit_value: bool) -> Self { self.omit_value = omit_value; self @@ -73,6 +76,7 @@ impl PointGetterBuilder { /// /// Defaults to `IsolationLevel::Si`. #[inline] + #[must_use] pub fn isolation_level(mut self, isolation_level: IsolationLevel) -> Self { self.isolation_level = isolation_level; self @@ -82,6 +86,7 @@ impl PointGetterBuilder { /// /// Defaults to none. #[inline] + #[must_use] pub fn bypass_locks(mut self, locks: TsSet) -> Self { self.bypass_locks = locks; self @@ -91,6 +96,7 @@ impl PointGetterBuilder { /// /// Defaults to none. #[inline] + #[must_use] pub fn access_locks(mut self, locks: TsSet) -> Self { self.access_locks = locks; self @@ -101,6 +107,7 @@ impl PointGetterBuilder { /// /// Default is false. #[inline] + #[must_use] pub fn check_has_newer_ts_data(mut self, enabled: bool) -> Self { self.check_has_newer_ts_data = enabled; self diff --git a/src/storage/mvcc/reader/scanner/backward.rs b/src/storage/mvcc/reader/scanner/backward.rs index 6f385985e4b..95a19421ef9 100644 --- a/src/storage/mvcc/reader/scanner/backward.rs +++ b/src/storage/mvcc/reader/scanner/backward.rs @@ -415,7 +415,7 @@ impl BackwardKvScanner { // Value is in the default CF. self.ensure_default_cursor()?; let value = super::near_reverse_load_data_by_write( - &mut self.default_cursor.as_mut().unwrap(), + self.default_cursor.as_mut().unwrap(), user_key, write.start_ts, &mut self.statistics, diff --git a/src/storage/mvcc/reader/scanner/forward.rs b/src/storage/mvcc/reader/scanner/forward.rs index a13b39303a7..3c836ce6526 100644 --- a/src/storage/mvcc/reader/scanner/forward.rs +++ b/src/storage/mvcc/reader/scanner/forward.rs @@ -2304,7 +2304,7 @@ mod delta_entry_tests { test_data .iter() .filter(|(key, ..)| *key >= from_key && (to_key.is_empty() || *key < to_key)) - .map(|(key, lock, writes)| { + .flat_map(|(key, lock, writes)| { let mut entries_of_key = vec![]; if let Some((ts, lock_type, value)) = lock { @@ -2351,7 +2351,6 @@ mod delta_entry_tests { entries_of_key }) - .flatten() .collect::>() }; diff --git a/src/storage/mvcc/reader/scanner/mod.rs b/src/storage/mvcc/reader/scanner/mod.rs index e72b2860c1f..794c68327a9 100644 --- a/src/storage/mvcc/reader/scanner/mod.rs +++ b/src/storage/mvcc/reader/scanner/mod.rs @@ -34,6 +34,7 @@ impl ScannerBuilder { /// /// Defaults to `true`. #[inline] + #[must_use] pub fn fill_cache(mut self, fill_cache: bool) -> Self { self.0.fill_cache = fill_cache; self @@ -46,6 +47,7 @@ impl ScannerBuilder { /// /// Defaults to `false`. #[inline] + #[must_use] pub fn omit_value(mut self, omit_value: bool) -> Self { self.0.omit_value = omit_value; self @@ -55,6 +57,7 @@ impl ScannerBuilder { /// /// Defaults to `IsolationLevel::Si`. #[inline] + #[must_use] pub fn isolation_level(mut self, isolation_level: IsolationLevel) -> Self { self.0.isolation_level = isolation_level; self @@ -64,6 +67,7 @@ impl ScannerBuilder { /// /// Default is 'false'. #[inline] + #[must_use] pub fn desc(mut self, desc: bool) -> Self { self.0.desc = desc; self @@ -74,6 +78,7 @@ impl ScannerBuilder { /// /// Default is `(None, None)`. #[inline] + #[must_use] pub fn range(mut self, lower_bound: Option, upper_bound: Option) -> Self { self.0.lower_bound = lower_bound; self.0.upper_bound = upper_bound; @@ -85,6 +90,7 @@ impl ScannerBuilder { /// /// Default is empty. #[inline] + #[must_use] pub fn bypass_locks(mut self, locks: TsSet) -> Self { self.0.bypass_locks = locks; self @@ -95,6 +101,7 @@ impl ScannerBuilder { /// /// Default is empty. #[inline] + #[must_use] pub fn access_locks(mut self, locks: TsSet) -> Self { self.0.access_locks = locks; self @@ -106,6 +113,7 @@ impl ScannerBuilder { /// /// NOTE: user should be careful to use it with `ExtraOp::ReadOldValue`. #[inline] + #[must_use] pub fn hint_min_ts(mut self, min_ts: Option) -> Self { self.0.hint_min_ts = min_ts; self @@ -117,6 +125,7 @@ impl ScannerBuilder { /// /// NOTE: user should be careful to use it with `ExtraOp::ReadOldValue`. #[inline] + #[must_use] pub fn hint_max_ts(mut self, max_ts: Option) -> Self { self.0.hint_max_ts = max_ts; self @@ -127,6 +136,7 @@ impl ScannerBuilder { /// /// Default is false. #[inline] + #[must_use] pub fn check_has_newer_ts_data(mut self, enabled: bool) -> Self { self.0.check_has_newer_ts_data = enabled; self diff --git a/src/storage/txn/commands/acquire_pessimistic_lock.rs b/src/storage/txn/commands/acquire_pessimistic_lock.rs index 1ab2fd01705..777cd77a577 100644 --- a/src/storage/txn/commands/acquire_pessimistic_lock.rs +++ b/src/storage/txn/commands/acquire_pessimistic_lock.rs @@ -74,16 +74,12 @@ fn extract_lock_info_from_result(res: &StorageResult) -> &LockInfo { } impl WriteCommand for AcquirePessimisticLock { - fn process_write( - mut self, - snapshot: S, - mut context: WriteContext<'_, L>, - ) -> Result { + fn process_write(mut self, snapshot: S, context: WriteContext<'_, L>) -> Result { let (start_ts, ctx, keys) = (self.start_ts, self.ctx, self.keys); let mut txn = MvccTxn::new(start_ts, context.concurrency_manager); let mut reader = ReaderWithStats::new( SnapshotReader::new_with_ctx(start_ts, snapshot, &ctx), - &mut context.statistics, + context.statistics, ); let rows = keys.len(); diff --git a/src/storage/txn/commands/check_secondary_locks.rs b/src/storage/txn/commands/check_secondary_locks.rs index e5ebf59de00..901bb4144d7 100644 --- a/src/storage/txn/commands/check_secondary_locks.rs +++ b/src/storage/txn/commands/check_secondary_locks.rs @@ -52,7 +52,7 @@ enum SecondaryLockStatus { } impl WriteCommand for CheckSecondaryLocks { - fn process_write(self, snapshot: S, mut context: WriteContext<'_, L>) -> Result { + fn process_write(self, snapshot: S, context: WriteContext<'_, L>) -> Result { // It is not allowed for commit to overwrite a protected rollback. So we update max_ts // to prevent this case from happening. context.concurrency_manager.update_max_ts(self.start_ts); @@ -60,7 +60,7 @@ impl WriteCommand for CheckSecondaryLocks { let mut txn = MvccTxn::new(self.start_ts, context.concurrency_manager); let mut reader = ReaderWithStats::new( SnapshotReader::new_with_ctx(self.start_ts, snapshot, &self.ctx), - &mut context.statistics, + context.statistics, ); let mut released_locks = ReleasedLocks::new(self.start_ts, TimeStamp::zero()); let mut result = SecondaryLocksStatus::Locked(Vec::new()); diff --git a/src/storage/txn/commands/check_txn_status.rs b/src/storage/txn/commands/check_txn_status.rs index cecc0544ffe..ee27fec67d6 100644 --- a/src/storage/txn/commands/check_txn_status.rs +++ b/src/storage/txn/commands/check_txn_status.rs @@ -64,7 +64,7 @@ impl WriteCommand for CheckTxnStatus { /// situation, `self.start_ts` is T2's `start_ts`, `caller_start_ts` is T1's `start_ts`, and /// the `current_ts` is literally the timestamp when this function is invoked; it may not be /// accurate. - fn process_write(self, snapshot: S, mut context: WriteContext<'_, L>) -> Result { + fn process_write(self, snapshot: S, context: WriteContext<'_, L>) -> Result { let mut new_max_ts = self.lock_ts; if !self.current_ts.is_max() && self.current_ts > new_max_ts { new_max_ts = self.current_ts; @@ -77,7 +77,7 @@ impl WriteCommand for CheckTxnStatus { let mut txn = MvccTxn::new(self.lock_ts, context.concurrency_manager); let mut reader = ReaderWithStats::new( SnapshotReader::new_with_ctx(self.lock_ts, snapshot, &self.ctx), - &mut context.statistics, + context.statistics, ); fail_point!("check_txn_status", |err| Err( diff --git a/src/storage/txn/commands/cleanup.rs b/src/storage/txn/commands/cleanup.rs index 87e9ae7e9e5..0b01f4ff311 100644 --- a/src/storage/txn/commands/cleanup.rs +++ b/src/storage/txn/commands/cleanup.rs @@ -39,7 +39,7 @@ impl CommandExt for Cleanup { } impl WriteCommand for Cleanup { - fn process_write(self, snapshot: S, mut context: WriteContext<'_, L>) -> Result { + fn process_write(self, snapshot: S, context: WriteContext<'_, L>) -> Result { // It is not allowed for commit to overwrite a protected rollback. So we update max_ts // to prevent this case from happening. context.concurrency_manager.update_max_ts(self.start_ts); @@ -47,7 +47,7 @@ impl WriteCommand for Cleanup { let mut txn = MvccTxn::new(self.start_ts, context.concurrency_manager); let mut reader = ReaderWithStats::new( SnapshotReader::new_with_ctx(self.start_ts, snapshot, &self.ctx), - &mut context.statistics, + context.statistics, ); let mut released_locks = ReleasedLocks::new(self.start_ts, TimeStamp::zero()); diff --git a/src/storage/txn/commands/commit.rs b/src/storage/txn/commands/commit.rs index 5857d9f9ef4..cd9774a1751 100644 --- a/src/storage/txn/commands/commit.rs +++ b/src/storage/txn/commands/commit.rs @@ -39,7 +39,7 @@ impl CommandExt for Commit { } impl WriteCommand for Commit { - fn process_write(self, snapshot: S, mut context: WriteContext<'_, L>) -> Result { + fn process_write(self, snapshot: S, context: WriteContext<'_, L>) -> Result { if self.commit_ts <= self.lock_ts { return Err(Error::from(ErrorInner::InvalidTxnTso { start_ts: self.lock_ts, @@ -49,7 +49,7 @@ impl WriteCommand for Commit { let mut txn = MvccTxn::new(self.lock_ts, context.concurrency_manager); let mut reader = ReaderWithStats::new( SnapshotReader::new_with_ctx(self.lock_ts, snapshot, &self.ctx), - &mut context.statistics, + context.statistics, ); let rows = self.keys.len(); diff --git a/src/storage/txn/commands/pessimistic_rollback.rs b/src/storage/txn/commands/pessimistic_rollback.rs index 381562c0305..4d8113d53a5 100644 --- a/src/storage/txn/commands/pessimistic_rollback.rs +++ b/src/storage/txn/commands/pessimistic_rollback.rs @@ -39,15 +39,11 @@ impl CommandExt for PessimisticRollback { impl WriteCommand for PessimisticRollback { /// Delete any pessimistic lock with small for_update_ts belongs to this transaction. - fn process_write( - mut self, - snapshot: S, - mut context: WriteContext<'_, L>, - ) -> Result { + fn process_write(mut self, snapshot: S, context: WriteContext<'_, L>) -> Result { let mut txn = MvccTxn::new(self.start_ts, context.concurrency_manager); let mut reader = ReaderWithStats::new( SnapshotReader::new_with_ctx(self.start_ts, snapshot, &self.ctx), - &mut context.statistics, + context.statistics, ); let ctx = mem::take(&mut self.ctx); diff --git a/src/storage/txn/commands/prewrite.rs b/src/storage/txn/commands/prewrite.rs index dbdf583c68d..46bff4d0915 100644 --- a/src/storage/txn/commands/prewrite.rs +++ b/src/storage/txn/commands/prewrite.rs @@ -389,7 +389,7 @@ impl Prewriter { let mut txn = MvccTxn::new(self.start_ts, context.concurrency_manager); let mut reader = ReaderWithStats::new( SnapshotReader::new_with_ctx(self.start_ts, snapshot, &self.ctx), - &mut context.statistics, + context.statistics, ); // Set extra op here for getting the write record when check write conflict in prewrite. diff --git a/src/storage/txn/commands/resolve_lock.rs b/src/storage/txn/commands/resolve_lock.rs index fc395b39b6f..0c750225362 100644 --- a/src/storage/txn/commands/resolve_lock.rs +++ b/src/storage/txn/commands/resolve_lock.rs @@ -63,17 +63,13 @@ impl CommandExt for ResolveLock { } impl WriteCommand for ResolveLock { - fn process_write( - mut self, - snapshot: S, - mut context: WriteContext<'_, L>, - ) -> Result { + fn process_write(mut self, snapshot: S, context: WriteContext<'_, L>) -> Result { let (ctx, txn_status, key_locks) = (self.ctx, self.txn_status, self.key_locks); let mut txn = MvccTxn::new(TimeStamp::zero(), context.concurrency_manager); let mut reader = ReaderWithStats::new( SnapshotReader::new_with_ctx(TimeStamp::zero(), snapshot, &ctx), - &mut context.statistics, + context.statistics, ); let mut scan_key = self.scan_key.take(); diff --git a/src/storage/txn/commands/resolve_lock_lite.rs b/src/storage/txn/commands/resolve_lock_lite.rs index 54698e87e5f..ccca17a556b 100644 --- a/src/storage/txn/commands/resolve_lock_lite.rs +++ b/src/storage/txn/commands/resolve_lock_lite.rs @@ -37,11 +37,11 @@ impl CommandExt for ResolveLockLite { } impl WriteCommand for ResolveLockLite { - fn process_write(self, snapshot: S, mut context: WriteContext<'_, L>) -> Result { + fn process_write(self, snapshot: S, context: WriteContext<'_, L>) -> Result { let mut txn = MvccTxn::new(self.start_ts, context.concurrency_manager); let mut reader = ReaderWithStats::new( SnapshotReader::new_with_ctx(self.start_ts, snapshot, &self.ctx), - &mut context.statistics, + context.statistics, ); let rows = self.resolve_keys.len(); diff --git a/src/storage/txn/commands/rollback.rs b/src/storage/txn/commands/rollback.rs index b8c69bedd1f..c05781c1734 100644 --- a/src/storage/txn/commands/rollback.rs +++ b/src/storage/txn/commands/rollback.rs @@ -35,11 +35,11 @@ impl CommandExt for Rollback { } impl WriteCommand for Rollback { - fn process_write(self, snapshot: S, mut context: WriteContext<'_, L>) -> Result { + fn process_write(self, snapshot: S, context: WriteContext<'_, L>) -> Result { let mut txn = MvccTxn::new(self.start_ts, context.concurrency_manager); let mut reader = ReaderWithStats::new( SnapshotReader::new_with_ctx(self.start_ts, snapshot, &self.ctx), - &mut context.statistics, + context.statistics, ); let rows = self.keys.len(); diff --git a/src/storage/txn/commands/txn_heart_beat.rs b/src/storage/txn/commands/txn_heart_beat.rs index 273d886753a..9b28af1a180 100644 --- a/src/storage/txn/commands/txn_heart_beat.rs +++ b/src/storage/txn/commands/txn_heart_beat.rs @@ -43,12 +43,12 @@ impl CommandExt for TxnHeartBeat { } impl WriteCommand for TxnHeartBeat { - fn process_write(self, snapshot: S, mut context: WriteContext<'_, L>) -> Result { + fn process_write(self, snapshot: S, context: WriteContext<'_, L>) -> Result { // TxnHeartBeat never remove locks. No need to wake up waiters. let mut txn = MvccTxn::new(self.start_ts, context.concurrency_manager); let mut reader = ReaderWithStats::new( SnapshotReader::new_with_ctx(self.start_ts, snapshot, &self.ctx), - &mut context.statistics, + context.statistics, ); fail_point!("txn_heart_beat", |err| Err( crate::storage::mvcc::Error::from(crate::storage::mvcc::txn::make_txn_error( diff --git a/src/storage/txn/flow_controller.rs b/src/storage/txn/flow_controller.rs index e63de54fa61..dbb109b5d61 100644 --- a/src/storage/txn/flow_controller.rs +++ b/src/storage/txn/flow_controller.rs @@ -91,7 +91,6 @@ impl Drop for FlowController { if let Err(e) = h.unwrap().join() { error!("join flow controller failed"; "err" => ?e); - return; } } } diff --git a/src/storage/txn/store.rs b/src/storage/txn/store.rs index 1cd94a822ec..cfa910b944d 100644 --- a/src/storage/txn/store.rs +++ b/src/storage/txn/store.rs @@ -70,9 +70,7 @@ pub trait Scanner: Send { } Ok(None) => break, Err( - e - @ - Error(box ErrorInner::Mvcc(MvccError(box MvccErrorInner::KeyIsLocked { + e @ Error(box ErrorInner::Mvcc(MvccError(box MvccErrorInner::KeyIsLocked { .. }))), ) => { @@ -175,7 +173,7 @@ impl TxnEntry { let v = WriteRef::parse(&write.1) .map_err(MvccError::from)? .to_owned(); - let v = v.short_value.unwrap_or_else(Vec::default); + let v = v.short_value.unwrap_or_default(); Ok((k, v)) } } diff --git a/tests/integrations/raftstore/test_replication_mode.rs b/tests/integrations/raftstore/test_replication_mode.rs index aa8ad427881..75f043647d3 100644 --- a/tests/integrations/raftstore/test_replication_mode.rs +++ b/tests/integrations/raftstore/test_replication_mode.rs @@ -449,7 +449,7 @@ fn test_assign_commit_groups_with_migrate_region() { // Split 1 region into 2 regions. let region = cluster.get_region(b""); - cluster.must_split(®ion, &b"k".to_vec()); + cluster.must_split(®ion, b"k"); // Put a key value pair. cluster.must_put(b"a1", b"v0"); cluster.must_put(b"k1", b"v0");