From 5c33a578f5d0df0d78f81b78ae748e6ca25b376a Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Tue, 27 Oct 2026 15:17:26 +0100 Subject: [PATCH 1/4] chore: fixing `cargo clippy` --- core/src/page.rs | 2 +- core/src/page_id.rs | 2 +- core/src/proof/multi_proof.rs | 32 ++--- core/src/proof/path_proof.rs | 12 +- core/src/trie_pos.rs | 10 +- core/src/update.rs | 20 +-- examples/witness_verification/src/main.rs | 2 +- fuzz/fuzz_targets/api_surface.rs | 4 +- fuzz/fuzz_targets/bitwise_memcpy.rs | 4 +- fuzz/fuzz_targets/reconstruct_key.rs | 8 +- nomt-test-utils/src/lib.rs | 2 +- nomt/src/beatree/allocator/free_list.rs | 17 ++- nomt/src/beatree/branch/node.rs | 36 ++--- nomt/src/beatree/index.rs | 2 +- nomt/src/beatree/iterator.rs | 33 +++-- nomt/src/beatree/leaf_cache.rs | 2 +- nomt/src/beatree/mod.rs | 6 +- nomt/src/beatree/ops/bit_ops.rs | 34 ++--- nomt/src/beatree/ops/mod.rs | 8 +- nomt/src/beatree/ops/overflow.rs | 4 +- nomt/src/beatree/ops/reconstruction.rs | 6 +- nomt/src/beatree/ops/update/branch_ops.rs | 24 ++-- nomt/src/beatree/ops/update/branch_stage.rs | 17 ++- nomt/src/beatree/ops/update/branch_updater.rs | 42 ++---- .../ops/update/extend_range_protocol.rs | 6 +- nomt/src/beatree/ops/update/leaf_stage.rs | 38 +++--- nomt/src/beatree/ops/update/leaf_updater.rs | 10 +- nomt/src/beatree/ops/update/tests.rs | 10 +- nomt/src/bitbox/ht_file.rs | 4 +- nomt/src/bitbox/mod.rs | 8 +- nomt/src/bitbox/wal/read.rs | 4 +- nomt/src/bitbox/wal/write.rs | 4 +- nomt/src/io/page_pool.rs | 3 +- nomt/src/io/unix.rs | 2 +- nomt/src/lib.rs | 4 +- nomt/src/merkle/page_set.rs | 8 +- nomt/src/merkle/page_walker.rs | 20 ++- nomt/src/merkle/seek.rs | 20 +-- nomt/src/merkle/worker.rs | 12 +- nomt/src/metrics.rs | 4 +- nomt/src/overlay.rs | 16 +-- nomt/src/page_cache.rs | 2 +- nomt/src/page_region.rs | 2 +- nomt/src/rw_pass_cell/mod.rs | 6 +- nomt/src/seglog/mod.rs | 127 +++++++++--------- nomt/src/seglog/segment_rw.rs | 18 +-- nomt/src/store/meta.rs | 2 +- nomt/src/store/mod.rs | 12 +- nomt/src/store/sync.rs | 2 +- nomt/src/task.rs | 2 +- nomt/tests/compute_root.rs | 2 +- nomt/tests/extend_range_protocol.rs | 4 +- nomt/tests/fill_and_empty.rs | 4 +- nomt/tests/last_layer_trie.rs | 2 +- nomt/tests/rollback.rs | 21 ++- nomt/tests/witness_check.rs | 10 +- torture/src/agent.rs | 4 +- torture/src/logging.rs | 4 +- torture/src/supervisor/controller.rs | 4 +- torture/src/supervisor/mod.rs | 6 +- torture/src/supervisor/resource.rs | 9 +- torture/src/supervisor/workload.rs | 20 +-- trickfs/src/latency.rs | 2 +- trickfs/src/lib.rs | 4 +- 64 files changed, 366 insertions(+), 405 deletions(-) diff --git a/core/src/page.rs b/core/src/page.rs index 158151b787..8890a088a1 100644 --- a/core/src/page.rs +++ b/core/src/page.rs @@ -25,7 +25,7 @@ pub const DEPTH: usize = 6; // Total number of nodes stored in one Page. It depends on the `DEPTH` // of the rootless sub-binary tree stored in a page following this formula: // (2^(DEPTH + 1)) - 2 -pub const NODES_PER_PAGE: usize = (1 << DEPTH + 1) - 2; +pub const NODES_PER_PAGE: usize = (1 << (DEPTH + 1)) - 2; /// A raw, unsized page data slice. pub type RawPage = [[u8; 32]]; diff --git a/core/src/page_id.rs b/core/src/page_id.rs index 2b98daa2d4..99b0eabe32 100644 --- a/core/src/page_id.rs +++ b/core/src/page_id.rs @@ -99,7 +99,7 @@ impl PageId { let leading_zeros = uint.leading_zeros(); let bit_count = 256 - leading_zeros; - let sextets = (bit_count + 5) / 6; + let sextets = bit_count.div_ceil(6); if bit_count == 0 { return Ok(ROOT_PAGE_ID); diff --git a/core/src/proof/multi_proof.rs b/core/src/proof/multi_proof.rs index c90815b1c7..ca0b21caed 100644 --- a/core/src/proof/multi_proof.rs +++ b/core/src/proof/multi_proof.rs @@ -252,7 +252,7 @@ impl MultiProof { match proof_range.step(&path_proofs) { PathProofRangeStep::Bisect { left, right } => { // insert collected common siblings - siblings.extend(common_siblings.drain(..)); + siblings.append(&mut common_siblings); // push into the stack the right Bisection and work on the left one proof_range = left; @@ -341,7 +341,7 @@ impl VerifiedMultiProof { /// Fails if the key is out of the scope of this proof. pub fn confirm_value(&self, expected_leaf: &LeafData) -> Result { let index = self.find_index_for(&expected_leaf.key_path)?; - Ok(self.confirm_value_inner(&expected_leaf, index)) + Ok(self.confirm_value_inner(expected_leaf, index)) } /// Check whether the specific path with index `index` proves that a key has no value in @@ -395,7 +395,7 @@ impl VerifiedMultiProof { path.terminal.path()[..depth] == expected_leaf.key_path.view_bits::()[..depth]; if in_scope { - Ok(self.confirm_value_inner(&expected_leaf, index)) + Ok(self.confirm_value_inner(expected_leaf, index)) } else { Err(KeyOutOfScope) } @@ -468,7 +468,7 @@ pub fn verify( inner: verified_paths, bisections: verified_bisections, siblings: multi_proof.siblings.clone(), - root: root, + root, }) } @@ -670,12 +670,12 @@ impl CommonSiblings { while self .bisection_stack .last() - .map_or(false, |b| b.start_depth >= depth) + .is_some_and(|b| b.start_depth >= depth) { let _ = self.bisection_stack.pop(); } - while self.stack.last().map_or(false, |(d, _)| *d >= depth) { + while self.stack.last().is_some_and(|(d, _)| *d >= depth) { let _ = self.stack.pop(); } } @@ -689,7 +689,7 @@ impl CommonSiblings { } fn pop_if_at_depth(&mut self, depth: usize) -> Option { - if self.stack.last().map_or(false, |(d, _)| *d == depth) { + if self.stack.last().is_some_and(|(d, _)| *d == depth) { self.stack.pop().map(|(_, n)| n) } else { None @@ -752,7 +752,7 @@ pub fn verify_update( &[] }; - common_siblings.advance(&proof); + common_siblings.advance(proof); hash_and_compact_terminal::( &mut pending_siblings, terminal, @@ -784,7 +784,7 @@ pub fn verify_update( } // if this is either the first op or this has the same terminal as the previous op... - if last_terminal_index.map_or(true, |x| x == next_terminal_index) { + if last_terminal_index.is_none_or(|x| x == next_terminal_index) { last_terminal_index = Some(next_terminal_index); working_ops.push((key, op)); continue; @@ -801,7 +801,7 @@ pub fn verify_update( let terminal = &proof.inner[terminal_index]; let next_terminal = Some(&proof.inner[terminal_index + 1]); - common_siblings.advance(&proof); + common_siblings.advance(proof); hash_and_compact_terminal::( &mut pending_siblings, terminal, @@ -812,12 +812,12 @@ pub fn verify_update( } // ingest the currently updated terminal. - let ops = core::mem::replace(&mut working_ops, Vec::new()); + let ops = std::mem::take(&mut working_ops); working_ops.push((key, op)); let terminal = &proof.inner[updated_index]; let next_terminal = proof.inner.get(updated_index + 1); - common_siblings.advance(&proof); + common_siblings.advance(proof); hash_and_compact_terminal::( &mut pending_siblings, @@ -862,7 +862,7 @@ fn hash_and_compact_terminal( skip // go to root }; - let ops = crate::update::leaf_ops_spliced(leaf, &ops); + let ops = crate::update::leaf_ops_spliced(leaf, ops); let sub_root = crate::update::build_trie::(skip, ops, |_| {}); let mut cur_node = sub_root; @@ -878,7 +878,7 @@ fn hash_and_compact_terminal( .rev() .take(up_layers) { - let sibling = if pending_siblings.last().map_or(false, |p| p.1 == cur_layer) { + let sibling = if pending_siblings.last().is_some_and(|p| p.1 == cur_layer) { // is this even possible? maybe not. but being extra cautious... let _ = common_siblings.pop_if_at_depth(cur_layer); // UNWRAP: guaranteed to exist. @@ -1409,7 +1409,7 @@ mod tests { let v1 = Blake3Hasher::hash_leaf(&leaf_1); let v2 = Blake3Hasher::hash_leaf(&leaf_2); let s3 = Blake3Hasher::hash_internal(&InternalData { - left: v0.clone(), + left: v0, right: v2, }); let root = Blake3Hasher::hash_internal(&InternalData { @@ -1472,7 +1472,7 @@ mod tests { let v1 = Blake3Hasher::hash_leaf(&leaf_1); let v2 = Blake3Hasher::hash_leaf(&leaf_2); let s3 = Blake3Hasher::hash_internal(&InternalData { - left: v0.clone(), + left: v0, right: v2, }); let root = Blake3Hasher::hash_internal(&InternalData { diff --git a/core/src/proof/path_proof.rs b/core/src/proof/path_proof.rs index e893c366bb..b14f401f35 100644 --- a/core/src/proof/path_proof.rs +++ b/core/src/proof/path_proof.rs @@ -27,7 +27,7 @@ impl PathProofTerminal { /// Return the bit-path to the Terminal Node pub fn path(&self) -> &BitSlice { match self { - Self::Leaf(leaf_data) => &leaf_data.key_path.view_bits(), + Self::Leaf(leaf_data) => leaf_data.key_path.view_bits(), Self::Terminator(key_path) => key_path.path(), } } @@ -118,8 +118,8 @@ pub fn hash_path( }; let next = InternalData { - left: left.clone(), - right: right.clone(), + left, + right, }; node = H::hash_internal(&next); } @@ -197,7 +197,7 @@ impl VerifiedPathProof { self.in_scope(key_path).map(|_| { self.terminal() .as_ref() - .map_or(true, |d| &d.key_path != key_path) + .is_none_or(|d| &d.key_path != key_path) }) } @@ -303,7 +303,7 @@ pub fn verify_update( // left frontier let mut pending_siblings: Vec<(Node, usize)> = Vec::new(); for (i, path) in paths.iter().enumerate() { - let leaf = path.inner.terminal().map(|x| x.clone()); + let leaf = path.inner.terminal().cloned(); let ops = &path.ops; let skip = path.inner.path().len(); @@ -335,7 +335,7 @@ pub fn verify_update( .take(up_layers) .zip(path.inner.siblings.iter().rev()) { - let sibling = if pending_siblings.last().map_or(false, |p| p.1 == cur_layer) { + let sibling = if pending_siblings.last().is_some_and(|p| p.1 == cur_layer) { // unwrap: checked above pending_siblings.pop().unwrap().0 } else { diff --git a/core/src/trie_pos.rs b/core/src/trie_pos.rs index 422eb9cc2c..d3c5280ec8 100644 --- a/core/src/trie_pos.rs +++ b/core/src/trie_pos.rs @@ -101,7 +101,7 @@ impl TriePosition { TriePosition { path, depth, - node_index: node_index(&page_path), + node_index: node_index(page_path), } } @@ -170,7 +170,7 @@ impl TriePosition { #[inline] pub fn down(&mut self, bit: bool) { assert_ne!(self.depth, 256, "can't descend past 256 bits"); - if self.depth as usize % DEPTH == 0 { + if (self.depth as usize).is_multiple_of(DEPTH) { self.node_index = bit as usize; } else { let children = self.child_node_indices(); @@ -201,8 +201,8 @@ impl TriePosition { } self.depth = new_depth; - let prev_page_depth = (prev_depth as usize + DEPTH - 1) / DEPTH; - let new_page_depth = (self.depth as usize + DEPTH - 1) / DEPTH; + let prev_page_depth = (prev_depth as usize).div_ceil(DEPTH); + let new_page_depth = (self.depth as usize).div_ceil(DEPTH); if prev_page_depth == new_page_depth { for _ in 0..d { self.node_index = parent_node_index(self.node_index); @@ -364,7 +364,7 @@ fn bottom_node_index(node_index: usize) -> u8 { /// Given a node index, get the index of the sibling. fn sibling_index(node_index: usize) -> usize { - if node_index % 2 == 0 { + if node_index.is_multiple_of(2) { node_index + 1 } else { node_index - 1 diff --git a/core/src/update.rs b/core/src/update.rs index f86f3a3ae6..3471708452 100644 --- a/core/src/update.rs +++ b/core/src/update.rs @@ -30,10 +30,10 @@ pub fn leaf_ops_spliced( // splice: before / item / after // skip deleted. ops[..splice_index] - .into_iter() + .iter() .cloned() .chain(preserve_value) - .chain(ops[splice_index..].into_iter().cloned()) + .chain(ops[splice_index..].iter().cloned()) .filter_map(|(k, o)| o.map(move |value| (k, value))) } @@ -220,7 +220,7 @@ pub fn build_trie( { layer -= 1; - let sibling = if pending_siblings.last().map_or(false, |l| l.1 == layer + 1) { + let sibling = if pending_siblings.last().is_some_and(|l| l.1 == layer + 1) { // unwrap: just checked pending_siblings.pop().unwrap().0 } else { @@ -252,11 +252,11 @@ pub fn build_trie( c = leaf_ops.next(); } - let new_root = pending_siblings + + pending_siblings .pop() .map(|n| n.0) - .unwrap_or(trie::TERMINATOR); - new_root + .unwrap_or(trie::TERMINATOR) } #[cfg(test)] @@ -304,8 +304,8 @@ mod tests { fn leaf(key: u8) -> (LeafData, [u8; 32]) { let key = [key; 32]; let leaf = trie::LeafData { - key_path: key.clone(), - value_hash: key.clone(), + key_path: key, + value_hash: key, }; let hash = DummyNodeHasher::hash_leaf(&leaf); @@ -315,8 +315,8 @@ mod tests { fn branch_hash(left: [u8; 32], right: [u8; 32]) -> [u8; 32] { let data = trie::InternalData { left, right }; - let hash = DummyNodeHasher::hash_internal(&data); - hash + + DummyNodeHasher::hash_internal(&data) } #[derive(Default)] diff --git a/examples/witness_verification/src/main.rs b/examples/witness_verification/src/main.rs index 724948b61e..ea1355ddd8 100644 --- a/examples/witness_verification/src/main.rs +++ b/examples/witness_verification/src/main.rs @@ -14,7 +14,7 @@ fn main() -> Result<()> { // Constructing the verified operations let verified = witnessed_path .inner - .verify::(&witnessed_path.path.path(), prev_root.into_inner()) + .verify::(witnessed_path.path.path(), prev_root.into_inner()) .unwrap(); // Among all read operations performed the ones that interact diff --git a/fuzz/fuzz_targets/api_surface.rs b/fuzz/fuzz_targets/api_surface.rs index 930ed176bd..6cd1aaa8f4 100644 --- a/fuzz/fuzz_targets/api_surface.rs +++ b/fuzz/fuzz_targets/api_surface.rs @@ -249,7 +249,7 @@ impl Context { }; let mut buf = vec![0; size]; input.fill_buffer(&mut buf)?; - Ok(Some(buf.into())) + Ok(Some(buf)) } else { Ok(None) } @@ -399,7 +399,7 @@ impl<'a> Arbitrary<'a> for NomtCalls { } } - session.sort_unstable_by(|(a, _), (b, _)| a.cmp(b)); + session.sort_unstable_by_key(|(a, _)| *a); // Now having an idea what the session would look like we should create the calls to the // api. diff --git a/fuzz/fuzz_targets/bitwise_memcpy.rs b/fuzz/fuzz_targets/bitwise_memcpy.rs index 29e1b1e9b4..f80ae4e1c3 100644 --- a/fuzz/fuzz_targets/bitwise_memcpy.rs +++ b/fuzz/fuzz_targets/bitwise_memcpy.rs @@ -51,7 +51,7 @@ impl<'a> Arbitrary<'a> for Run { // Destination must be long enough to store the source. let destination_bit_start = input.int_in_range(0..=7)?; - let min_destination_len = (destination_bit_start + source.bit_len + 7) / 8; + let min_destination_len = (destination_bit_start + source.bit_len).div_ceil(8); let destination_len = input.int_in_range(min_destination_len..=MAX_BYTES_LEN)?; let mut destination_bytes = vec![0; destination_len]; input.fill_buffer(&mut destination_bytes)?; @@ -70,7 +70,7 @@ impl<'a> Arbitrary<'a> for Run { impl<'a> Arbitrary<'a> for Source { fn arbitrary(input: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result { - let bytes_len = (input.int_in_range(0..=MAX_BYTES_LEN)? as usize).next_multiple_of(8); + let bytes_len = input.int_in_range(0..=MAX_BYTES_LEN)?.next_multiple_of(8); let mut bytes: Vec = vec![0; bytes_len]; input.fill_buffer(&mut bytes)?; diff --git a/fuzz/fuzz_targets/reconstruct_key.rs b/fuzz/fuzz_targets/reconstruct_key.rs index 89cc9ae465..034f2f9d7a 100644 --- a/fuzz/fuzz_targets/reconstruct_key.rs +++ b/fuzz/fuzz_targets/reconstruct_key.rs @@ -51,8 +51,8 @@ impl<'a> Arbitrary<'a> for Run { fn arbitrary(input: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result { let raw_separator = RawSeparator::arbitrary(input)?; - let raw_prefix_bit_len = input.int_in_range(0..=(256 - raw_separator.bit_len))?; - let raw_prefix_min_byte_len = (raw_prefix_bit_len + 7) / 8; + let raw_prefix_bit_len: usize = input.int_in_range(0..=(256 - raw_separator.bit_len))?; + let raw_prefix_min_byte_len = raw_prefix_bit_len.div_ceil(8); let raw_prefix_byte_len = input.int_in_range(raw_prefix_min_byte_len..=(1 << 12))?; let mut raw_prefix_bytes = vec![0; raw_prefix_byte_len]; input.fill_buffer(&mut raw_prefix_bytes)?; @@ -71,11 +71,11 @@ impl<'a> Arbitrary<'a> for Run { impl<'a> Arbitrary<'a> for RawSeparator { fn arbitrary(input: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result { - let bit_start = input.int_in_range(0..=7)?; + let bit_start: usize = input.int_in_range(0..=7)?; let bit_len = input.int_in_range(0..=(256 - bit_start))?; - let bytes_len = (((bit_start + bit_len + 7) / 8) as usize).next_multiple_of(8); + let bytes_len = (bit_start + bit_len).div_ceil(8).next_multiple_of(8); let mut bytes: Vec = vec![0; bytes_len]; input.fill_buffer(&mut bytes)?; diff --git a/nomt-test-utils/src/lib.rs b/nomt-test-utils/src/lib.rs index 5e33a962fb..0c197557bc 100644 --- a/nomt-test-utils/src/lib.rs +++ b/nomt-test-utils/src/lib.rs @@ -346,7 +346,7 @@ fn seeded_key(seed: u64) -> KeyPath { let mut rng = Lcg64Xsh32::from_seed(rng_seed); let mut key = [0; 32]; - for chunk in key.chunks_exact_mut(4) { + for chunk in key.as_chunks_mut::<4>().0 { chunk.copy_from_slice(&rng.next_u32().to_le_bytes()); } diff --git a/nomt/src/beatree/allocator/free_list.rs b/nomt/src/beatree/allocator/free_list.rs index 0e2b87df33..8de18434eb 100644 --- a/nomt/src/beatree/allocator/free_list.rs +++ b/nomt/src/beatree/allocator/free_list.rs @@ -76,8 +76,7 @@ impl FreeList { let pns = self .portions .iter() - .map(|&(ref pn, ref pns)| std::iter::once(pn).chain(pns)) - .flatten() + .flat_map(|(pn, pns)| std::iter::once(pn).chain(pns)) .copied(); BTreeSet::from_iter(pns) @@ -185,7 +184,7 @@ impl FreeList { } // append the released free list pages - to_push.extend(self.released_portions.drain(..)); + to_push.append(&mut self.released_portions); let new_pages = self.preallocate(&mut to_push, bump); let pages = self.push_and_encode(page_pool, &to_push, new_pages); @@ -327,12 +326,12 @@ impl FreeList { let head_full = self .portions .last() - .map_or(true, |h| h.1.len() == MAX_PNS_PER_PAGE); + .is_none_or(|h| h.1.len() == MAX_PNS_PER_PAGE); let fragmentation = self .portions .last() - .map_or(false, |h| h.1.len() == MAX_PNS_PER_PAGE - 1) + .is_some_and(|h| h.1.len() == MAX_PNS_PER_PAGE - 1) && new_pages.peek().is_some() && i + 1 == to_push.len(); @@ -369,7 +368,7 @@ impl FreeList { Some(( *head_pn, - encode_free_list_page(page_pool, prev_pn, &head_pns), + encode_free_list_page(page_pool, prev_pn, head_pns), )) } else { None @@ -415,7 +414,7 @@ fn encode_free_list_page(page_pool: &PagePool, prev: PageNumber, pns: &[PageNumb let mut e = FreeListPageMut(&mut page[..]); e.set_prev_pn(prev); e.set_item_count(pns.len() as u16); - for (i, pn) in pns.into_iter().enumerate() { + for (i, pn) in pns.iter().enumerate() { e.set_item(i, *pn); } } @@ -443,7 +442,7 @@ impl<'a> CleanFreeList<'a> { portions[n_portions - 2].1[MAX_PNS_PER_PAGE - n - 1] } else { let portion_offset = 2 + (n / MAX_PNS_PER_PAGE); - n = n % MAX_PNS_PER_PAGE; + n %= MAX_PNS_PER_PAGE; portions[n_portions - portion_offset].1[MAX_PNS_PER_PAGE - n - 1] } @@ -454,7 +453,7 @@ impl<'a> CleanFreeList<'a> { } else { n -= head_len; let portion_offset = 2 + (n / MAX_PNS_PER_PAGE); - n = n % MAX_PNS_PER_PAGE; + n %= MAX_PNS_PER_PAGE; portions[n_portions - portion_offset].1[MAX_PNS_PER_PAGE - n - 1] } diff --git a/nomt/src/beatree/branch/node.rs b/nomt/src/beatree/branch/node.rs index 21a3cb80b5..dda0f93f75 100644 --- a/nomt/src/beatree/branch/node.rs +++ b/nomt/src/beatree/branch/node.rs @@ -52,7 +52,7 @@ impl BranchNode { } pub fn as_slice(&self) -> &[u8] { - &*self.page + &self.page } pub fn page(&self) -> Page { @@ -66,7 +66,7 @@ impl BranchNode { } pub fn as_mut_slice(&mut self) -> &mut [u8] { - &mut *self.page + &mut self.page } pub fn bbn_pn(&self) -> u32 { @@ -117,7 +117,7 @@ impl BranchNode { fn set_prefix(&mut self, key: &[u8; 32]) { let start = BRANCH_NODE_HEADER_SIZE + self.n() as usize * 2; let prefix_len = self.prefix_len() as usize; - let end = start + ((prefix_len + 7) / 8).next_multiple_of(8); + let end = start + prefix_len.div_ceil(8).next_multiple_of(8); bitwise_memcpy(&mut self.as_mut_slice()[start..end], 0, key, 0, prefix_len); } @@ -173,7 +173,7 @@ impl BranchNode { let separators_start = BRANCH_NODE_HEADER_SIZE + (n * 2); slice[separators_start..].view_bits_mut()[prefix_len..][bit_offset_start..bit_offset_end] - .copy_from_bitslice(&separator); + .copy_from_bitslice(separator); } pub fn node_pointer(&self, i: usize) -> u32 { @@ -269,7 +269,7 @@ impl<'a> BranchNodeView<'a> { let byte_len = if bit_len == 0 { 0 } else { - (((bit_start + bit_len) + 7) / 8).next_multiple_of(8) + (bit_start + bit_len).div_ceil(8).next_multiple_of(8) }; RawSeparatorsData { @@ -312,7 +312,7 @@ impl<'a> BranchNodeView<'a> { let bit_len = self.prefix_len() as usize; let start = BRANCH_NODE_HEADER_SIZE + self.n() as usize * 2; - let end = start + ((bit_len + 7) / 8); + let end = start + bit_len.div_ceil(8); (&self.inner[start..end], bit_len) } @@ -368,7 +368,7 @@ pub type RawSeparatorsMut<'a> = (&'a mut [u8], usize, usize); pub fn body_size(prefix_len: usize, total_separator_lengths: usize, n: usize) -> usize { // prefix plus separator lengths are measured in bits, which we round // up to the next byte boundary. They are preceded by cells and followed by node pointers - (n * 2) + (prefix_len + total_separator_lengths + 7) / 8 + (n * 4) + (n * 2) + (prefix_len + total_separator_lengths).div_ceil(8) + (n * 4) } /// Given inputs describing a range of compressed separators, output the sum of the separator @@ -503,7 +503,7 @@ impl BranchNodeBuilder { let bit_prefix_len_difference = base.prefix_len() as isize - self.branch.prefix_len() as isize; let is_prefix_extension = bit_prefix_len_difference.is_positive(); - let bit_prefix_len_difference = bit_prefix_len_difference.abs() as usize; + let bit_prefix_len_difference = bit_prefix_len_difference.unsigned_abs(); // 1. copy and update cells // self.separator_bit_offset is the end offset of the last inserted separator @@ -514,7 +514,7 @@ impl BranchNodeBuilder { base_prev_cell_pointer = base.view().cell(from - 1) } - for (base_cell, cell) in (&base.view().cells()[from..to]) + for (base_cell, cell) in base.view().cells()[from..to] .iter() .zip(&mut self.branch.cells_mut()[self.index..self.index + n_items]) { @@ -528,7 +528,7 @@ impl BranchNodeBuilder { separator_len = separator_len.saturating_sub(bit_prefix_len_difference); } - cell_pointer += separator_len as usize; + cell_pointer += separator_len; cell.copy_from_slice(&u16::try_from(cell_pointer).unwrap().to_le_bytes()); } @@ -592,13 +592,13 @@ impl BranchNodeBuilder { // the base prefix and added in front of every separator. // The interested bits are the last bits of the prefix - let bits_to_skip = base.prefix_len() as usize - bit_prefix_len_difference as usize; + let bits_to_skip = base.prefix_len() as usize - bit_prefix_len_difference; let bytes_to_skip = bits_to_skip / 8; let prefix_bit_start = bits_to_skip % 8; let base_prefix_start = BRANCH_NODE_HEADER_SIZE + base.n() as usize * 2; let start = base_prefix_start + bytes_to_skip; - let byte_len = (((bit_prefix_len_difference as usize) + 7) / 8).next_multiple_of(8); + let byte_len = bit_prefix_len_difference.div_ceil(8).next_multiple_of(8); Some((start, start + byte_len, prefix_bit_start)) } else { @@ -644,17 +644,17 @@ impl BranchNodeBuilder { if *bit_start > 7 { // skip some bytes because they are part of the prefix let bytes_to_skip = *bit_start / 8; - *bit_start = *bit_start % 8; + *bit_start %= 8; *byte_init += bytes_to_skip; } }; - let bit_len; - if is_prefix_extension { + + let bit_len = if is_prefix_extension { // carry_prefix is already being applied, so skip bits in the new node's separator separator_bit_start += bit_prefix_len_difference; handle_prefix_offset(&mut separator_bit_start, &mut separator_bytes_start); - bit_len = base_separator_bit_len; + base_separator_bit_len } else { // the prefix in the new node is bigger, so skip bits in the base's separator base_separator_bit_start += bit_prefix_len_difference; @@ -662,8 +662,8 @@ impl BranchNodeBuilder { &mut base_separator_bit_start, &mut base_separator_bytes_start, ); - bit_len = separator_bit_len; - } + separator_bit_len + }; bitwise_memcpy( &mut self.branch.page diff --git a/nomt/src/beatree/index.rs b/nomt/src/beatree/index.rs index 6537c77541..ea79f39dff 100644 --- a/nomt/src/beatree/index.rs +++ b/nomt/src/beatree/index.rs @@ -22,7 +22,7 @@ impl Index { pub fn lookup(&self, key: Key) -> Option<(Key, Arc)> { self.first_key_map .get_prev(&key) - .map(|(sep, b)| (sep.clone(), b.clone())) + .map(|(sep, b)| (*sep, b.clone())) } /// Get the first separator greater than the given key. diff --git a/nomt/src/beatree/iterator.rs b/nomt/src/beatree/iterator.rs index aaaa676770..678ec24193 100644 --- a/nomt/src/beatree/iterator.rs +++ b/nomt/src/beatree/iterator.rs @@ -118,9 +118,9 @@ impl BeatreeIterator { Action::TakeMemory => match self.memory_values.next().unwrap() { // PANIC: this case is checked previously. (_, ValueChange::Delete) => panic!(), - (k, ValueChange::Insert(val)) => return Some(IterOutput::Item(*k, val)), + (k, ValueChange::Insert(val)) => Some(IterOutput::Item(*k, val)), (k, ValueChange::InsertOverflow(ref overflow_cell, ref value_hash)) => { - return Some(IterOutput::OverflowItem(*k, *value_hash, overflow_cell)) + Some(IterOutput::OverflowItem(*k, *value_hash, overflow_cell)) } }, } @@ -169,13 +169,13 @@ impl CurrentLeaf { } fn is_in_range(&self, end: Option<&Key>) -> bool { - end.map_or(true, |end| { + end.is_none_or(|end| { super::key_cmp(&self.leaf.key(self.index), end).is_lt() }) } fn is_last_output_in_range(&self, end: Option<&Key>) -> bool { - end.map_or(true, |end| { + end.is_none_or(|end| { super::key_cmp(&self.leaf.key(self.index - 1), end).is_lt() }) } @@ -245,7 +245,7 @@ impl LeafIterator { LeafIteratorState::Proceeding { current, .. } => { let next = current.index + 1; next < current.leaf.n() - && self.end.as_ref().map_or(true, |end| { + && self.end.as_ref().is_none_or(|end| { super::key_cmp(¤t.leaf.key(next), end).is_lt() }) } @@ -331,14 +331,14 @@ impl LeafIterator { // out of range. look up next. let next_key = self .index - .next_key(get_key(&*branch, next_index_in_branch - 1)); + .next_key(get_key(&branch, next_index_in_branch - 1)); match next_key { None => LeafIteratorState::Done { last: Some(last) }, Some(k) if self .end .as_ref() - .map_or(false, |end| super::key_cmp(end, &k).is_le()) => + .is_some_and(|end| super::key_cmp(end, &k).is_le()) => { LeafIteratorState::Done { last: Some(last) } } @@ -357,7 +357,7 @@ impl LeafIterator { let separator = get_key(&branch, next_index_in_branch); if self .end - .map_or(true, |end| super::key_cmp(&separator, &end).is_lt()) + .is_none_or(|end| super::key_cmp(&separator, &end).is_lt()) { LeafIteratorState::Blocked { index_in_branch: next_index_in_branch, @@ -458,7 +458,7 @@ impl Iterator for NeededLeavesIter { if self .end .as_ref() - .map_or(true, |end| super::key_cmp(&key, end).is_lt()) + .is_none_or(|end| super::key_cmp(&key, end).is_lt()) { self.state = Some((branch, range)); Some(pn) @@ -467,10 +467,7 @@ impl Iterator for NeededLeavesIter { } } else { let last_separator = get_key(&branch, branch.n() as usize - 1); - let next_separator = match self.index.next_key(last_separator) { - None => return None, - Some(k) => k, - }; + let next_separator = self.index.next_key(last_separator)?; // UNWRAP: keys returned by `next_key` always exist; qed. let next_branch = self.index.lookup(next_separator).unwrap().1; @@ -517,7 +514,7 @@ impl StagingIterator { } } - fn peek<'a>(&'a mut self) -> Option<(&'a Key, &'a ValueChange)> { + fn peek(&mut self) -> Option<(&Key, &ValueChange)> { let primary_peek = self.primary.peek(); let secondary_peek = self.secondary.as_mut().and_then(|s| s.peek()); @@ -535,7 +532,7 @@ impl StagingIterator { } } - fn next<'a>(&'a mut self) -> Option<(&'a Key, &'a ValueChange)> { + fn next(&mut self) -> Option<(&Key, &ValueChange)> { let primary_peek = self.primary.peek().map(|(k, _)| k); let secondary_peek = self .secondary @@ -562,7 +559,7 @@ impl StagingIterator { } } - fn next_secondary<'a>(&'a mut self) -> Option<(&'a Key, &'a ValueChange)> { + fn next_secondary(&mut self) -> Option<(&Key, &ValueChange)> { self.secondary.as_mut().and_then(|s| s.next()) } } @@ -574,11 +571,11 @@ struct OrdMapOwnedIter { } impl OrdMapOwnedIter { - fn peek<'a>(&'a mut self) -> Option<(&'a Key, &'a ValueChange)> { + fn peek(&mut self) -> Option<(&Key, &ValueChange)> { self.iter.peek().map(|x| (x.0, x.1)) } - fn next<'a>(&'a mut self) -> Option<(&'a Key, &'a ValueChange)> { + fn next(&mut self) -> Option<(&Key, &ValueChange)> { self.iter.next().map(|x| (x.0, x.1)) } } diff --git a/nomt/src/beatree/leaf_cache.rs b/nomt/src/beatree/leaf_cache.rs index 7915f95655..3e944e9aa1 100644 --- a/nomt/src/beatree/leaf_cache.rs +++ b/nomt/src/beatree/leaf_cache.rs @@ -40,7 +40,7 @@ impl LeafCache { pub fn get(&self, page_number: PageNumber) -> Option> { let mut shard = self.inner.shard_for(page_number); - shard.cache.get(&page_number).map(|x| x.clone()) + shard.cache.get(&page_number).cloned() } /// Insert a cache entry. This does not evict anything. diff --git a/nomt/src/beatree/mod.rs b/nomt/src/beatree/mod.rs index c231feaee1..a675e68fc8 100644 --- a/nomt/src/beatree/mod.rs +++ b/nomt/src/beatree/mod.rs @@ -105,11 +105,9 @@ impl Tree { commit_concurrency: usize, leaf_cache_size: usize, ) -> Result { - let ln_freelist_pn = Some(ln_freelist_pn) - .map(PageNumber) + let ln_freelist_pn = Some(PageNumber(ln_freelist_pn)) .filter(|&x| x != FREELIST_EMPTY); - let bbn_freelist_pn = Some(bbn_freelist_pn) - .map(PageNumber) + let bbn_freelist_pn = Some(PageNumber(bbn_freelist_pn)) .filter(|&x| x != FREELIST_EMPTY); let ln_bump = PageNumber(ln_bump); diff --git a/nomt/src/beatree/ops/bit_ops.rs b/nomt/src/beatree/ops/bit_ops.rs index e9924b54cb..9b07bfcfc8 100644 --- a/nomt/src/beatree/ops/bit_ops.rs +++ b/nomt/src/beatree/ops/bit_ops.rs @@ -59,7 +59,7 @@ pub fn reconstruct_key(maybe_prefix: Option, separator: RawSeparators let mut key = [0u8; 32]; let prefix_bit_len = maybe_prefix.as_ref().map(|p| p.1).unwrap_or(0); - let prefix_byte_len = (prefix_bit_len + 7) / 8; + let prefix_byte_len = prefix_bit_len.div_ceil(8); let prefix_end_bit_offset = prefix_bit_len % 8; let (separator_bytes, separator_bit_start, separator_bit_len) = separator; @@ -139,13 +139,13 @@ pub fn bitwise_memcpy( let mut shift = match destination_bit_start as isize - source_bit_start as isize { 0 => None, - shift if shift < 0 => Some(Shift::Left(shift.abs() as usize)), + shift if shift < 0 => Some(Shift::Left(shift.unsigned_abs())), shift => Some(Shift::Right(shift as usize, None, None)), }; // chunk is an 8-byte slice of the separator which will be cast to a u64 to simplify shifting let n_chunks = source.len() / 8; - let bytes_to_write = (destination_bit_start + source_bit_len + 7) / 8; + let bytes_to_write = (destination_bit_start + source_bit_len).div_ceil(8); // container of all bits that will not be overwritten let mut chunk_data: Option = None; @@ -329,7 +329,7 @@ pub mod benches { } else { prefix_bytes - 1 }; - let separator_byte_len = ((separator_bit_len as usize + 7) / 8).next_multiple_of(8); + let separator_byte_len = (separator_bit_len as usize).div_ceil(8).next_multiple_of(8); group.bench_function(BenchmarkId::new("prefix_len_bits", prefix_bits), |b| { b.iter_batched( @@ -415,7 +415,7 @@ mod tests { } else { 0 }; - let prefix_byte_len = (prefix_bit_len + 7) / 8; + let prefix_byte_len = prefix_bit_len.div_ceil(8); let prefix_seed = TestKeyPath::arbitrary(g).into_inner(); let prefix_bytes = use_prefix.then(|| prefix_seed[..prefix_byte_len].to_vec()); @@ -426,7 +426,7 @@ mod tests { }; let separator_bit_len = arbitrary_bit_len(g, 256 - prefix_bit_len); let separator_byte_len = - ((separator_bit_start + separator_bit_len + 7) / 8).next_multiple_of(8); + (separator_bit_start + separator_bit_len).div_ceil(8).next_multiple_of(8); let separator_seed = TestKeyPath::arbitrary(g).into_inner(); let mut separator_bytes = vec![0; separator_byte_len]; for (index, byte) in separator_bytes.iter_mut().enumerate() { @@ -497,8 +497,8 @@ mod tests { // one iteration without shifts and then all the subsequent are left shifts for i in 0..8 { let separator_bit_start = i; - let separator_bit_len = 256 - i; - let separator_byte_len = ((separator_bit_len as usize + 7) / 8).next_multiple_of(8); + let separator_bit_len: usize = 256 - i; + let separator_byte_len = separator_bit_len.div_ceil(8).next_multiple_of(8); let separator_bytes = vec![170; separator_byte_len]; @@ -513,9 +513,9 @@ mod tests { #[test] fn reconstruct_key_shorter_separator() { // test separator smaller then 256 to ensure the garbage at the end is properly removed - for separator_bit_len in 0..256 { + for separator_bit_len in 0..256usize { let separator_bit_start = 0; - let separator_byte_len = ((separator_bit_len as usize + 7) / 8).next_multiple_of(8); + let separator_byte_len = separator_bit_len.div_ceil(8).next_multiple_of(8); let separator_bytes = vec![170; separator_byte_len]; @@ -543,7 +543,7 @@ mod tests { for separator_bit_start in separator_bit_start_range { for separator_bit_len in prefix_bit_len..=256 - prefix_bit_len { let separator_byte_len = - ((separator_bit_start + separator_bit_len + 7 as usize) / 8) + (separator_bit_start + separator_bit_len).div_ceil(8) .next_multiple_of(8); let separator_bytes = vec![255; separator_byte_len]; @@ -573,8 +573,8 @@ mod tests { } let prefix_bit_len = 16 + i; let separator_bit_start = i; - let separator_bit_len = 256 - prefix_bit_len; - let separator_byte_len = ((separator_bit_len as usize + 7) / 8).next_multiple_of(8); + let separator_bit_len: usize = 256 - prefix_bit_len; + let separator_byte_len = separator_bit_len.div_ceil(8).next_multiple_of(8); let separator_bytes = vec![170; separator_byte_len]; @@ -600,8 +600,8 @@ mod tests { for separator_bit_start_offset in 1..(8 - i) { let separator_bit_start = i + separator_bit_start_offset; - let separator_bit_len = 256 - prefix_bit_len; - let separator_byte_len = ((separator_bit_len as usize + 7) / 8).next_multiple_of(8); + let separator_bit_len: usize = 256 - prefix_bit_len; + let separator_byte_len = separator_bit_len.div_ceil(8).next_multiple_of(8); let separator_bytes = vec![170; separator_byte_len]; @@ -629,8 +629,8 @@ mod tests { for separator_bit_start_offset in 0..i { let separator_bit_start = separator_bit_start_offset; - let separator_bit_len = 256 - prefix_bit_len; - let separator_byte_len = ((separator_bit_len as usize + 7) / 8).next_multiple_of(8); + let separator_bit_len: usize = 256 - prefix_bit_len; + let separator_byte_len = separator_bit_len.div_ceil(8).next_multiple_of(8); let separator_bytes = vec![170; separator_byte_len]; diff --git a/nomt/src/beatree/ops/mod.rs b/nomt/src/beatree/ops/mod.rs index a6a3db62cf..0db25632f1 100644 --- a/nomt/src/beatree/ops/mod.rs +++ b/nomt/src/beatree/ops/mod.rs @@ -32,7 +32,7 @@ pub fn partial_lookup(key: Key, bbn_index: &Index) -> Option { Some((_, branch)) => branch, }; - search_branch(&branch, key.clone()).map(|(_, leaf_pn)| leaf_pn) + search_branch(&branch, key).map(|(_, leaf_pn)| leaf_pn) } /// Find the associated value associated with the key in the given leaf node, if any. @@ -103,13 +103,13 @@ pub fn search_branch(branch: &BranchNode, key: Key) -> Option<(usize, PageNumber let (found, pos) = find_key_pos(branch, &key, None); if found { - return Some((pos, branch.node_pointer(pos).into())); + Some((pos, branch.node_pointer(pos).into())) } else if pos == 0 { - return None; + None } else { // first key greater than the one we are looking for has been returned, // thus the correct child is the previous one - return Some((pos - 1, branch.node_pointer(pos - 1).into())); + Some((pos - 1, branch.node_pointer(pos - 1).into())) } } diff --git a/nomt/src/beatree/ops/overflow.rs b/nomt/src/beatree/ops/overflow.rs index 527130cb34..620d87d504 100644 --- a/nomt/src/beatree/ops/overflow.rs +++ b/nomt/src/beatree/ops/overflow.rs @@ -174,7 +174,7 @@ fn total_needed_pages(value_size: usize) -> usize { } fn needed_pages(size: usize) -> usize { - (size + BODY_SIZE - 1) / BODY_SIZE + size.div_ceil(BODY_SIZE) } /// Read a large value from pages referenced by an overflow cell using blocking I/O. @@ -315,7 +315,7 @@ pub fn delete(cell: &[u8], leaf_reader: &StoreReader, freed: &mut Vec 0 { + if !bytes.is_empty() { break; } } diff --git a/nomt/src/beatree/ops/reconstruction.rs b/nomt/src/beatree/ops/reconstruction.rs index ad0bb2ecfe..d5df9ed537 100644 --- a/nomt/src/beatree/ops/reconstruction.rs +++ b/nomt/src/beatree/ops/reconstruction.rs @@ -48,7 +48,7 @@ pub fn reconstruct( pn ); - let mut branch = BranchNode::new_in(&page_pool); + let mut branch = BranchNode::new_in(page_pool); branch.as_mut_slice().copy_from_slice(node); let mut separator = [0u8; 32]; @@ -136,14 +136,14 @@ impl SeqFileReader { }) } - pub fn next<'a>(&'a mut self) -> Result> { + pub fn next(&mut self) -> Result> { if self.pn >= self.bump { return Ok(None); } let node = unsafe { let offset = self.pn as usize * BRANCH_NODE_SIZE; - let ptr = self.ptr.offset(offset as isize); + let ptr = self.ptr.add(offset); std::slice::from_raw_parts(ptr, BRANCH_NODE_SIZE) }; diff --git a/nomt/src/beatree/ops/update/branch_ops.rs b/nomt/src/beatree/ops/update/branch_ops.rs index 04d5a48858..453bfb5350 100644 --- a/nomt/src/beatree/ops/update/branch_ops.rs +++ b/nomt/src/beatree/ops/update/branch_ops.rs @@ -207,7 +207,7 @@ impl BranchOpsTracker { let mut gauge = BranchGauge::default(); while pos < self.ops.len() && gauge.body_size() < target { - match *&self.ops[pos] { + match self.ops[pos] { BranchOp::Insert(key, _) => { if gauge.body_size_after(key, separator_len(&key)) > BRANCH_NODE_BODY_SIZE { // Rare case: body was artifically small due to long shared prefix. @@ -462,7 +462,7 @@ mod tests { // to the ops is just after the target. let mut rightsized = false; ops_tracker.ops = (0..) - .map(|i| key(i)) + .map(key) .take_while(|key| { let res = !rightsized; rightsized = gauge.body_size_after(*key, separator_len(key)) >= target; @@ -566,13 +566,13 @@ mod tests { }) .take_while(|keep_chunk| { let res = !rightsized; - rightsized = gauge.body_size_after_chunk(&base, &keep_chunk) >= target; + rightsized = gauge.body_size_after_chunk(&base, keep_chunk) >= target; if res { - gauge.ingest_chunk(&base, &keep_chunk); + gauge.ingest_chunk(&base, keep_chunk); } res }) - .map(|keep_chunk| BranchOp::KeepChunk(keep_chunk)) + .map(BranchOp::KeepChunk) .collect(); let n_ops = ops_tracker.ops.len(); @@ -605,7 +605,7 @@ mod tests { // to the ops is just after BRANCH_MERGE_THRESHOLD. let mut rightsized = false; ops_tracker.ops = (0..) - .map(|i| compressed_key(i)) + .map(compressed_key) .take_while(|key| { let res = !rightsized; rightsized = @@ -654,7 +654,7 @@ mod tests { // to the ops is just after BRANCH_MERGE_THRESHOLD. let mut rightsized = false; ops_tracker.ops = (0..) - .map(|i| compressed_key(i)) + .map(compressed_key) .take_while(|key| { let res = !rightsized; rightsized = @@ -701,7 +701,7 @@ mod tests { // Collect BranchOp::Insert into ops_tracker.ops until the gauge associated // to the ops is just after the BRANCH_MERGE_THRESHOLD / 2 ops_tracker.ops = (0..) - .map(|i| compressed_key(i)) + .map(compressed_key) .take_while(|key| { if gauge.body_size_after(*key, separator_len(key)) >= BRANCH_MERGE_THRESHOLD / 2 { false @@ -774,7 +774,7 @@ mod tests { // Collect BranchOp::Insert into updater.ops until the gauge associated // to the ops is just after the BRANCH_MERGE_THRESHOLD / 2 ops_tracker.ops = (0..) - .map(|i| compressed_key(i)) + .map(compressed_key) .take_while(|key| { if gauge.body_size_after(*key, separator_len(key)) >= BRANCH_MERGE_THRESHOLD / 2 { false @@ -822,14 +822,14 @@ mod tests { .take_while(|keep_chunk| { let res = !rightsized; rightsized = - gauge.body_size_after_chunk(&base, &keep_chunk) >= BRANCH_MERGE_THRESHOLD; + gauge.body_size_after_chunk(&base, keep_chunk) >= BRANCH_MERGE_THRESHOLD; if res { - gauge.ingest_chunk(&base, &keep_chunk); + gauge.ingest_chunk(&base, keep_chunk); total_kept_itmes += keep_chunk.end - keep_chunk.start; } res }) - .map(|keep_chunk| BranchOp::KeepChunk(keep_chunk)) + .map(BranchOp::KeepChunk) .collect(); ops_tracker.ops.extend(keep_ops); diff --git a/nomt/src/beatree/ops/update/branch_stage.rs b/nomt/src/beatree/ops/update/branch_stage.rs index 823008ffb5..340330c629 100644 --- a/nomt/src/beatree/ops/update/branch_stage.rs +++ b/nomt/src/beatree/ops/update/branch_stage.rs @@ -79,7 +79,7 @@ pub fn run( bbn_writer, page_pool, io_handle, - &*changeset, + &changeset, worker_params, ) }; @@ -128,13 +128,12 @@ fn apply_bbn_changes( output.freed_pages.push(deleted_pn); } - branch_changeset.push((key.clone(), changed_branch.inserted.map(|(node, _)| node))); + branch_changeset.push((key, changed_branch.inserted.map(|(node, _)| node))); } output.submitted_io += worker_output.branches_tracker.extra_freed.len(); output - .freed_pages - .extend(worker_output.branches_tracker.extra_freed.drain(..)); + .freed_pages.append(&mut worker_output.branches_tracker.extra_freed); output.post_io_drop.deferred_drop_pages.push(std::mem::take( &mut worker_output.branches_tracker.deferred_drop_pages, )); @@ -144,7 +143,7 @@ fn apply_bbn_changes( // who share the pages they have worked on with the extension range protocol. // This function filters some work to avoid the incorrect elimination of pages. fn filter_branch_changeset(branch_changeset: &mut Vec<(Key, Option>)>) { - branch_changeset.sort_by(|(k1, _), (k2, _)| k1.cmp(k2)); + branch_changeset.sort_by_key(|(k1, _)| *k1); let mut to_remove = vec![]; // If there are two changes with the same separator produced // by two workers, one is expected to be deleted and the other @@ -220,7 +219,7 @@ fn prepare_workers( // iter: find endpoint for previous worker and push next worker. // look up the branch for the (ops/N)th operation, find out how many ops it covers, // and set the end range accordingly. - while remaining_workers > 0 && changeset_remaining.len() > 0 { + while remaining_workers > 0 && !changeset_remaining.is_empty() { let pivot_idx = changeset_remaining.len() / (remaining_workers + 1); // If pivot_idx == 0 the number of changeset_remaining @@ -369,7 +368,7 @@ fn run_worker( for (key, op) in &changeset[worker_params.op_range.clone()] { // ensure key is in scope for branch updater. if not, digest it. merge rightwards until // done _or_ key is in scope. - while !branch_updater.is_in_scope(&key) { + while !branch_updater.is_in_scope(key) { // After `digest`, some changed items could have been produced and they could be used // to respond to the left neighbor. However, we should only respond if we are sure that // we will not introduce changed items with smaller separators later on. @@ -393,7 +392,7 @@ fn run_worker( }; has_extended_range = false; - if worker_params.range.high.map_or(false, |high| k >= high) { + if worker_params.range.high.is_some_and(|high| k >= high) { has_extended_range = true; request_range_extension(&mut worker_params, &mut new_branch_state.branches_tracker); } @@ -417,7 +416,7 @@ fn run_worker( if worker_params .range .high - .map_or(false, |high| cutoff >= high) + .is_some_and(|high| cutoff >= high) { has_extended_range = true; request_range_extension(&mut worker_params, &mut new_branch_state.branches_tracker); diff --git a/nomt/src/beatree/ops/update/branch_updater.rs b/nomt/src/beatree/ops/update/branch_updater.rs index 8cca63c91f..e51c786f07 100644 --- a/nomt/src/beatree/ops/update/branch_updater.rs +++ b/nomt/src/beatree/ops/update/branch_updater.rs @@ -42,14 +42,14 @@ impl BaseBranch { if found { // the key was present return its index and point to the right after key self.low = pos + 1; - return Some((true, pos)); + Some((true, pos)) } else if pos == self.low { // there are no keys left bigger than the specified one - return None; + None } else { // key was not present, return and point to the smallest bigger key self.low = pos; - return Some((false, pos)); + Some((false, pos)) } } @@ -152,7 +152,7 @@ impl BranchUpdater { } pub fn is_in_scope(&self, key: &Key) -> bool { - self.cutoff.map_or(true, |k| *key < k) + self.cutoff.is_none_or(|k| *key < k) } pub fn reset_base(&mut self, base: Option, cutoff: Option) { @@ -168,10 +168,7 @@ impl BranchUpdater { // Collect in `self.ops` all separators that are skipped. // Returns the index at which 'up_to' was found, otherwise, returns None. fn keep_up_to(&mut self, up_to: Option<&Key>) -> Option { - if self.base.is_none() { - // empty db - return None; - } + self.base.as_ref()?; // UNWRAP: self.base is not None let base = self.base.as_mut().unwrap(); @@ -187,18 +184,14 @@ impl BranchUpdater { base.low = base_n; (false, base_n) } - Some(up_to) => match base.find_key(up_to) { - Some(res) => res, - // already at the end - None => return None, - }, + Some(up_to) => base.find_key(up_to)?, }; if from != to { self.ops_tracker.push_chunk(base, from, to); } - return if found { Some(to) } else { None }; + if found { Some(to) } else { None } } // Try to perform a split of the current available ops with a target branch node size. @@ -235,7 +228,7 @@ fn build_branch( ops: &[BranchOp], gauge: &BranchGauge, ) -> BranchNode { - let branch = BranchNode::new_in(&page_pool); + let branch = BranchNode::new_in(page_pool); let mut builder = BranchNodeBuilder::new( branch, @@ -283,8 +276,7 @@ fn build_branch( } else { None } - }) - .into_iter(), + }), ); for pos in compressed_end..base_range.end { @@ -378,6 +370,7 @@ fn build_branch( } #[derive(Clone)] +#[derive(Default)] pub struct BranchGauge { // key and length of the first separator if any first_separator: Option<(Key, usize)>, @@ -389,17 +382,6 @@ pub struct BranchGauge { n: usize, } -impl Default for BranchGauge { - fn default() -> Self { - BranchGauge { - first_separator: None, - prefix_len: 0, - sum_separator_lengths: 0, - prefix_compressed: None, - n: 0, - } - } -} impl BranchGauge { pub fn ingest_key(&mut self, key: Key, len: usize) { @@ -998,14 +980,14 @@ pub mod tests { assert!(new_branch_1.prefix_compressed() != new_branch_1.n()); assert_eq!( - get_key(&new_branch_1, new_branch_1.n() as usize - 1), + get_key(new_branch_1, new_branch_1.n() as usize - 1), key2(0) ); let branch_1_body_size = { let mut gauge = BranchGauge::default(); for i in 0..new_branch_1.n() as usize { - let key = get_key(&new_branch_1, i); + let key = get_key(new_branch_1, i); gauge.ingest_key(key, separator_len(&key)) } gauge.body_size() diff --git a/nomt/src/beatree/ops/update/extend_range_protocol.rs b/nomt/src/beatree/ops/update/extend_range_protocol.rs index 5b0859d508..5bda6eadbf 100644 --- a/nomt/src/beatree/ops/update/extend_range_protocol.rs +++ b/nomt/src/beatree/ops/update/extend_range_protocol.rs @@ -92,11 +92,11 @@ pub fn try_answer_left_neighbor( if entry.inserted.is_some() { found_next_node = true; - new_high_range = entry.next_separator.clone(); + new_high_range = entry.next_separator; return false; } - separator = entry.next_separator.clone(); + separator = entry.next_separator; true }) @@ -111,7 +111,7 @@ pub fn try_answer_left_neighbor( // and they will be passed to the left worker if let Some(low) = separator { - if worker_params.range.high.map_or(true, |high| low < high) { + if worker_params.range.high.is_none_or(|high| low < high) { // special case where there is one unchanged range left, // which is the last one, up to the worker.range.high found_unchanged_range = true; diff --git a/nomt/src/beatree/ops/update/leaf_stage.rs b/nomt/src/beatree/ops/update/leaf_stage.rs index c47ad4bfc7..6b7678ff5a 100644 --- a/nomt/src/beatree/ops/update/leaf_stage.rs +++ b/nomt/src/beatree/ops/update/leaf_stage.rs @@ -105,10 +105,10 @@ pub fn run( ValueChange::Insert(v) => Ok((*k, Some((v.clone(), false)))), ValueChange::InsertOverflow(large_value, value_hash) => { let (pages, num_writes) = - overflow::chunk(&large_value, &leaf_writer, &page_pool, &io_handle)?; + overflow::chunk(large_value, &leaf_writer, &page_pool, &io_handle)?; overflow_io += num_writes; - let cell = overflow::encode_cell(large_value.len(), value_hash.clone(), &pages); + let cell = overflow::encode_cell(large_value.len(), *value_hash, &pages); Ok((*k, Some((cell, true)))) } ValueChange::Delete => Ok((*k, None)), @@ -150,12 +150,12 @@ pub fn run( // end of this scope, not the end of `run_worker`. run_worker( bbn_index, - &*leaf_cache, + &leaf_cache, leaf_reader, leaf_writer, io_handle, &mut prepared_leaves_iter, - &*changeset, + &changeset, worker_params, ) }; @@ -215,8 +215,7 @@ fn apply_worker_changes( output.submitted_io += worker_output.leaves_tracker.extra_freed.len(); output - .freed_pages - .extend(worker_output.leaves_tracker.extra_freed.drain(..)); + .freed_pages.append(&mut worker_output.leaves_tracker.extra_freed); output.post_io_work.worker_changes.push(worker_output); } @@ -225,7 +224,7 @@ fn apply_worker_changes( // who share the pages they have worked on with the extension range protocol. // This function filters some work to avoid the incorrect elimination of pages. fn filter_leaves_changeset(leaf_changeset: &mut Vec<(Key, Option)>) { - leaf_changeset.sort_by(|(k1, _), (k2, _)| k1.cmp(k2)); + leaf_changeset.sort_by_key(|(k1, _)| *k1); let mut to_remove = vec![]; // If there are two changes with the same separator produced // by two workers, one is expected to be deleted and the other @@ -294,8 +293,7 @@ pub fn enforce_first_leaf_separator( loop { // `separator` is being eliminated, so it must exist in the previous state maybe_new_first = indexed_leaf(bbn_index, separator) - .map(|(_, maybe_next_separator, _)| maybe_next_separator) - .flatten() + .and_then(|(_, maybe_next_separator, _)| maybe_next_separator) .map(|next_separator| { // UNWRAP: the leaf_pn of a just indexed leaf. It must exist. indexed_leaf(bbn_index, next_separator) @@ -313,7 +311,7 @@ pub fn enforce_first_leaf_separator( match &leaf_changeset[idx] { // The previous leaf, candidate to be the new first one has been eliminated. - (separator, None) if maybe_new_first.map_or(false, |(s, _)| s == *separator) => { + (separator, None) if maybe_new_first.is_some_and(|(s, _)| s == *separator) => { idx += 1; } // The candidate will be the new first leaf or a new leaf with a smaller @@ -324,12 +322,12 @@ pub fn enforce_first_leaf_separator( if let Some((separator, Some(_))) = leaf_changeset.get(idx).copied() { // New leaf with a separator smaller or equal to the candidate. - if maybe_new_first.map_or(true, |(s, _)| s >= separator) { + if maybe_new_first.is_none_or(|(s, _)| s >= separator) { leaf_changeset[0].1 = leaf_changeset[idx].1; // If the new leaf corresponds to an update of the candidate, // remove the older separator. // Otherwise just remove the new first leaf entry. - if maybe_new_first.map_or(false, |(s, _)| s == separator) { + if maybe_new_first.is_some_and(|(s, _)| s == separator) { leaf_changeset[idx].1 = None; } else { leaf_changeset.remove(idx); @@ -375,7 +373,7 @@ fn prepare_workers( // iter: find endpoint for previous worker and push next worker. // look up the leaf for the (ops/N)th operation, find out how many ops it covers, // and set the end range accordingly. - while remaining_workers > 0 && changeset_remaining.len() > 0 { + while remaining_workers > 0 && !changeset_remaining.is_empty() { let pivot_idx = changeset_remaining.len() / (remaining_workers + 1); // If pivot_idx == 0 the number of changeset_remaining @@ -506,7 +504,7 @@ fn reset_leaf_base_fresh( // fast path: this leaf was expected to be used and prepared. avoid heavy index lookup. if prepared_leaves .peek() - .map_or(false, |prepared| prepared.separator <= key) + .is_some_and(|prepared| prepared.separator <= key) { // UNWRAP: we just checked. // note that the separator < key condition above only fails if we need to merge with an @@ -578,7 +576,7 @@ fn run_worker( // point leaf updater at first leaf. reset_leaf_base( &bbn_index, - &leaf_cache, + leaf_cache, &leaf_reader, &mut new_leaf_state.leaves_tracker, &mut leaf_updater, @@ -590,7 +588,7 @@ fn run_worker( for (key, op) in &changeset[worker_params.op_range.clone()] { // ensure key is in scope for leaf updater. if not, digest it. merge rightwards until // done _or_ key is in scope. - while !leaf_updater.is_in_scope(&key) { + while !leaf_updater.is_in_scope(key) { // After `digest`, some changed items could have been produced and they could be used // to respond to the left neighbor. However, we should only respond if we are sure that // we will not introduce changed items with smaller separators later on. @@ -613,7 +611,7 @@ fn run_worker( }; has_extended_range = false; - if worker_params.range.high.map_or(false, |high| k >= high) { + if worker_params.range.high.is_some_and(|high| k >= high) { has_extended_range = true; super::extend_range_protocol::request_range_extension( &mut worker_params, @@ -647,7 +645,7 @@ fn run_worker( if worker_params .range .high - .map_or(false, |high| cutoff >= high) + .is_some_and(|high| cutoff >= high) { has_extended_range = true; request_range_extension(&mut worker_params, &mut new_leaf_state.leaves_tracker); @@ -750,8 +748,8 @@ fn preload_and_prepare( let mut changeset_leaves: Vec = Vec::new(); let mut submissions = 0; for key in changeset { - if let Some(ref last) = changeset_leaves.last() { - if last.cutoff.map_or(true, |c| key < c) { + if let Some(last) = changeset_leaves.last() { + if last.cutoff.is_none_or(|c| key < c) { continue; } } diff --git a/nomt/src/beatree/ops/update/leaf_updater.rs b/nomt/src/beatree/ops/update/leaf_updater.rs index 4da53aaafb..5969580bf1 100644 --- a/nomt/src/beatree/ops/update/leaf_updater.rs +++ b/nomt/src/beatree/ops/update/leaf_updater.rs @@ -38,7 +38,7 @@ impl BaseLeaf { let interesed_cell_pointers = &self.node.cell_pointers()[self.low..]; let res = interesed_cell_pointers.binary_search_by(|cell_pointer| { let k = leaf_node::extract_key(cell_pointer); - k.cmp(&key) + k.cmp(key) }); // the returned position is relative to `cell_pointers[self.low..]` @@ -48,13 +48,13 @@ impl BaseLeaf { Ok(pos) => { let absolute_pos = self.low + pos; self.low = absolute_pos + 1; - return Some((true, absolute_pos)); + Some((true, absolute_pos)) } // If the key is not present, then `self.low` is updated to point to // the first key bigger than the one we looked for Err(pos) => { - self.low = self.low + pos; - return Some((false, self.low)); + self.low += pos; + Some((false, self.low)) } } } @@ -126,7 +126,7 @@ impl LeafUpdater { } pub fn is_in_scope(&self, key: &Key) -> bool { - self.cutoff.map_or(true, |k| *key < k) + self.cutoff.is_none_or(|k| *key < k) } pub fn reset_base(&mut self, base: Option, cutoff: Option) { diff --git a/nomt/src/beatree/ops/update/tests.rs b/nomt/src/beatree/ops/update/tests.rs index 30ac13582d..f61d549ba1 100644 --- a/nomt/src/beatree/ops/update/tests.rs +++ b/nomt/src/beatree/ops/update/tests.rs @@ -240,7 +240,7 @@ fn exec_leaf_stage( let bbn_index = &TREE_DATA.bbn_index; let leaf_cache = LeafCache::new(commit_concurrency, 1024); - let leaf_page_numbers = leaf_page_numbers(&bbn_index, changeset.keys().cloned()); + let leaf_page_numbers = leaf_page_numbers(bbn_index, changeset.keys().cloned()); let io_handle = IO_POOL.make_handle(); let leaf_stage_output = super::leaf_stage::run( @@ -336,7 +336,7 @@ fn is_valid_leaf_stage_output( // all new leaves must respect the half-full requirement except for the last one if leaf::node::body_size(n, value_size_sum) < LEAF_MERGE_THRESHOLD { - if found_underfull_leaf == true { + if found_underfull_leaf { return false; } found_underfull_leaf = true; @@ -380,7 +380,7 @@ fn leaf_stage_inner(input: StageInputs) -> TestResult { TestResult::from_bool(is_valid_leaf_stage_output( leaf_stage_output, prior_leaf_page_numbers, - deletions.into_iter().map(|(k, _)| k).collect(), + deletions.into_keys().collect(), insertions .into_iter() .map(|(k, v)| (k, v.as_option().unwrap().to_vec())) @@ -531,9 +531,7 @@ fn branch_stage_inner(input: StageInputs) -> TestResult { let mut changeset: BTreeMap<[u8; 32], Option> = insertions.clone(); changeset.extend(deletions.clone()); - let bbn_page_numbers: BTreeSet<_> = changeset - .iter() - .map(|(key, _)| bbn_index.lookup(*key).unwrap().1.bbn_pn()) + let bbn_page_numbers: BTreeSet<_> = changeset.keys().map(|key| bbn_index.lookup(*key).unwrap().1.bbn_pn()) .collect(); let mut new_bbn_index = bbn_index.clone(); diff --git a/nomt/src/bitbox/ht_file.rs b/nomt/src/bitbox/ht_file.rs index 16f6bb72a6..de5d7bed48 100644 --- a/nomt/src/bitbox/ht_file.rs +++ b/nomt/src/bitbox/ht_file.rs @@ -39,7 +39,7 @@ pub(super) fn expected_file_len(num_pages: u32) -> u64 { } pub(super) fn num_meta_byte_pages(num_pages: u32) -> u32 { - ((num_pages as u64 + PAGE_SIZE as u64 - 1) / PAGE_SIZE as u64) as u32 + (num_pages as u64).div_ceil(PAGE_SIZE as u64) as u32 } /// Opens the HT file, checks its length and reads the meta map. @@ -56,7 +56,7 @@ pub fn open( let mut meta_bytes = Vec::with_capacity(meta_byte_pages as usize * PAGE_SIZE); for pn in 0..meta_byte_pages { let extra_meta_page = io::read_page(page_pool, ht_fd, pn as u64)?; - meta_bytes.extend_from_slice(&*extra_meta_page); + meta_bytes.extend_from_slice(&extra_meta_page); } Ok(( diff --git a/nomt/src/bitbox/mod.rs b/nomt/src/bitbox/mod.rs index d499e3e2d8..bc3cdea71e 100644 --- a/nomt/src/bitbox/mod.rs +++ b/nomt/src/bitbox/mod.rs @@ -285,7 +285,7 @@ impl DB { if occupied_buckets_delta < 0 { self.shared .occupied_buckets - .fetch_sub(occupied_buckets_delta.abs() as usize, Ordering::Relaxed); + .fetch_sub(occupied_buckets_delta.unsigned_abs(), Ordering::Relaxed); } else if occupied_buckets_delta > 0 { self.shared .occupied_buckets @@ -350,7 +350,7 @@ impl SyncController { sync_seqn, &page_pool, updated_pages, - &mut *wal_blob_builder, + &mut wal_blob_builder, )?; drop(wal_blob_builder); @@ -664,7 +664,7 @@ fn allocate_bucket_raw( meta_map: &mut MetaMap, seed: &[u8; 16], ) -> Option { - let mut probe_seq = ProbeSequence::new_raw(page_id, &meta_map, seed); + let mut probe_seq = ProbeSequence::new_raw(page_id, meta_map, seed); let mut i = 0; loop { @@ -673,7 +673,7 @@ fn allocate_bucket_raw( // Give up. return None; } - match probe_seq.next(&meta_map) { + match probe_seq.next(meta_map) { ProbeResult::PossibleHit(_) => continue, ProbeResult::Tombstone(bucket) | ProbeResult::Empty(bucket) => { meta_map.set_full(bucket as usize, probe_seq.hash); diff --git a/nomt/src/bitbox/wal/read.rs b/nomt/src/bitbox/wal/read.rs index aabd2df7a9..a5a99db3f3 100644 --- a/nomt/src/bitbox/wal/read.rs +++ b/nomt/src/bitbox/wal/read.rs @@ -45,7 +45,7 @@ impl WalBlobReader { pub fn new(page_pool: &PagePool, mut wal_fd: &File) -> anyhow::Result { let stat = wal_fd.metadata()?; let file_size = stat.len() as usize; - if file_size % PAGE_SIZE != 0 { + if !file_size.is_multiple_of(PAGE_SIZE) { anyhow::bail!("WAL file size is not a multiple of the page size"); } @@ -62,7 +62,7 @@ impl WalBlobReader { Err(e) => return Err(e.into()), }; pn += 1; - wal.extend_from_slice(&*page); + wal.extend_from_slice(&page); } let mut reader = Self { diff --git a/nomt/src/bitbox/wal/write.rs b/nomt/src/bitbox/wal/write.rs index b3d17c5bdc..29d88fd562 100644 --- a/nomt/src/bitbox/wal/write.rs +++ b/nomt/src/bitbox/wal/write.rs @@ -37,7 +37,7 @@ impl Mmap { /// updating `self.size` to the new size and potentially `self.ptr` to point to the new /// mapping, if the kernel decided to move it. fn resize(&mut self, new_size: usize) -> bool { - assert!(new_size % PAGE_SIZE == 0); + assert!(new_size.is_multiple_of(PAGE_SIZE)); #[cfg(target_os = "linux")] unsafe { @@ -197,7 +197,7 @@ impl WalBlobBuilder { let ptr = self.mmap.ptr; // round up to the nearest page size. - let len = (self.cur + PAGE_SIZE - 1) / PAGE_SIZE * PAGE_SIZE; + let len = self.cur.div_ceil(PAGE_SIZE) * PAGE_SIZE; // Note we don't madvise(DONTNEED) or any other tricks for now. If we did, then each time // we write a page it would need to be mounted and thus zero filled. diff --git a/nomt/src/io/page_pool.rs b/nomt/src/io/page_pool.rs index 6fa6a91db8..a7269aa566 100644 --- a/nomt/src/io/page_pool.rs +++ b/nomt/src/io/page_pool.rs @@ -51,6 +51,7 @@ impl Page { /// 2. that the [`PagePool`] is the same that was used to allocate the page. /// 3. that the [`PagePool`] is not dropped while the slice is used. /// 4. that there is only a single mutable slice into the page at any given time. + #[allow(clippy::mut_from_ref)] pub unsafe fn as_mut_slice(&self) -> &mut [u8] { std::slice::from_raw_parts_mut(self.as_mut_ptr(), PAGE_SIZE) } @@ -89,7 +90,7 @@ impl FatPage { impl Clone for FatPage { fn clone(&self) -> Self { let mut new_page = self.page_pool.alloc_fat_page(); - new_page.copy_from_slice(&*self); + new_page.copy_from_slice(self); new_page } } diff --git a/nomt/src/io/unix.rs b/nomt/src/io/unix.rs index d4b0a24e85..ea720ba575 100644 --- a/nomt/src/io/unix.rs +++ b/nomt/src/io/unix.rs @@ -65,7 +65,7 @@ fn execute(mut command: IoCommand) -> CompleteIo { ) }, IoKind::WriteArc(fd, page_index, ref page) => unsafe { - let page: &[u8] = &*page; + let page: &[u8] = page; libc::pwrite( fd, page.as_ptr() as *const libc::c_void, diff --git a/nomt/src/lib.rs b/nomt/src/lib.rs index 1e82e2cf21..e8d512e132 100644 --- a/nomt/src/lib.rs +++ b/nomt/src/lib.rs @@ -262,7 +262,7 @@ impl Nomt { /// Returns a recent root of the trie. pub fn root(&self) -> Root { - self.shared.lock().root.clone() + self.shared.lock().root } /// Returns true if the trie has no items in it. @@ -399,7 +399,7 @@ impl Nomt { actuals.push((key, value)); } - sess.finish(actuals)?.commit(&self)?; + sess.finish(actuals)?.commit(self)?; Ok(()) } diff --git a/nomt/src/merkle/page_set.rs b/nomt/src/merkle/page_set.rs index c39faf7851..e66fbcbe6a 100644 --- a/nomt/src/merkle/page_set.rs +++ b/nomt/src/merkle/page_set.rs @@ -96,17 +96,17 @@ impl PageSet { impl super::page_walker::PageSet for PageSet { fn fresh(&self, page_id: &PageId) -> PageMut { - let page = PageMut::pristine_empty(&self.page_pool, &page_id); - page + + PageMut::pristine_empty(&self.page_pool, page_id) } fn contains(&self, page_id: &PageId) -> bool { - self.map.contains_key(&page_id) + self.map.contains_key(page_id) } fn get(&self, page_id: &PageId) -> Option<(Page, PageOrigin)> { self.map - .get(&page_id) + .get(page_id) .map(|(p, page_origin)| (p.clone(), page_origin.clone())) .or_else(|| self.get_warmed_up(page_id)) } diff --git a/nomt/src/merkle/page_walker.rs b/nomt/src/merkle/page_walker.rs index 18fd6be908..f84ff94c01 100644 --- a/nomt/src/merkle/page_walker.rs +++ b/nomt/src/merkle/page_walker.rs @@ -355,7 +355,7 @@ impl PageWalker { ); self.down(page_set, &down[1..], true); } else { - self.down(page_set, &down, true); + self.down(page_set, down, true); } if self.position.is_root() { @@ -628,8 +628,8 @@ impl PageWalker { match page_id { Some(page_id) => { if let Some(ref parent_page) = self.parent_page { - assert!(&page_id != &parent_page); - assert!(page_id.is_descendant_of(&parent_page)); + assert!(page_id != parent_page); + assert!(page_id.is_descendant_of(parent_page)); } } None => assert!(self.parent_page.is_none()), @@ -661,7 +661,7 @@ impl PageWalker { .stack .last() .map(|item| item.page_id.clone()) - .or(self.parent_page.as_ref().map(|p| p.clone())); + .or(self.parent_page.clone()); let start_len = self.stack.len(); let mut cur_ancestor = page_id; @@ -1427,12 +1427,10 @@ mod tests { }) }; - let expected_siblings = vec![ - (node_hash(path_1, val(1)), 1), + let expected_siblings = [(node_hash(path_1, val(1)), 1), (node_hash(path_2, val(2)), 2), (node_hash(path_3, val(3)), 3), - (node_hash(path_4, val(4)), 4), - ]; + (node_hash(path_4, val(4)), 4)]; // replace those leaf nodes one at a time. // the sibling stack will be populated as we go. @@ -2175,7 +2173,7 @@ mod tests { updates.iter().find(|update| update.page_id == ROOT_PAGE_ID); updates .iter() - .find(|update| update.page_id.length_dependent_encoding() == &[24]); + .find(|update| update.page_id.length_dependent_encoding() == [24]); page_set.apply(updates); let mut page_id = ROOT_PAGE_ID; @@ -2198,7 +2196,7 @@ mod tests { // Make sure that elision bitfield was updated correctly. let reconstructed_page = reconstructed_pages .iter() - .find(|(page_id, _, _, _, _)| page_id.length_dependent_encoding() == &[24, 24]) + .find(|(page_id, _, _, _, _)| page_id.length_dependent_encoding() == [24, 24]) .map(|(_, page, _, _, _)| page) .unwrap(); @@ -2250,7 +2248,7 @@ mod tests { .map(|idx| correct_pages.remove(idx).page) .unwrap(); - let page = if page_id.length_dependent_encoding() == &[24, 24] { + let page = if page_id.length_dependent_encoding() == [24, 24] { // The correct pages are build without elision, // so the elided children bitfield is not present. let mut no_bitfield_page = page.deep_copy(); diff --git a/nomt/src/merkle/seek.rs b/nomt/src/merkle/seek.rs index 6b7cbc4f4c..8dc0fb003c 100644 --- a/nomt/src/merkle/seek.rs +++ b/nomt/src/merkle/seek.rs @@ -114,11 +114,11 @@ impl SeekRequest { RequestState::FetchingLeaf { ref mut needed_leaves, .. - } => needed_leaves.next().map(|pn| IoQuery::LeafPage(pn)), + } => needed_leaves.next().map(IoQuery::LeafPage), RequestState::FetchingLeaves { ref mut needed_leaves, .. - } => needed_leaves.next().map(|pn| IoQuery::LeafPage(pn)), + } => needed_leaves.next().map(IoQuery::LeafPage), RequestState::Completed(_) => None, } } @@ -137,7 +137,7 @@ impl SeekRequest { }; // terminator should have yielded completion. - assert!(self.position.depth() as usize % DEPTH == 0); + assert!((self.position.depth() as usize).is_multiple_of(DEPTH)); self.page_id = Some(page_id.clone()); @@ -254,17 +254,17 @@ impl SeekRequest { } Some(IterOutput::Item(key, value)) => { let (new_d_idx, should_skip) = - manage_deletions(&overlay_deletions, deletions_idx, &key); + manage_deletions(overlay_deletions, deletions_idx, &key); deletions_idx = new_d_idx; if should_skip { continue; } - break (key, H::hash_value(&value)); + break (key, H::hash_value(value)); } Some(IterOutput::OverflowItem(key, value_hash, _)) => { let (new_d_idx, should_skip) = - manage_deletions(&overlay_deletions, deletions_idx, &key); + manage_deletions(overlay_deletions, deletions_idx, &key); deletions_idx = new_d_idx; if should_skip { continue; @@ -307,7 +307,7 @@ impl SeekRequest { match iter_output { IterOutput::Blocked => return, IterOutput::Item(key, value) => { - collected_leaf_data.push((key, H::hash_value(&value))) + collected_leaf_data.push((key, H::hash_value(value))) } IterOutput::OverflowItem(key, value_hash, _) => { collected_leaf_data.push((key, value_hash)) @@ -472,7 +472,7 @@ impl RequestState { // If an insertion is found within the overlay, it is expected to be // the item associated with the leaf that is being fetched. ValueChange::Insert(value) => H::hash_value(value), - ValueChange::InsertOverflow(_, value_hash) => value_hash.clone(), + ValueChange::InsertOverflow(_, value_hash) => *value_hash, }; return RequestState::Completed(Some(trie::LeafData { @@ -515,7 +515,7 @@ fn range_bounds(raw_path: KeyPath, depth: usize) -> (KeyPath, Option) { return (KeyPath::default(), None); } let start = raw_path; - let mut end = start.clone(); + let mut end = start; let mut depth = depth - 1; loop { let end_bits = end.view_bits_mut::(); @@ -631,7 +631,7 @@ impl Seeker { /// Take the result of a complete request. pub fn take_completion(&mut self) -> Option { - if self.requests.front().map_or(false, |r| r.is_completed()) { + if self.requests.front().is_some_and(|r| r.is_completed()) { // UNWRAP: just checked existence. let request = self.requests.pop_front().unwrap(); // PANIC: checked above. diff --git a/nomt/src/merkle/worker.rs b/nomt/src/merkle/worker.rs index c1811f3f66..db579b2bb7 100644 --- a/nomt/src/merkle/worker.rs +++ b/nomt/src/merkle/worker.rs @@ -341,7 +341,7 @@ impl RangeUpdater { // find batch size. for (k, v) in &self.shared.read_write[start_index..] { - if !seek_result.position.subtrie_contains(&k) { + if !seek_result.position.subtrie_contains(k) { break; } batch_size += 1; @@ -362,7 +362,7 @@ impl RangeUpdater { let is_non_exclusive = seek_result .page_id .as_ref() - .map_or(true, |p_id| !self.region.contains_exclusive(p_id)); + .is_none_or(|p_id| !self.region.contains_exclusive(p_id)); if is_non_exclusive { self.shared.push_pending_subtrie( @@ -417,7 +417,7 @@ impl RangeUpdater { match ops { None => self.page_walker.advance(seek_result.position.clone()), Some(ref ops) => { - let ops = nomt_core::update::leaf_ops_spliced(seek_result.terminal.clone(), &ops); + let ops = nomt_core::update::leaf_ops_spliced(seek_result.terminal.clone(), ops); self.page_walker .advance_and_replace(page_set, seek_result.position.clone(), ops) } @@ -464,7 +464,7 @@ impl RangeUpdater { while start_index < self.range_end || !seeker.is_empty() { let completion = if warmed_up .front() - .map_or(false, |res| match seeker.first_key() { + .is_some_and(|res| match seeker.first_key() { None => true, Some(k) => &res.key < k, }) { @@ -541,7 +541,7 @@ impl RangeUpdater { self.shared.push_pending_root_nodes(new_nodes); - return Ok(self.write_pass.consume()); + Ok(self.write_pass.consume()) } } @@ -550,7 +550,7 @@ fn subtrie_ops(read_write: &[(KeyPath, KeyReadWrite)]) -> Vec<(KeyPath, Option { - Some((key.clone(), val.clone())) + Some((*key, *val)) } KeyReadWrite::Read(_) => None, }) diff --git a/nomt/src/metrics.rs b/nomt/src/metrics.rs index fa45acdee0..8cb6ac1744 100644 --- a/nomt/src/metrics.rs +++ b/nomt/src/metrics.rs @@ -67,14 +67,14 @@ impl Metrics { /// /// panics if the specified [`Metric`] is not a Timer pub fn record<'a>(&'a self, metric: Metric) -> Option { - self.metrics.as_ref().and_then(|metrics| { + self.metrics.as_ref().map(|metrics| { let timer = match metric { Metric::PageFetchTime => &metrics.page_fetch_time, Metric::ValueFetchTime => &metrics.value_fetch_time, _ => panic!("Specified metric is not a Timer"), }; - Some(timer.record()) + timer.record() }) } diff --git a/nomt/src/overlay.rs b/nomt/src/overlay.rs index 8cd9c453b9..f5ddba40e9 100644 --- a/nomt/src/overlay.rs +++ b/nomt/src/overlay.rs @@ -286,7 +286,7 @@ impl LiveOverlay { .unwrap_or(&parent.data) .parent_status .as_ref() - .map_or(false, |status| !status.is_committed()) + .is_some_and(|status| !status.is_committed()) { return Err(InvalidAncestors::Incomplete); } @@ -307,7 +307,7 @@ impl LiveOverlay { pub(super) fn page(&self, page_id: &PageId) -> Option<&DirtyPage> { self.parent .as_ref() - .and_then(|parent| parent.index.pages.get(&page_id)) + .and_then(|parent| parent.index.pages.get(page_id)) .and_then(|seqn| seqn.checked_sub(self.min_seqn)) .map(|seqn_diff| { if seqn_diff as usize == self.ancestor_data.len() { @@ -355,11 +355,11 @@ impl LiveOverlay { } /// Iterate all value changes within the given key bounds. - pub(super) fn value_iter<'a>( - &'a self, + pub(super) fn value_iter( + &self, start: KeyPath, end: Option, - ) -> impl Iterator { + ) -> impl Iterator { self.parent .as_ref() .map(move |parent| { @@ -367,7 +367,7 @@ impl LiveOverlay { .index .values .range(start..) - .take_while(move |(k, _)| end.as_ref().map_or(true, |end| end > k)) + .take_while(move |(k, _)| end.as_ref().is_none_or(|end| end > k)) .filter_map(|(k, seqn)| seqn.checked_sub(self.min_seqn).map(|s| (k, s))) .map(|(k, seqn_diff)| (*k, self.value_inner(k, seqn_diff))) }) @@ -632,7 +632,7 @@ mod tests { LiveOverlay::new(ancestors.iter().take(2)), Err(InvalidAncestors::Incomplete) )); - assert!(matches!(LiveOverlay::new(ancestors.iter().take(3)), Ok(_))); + assert!(LiveOverlay::new(ancestors.iter().take(3)).is_ok()); } #[test] @@ -721,7 +721,7 @@ mod tests { LiveOverlay::new(ancestors.iter().take(1)), Err(InvalidAncestors::Incomplete) )); - assert!(matches!(LiveOverlay::new(ancestors.iter().take(2)), Ok(_))); + assert!(LiveOverlay::new(ancestors.iter().take(2)).is_ok()); } #[test] diff --git a/nomt/src/page_cache.rs b/nomt/src/page_cache.rs index d061be4436..8a61608790 100644 --- a/nomt/src/page_cache.rs +++ b/nomt/src/page_cache.rs @@ -20,7 +20,7 @@ use std::{collections::HashMap, fmt, num::NonZeroUsize, sync::Arc}; // Total number of nodes stored in one Page. It depends on the `DEPTH` // of the rootless sub-binary tree stored in a page following this formula: // (2^(DEPTH + 1)) - 2 -pub const NODES_PER_PAGE: usize = (1 << DEPTH + 1) - 2; +pub const NODES_PER_PAGE: usize = (1 << (DEPTH + 1)) - 2; #[inline] fn read_node(data: &FatPage, index: usize) -> Node { diff --git a/nomt/src/page_region.rs b/nomt/src/page_region.rs index df9ce55d7d..a515871312 100644 --- a/nomt/src/page_region.rs +++ b/nomt/src/page_region.rs @@ -101,7 +101,7 @@ impl PageRegion { /// Whether the region contains a page ID non-exclusively. pub fn contains_non_exclusive(&self, page: &PageId) -> bool { - self.non_exclusive_max().map_or(false, |non_exclusive_max| { + self.non_exclusive_max().is_some_and(|non_exclusive_max| { page == &non_exclusive_max || non_exclusive_max.is_descendant_of(page) }) } diff --git a/nomt/src/rw_pass_cell/mod.rs b/nomt/src/rw_pass_cell/mod.rs index fdbc86fde9..4b094def52 100644 --- a/nomt/src/rw_pass_cell/mod.rs +++ b/nomt/src/rw_pass_cell/mod.rs @@ -205,15 +205,15 @@ impl WritePass { /// Panics if any of the regions overlap with each other or are not encompassed by the /// region of this pass. pub fn split_n(mut self, regions: Vec) -> Vec { - if regions.len() == 0 { + if regions.is_empty() { return Vec::new(); } for (i, region) in regions.iter().enumerate() { - assert!(self.region().encompasses(®ion)); + assert!(self.region().encompasses(region)); for other_region in regions.iter().skip(i + 1) { - assert!(region.excludes_unique(&other_region)); + assert!(region.excludes_unique(other_region)); } } diff --git a/nomt/src/seglog/mod.rs b/nomt/src/seglog/mod.rs index cb1413c821..1254f79267 100644 --- a/nomt/src/seglog/mod.rs +++ b/nomt/src/seglog/mod.rs @@ -365,7 +365,7 @@ impl SegmentedLog { } self.root_dir_fd.sync_data()?; - if let Some(head_segment_writer) = self.head_segment_writer.take().take() { + if let Some(head_segment_writer) = self.head_segment_writer.take() { let file = head_segment_writer.into_inner(); drop(file); } @@ -426,13 +426,13 @@ impl Recovery { } fn scan_root_dir(&mut self, root_dir_path: &PathBuf, filename_prefix: &str) -> Result<()> { - let dir = fs::read_dir(&root_dir_path)?; + let dir = fs::read_dir(root_dir_path)?; for entry in dir { let entry = entry?; let filename = entry.file_name(); if let Some(filename) = filename.to_str() { let path = entry.path(); - if filename.starts_with(&filename_prefix) { + if filename.starts_with(filename_prefix) { let id = segment_filename::parse(filename_prefix, filename)?; self.candidates.push(Segment { id, @@ -517,7 +517,7 @@ impl Recovery { if min.is_none() { min = Some(record_id); } - if max.map_or(true, |max| record_id > max) { + if max.is_none_or(|max| record_id > max) { max = Some(record_id); } last = Some(record_id); @@ -525,8 +525,8 @@ impl Recovery { // If the segment is empty, we set the min and max to nil. They are always Some after this // function returns. let candidate = &mut self.candidates[index]; - candidate.min = min.unwrap_or(0.into()).into(); - candidate.max = max.unwrap_or(0.into()).into(); + candidate.min = min.unwrap_or(0.into()); + candidate.max = max.unwrap_or(0.into()); Ok(()) } @@ -624,15 +624,14 @@ fn truncate_head_segment( ) -> std::io::Result { let end = match scan_record_end(path, new_end_live)? { None => { - return Err(std::io::Error::new( - std::io::ErrorKind::Other, + return Err(std::io::Error::other( anyhow::anyhow!("Failed to find the last live record in the head segment"), )); } Some(offset) => offset, }; - let mut file = OpenOptions::new().append(true).write(true).open(path)?; + let mut file = OpenOptions::new().append(true).open(path)?; file.set_len(end)?; file.sync_data()?; file.seek(SeekFrom::Start(end))?; @@ -923,9 +922,9 @@ mod tests { assert_eq!(records.len(), 0); drop(records); - let record_id_1 = log.append(&vec![1u8; 10])?; - let record_id_2 = log.append(&vec![2u8; 10])?; - let record_id_3 = log.append(&vec![3u8; 10])?; + let record_id_1 = log.append(&[1u8; 10])?; + let record_id_2 = log.append(&[2u8; 10])?; + let record_id_3 = log.append(&[3u8; 10])?; drop(log); assert_eq!(record_id_1, RecordId::from(1)); @@ -948,9 +947,9 @@ mod tests { let max_segment_size = default_max_segment_size(); let h = TestHarness::new()?; - h.new_segment(1)?.write_record(1, &vec![1u8; 10])?.write()?; - h.new_segment(2)?.write_record(2, &vec![2u8; 5])?.write()?; - h.new_segment(3)?.write_record(3, &vec![3u8; 10])?.write()?; + h.new_segment(1)?.write_record(1, &[1u8; 10])?.write()?; + h.new_segment(2)?.write_record(2, &[2u8; 5])?.write()?; + h.new_segment(3)?.write_record(3, &[3u8; 10])?.write()?; let (_log, records) = h.open_log(max_segment_size, 1, 3)?; assert_eq!(records.len(), 3); @@ -968,10 +967,10 @@ mod tests { let h = TestHarness::new()?; h.new_segment(1)? - .write_record(1, &vec![1u8; 10])? - .write_record(2, &vec![2u8; 10])? + .write_record(1, &[1u8; 10])? + .write_record(2, &[2u8; 10])? .write()?; - h.new_segment(2)?.write_record(3, &vec![3u8; 10])?.write()?; + h.new_segment(2)?.write_record(3, &[3u8; 10])?.write()?; h.assert_segment_file_count(2)?; let max_segment_size = default_max_segment_size(); let (_log, records) = h.open_log(max_segment_size, 1, 2)?; @@ -993,8 +992,8 @@ mod tests { let h = TestHarness::new()?; h.new_segment(1)? - .write_record(1, &vec![1u8; 10])? - .write_record(2, &vec![2u8; 10])? + .write_record(1, &[1u8; 10])? + .write_record(2, &[2u8; 10])? .write()?; h.new_segment(2)? .write_header_only(RecordId::from(3), 16)? @@ -1022,16 +1021,16 @@ mod tests { let h = TestHarness::new()?; h.new_segment(1)? - .write_record(1, &vec![1u8; 10])? - .write_record(2, &vec![2u8; 10])? + .write_record(1, &[1u8; 10])? + .write_record(2, &[2u8; 10])? .write()?; h.new_segment(2)? - .write_record(3, &vec![3u8; 10])? - .write_record(4, &vec![4u8; 10])? + .write_record(3, &[3u8; 10])? + .write_record(4, &[4u8; 10])? .write()?; h.new_segment(3)? - .write_record(5, &vec![5u8; 10])? - .write_record(6, &vec![6u8; 10])? + .write_record(5, &[5u8; 10])? + .write_record(6, &[6u8; 10])? .write()?; let (_log, records) = h.open_log(default_max_segment_size(), 4, 5)?; @@ -1047,8 +1046,8 @@ mod tests { fn recovery_fail_gap_in_segments() -> Result<()> { let h = TestHarness::new()?; - h.new_segment(1)?.write_record(1, &vec![1u8; 10])?.write()?; - h.new_segment(3)?.write_record(3, &vec![3u8; 10])?.write()?; + h.new_segment(1)?.write_record(1, &[1u8; 10])?.write()?; + h.new_segment(3)?.write_record(3, &[3u8; 10])?.write()?; let err = h.open_log(default_max_segment_size(), 1, 3); match err { Err(err) => { @@ -1065,8 +1064,8 @@ mod tests { let h = TestHarness::new()?; h.new_segment(1)? - .write_record(1, &vec![1u8])? - .write_record(3, &vec![2u8])? + .write_record(1, &[1u8])? + .write_record(3, &[2u8])? .write()?; let err = h.open_log(default_max_segment_size(), 1, 3); match err { @@ -1092,7 +1091,7 @@ mod tests { h.new_segment(1)? .write_header_only(RecordId::from(1), 10)? .write()?; - h.new_segment(2)?.write_record(2, &vec![2u8; 10])?.write()?; + h.new_segment(2)?.write_record(2, &[2u8; 10])?.write()?; let err = h.open_log(default_max_segment_size(), 1, 2); match err { Ok(_) => panic!("Expected error"), @@ -1109,7 +1108,7 @@ mod tests { let h = TestHarness::new()?; // Empty non-head segment. h.new_segment(1)?.write()?; - h.new_segment(2)?.write_record(2, &vec![2u8; 10])?.write()?; + h.new_segment(2)?.write_record(2, &[2u8; 10])?.write()?; h.open_log(default_max_segment_size(), 2, 2).unwrap(); Ok(()) } @@ -1120,12 +1119,12 @@ mod tests { let max_segment_size = max_segment_size_for_n_records(2); let h = TestHarness::new()?; h.new_segment(1)? - .write_record(1, &vec![1u8; 10])? - .write_record(2, &vec![2u8; 10])? + .write_record(1, &[1u8; 10])? + .write_record(2, &[2u8; 10])? .write()?; h.new_segment(2)? - .write_record(3, &vec![3u8; 10])? - .write_record(4, &vec![4u8; 10])? + .write_record(3, &[3u8; 10])? + .write_record(4, &[4u8; 10])? .write()?; // Recover the log. Only first two records should be present. @@ -1135,8 +1134,8 @@ mod tests { assert_eq!(records[1], (RecordId::from(2), vec![2u8; 10])); // Append new records. - let record_id_3 = log.append(&vec![5u8; 10])?; - let record_id_4 = log.append(&vec![6u8; 10])?; + let record_id_3 = log.append(&[5u8; 10])?; + let record_id_4 = log.append(&[6u8; 10])?; drop(log); assert_eq!(record_id_3, RecordId::from(3)); @@ -1161,11 +1160,11 @@ mod tests { let max_segment_size = max_segment_size_for_n_records(2); let h = TestHarness::new()?; h.new_segment(1)? - .write_record(1, &vec![1u8; 10])? - .write_record(2, &vec![2u8; 10])? + .write_record(1, &[1u8; 10])? + .write_record(2, &[2u8; 10])? .write()?; h.new_segment(2)? - .write_record(3, &vec![3u8; 10])? + .write_record(3, &[3u8; 10])? .write_header_only(RecordId::from(4), 10)? .write()?; @@ -1180,8 +1179,8 @@ mod tests { assert_eq!(records[2], (RecordId::from(3), vec![3u8; 10])); // Append new records. - let record_id_4 = log.append(&vec![5u8; 10])?; - let record_id_5 = log.append(&vec![6u8; 10])?; + let record_id_4 = log.append(&[5u8; 10])?; + let record_id_5 = log.append(&[6u8; 10])?; drop(log); assert_eq!(record_id_4, RecordId::from(4)); @@ -1205,9 +1204,9 @@ mod tests { #[test] fn prune_oldest() -> Result<()> { let h = TestHarness::new()?; - h.new_segment(1)?.write_record(1, &vec![1u8; 10])?.write()?; - h.new_segment(2)?.write_record(2, &vec![2u8; 10])?.write()?; - h.new_segment(3)?.write_record(3, &vec![3u8; 10])?.write()?; + h.new_segment(1)?.write_record(1, &[1u8; 10])?.write()?; + h.new_segment(2)?.write_record(2, &[2u8; 10])?.write()?; + h.new_segment(3)?.write_record(3, &[3u8; 10])?.write()?; let (mut log, _records) = h.open_log(default_max_segment_size(), 1, 3)?; h.assert_segment_file_count(3)?; @@ -1229,9 +1228,9 @@ mod tests { #[test] fn prune_recent() -> Result<()> { let h = TestHarness::new()?; - h.new_segment(1)?.write_record(1, &vec![1u8; 10])?.write()?; - h.new_segment(2)?.write_record(2, &vec![2u8; 10])?.write()?; - h.new_segment(3)?.write_record(3, &vec![3u8; 10])?.write()?; + h.new_segment(1)?.write_record(1, &[1u8; 10])?.write()?; + h.new_segment(2)?.write_record(2, &[2u8; 10])?.write()?; + h.new_segment(3)?.write_record(3, &[3u8; 10])?.write()?; let (mut log, _records) = h.open_log(default_max_segment_size(), 1, 3)?; h.assert_segment_file_count(3)?; @@ -1258,7 +1257,7 @@ mod tests { fn test_live_range_empty_log_append() -> Result<()> { let h = TestHarness::new()?; let (mut log, _) = h.open_log(default_max_segment_size(), 0, 0)?; - let record_id_1 = log.append(&vec![1u8; 10])?; + let record_id_1 = log.append(&[1u8; 10])?; assert_eq!(record_id_1, RecordId::from(1)); assert_eq!(log.live_range(), (RecordId::from(1), RecordId::from(1))); Ok(()) @@ -1271,17 +1270,17 @@ mod tests { // Test that the new log has live range (0,0) let (mut log, _) = h.open_log(default_max_segment_size(), 0, 0)?; assert_eq!(log.live_range(), (RecordId::nil(), RecordId::nil())); - let record_id_1 = log.append(&vec![1u8; 10])?; + let record_id_1 = log.append(&[1u8; 10])?; assert_eq!(log.live_range(), (RecordId::from(1), RecordId::from(1))); drop(log); // Reopen the log and append another record. let (mut log, _) = h.open_log(default_max_segment_size(), 1, 1)?; - let record_id_2 = log.append(&vec![2u8; 10])?; + let record_id_2 = log.append(&[2u8; 10])?; assert_eq!(log.live_range(), (record_id_1, record_id_2)); // Test that appending to a log with live range (1, 1) updates its live range to (1, 2) - let record_id_3 = log.append(&vec![3u8; 10])?; + let record_id_3 = log.append(&[3u8; 10])?; assert_eq!(log.live_range(), (record_id_1, record_id_3)); Ok(()) @@ -1290,11 +1289,11 @@ mod tests { #[test] fn test_live_range_append_to_nonempty_log() -> Result<()> { let h = TestHarness::new()?; - h.new_segment(1)?.write_record(1, &vec![1u8; 10])?.write()?; - h.new_segment(2)?.write_record(2, &vec![2u8; 10])?.write()?; + h.new_segment(1)?.write_record(1, &[1u8; 10])?.write()?; + h.new_segment(2)?.write_record(2, &[2u8; 10])?.write()?; let (mut log, _) = h.open_log(default_max_segment_size(), 1, 2)?; assert_eq!(log.live_range(), (RecordId::from(1), RecordId::from(2))); - let record_id_3 = log.append(&vec![3u8; 10])?; + let record_id_3 = log.append(&[3u8; 10])?; assert_eq!(log.live_range(), (RecordId::from(1), record_id_3)); Ok(()) } @@ -1302,8 +1301,8 @@ mod tests { #[test] fn test_live_range_prune_oldest() -> Result<()> { let h = TestHarness::new()?; - h.new_segment(1)?.write_record(1, &vec![1u8; 10])?.write()?; - h.new_segment(2)?.write_record(2, &vec![2u8; 10])?.write()?; + h.new_segment(1)?.write_record(1, &[1u8; 10])?.write()?; + h.new_segment(2)?.write_record(2, &[2u8; 10])?.write()?; let (mut log, _) = h.open_log(default_max_segment_size(), 1, 2)?; assert_eq!(log.live_range(), (RecordId::from(1), RecordId::from(2))); log.prune_oldest(2.into())?; @@ -1314,8 +1313,8 @@ mod tests { #[test] fn test_live_range_prune_recent() -> Result<()> { let h = TestHarness::new()?; - h.new_segment(1)?.write_record(1, &vec![1u8; 10])?.write()?; - h.new_segment(2)?.write_record(2, &vec![2u8; 10])?.write()?; + h.new_segment(1)?.write_record(1, &[1u8; 10])?.write()?; + h.new_segment(2)?.write_record(2, &[2u8; 10])?.write()?; let (mut log, _) = h.open_log(default_max_segment_size(), 1, 2)?; assert_eq!(log.live_range(), (RecordId::from(1), RecordId::from(2))); log.prune_recent(1.into())?; @@ -1354,8 +1353,8 @@ mod tests { #[test] fn test_live_range_prune_recent_to_empty() -> Result<()> { let h = TestHarness::new()?; - h.new_segment(1)?.write_record(1, &vec![1u8; 10])?.write()?; - h.new_segment(2)?.write_record(2, &vec![2u8; 10])?.write()?; + h.new_segment(1)?.write_record(1, &[1u8; 10])?.write()?; + h.new_segment(2)?.write_record(2, &[2u8; 10])?.write()?; let (mut log, _) = h.open_log(default_max_segment_size(), 1, 2)?; assert_eq!(log.live_range(), (RecordId::from(1), RecordId::from(2))); log.prune_recent(0.into())?; @@ -1367,8 +1366,8 @@ mod tests { #[test] fn test_live_range_prune_oldest_to_empty() -> Result<()> { let h = TestHarness::new()?; - h.new_segment(1)?.write_record(1, &vec![1u8; 10])?.write()?; - h.new_segment(2)?.write_record(2, &vec![2u8; 10])?.write()?; + h.new_segment(1)?.write_record(1, &[1u8; 10])?.write()?; + h.new_segment(2)?.write_record(2, &[2u8; 10])?.write()?; let (mut log, _) = h.open_log(default_max_segment_size(), 1, 2)?; assert_eq!(log.live_range(), (RecordId::from(1), RecordId::from(2))); log.prune_oldest(0.into())?; diff --git a/nomt/src/seglog/segment_rw.rs b/nomt/src/seglog/segment_rw.rs index 7019093188..c4780df8ff 100644 --- a/nomt/src/seglog/segment_rw.rs +++ b/nomt/src/seglog/segment_rw.rs @@ -45,7 +45,7 @@ impl SegmentFileWriter { // Calculate the next aligned position. let record_alignment = RECORD_ALIGNMENT as u64; let current_end = self.file_size + payload.len() as u64; - let next_pos = if current_end % record_alignment == 0 { + let next_pos = if current_end.is_multiple_of(record_alignment) { current_end } else { ((current_end / record_alignment) + 1) * record_alignment @@ -118,8 +118,7 @@ impl SegmentFileReader { self.buf_reader .seek(SeekFrom::Current(-(HEADER_SIZE as i64)))?; - return Err(std::io::Error::new( - std::io::ErrorKind::Other, + return Err(std::io::Error::other( anyhow::anyhow!( "Record payload length is too large: {}", header.payload_length() @@ -131,8 +130,7 @@ impl SegmentFileReader { // an integer number of pages. let cur_pos = self.buf_reader.stream_position()?; let record_alignment = RECORD_ALIGNMENT as u64; - let next_pos = ((cur_pos + self.payload_length.unwrap() as u64 + record_alignment - 1) - / record_alignment) + let next_pos = (cur_pos + self.payload_length.unwrap() as u64).div_ceil(record_alignment) * record_alignment; self.next_pos = Some(next_pos); Ok(Some(header)) @@ -167,7 +165,7 @@ impl SegmentFileReader { /// Returns the current position of the reader. pub fn pos(&mut self) -> std::io::Result { - Ok(self.buf_reader.stream_position()?) + self.buf_reader.stream_position() } } @@ -360,12 +358,10 @@ mod tests { let temp_file = NamedTempFile::new().unwrap(); let mut writer = SegmentFileWriter::new(temp_file.reopen().unwrap(), 0); - let payloads = vec![ - vec![1, 2, 3], + let payloads = [vec![1, 2, 3], vec![4, 5, 6, 7], vec![8; RECORD_ALIGNMENT as usize - HEADER_SIZE as usize], - vec![9; RECORD_ALIGNMENT as usize * 2 - HEADER_SIZE as usize + 1], - ]; + vec![9; RECORD_ALIGNMENT as usize * 2 - HEADER_SIZE as usize + 1]]; for (i, payload) in payloads.iter().enumerate() { writer @@ -411,7 +407,7 @@ mod tests { let mut writer = SegmentFileWriter::new(temp_file.reopen().unwrap(), 0); // Write a header with a payload length larger than MAX_RECORD_PAYLOAD_SIZE - let oversized_payload_length = MAX_RECORD_PAYLOAD_SIZE as u32 + 1; + let oversized_payload_length = MAX_RECORD_PAYLOAD_SIZE + 1; writer .write_header(oversized_payload_length, RecordId(1)) .unwrap(); diff --git a/nomt/src/store/meta.rs b/nomt/src/store/meta.rs index 94d125f193..be52bea1ae 100644 --- a/nomt/src/store/meta.rs +++ b/nomt/src/store/meta.rs @@ -112,7 +112,7 @@ impl Meta { errors.push(format!("invalid magic: {:?}", self.magic)); } if self.version < 1 { - errors.push(format!("invalid version: 0")); + errors.push("invalid version: 0".to_string()); } else if self.version > VERSION { errors.push(format!( "DB manifest version ({}) is newer than supported ({})", diff --git a/nomt/src/store/mod.rs b/nomt/src/store/mod.rs index a3f986baae..061196ec26 100644 --- a/nomt/src/store/mod.rs +++ b/nomt/src/store/mod.rs @@ -60,7 +60,7 @@ impl Store { let should_create = !o.path.exists() || is_directory_empty(o.path.as_path())?; if should_create { // NB: note TOCTOU here. Deemed acceptable for this case. - (db_dir_fd, flock) = create(&page_pool, &o)?; + (db_dir_fd, flock) = create(&page_pool, o)?; } else { let mut options = OpenOptions::new(); options.read(true); @@ -94,7 +94,7 @@ impl Store { if o_direct { options.custom_flags(libc::O_DIRECT); } - options.open(&o.path.join("meta"))? + options.open(o.path.join("meta"))? }; let ln_fd = { @@ -104,7 +104,7 @@ impl Store { if o_direct { options.custom_flags(libc::O_DIRECT); } - Arc::new(options.open(&o.path.join("ln"))?) + Arc::new(options.open(o.path.join("ln"))?) }; let bbn_fd = { let mut options = OpenOptions::new(); @@ -113,7 +113,7 @@ impl Store { if o_direct { options.custom_flags(libc::O_DIRECT); } - Arc::new(options.open(&o.path.join("bbn"))?) + Arc::new(options.open(o.path.join("bbn"))?) }; let ht_fd = { let mut options = OpenOptions::new(); @@ -122,7 +122,7 @@ impl Store { if o_direct { options.custom_flags(libc::O_DIRECT); } - options.open(&o.path.join("ht"))? + options.open(o.path.join("ht"))? }; let wal_fd = { let options = &mut OpenOptions::new(); @@ -131,7 +131,7 @@ impl Store { if o_direct { options.custom_flags(libc::O_DIRECT); } - options.open(&o.path.join("wal"))? + options.open(o.path.join("wal"))? }; #[cfg(target_os = "macos")] diff --git a/nomt/src/store/sync.rs b/nomt/src/store/sync.rs index 12b53b01d5..b6b052c747 100644 --- a/nomt/src/store/sync.rs +++ b/nomt/src/store/sync.rs @@ -85,7 +85,7 @@ impl Sync { rollback_start_live, rollback_end_live, }; - Meta::write(&shared.io_pool.page_pool(), &shared.meta_fd, &new_meta)?; + Meta::write(shared.io_pool.page_pool(), &shared.meta_fd, &new_meta)?; self.sync_seqn += 1; if let Some(PanicOnSyncMode::PostMeta) = self.panic_on_sync { diff --git a/nomt/src/task.rs b/nomt/src/task.rs index 1a22f5d07c..ff4e480a18 100644 --- a/nomt/src/task.rs +++ b/nomt/src/task.rs @@ -14,7 +14,7 @@ pub fn spawn_task( F: FnOnce() -> R + Send + 'static, { thread_pool.execute(move || { - let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| task())); + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(task)); let _ = tx.send(res); }); } diff --git a/nomt/tests/compute_root.rs b/nomt/tests/compute_root.rs index db0111d5e3..6d854c9cd9 100644 --- a/nomt/tests/compute_root.rs +++ b/nomt/tests/compute_root.rs @@ -128,7 +128,7 @@ fn run_verifier( KeyReadWrite::Read(_) => None, }) .collect(); - updates.sort_by(|a, b| a.0.cmp(&b.0)); + updates.sort_by_key(|a| a.0); verify_multi_proof_update::(&verified, updates) .expect("verify_multi_proof_update must succeed") diff --git a/nomt/tests/extend_range_protocol.rs b/nomt/tests/extend_range_protocol.rs index 126c39b903..e3c8cf7d1a 100644 --- a/nomt/tests/extend_range_protocol.rs +++ b/nomt/tests/extend_range_protocol.rs @@ -33,7 +33,7 @@ fn insert_delete_and_read(name: impl AsRef, to_delete: Vec) { let mut t = Test::new_with_params(name, 2, 64_000, None, true); // insert values - for (k, value_size) in KEYS_AND_VALUE_SIZES.clone() { + for (k, value_size) in KEYS_AND_VALUE_SIZES { t.write(key(k), Some(vec![k; value_size])); } t.commit(); @@ -45,7 +45,7 @@ fn insert_delete_and_read(name: impl AsRef, to_delete: Vec) { t.commit(); // read values - for (k, value_size) in KEYS_AND_VALUE_SIZES.clone() { + for (k, value_size) in KEYS_AND_VALUE_SIZES { if to_delete.contains(&k) { let res = t.read(key(k)); assert_eq!(None, res); diff --git a/nomt/tests/fill_and_empty.rs b/nomt/tests/fill_and_empty.rs index b7b597c0b3..9111cf48c4 100644 --- a/nomt/tests/fill_and_empty.rs +++ b/nomt/tests/fill_and_empty.rs @@ -20,13 +20,13 @@ fn fill_and_empty(seed: [u8; 16], commit_concurrency: usize) { let commit_size = db_size / 16; let mut items = std::collections::BTreeSet::new(); - while items.len() < db_size as usize { + while items.len() < db_size { items.insert(rand_key(&mut rng)); } let mut items: Vec<_> = items.into_iter().collect(); items.shuffle(&mut rng); - let mut to_delete: Vec = (0..db_size as usize).collect(); + let mut to_delete: Vec = (0..db_size).collect(); to_delete.shuffle(&mut rng); let mut t = Test::new_with_params( diff --git a/nomt/tests/last_layer_trie.rs b/nomt/tests/last_layer_trie.rs index 309e9c6be4..048c39870e 100644 --- a/nomt/tests/last_layer_trie.rs +++ b/nomt/tests/last_layer_trie.rs @@ -13,7 +13,7 @@ fn last_layer_trie() { ); let key1 = [170; 32]; - let mut key2 = key1.clone(); + let mut key2 = key1; key2[31] = 171; // write two leaf nodes at the last layer of the trie diff --git a/nomt/tests/rollback.rs b/nomt/tests/rollback.rs index a3216ca530..331795bd3b 100644 --- a/nomt/tests/rollback.rs +++ b/nomt/tests/rollback.rs @@ -130,8 +130,7 @@ impl TestPlan { let value: Vec = if overflow { // 32KB - std::iter::repeat(blake3::hash(&key).as_bytes()) - .take(1024) + std::iter::repeat_n(blake3::hash(&key).as_bytes(), 1024) .flatten() .copied() .collect() @@ -142,7 +141,7 @@ impl TestPlan { per_commit_insert.insert(key, value.clone()); every_key.insert(key); - state_emu.insert(key.clone(), value.clone()); + state_emu.insert(key, value.clone()); } // Remove 1 key (if possible) each iteration @@ -184,12 +183,12 @@ impl TestPlan { let session = nomt.begin_session(SessionParams::default()); let mut operations = Vec::new(); for (key, value) in to_insert[commit_no].iter() { - operations.push((key.clone(), KeyReadWrite::Write(Some(value.clone())))); + operations.push((*key, KeyReadWrite::Write(Some(value.clone())))); } for key in to_remove[commit_no].iter() { - operations.push((key.clone(), KeyReadWrite::Write(None))); + operations.push((*key, KeyReadWrite::Write(None))); } - operations.sort_by_key(|(key, _)| key.clone()); + operations.sort_by_key(|(key, _)| *key); let finished = session.finish(operations).unwrap(); finished.commit(&nomt).unwrap(); let post_root = nomt.root(); @@ -210,14 +209,14 @@ impl TestPlan { let session = nomt.begin_session(SessionParams::default()); let mut operations = Vec::new(); for (key, value) in self.to_insert[commit_no].iter() { - operations.push((key.clone(), KeyReadWrite::Write(Some(value.clone())))); + operations.push((*key, KeyReadWrite::Write(Some(value.clone())))); } for key in self.to_remove[commit_no].iter() { - operations.push((key.clone(), KeyReadWrite::Write(None))); + operations.push((*key, KeyReadWrite::Write(None))); } - operations.sort_by_key(|(key, _)| key.clone()); + operations.sort_by_key(|(key, _)| *key); let finished = session.finish(operations).unwrap(); - finished.commit(&nomt).unwrap(); + finished.commit(nomt).unwrap(); } } @@ -283,7 +282,7 @@ fn display_keys<'a>(keys: impl IntoIterator) -> String { let mut keys: Vec<_> = keys.into_iter().collect(); keys.sort(); keys.iter() - .map(|k| hex::encode(k)) + .map(hex::encode) .collect::>() .join(", ") } diff --git a/nomt/tests/witness_check.rs b/nomt/tests/witness_check.rs index e02b929849..3c5bc49905 100644 --- a/nomt/tests/witness_check.rs +++ b/nomt/tests/witness_check.rs @@ -58,7 +58,7 @@ fn produced_witness_validity() { for (i, witnessed_path) in witness.path_proofs.iter().enumerate() { let verified = witnessed_path .inner - .verify::(&witnessed_path.path.path(), prev_root.into_inner()) + .verify::(witnessed_path.path.path(), prev_root.into_inner()) .unwrap(); for read in witness .operations @@ -87,7 +87,7 @@ fn produced_witness_validity() { .skip_while(|r| r.path_index != i) .take_while(|r| r.path_index == i) { - write_ops.push((write.key, write.value.clone())); + write_ops.push((write.key, write.value)); } if !write_ops.is_empty() { @@ -158,7 +158,7 @@ fn test_verify_update_with_identical_paths() { let witnessed_path = &witness.path_proofs[0]; let verified_proof = witnessed_path .inner - .verify::(&witnessed_path.path.path(), root.into_inner()) + .verify::(witnessed_path.path.path(), root.into_inner()) .unwrap(); // Create two identical PathUpdate objects @@ -203,7 +203,7 @@ fn property_generated_witnesses_verify() { for (i, witnessed_path) in witness.path_proofs.iter().enumerate() { let verified = witnessed_path .inner - .verify::(&witnessed_path.path.path(), prev_root.into_inner()) + .verify::(witnessed_path.path.path(), prev_root.into_inner()) .unwrap(); for read in witness @@ -233,7 +233,7 @@ fn property_generated_witnesses_verify() { .skip_while(|w| w.path_index != i) .take_while(|w| w.path_index == i) { - write_ops.push((write.key, write.value.clone())); + write_ops.push((write.key, write.value)); } if !write_ops.is_empty() { diff --git a/torture/src/agent.rs b/torture/src/agent.rs index 2220d5bffd..d117c2a2cf 100644 --- a/torture/src/agent.rs +++ b/torture/src/agent.rs @@ -427,7 +427,7 @@ impl Agent { // Perform the commit. let commit_result = - block_in_place(|| session.finish(actuals)?.commit(&nomt), "Panic in commit"); + block_in_place(|| session.finish(actuals)?.commit(nomt), "Panic in commit"); let commit_outcome = classify_result(commit_result); // Log the outcome if it was not successful. @@ -521,7 +521,7 @@ where F: FnOnce() -> anyhow::Result + Send, { tokio::task::block_in_place(|| { - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| task())) + std::panic::catch_unwind(std::panic::AssertUnwindSafe(task)) .unwrap_or_else(|e| panic_to_err(panic_context, e)) }) } diff --git a/torture/src/logging.rs b/torture/src/logging.rs index be984122a7..b37d705785 100644 --- a/torture/src/logging.rs +++ b/torture/src/logging.rs @@ -48,7 +48,7 @@ fn env_filter(kind: Kind) -> EnvFilter { .unwrap(), ), Err(std::env::VarError::NotPresent) => { - return None; + None } Err(std::env::VarError::NotUnicode(_)) => { panic!("Environment variable {} is not unicode", var_name); @@ -67,7 +67,7 @@ where .with_thread_ids(false) .with_thread_names(false) .compact() - .with_timer(fmt::time::SystemTime::default()); + .with_timer(fmt::time::SystemTime); fmt::Subscriber::builder() .with_env_filter(env_filter(kind)) diff --git a/torture/src/supervisor/controller.rs b/torture/src/supervisor/controller.rs index ae72a131b4..ab03ae5265 100644 --- a/torture/src/supervisor/controller.rs +++ b/torture/src/supervisor/controller.rs @@ -50,7 +50,7 @@ impl SpawnedAgentController { })) .await?; match response { - crate::message::ToSupervisor::InitResponse(outcome) => return Ok(outcome), + crate::message::ToSupervisor::InitResponse(outcome) => Ok(outcome), _ => { panic!("expected init, unexpected response: {:?}", response); } @@ -81,7 +81,7 @@ impl SpawnedAgentController { })) .await?; match response { - crate::message::ToSupervisor::OpenResponse(outcome) => return Ok(outcome), + crate::message::ToSupervisor::OpenResponse(outcome) => Ok(outcome), _ => { panic!("expected open, unexpected response: {:?}", response); } diff --git a/torture/src/supervisor/mod.rs b/torture/src/supervisor/mod.rs index 8f9b74a4ad..5024a4e1cc 100644 --- a/torture/src/supervisor/mod.rs +++ b/torture/src/supervisor/mod.rs @@ -136,14 +136,14 @@ async fn join_interruptable( match res { Ok(Ok(())) => { // We received the first interrupt meaning that the control loop was cancelled. - return ExitReason::Interrupted + ExitReason::Interrupted }, - Ok(Err(e)) => return ExitReason::Error(e), + Ok(Err(e)) => ExitReason::Error(e), Err(join_err) => { // UNWRAP: the task cannot be cancelled because the only place it can get // cancelled is here and we don't cancel it. So it must be a panic. let panic_box = join_err.try_into_panic().unwrap(); - return ExitReason::Panic(panic_box); + ExitReason::Panic(panic_box) }, } } diff --git a/torture/src/supervisor/resource.rs b/torture/src/supervisor/resource.rs index b5508e5749..c11226bc24 100644 --- a/torture/src/supervisor/resource.rs +++ b/torture/src/supervisor/resource.rs @@ -7,7 +7,7 @@ use std::{ use rand::{prelude::*, SeedableRng}; /// 1GiB is the minimum amount of space that can be assigned to a workload. -const MIN_ASSIGNED_SPACE: u64 = 1 * (1 << 30); +const MIN_ASSIGNED_SPACE: u64 = 1 << 30; /// 5GiB is the maximum amount of memory that can be assigned to a workload /// which will use both disk and memory. @@ -194,9 +194,7 @@ pub fn process_memory_occupied(pid: u32) -> Option { let mut statm = String::new(); statm_file.read_to_string(&mut statm).expect(&format_err); let occupied_memory = statm - .split(' ') - .skip(1) - .next() + .split(' ').nth(1) .map(|value| value.parse::().expect(&format_err)) .expect(&format_err); Some(occupied_memory) @@ -216,7 +214,7 @@ fn mem_info() -> (u64, u64) { .split('\n') .find(|entry| entry.starts_with(name)) .and_then(|entry| entry.split(':').nth(1)) - .and_then(|value| value.trim_start().split(' ').nth(0)) + .and_then(|value| value.trim_start().split(' ').next()) .and_then(|value| value.parse::().ok()) }; // /proc/meminfo shows values in KiB. @@ -269,7 +267,6 @@ pub fn is_exceeding_resources( fn dir_size(path: &Path) -> u64 { std::fs::read_dir(path) .unwrap() - .into_iter() .filter_map(|entry| entry.ok()) .map(|entry| { let entry_metadata = entry.metadata().unwrap(); diff --git a/torture/src/supervisor/workload.rs b/torture/src/supervisor/workload.rs index d3e75e5f0d..07ab8d4814 100644 --- a/torture/src/supervisor/workload.rs +++ b/torture/src/supervisor/workload.rs @@ -294,7 +294,7 @@ impl Workload { if self .scheduled_rollback .as_ref() - .map_or(false, |(r, _)| r.sync_seqn == self.committed.sync_seqn) + .is_some_and(|(r, _)| r.sync_seqn == self.committed.sync_seqn) { // UNWRAP: scheduled_rollback has just be checked to be `Some` let (scheduled_rollback, should_crash) = self.scheduled_rollback.take().unwrap(); @@ -509,7 +509,7 @@ impl Workload { async fn schedule_rollback(&mut self, should_crash: bool) -> anyhow::Result<()> { let n_commits_to_rollback = - self.rng.random_range(1..self.config.max_rollback_commits) as usize; + self.rng.random_range(1..self.config.max_rollback_commits); let last_snapshot = &self.committed; let rollback_sync_seqn = last_snapshot.sync_seqn + n_commits_to_rollback as u32; @@ -561,7 +561,7 @@ impl Workload { .send_request(crate::message::ToAgent::Rollback( crate::message::RollbackPayload { n_commits: n_commits_to_rollback, - should_crash: should_crash.clone(), + should_crash, }, )) .await?; @@ -790,7 +790,7 @@ impl Workload { for change in changeset { match change { KeyValueChange::Insert(key, value) - if self.rr().send_request_query(*key).await?.as_ref() != Some(&value) => + if self.rr().send_request_query(*key).await?.as_ref() != Some(value) => { return Err(anyhow::anyhow!("Inserted item not present after commit")); } @@ -899,7 +899,7 @@ impl Workload { }; let value = self.rr().send_request_query(*key).await?; - if value.as_ref().map_or(true, |v| v != expected_value) { + if value.as_ref() != Some(expected_value) { return Err(anyhow::anyhow!( "Wrong key in snapshot,\n key: {:?},\n expected value: {:?},\n found value: {:?}", hex::encode(key), @@ -927,7 +927,7 @@ impl Workload { ) .await?; if let InitOutcome::Success = outcome { - () + } else { return Err(anyhow::anyhow!("Unexpected init outcome: {:?}", outcome)); } @@ -978,7 +978,7 @@ impl Workload { if let Some(agent) = self.agent.as_ref() { if let Some(agent_pid) = agent.pid() { let filename = &self.workload_dir.path().join("backtrace.txt"); - match pbt::collect_process_backtrace(&filename, agent_pid).await { + match pbt::collect_process_backtrace(filename, agent_pid).await { Ok(()) => { tracing::info!("Backtrace collected in {}", filename.display()); } @@ -1060,7 +1060,7 @@ impl Workload { } } - changes.sort_by(|a, b| a.key().cmp(&b.key())); + changes.sort_by(|a, b| a.key().cmp(b.key())); (snapshot, reads, changes) } @@ -1079,7 +1079,7 @@ impl Workload { key.copy_from_slice(next_key); } } - reads.push(key.clone()); + reads.push(key); } reads @@ -1098,7 +1098,7 @@ impl Workload { let mut key = [0; 32]; loop { rng.fill_bytes(&mut key); - if !self.committed.state.contains_key(&key) && new_keys.insert(key.clone()) { + if !self.committed.state.contains_key(&key) && new_keys.insert(key) { return key; } } diff --git a/trickfs/src/latency.rs b/trickfs/src/latency.rs index 512fce07bc..24a7ad8f68 100644 --- a/trickfs/src/latency.rs +++ b/trickfs/src/latency.rs @@ -80,7 +80,7 @@ fn scheduler(rx: Receiver<(Reply, Duration)>) { /// Insert the reply into the scheduled queue following an order by the deadlines. fn schedule_new_reply(scheduled: &mut VecDeque<(Reply, Instant)>, reply: Reply, delay: Duration) { - let deadline = std::time::Instant::now() + delay.clone(); + let deadline = std::time::Instant::now() + delay; // If two replies happen to have the same deadline, then they will be kept in FIFO order. let idx = match scheduled.binary_search_by_key(&deadline, |(_, d)| *d) { Ok(idx) => idx + 1, diff --git a/trickfs/src/lib.rs b/trickfs/src/lib.rs index 606a8b70dd..2944c0afb2 100644 --- a/trickfs/src/lib.rs +++ b/trickfs/src/lib.rs @@ -142,7 +142,7 @@ impl InodeData { /// Return the number of blocks in this file or directory. pub fn blocks(&self) -> u64 { // Derive the number of blocks from the file size. - (self.file_size + BLK_SIZE - 1) / BLK_SIZE + self.file_size.div_ceil(BLK_SIZE) } /// Returns the size of the file in bytes. @@ -1309,7 +1309,7 @@ mod tests { handle.set_trigger_enospc(true); let _ = file.write_all(test_data).unwrap_err(); handle.set_trigger_enospc(false); - let _ = file.write_all(test_data).unwrap(); + file.write_all(test_data).unwrap(); drop(file); unmount_and_join(mount_handle, mountpoint.path()).unwrap(); From 1119563ea3aed68d681198e0cd593eaee90631ef Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Tue, 27 Oct 2026 15:50:58 +0100 Subject: [PATCH 2/4] more fixes --- core/src/proof/path_proof.rs | 5 +-- core/src/trie.rs | 6 ++-- core/src/trie_pos.rs | 1 + core/src/update.rs | 2 -- nomt/src/beatree/branch/node.rs | 1 - nomt/src/beatree/iterator.rs | 4 +-- nomt/src/beatree/mod.rs | 8 ++--- nomt/src/beatree/ops/bit_ops.rs | 16 +++++---- nomt/src/beatree/ops/reconstruction.rs | 6 ++-- nomt/src/beatree/ops/update/branch_stage.rs | 9 ++--- nomt/src/beatree/ops/update/branch_updater.rs | 34 ++++++++----------- nomt/src/beatree/ops/update/leaf_stage.rs | 21 +++++------- nomt/src/beatree/ops/update/leaf_updater.rs | 4 +-- nomt/src/beatree/ops/update/mod.rs | 1 + nomt/src/beatree/ops/update/tests.rs | 4 ++- nomt/src/bitbox/ht_file.rs | 12 +++++-- nomt/src/bitbox/mod.rs | 10 +++--- nomt/src/bitbox/validate.rs | 4 +-- nomt/src/lib.rs | 11 +++--- nomt/src/merkle/page_set.rs | 1 - nomt/src/merkle/page_walker.rs | 19 +++++------ nomt/src/merkle/seek.rs | 13 +++---- nomt/src/options.rs | 6 ++++ nomt/src/rw_pass_cell/mod.rs | 6 ++-- nomt/src/seglog/mod.rs | 7 ++-- nomt/src/seglog/segment_rw.rs | 16 ++++----- nomt/src/store/flock.rs | 1 + nomt/src/store/sync.rs | 1 + nomt/tests/common/mod.rs | 2 ++ nomt/tests/fill_and_empty.rs | 3 +- nomt/tests/prove_in_session.rs | 8 ++--- nomt/tests/rollback.rs | 25 +++++++------- torture/src/agent.rs | 1 + torture/src/logging.rs | 4 +-- torture/src/supervisor/controller.rs | 2 +- torture/src/supervisor/mod.rs | 2 +- torture/src/supervisor/resource.rs | 3 +- torture/src/supervisor/workload.rs | 33 +++++------------- 38 files changed, 144 insertions(+), 168 deletions(-) diff --git a/core/src/proof/path_proof.rs b/core/src/proof/path_proof.rs index b14f401f35..cc23271e1d 100644 --- a/core/src/proof/path_proof.rs +++ b/core/src/proof/path_proof.rs @@ -117,10 +117,7 @@ pub fn hash_path( (node, sibling) }; - let next = InternalData { - left, - right, - }; + let next = InternalData { left, right }; node = H::hash_internal(&next); } diff --git a/core/src/trie.rs b/core/src/trie.rs index 8f72f37c66..fed7b30e1e 100644 --- a/core/src/trie.rs +++ b/core/src/trie.rs @@ -3,10 +3,10 @@ //! //! All nodes are 256 bits. There are three kinds of nodes. //! 1. Internal nodes, which each have two children. The value of an internal node is -//! given by hashing the concatenation of the two child nodes and setting the MSB to 0. +//! given by hashing the concatenation of the two child nodes and setting the MSB to 0. //! 2. Leaf nodes, which have zero children. The value of a leaf node is given by hashing -//! the concatenation of the 256-bit lookup path and the hash of the value stored at the leaf, -//! and setting the MSB to 1. +//! the concatenation of the 256-bit lookup path and the hash of the value stored at the leaf, +//! and setting the MSB to 1. //! 3. [`TERMINATOR`] nodes, which have the special value of all 0s. These nodes have no children //! and serve as a stand-in for an empty sub-trie at any height. Terminator nodes enable the //! trie to be tractably represented. diff --git a/core/src/trie_pos.rs b/core/src/trie_pos.rs index d3c5280ec8..68b69ad276 100644 --- a/core/src/trie_pos.rs +++ b/core/src/trie_pos.rs @@ -116,6 +116,7 @@ impl TriePosition { /// Parse a `TriePosition` from a bit string. #[cfg(test)] + #[allow(clippy::should_implement_trait)] pub fn from_str(s: &str) -> Self { let mut bitvec = BitVec::::new(); if s.len() > 256 { diff --git a/core/src/update.rs b/core/src/update.rs index 3471708452..6c4b90193d 100644 --- a/core/src/update.rs +++ b/core/src/update.rs @@ -252,7 +252,6 @@ pub fn build_trie( c = leaf_ops.next(); } - pending_siblings .pop() .map(|n| n.0) @@ -315,7 +314,6 @@ mod tests { fn branch_hash(left: [u8; 32], right: [u8; 32]) -> [u8; 32] { let data = trie::InternalData { left, right }; - DummyNodeHasher::hash_internal(&data) } diff --git a/nomt/src/beatree/branch/node.rs b/nomt/src/beatree/branch/node.rs index dda0f93f75..4a9489fc60 100644 --- a/nomt/src/beatree/branch/node.rs +++ b/nomt/src/beatree/branch/node.rs @@ -649,7 +649,6 @@ impl BranchNodeBuilder { } }; - let bit_len = if is_prefix_extension { // carry_prefix is already being applied, so skip bits in the new node's separator separator_bit_start += bit_prefix_len_difference; diff --git a/nomt/src/beatree/iterator.rs b/nomt/src/beatree/iterator.rs index 678ec24193..94477ddddd 100644 --- a/nomt/src/beatree/iterator.rs +++ b/nomt/src/beatree/iterator.rs @@ -449,9 +449,7 @@ impl Iterator for NeededLeavesIter { type Item = PageNumber; fn next(&mut self) -> Option { - let Some((branch, mut range)) = self.state.take() else { - return None; - }; + let (branch, mut range) = self.state.take()?; if let Some(i) = range.next() { let key = get_key(&branch, i); let pn = branch.node_pointer(i).into(); diff --git a/nomt/src/beatree/mod.rs b/nomt/src/beatree/mod.rs index a675e68fc8..126e6f123b 100644 --- a/nomt/src/beatree/mod.rs +++ b/nomt/src/beatree/mod.rs @@ -93,6 +93,7 @@ impl Shared { } impl Tree { + #[allow(clippy::too_many_arguments)] pub fn open( page_pool: PagePool, io_pool: &IoPool, @@ -105,10 +106,8 @@ impl Tree { commit_concurrency: usize, leaf_cache_size: usize, ) -> Result { - let ln_freelist_pn = Some(PageNumber(ln_freelist_pn)) - .filter(|&x| x != FREELIST_EMPTY); - let bbn_freelist_pn = Some(PageNumber(bbn_freelist_pn)) - .filter(|&x| x != FREELIST_EMPTY); + let ln_freelist_pn = Some(PageNumber(ln_freelist_pn)).filter(|&x| x != FREELIST_EMPTY); + let bbn_freelist_pn = Some(PageNumber(bbn_freelist_pn)).filter(|&x| x != FREELIST_EMPTY); let ln_bump = PageNumber(ln_bump); let bbn_bump = PageNumber(bbn_bump); @@ -585,6 +584,7 @@ impl ReadTransaction { /// If `Ok` is returned, then no I/O command has been submitted along the handle. /// If `Err` is returned, then an I/O command has been submitted along the handle, and the /// user_data is as specified. + #[allow(clippy::result_large_err)] pub fn lookup_async( &self, key: Key, diff --git a/nomt/src/beatree/ops/bit_ops.rs b/nomt/src/beatree/ops/bit_ops.rs index 9b07bfcfc8..f14ed80de7 100644 --- a/nomt/src/beatree/ops/bit_ops.rs +++ b/nomt/src/beatree/ops/bit_ops.rs @@ -329,7 +329,8 @@ pub mod benches { } else { prefix_bytes - 1 }; - let separator_byte_len = (separator_bit_len as usize).div_ceil(8).next_multiple_of(8); + let separator_byte_len = + (separator_bit_len as usize).div_ceil(8).next_multiple_of(8); group.bench_function(BenchmarkId::new("prefix_len_bits", prefix_bits), |b| { b.iter_batched( @@ -425,8 +426,9 @@ mod tests { usize::arbitrary(g) % 8 }; let separator_bit_len = arbitrary_bit_len(g, 256 - prefix_bit_len); - let separator_byte_len = - (separator_bit_start + separator_bit_len).div_ceil(8).next_multiple_of(8); + let separator_byte_len = (separator_bit_start + separator_bit_len) + .div_ceil(8) + .next_multiple_of(8); let separator_seed = TestKeyPath::arbitrary(g).into_inner(); let mut separator_bytes = vec![0; separator_byte_len]; for (index, byte) in separator_bytes.iter_mut().enumerate() { @@ -531,7 +533,7 @@ mod tests { fn reconstruct_key_garbage_in_last_remainder() { // There could be the possibility of having garbage in the last remainder for left_and_right in 0..2 { - for prefix_bit_len in 0..8 { + for prefix_bit_len in 0..8usize { let prefix = [255]; let separator_bit_start_range = if left_and_right == 0 { @@ -542,9 +544,9 @@ mod tests { for separator_bit_start in separator_bit_start_range { for separator_bit_len in prefix_bit_len..=256 - prefix_bit_len { - let separator_byte_len = - (separator_bit_start + separator_bit_len).div_ceil(8) - .next_multiple_of(8); + let separator_byte_len = (separator_bit_start + separator_bit_len) + .div_ceil(8) + .next_multiple_of(8); let separator_bytes = vec![255; separator_byte_len]; let separator = diff --git a/nomt/src/beatree/ops/reconstruction.rs b/nomt/src/beatree/ops/reconstruction.rs index d5df9ed537..70f84082bf 100644 --- a/nomt/src/beatree/ops/reconstruction.rs +++ b/nomt/src/beatree/ops/reconstruction.rs @@ -2,9 +2,9 @@ //! //! Algorithm sketch: //! 1. Read in all BBNs from the file. Order them in an in-memory std BTree by the first separator. -//! Skip future BBNs according to the commit sequence number. +//! Skip future BBNs according to the commit sequence number. //! 2. Iterate over BBNs in order, building next level of branches with targeted 75% fullness. -//! Create a sorted list of this next layer of BNs as we go. +//! Create a sorted list of this next layer of BNs as we go. //! 3. Repeat step 2 until the root node is created. use anyhow::{bail, ensure, Ok, Result}; @@ -60,7 +60,7 @@ pub fn reconstruct( separator[prefix.len()..prefix.len() + first.len()].copy_from_bitslice(first); } - if let Some(_) = index.insert(separator, Arc::new(branch)) { + if index.insert(separator, Arc::new(branch)).is_some() { bail!( "2 branch nodes with same separator, separator={:?}", separator diff --git a/nomt/src/beatree/ops/update/branch_stage.rs b/nomt/src/beatree/ops/update/branch_stage.rs index 340330c629..2143c61fff 100644 --- a/nomt/src/beatree/ops/update/branch_stage.rs +++ b/nomt/src/beatree/ops/update/branch_stage.rs @@ -133,7 +133,8 @@ fn apply_bbn_changes( output.submitted_io += worker_output.branches_tracker.extra_freed.len(); output - .freed_pages.append(&mut worker_output.branches_tracker.extra_freed); + .freed_pages + .append(&mut worker_output.branches_tracker.extra_freed); output.post_io_drop.deferred_drop_pages.push(std::mem::take( &mut worker_output.branches_tracker.deferred_drop_pages, )); @@ -413,11 +414,7 @@ fn run_worker( branch_updater.digest(&mut new_branch_state)? { has_extended_range = false; - if worker_params - .range - .high - .is_some_and(|high| cutoff >= high) - { + if worker_params.range.high.is_some_and(|high| cutoff >= high) { has_extended_range = true; request_range_extension(&mut worker_params, &mut new_branch_state.branches_tracker); } diff --git a/nomt/src/beatree/ops/update/branch_updater.rs b/nomt/src/beatree/ops/update/branch_updater.rs index e51c786f07..10a8207998 100644 --- a/nomt/src/beatree/ops/update/branch_updater.rs +++ b/nomt/src/beatree/ops/update/branch_updater.rs @@ -191,7 +191,11 @@ impl BranchUpdater { self.ops_tracker.push_chunk(base, from, to); } - if found { Some(to) } else { None } + if found { + Some(to) + } else { + None + } } // Try to perform a split of the current available ops with a target branch node size. @@ -268,15 +272,13 @@ fn build_branch( &base.node, base_range.start, compressed_end, - ops[ops_range] - .iter() - .filter_map(|op| { - if let BranchOp::Update(pos, pn) = op { - Some((pos - base_range.start, *pn)) - } else { - None - } - }), + ops[ops_range].iter().filter_map(|op| { + if let BranchOp::Update(pos, pn) = op { + Some((pos - base_range.start, *pn)) + } else { + None + } + }), ); for pos in compressed_end..base_range.end { @@ -369,8 +371,7 @@ fn build_branch( builder.finish() } -#[derive(Clone)] -#[derive(Default)] +#[derive(Clone, Default)] pub struct BranchGauge { // key and length of the first separator if any first_separator: Option<(Key, usize)>, @@ -382,7 +383,6 @@ pub struct BranchGauge { n: usize, } - impl BranchGauge { pub fn ingest_key(&mut self, key: Key, len: usize) { let Some((ref first, _)) = self.first_separator else { @@ -657,11 +657,7 @@ pub mod tests { ) -> Arc { let mut gauge = BranchGauge::default(); let mut items = Vec::new(); - loop { - let Some(next_key) = keys.next() else { - break; - }; - + for next_key in keys.by_ref() { let s_len = separator_len(&next_key); let size = gauge.body_size_after(next_key, s_len); @@ -893,7 +889,7 @@ pub mod tests { panic!() }; - assert!(new_branches.inner.get(&key(0)).is_none()); + assert!(!new_branches.inner.contains_key(&key(0))); } #[test] diff --git a/nomt/src/beatree/ops/update/leaf_stage.rs b/nomt/src/beatree/ops/update/leaf_stage.rs index 6b7678ff5a..f95858cb19 100644 --- a/nomt/src/beatree/ops/update/leaf_stage.rs +++ b/nomt/src/beatree/ops/update/leaf_stage.rs @@ -29,13 +29,9 @@ use crate::task::{join_task, spawn_task}; pub type LeavesTracker = super::NodesTracker; fn indexed_leaf(bbn_index: &Index, key: Key) -> Option<(Key, Option, PageNumber)> { - let Some((_, branch)) = bbn_index.lookup(key) else { - return None; - }; + let (_, branch) = bbn_index.lookup(key)?; - let Some((i, leaf_pn)) = search_branch(&branch, key) else { - return None; - }; + let (i, leaf_pn) = search_branch(&branch, key)?; let separator = get_key(&branch, i); let cutoff = if i + 1 < branch.n() as usize { @@ -82,6 +78,7 @@ pub struct LeafStageOutput { } /// Change the btree's leaves in the specified way +#[allow(clippy::too_many_arguments)] pub fn run( bbn_index: &Index, leaf_cache: LeafCache, @@ -215,7 +212,8 @@ fn apply_worker_changes( output.submitted_io += worker_output.leaves_tracker.extra_freed.len(); output - .freed_pages.append(&mut worker_output.leaves_tracker.extra_freed); + .freed_pages + .append(&mut worker_output.leaves_tracker.extra_freed); output.post_io_work.worker_changes.push(worker_output); } @@ -344,6 +342,7 @@ pub fn enforce_first_leaf_separator( } } +#[allow(clippy::type_complexity)] fn prepare_workers( bbn_index: &Index, changeset: &[(Key, Option<(Vec, bool)>)], @@ -435,6 +434,7 @@ fn prepare_workers( workers } +#[allow(clippy::too_many_arguments)] fn reset_leaf_base( bbn_index: &Index, leaf_cache: &LeafCache, @@ -551,6 +551,7 @@ struct LeafWorkerOutput { overflow_deleted: Vec>, } +#[allow(clippy::too_many_arguments, clippy::type_complexity)] fn run_worker( bbn_index: Index, leaf_cache: &LeafCache, @@ -642,11 +643,7 @@ fn run_worker( while let LeafDigestResult::NeedsMerge(cutoff) = leaf_updater.digest(&mut new_leaf_state)? { has_extended_range = false; - if worker_params - .range - .high - .is_some_and(|high| cutoff >= high) - { + if worker_params.range.high.is_some_and(|high| cutoff >= high) { has_extended_range = true; request_range_extension(&mut worker_params, &mut new_leaf_state.leaves_tracker); } diff --git a/nomt/src/beatree/ops/update/leaf_updater.rs b/nomt/src/beatree/ops/update/leaf_updater.rs index 5969580bf1..dda31a4543 100644 --- a/nomt/src/beatree/ops/update/leaf_updater.rs +++ b/nomt/src/beatree/ops/update/leaf_updater.rs @@ -783,7 +783,7 @@ mod tests { }; assert_eq!(merge_key, key(4)); - assert!(new_leaves.inner.get(&key(1)).is_none()); + assert!(!new_leaves.inner.contains_key(&key(1))); updater.reset_base( Some(BaseLeaf { @@ -858,7 +858,7 @@ mod tests { panic!() }; - assert!(new_leaves.inner.get(&key(1)).is_none()); + assert!(!new_leaves.inner.contains_key(&key(1))); } #[test] diff --git a/nomt/src/beatree/ops/update/mod.rs b/nomt/src/beatree/ops/update/mod.rs index b7ebc1a49f..0bf5c9aa1f 100644 --- a/nomt/src/beatree/ops/update/mod.rs +++ b/nomt/src/beatree/ops/update/mod.rs @@ -44,6 +44,7 @@ const LEAF_BULK_SPLIT_TARGET: usize = (LEAF_NODE_BODY_SIZE * 3) / 4; /// Change the btree in the specified way. Updates the branch index in-place. /// /// The changeset is a list of key value pairs to be added or removed from the btree. +#[allow(clippy::too_many_arguments)] pub fn update( changeset: OrdMap, mut bbn_index: Index, diff --git a/nomt/src/beatree/ops/update/tests.rs b/nomt/src/beatree/ops/update/tests.rs index f61d549ba1..6345336f56 100644 --- a/nomt/src/beatree/ops/update/tests.rs +++ b/nomt/src/beatree/ops/update/tests.rs @@ -531,7 +531,9 @@ fn branch_stage_inner(input: StageInputs) -> TestResult { let mut changeset: BTreeMap<[u8; 32], Option> = insertions.clone(); changeset.extend(deletions.clone()); - let bbn_page_numbers: BTreeSet<_> = changeset.keys().map(|key| bbn_index.lookup(*key).unwrap().1.bbn_pn()) + let bbn_page_numbers: BTreeSet<_> = changeset + .keys() + .map(|key| bbn_index.lookup(*key).unwrap().1.bbn_pn()) .collect(); let mut new_bbn_index = bbn_index.clone(); diff --git a/nomt/src/bitbox/ht_file.rs b/nomt/src/bitbox/ht_file.rs index de5d7bed48..6d847dca15 100644 --- a/nomt/src/bitbox/ht_file.rs +++ b/nomt/src/bitbox/ht_file.rs @@ -70,7 +70,11 @@ pub fn open( /// Lays out the meta page. If `preallocate` is true, preallocates the blocks for the file. pub fn create(path: PathBuf, num_pages: u32, preallocate: bool) -> std::io::Result<()> { let ht_path = path.join("ht"); - let ht_file = OpenOptions::new().write(true).create(true).open(ht_path)?; + let ht_file = OpenOptions::new() + .write(true) + .create(true) + .truncate(false) + .open(ht_path)?; // number of pages + pages required for meta bits. let page_count = num_pages + num_meta_byte_pages(num_pages); @@ -82,7 +86,11 @@ pub fn create(path: PathBuf, num_pages: u32, preallocate: bool) -> std::io::Resu drop(ht_file); let wal_path = path.join("wal"); - let wal_file = OpenOptions::new().write(true).create(true).open(wal_path)?; + let wal_file = OpenOptions::new() + .write(true) + .create(true) + .truncate(false) + .open(wal_path)?; wal_file.sync_all()?; drop(wal_file); Ok(()) diff --git a/nomt/src/bitbox/mod.rs b/nomt/src/bitbox/mod.rs index bc3cdea71e..5970fc2c25 100644 --- a/nomt/src/bitbox/mod.rs +++ b/nomt/src/bitbox/mod.rs @@ -176,6 +176,7 @@ impl DB { SyncController::new(self.clone()) } + #[allow(clippy::type_complexity)] fn prepare_sync( &self, sync_seqn: u32, @@ -309,6 +310,7 @@ pub struct SyncController { /// The channel to receive the result of the the begin_sync task. begin_sync_result_rx: Receiver>>, /// The pages along with their page numbers to write out to the HT file. + #[allow(clippy::type_complexity)] ht_to_write: Arc)>>>>, } @@ -346,12 +348,8 @@ impl SyncController { // if fails The sync coordinator will poison the database and all further commits will // be rejected. Therefore, there is no need to perform cleanup. - let (ht_pages, cache_updates) = bitbox.prepare_sync( - sync_seqn, - &page_pool, - updated_pages, - &mut wal_blob_builder, - )?; + let (ht_pages, cache_updates) = + bitbox.prepare_sync(sync_seqn, &page_pool, updated_pages, &mut wal_blob_builder)?; drop(wal_blob_builder); // Set the hash-table pages before spawning WAL writeout so they don't race with it. diff --git a/nomt/src/bitbox/validate.rs b/nomt/src/bitbox/validate.rs index cc00b66cbe..20e05eba14 100644 --- a/nomt/src/bitbox/validate.rs +++ b/nomt/src/bitbox/validate.rs @@ -111,12 +111,10 @@ fn ensure_bucket_reachable( ) -> anyhow::Result<()> { let hash = hash_raw_page_id(page_label, seed); let mut bucket = hash % meta_map.len() as u64; - let mut step = 0u64; let max_probes = meta_map.len().saturating_mul(2).max(MAX_VALIDATION_PROBES); - for _ in 0..max_probes { + for step in 0..max_probes as u64 { bucket += step; - step += 1; bucket %= meta_map.len() as u64; let bucket = bucket as usize; diff --git a/nomt/src/lib.rs b/nomt/src/lib.rs index e8d512e132..9bdc8c29fd 100644 --- a/nomt/src/lib.rs +++ b/nomt/src/lib.rs @@ -384,11 +384,12 @@ impl Nomt { // Begin a new session. We do not allow rollback for this operation because that would // interfere with the rollback log: if another rollback were to be issued, it must rollback // the changes in the rollback log and not the changes performed by the current rollback. - let mut session_params = SessionParams::default(); - session_params.record_rollback_delta = false; - - // We hold a write guard and don't need the session to take any other. - session_params.take_global_guard = false; + let session_params = SessionParams { + record_rollback_delta: false, + // We hold a write guard and don't need the session to take any other. + take_global_guard: false, + ..SessionParams::default() + }; let sess = self.begin_session(session_params); // Convert the traceback into a series of write commands. diff --git a/nomt/src/merkle/page_set.rs b/nomt/src/merkle/page_set.rs index e66fbcbe6a..f545d69aa6 100644 --- a/nomt/src/merkle/page_set.rs +++ b/nomt/src/merkle/page_set.rs @@ -96,7 +96,6 @@ impl PageSet { impl super::page_walker::PageSet for PageSet { fn fresh(&self, page_id: &PageId) -> PageMut { - PageMut::pristine_empty(&self.page_pool, page_id) } diff --git a/nomt/src/merkle/page_walker.rs b/nomt/src/merkle/page_walker.rs index f84ff94c01..063187704e 100644 --- a/nomt/src/merkle/page_walker.rs +++ b/nomt/src/merkle/page_walker.rs @@ -114,12 +114,7 @@ struct StackPage { } impl StackPage { - fn new( - page_id: PageId, - page: PageMut, - diff: PageDiff, - page_origin: PageOrigin, - ) -> Self { + fn new(page_id: PageId, page: PageMut, diff: PageDiff, page_origin: PageOrigin) -> Self { Self { elided_children: page.elided_children(), page_leaves_counter: page_origin.page_leaves_counter(), @@ -405,7 +400,7 @@ impl PageWalker { .unwrap() }; - self.stack.push(StackPage::new::( + self.stack.push(StackPage::new( ROOT_PAGE_ID, page, PageDiff::default(), @@ -447,7 +442,7 @@ impl PageWalker { }; self.stack - .push(StackPage::new::(page_id, page, diff, page_origin)); + .push(StackPage::new(page_id, page, diff, page_origin)); } self.position.down(bit); } @@ -670,7 +665,7 @@ impl PageWalker { // UNWRAP: all pages on the path to the terminal are present in the page set. let (page, page_origin) = page_set.get(&cur_ancestor).unwrap(); - self.stack.push(StackPage::new::( + self.stack.push(StackPage::new( cur_ancestor.clone(), page.deep_copy(), PageDiff::default(), @@ -1427,10 +1422,12 @@ mod tests { }) }; - let expected_siblings = [(node_hash(path_1, val(1)), 1), + let expected_siblings = [ + (node_hash(path_1, val(1)), 1), (node_hash(path_2, val(2)), 2), (node_hash(path_3, val(3)), 3), - (node_hash(path_4, val(4)), 4)]; + (node_hash(path_4, val(4)), 4), + ]; // replace those leaf nodes one at a time. // the sibling stack will be populated as we go. diff --git a/nomt/src/merkle/seek.rs b/nomt/src/merkle/seek.rs index 8dc0fb003c..8414c0164d 100644 --- a/nomt/src/merkle/seek.rs +++ b/nomt/src/merkle/seek.rs @@ -200,11 +200,8 @@ impl SeekRequest { // beatree leaves, and the requests will be woken one after the other when a needed leaf is received. // This is less consuming than the overhead introduced by making the second SeekRequest depend // on the first one or sharing some data between them. - self.state = RequestState::begin_leaves_fetch::( - read_transaction, - &self.position, - page.clone(), - ); + self.state = + RequestState::begin_leaves_fetch(read_transaction, &self.position, page.clone()); self.continue_leaves_fetch::(page_set, overlay, None); } } @@ -491,7 +488,7 @@ impl RequestState { } } - fn begin_leaves_fetch( + fn begin_leaves_fetch( read_transaction: &BeatreeReadTx, pos: &TriePosition, page: Page, @@ -631,9 +628,7 @@ impl Seeker { /// Take the result of a complete request. pub fn take_completion(&mut self) -> Option { - if self.requests.front().is_some_and(|r| r.is_completed()) { - // UNWRAP: just checked existence. - let request = self.requests.pop_front().unwrap(); + if let Some(request) = self.requests.pop_front_if(|r| r.is_completed()) { // PANIC: checked above. let RequestState::Completed(terminal) = request.state else { unreachable!() diff --git a/nomt/src/options.rs b/nomt/src/options.rs index c0f9a1436e..d057203f76 100644 --- a/nomt/src/options.rs +++ b/nomt/src/options.rs @@ -33,6 +33,12 @@ pub struct Options { pub(crate) page_cache_upper_levels: usize, } +impl Default for Options { + fn default() -> Self { + Self::new() + } +} + impl Options { /// Create a new `Options` instance with the default values and a random bitbox seed. pub fn new() -> Self { diff --git a/nomt/src/rw_pass_cell/mod.rs b/nomt/src/rw_pass_cell/mod.rs index 4b094def52..12a618dc5a 100644 --- a/nomt/src/rw_pass_cell/mod.rs +++ b/nomt/src/rw_pass_cell/mod.rs @@ -244,9 +244,7 @@ impl WritePass { /// /// All write-passes need to be consumed before being dropped to yield the parent region. pub fn consume(mut self) -> Option { - let Some(ref parent) = self.parent else { - return None; - }; + let parent = self.parent.as_ref()?; self.consumed = true; @@ -517,6 +515,8 @@ impl<'a, 'pass, T> DerefMut for WriteGuard<'a, 'pass, T> { /// Whether a region contains values or not. /// +/// # Safety +/// /// This trait is unsafe because the memory safety of the [`RwPassCell`] /// depends on it being implemented accurately, as well as on the Region trait being /// implemented correctly. diff --git a/nomt/src/seglog/mod.rs b/nomt/src/seglog/mod.rs index 1254f79267..8364a6014d 100644 --- a/nomt/src/seglog/mod.rs +++ b/nomt/src/seglog/mod.rs @@ -624,9 +624,9 @@ fn truncate_head_segment( ) -> std::io::Result { let end = match scan_record_end(path, new_end_live)? { None => { - return Err(std::io::Error::other( - anyhow::anyhow!("Failed to find the last live record in the head segment"), - )); + return Err(std::io::Error::other(anyhow::anyhow!( + "Failed to find the last live record in the head segment" + ))); } Some(offset) => offset, }; @@ -772,6 +772,7 @@ mod tests { }) } + #[allow(clippy::type_complexity)] fn open_log( &self, max_segment_size: u64, diff --git a/nomt/src/seglog/segment_rw.rs b/nomt/src/seglog/segment_rw.rs index c4780df8ff..a32418ee43 100644 --- a/nomt/src/seglog/segment_rw.rs +++ b/nomt/src/seglog/segment_rw.rs @@ -118,12 +118,10 @@ impl SegmentFileReader { self.buf_reader .seek(SeekFrom::Current(-(HEADER_SIZE as i64)))?; - return Err(std::io::Error::other( - anyhow::anyhow!( - "Record payload length is too large: {}", - header.payload_length() - ), - )); + return Err(std::io::Error::other(anyhow::anyhow!( + "Record payload length is too large: {}", + header.payload_length() + ))); } self.payload_length = Some(header.payload_length()); // It's not enough to just seek to the payload length because the records always span @@ -358,10 +356,12 @@ mod tests { let temp_file = NamedTempFile::new().unwrap(); let mut writer = SegmentFileWriter::new(temp_file.reopen().unwrap(), 0); - let payloads = [vec![1, 2, 3], + let payloads = [ + vec![1, 2, 3], vec![4, 5, 6, 7], vec![8; RECORD_ALIGNMENT as usize - HEADER_SIZE as usize], - vec![9; RECORD_ALIGNMENT as usize * 2 - HEADER_SIZE as usize + 1]]; + vec![9; RECORD_ALIGNMENT as usize * 2 - HEADER_SIZE as usize + 1], + ]; for (i, payload) in payloads.iter().enumerate() { writer diff --git a/nomt/src/store/flock.rs b/nomt/src/store/flock.rs index cbfe7b239b..ebfe4c3299 100644 --- a/nomt/src/store/flock.rs +++ b/nomt/src/store/flock.rs @@ -18,6 +18,7 @@ impl Flock { .read(true) .write(true) .create(true) + .truncate(false) .open(lock_path)?; match crate::sys::unix::try_lock_exclusive(&lock_fd) { diff --git a/nomt/src/store/sync.rs b/nomt/src/store/sync.rs index b6b052c747..94148dc3dc 100644 --- a/nomt/src/store/sync.rs +++ b/nomt/src/store/sync.rs @@ -30,6 +30,7 @@ impl Sync { } } + #[allow(clippy::too_many_arguments)] pub fn sync( &mut self, shared: &Shared, diff --git a/nomt/tests/common/mod.rs b/nomt/tests/common/mod.rs index f66304b74c..1300e4ecae 100644 --- a/nomt/tests/common/mod.rs +++ b/nomt/tests/common/mod.rs @@ -259,6 +259,7 @@ impl Arbitrary for ProofCase { } } +#[allow(dead_code)] fn arbitrary_present_access(g: &mut Gen, prior: Value) -> KeyReadWrite { match u8::arbitrary(g) % 3 { 0 => KeyReadWrite::Read(Some(prior)), @@ -267,6 +268,7 @@ fn arbitrary_present_access(g: &mut Gen, prior: Value) -> KeyReadWrite { } } +#[allow(dead_code)] fn arbitrary_missing_access(g: &mut Gen, allow_read_then_write: bool) -> KeyReadWrite { match if allow_read_then_write { u8::arbitrary(g) % 3 diff --git a/nomt/tests/fill_and_empty.rs b/nomt/tests/fill_and_empty.rs index 9111cf48c4..06d191c619 100644 --- a/nomt/tests/fill_and_empty.rs +++ b/nomt/tests/fill_and_empty.rs @@ -39,8 +39,7 @@ fn fill_and_empty(seed: [u8; 16], commit_concurrency: usize) { // inserting all the values let mut to_check = vec![]; - for i in 0..db_size { - let key = items[i]; + for (i, &key) in items.iter().enumerate() { let value = vec![i as u8; 400]; to_check.push((key, value.clone())); diff --git a/nomt/tests/prove_in_session.rs b/nomt/tests/prove_in_session.rs index 437da832db..e18f7ba846 100644 --- a/nomt/tests/prove_in_session.rs +++ b/nomt/tests/prove_in_session.rs @@ -10,13 +10,11 @@ use std::collections::{BTreeMap, BTreeSet}; #[test] fn prove_in_session() { - let mut accounts = 0; let mut t = Test::new("prove_in_session"); let _ = t.read_id(0); - for _ in 0..100 { + for accounts in 0..100 { common::set_balance(&mut t, accounts, 1000); - accounts += 1; } let root = t.commit().0.into_inner(); @@ -48,13 +46,11 @@ fn prove_in_session() { #[test] fn prove_in_session_against_overlay() { - let mut accounts = 0; let mut t = Test::new("prove_in_session_against_overlay"); let _ = t.read_id(0); - for _ in 0..100 { + for accounts in 0..100 { common::set_balance(&mut t, accounts, 1000); - accounts += 1; } let (overlay_a, _) = t.update(); let root = overlay_a.root().into_inner(); diff --git a/nomt/tests/rollback.rs b/nomt/tests/rollback.rs index 331795bd3b..b7f9da5e67 100644 --- a/nomt/tests/rollback.rs +++ b/nomt/tests/rollback.rs @@ -233,18 +233,22 @@ impl TestPlan { // Verify that all expected keys are in place and have the correct value. for (key, expected_value) in expected { let actual_value = nomt.read(key).unwrap(); - if actual_value.is_none() { - errors.push(format!( - "missing: the key {:x?} is not present", - hex::encode(key) - )); - } else if actual_value.as_ref() != Some(&expected_value) { - errors.push(format!( + match actual_value { + None => { + errors.push(format!( + "missing: the key {:x?} is not present", + hex::encode(key) + )); + } + Some(actual_value) if actual_value != expected_value => { + errors.push(format!( "wrong value: the key {:x?} has the wrong value. Expected {:x?}, found {:x?}", key, hex::encode(expected_value), - hex::encode(actual_value.unwrap()) + hex::encode(actual_value) )); + } + Some(_) => {} } } @@ -281,10 +285,7 @@ impl TestPlan { fn display_keys<'a>(keys: impl IntoIterator) -> String { let mut keys: Vec<_> = keys.into_iter().collect(); keys.sort(); - keys.iter() - .map(hex::encode) - .collect::>() - .join(", ") + keys.iter().map(hex::encode).collect::>().join(", ") } fn display_keys_and_values<'a>(kv: impl IntoIterator) -> String { diff --git a/torture/src/agent.rs b/torture/src/agent.rs index d117c2a2cf..a203cd11e9 100644 --- a/torture/src/agent.rs +++ b/torture/src/agent.rs @@ -547,6 +547,7 @@ fn is_enospc(err: &anyhow::Error) -> bool { } /// Abstraction over the stream of messages from the supervisor. +#[allow(clippy::type_complexity)] struct Stream { rd_stream: SymmetricallyFramed< FramedRead, LengthDelimitedCodec>, diff --git a/torture/src/logging.rs b/torture/src/logging.rs index b37d705785..cd5dd88ac8 100644 --- a/torture/src/logging.rs +++ b/torture/src/logging.rs @@ -47,9 +47,7 @@ fn env_filter(kind: Kind) -> EnvFilter { .parse(env) .unwrap(), ), - Err(std::env::VarError::NotPresent) => { - None - } + Err(std::env::VarError::NotPresent) => None, Err(std::env::VarError::NotUnicode(_)) => { panic!("Environment variable {} is not unicode", var_name); } diff --git a/torture/src/supervisor/controller.rs b/torture/src/supervisor/controller.rs index ab03ae5265..1036b73361 100644 --- a/torture/src/supervisor/controller.rs +++ b/torture/src/supervisor/controller.rs @@ -135,7 +135,7 @@ pub async fn spawn_agent_into( let stream = UnixStream::from_std(sock)?; let (rr, task) = comms::run(stream); - let _ = tokio::spawn(task); + tokio::spawn(task); // Assign a unique ID to the agent. static AGENT_COUNT: AtomicUsize = AtomicUsize::new(0); diff --git a/torture/src/supervisor/mod.rs b/torture/src/supervisor/mod.rs index 5024a4e1cc..e41ae0b513 100644 --- a/torture/src/supervisor/mod.rs +++ b/torture/src/supervisor/mod.rs @@ -129,7 +129,7 @@ async fn join_interruptable( tokio::select! { _ = sigint.recv() => { control_loop_jh.abort(); - return ExitReason::Interrupted; + ExitReason::Interrupted } res = &mut control_loop_jh => { // Control loop ended before receiving the second ^C. diff --git a/torture/src/supervisor/resource.rs b/torture/src/supervisor/resource.rs index c11226bc24..2ec7745d5e 100644 --- a/torture/src/supervisor/resource.rs +++ b/torture/src/supervisor/resource.rs @@ -194,7 +194,8 @@ pub fn process_memory_occupied(pid: u32) -> Option { let mut statm = String::new(); statm_file.read_to_string(&mut statm).expect(&format_err); let occupied_memory = statm - .split(' ').nth(1) + .split(' ') + .nth(1) .map(|value| value.parse::().expect(&format_err)) .expect(&format_err); Some(occupied_memory) diff --git a/torture/src/supervisor/workload.rs b/torture/src/supervisor/workload.rs index 07ab8d4814..a100e322c6 100644 --- a/torture/src/supervisor/workload.rs +++ b/torture/src/supervisor/workload.rs @@ -303,23 +303,20 @@ impl Workload { return Ok(()); } - if self.trick_handle.is_some() { + if let Some(trick_handle) = self.trick_handle.as_ref() { if self.enabled_enospc { let should_turn_off = self.rng.random_bool(self.config.enospc_off); if should_turn_off { info!("unsetting ENOSPC"); self.enabled_enospc = false; - self.trick_handle - .as_ref() - .unwrap() - .set_trigger_enospc(false); + trick_handle.set_trigger_enospc(false); } } else { let should_turn_on = self.rng.random_bool(self.config.enospc_on); if should_turn_on { info!("setting ENOSPC"); self.enabled_enospc = true; - self.trick_handle.as_ref().unwrap().set_trigger_enospc(true); + trick_handle.set_trigger_enospc(true); } } @@ -328,20 +325,14 @@ impl Workload { if should_turn_off { info!("unsetting latency injector"); self.enabled_latency = false; - self.trick_handle - .as_ref() - .unwrap() - .set_trigger_latency_injector(false); + trick_handle.set_trigger_latency_injector(false); } } else { let should_turn_on = self.rng.random_bool(self.config.latency_on); if should_turn_on { info!("setting latency injector"); self.enabled_latency = true; - self.trick_handle - .as_ref() - .unwrap() - .set_trigger_latency_injector(true); + trick_handle.set_trigger_latency_injector(true); } } } @@ -508,8 +499,7 @@ impl Workload { } async fn schedule_rollback(&mut self, should_crash: bool) -> anyhow::Result<()> { - let n_commits_to_rollback = - self.rng.random_range(1..self.config.max_rollback_commits); + let n_commits_to_rollback = self.rng.random_range(1..self.config.max_rollback_commits); let last_snapshot = &self.committed; let rollback_sync_seqn = last_snapshot.sync_seqn + n_commits_to_rollback as u32; @@ -927,7 +917,6 @@ impl Workload { ) .await?; if let InitOutcome::Success = outcome { - } else { return Err(anyhow::anyhow!("Unexpected init outcome: {:?}", outcome)); } @@ -1035,13 +1024,9 @@ impl Workload { let mut new_keys = HashSet::with_capacity(changeset_size); let mut sum_value_size = 0; let mut tot_items = 0; - loop { - let Some(change) = self.gen_key_value_change(&mut used_keys, &mut new_keys) else { - // Stop adding things to the changeset if `gen_key_value_change` - // cannot create a new change. - break; - }; - + // Stop adding things to the changeset if `gen_key_value_change` + // cannot create a new change. + while let Some(change) = self.gen_key_value_change(&mut used_keys, &mut new_keys) { if let Some(val) = change.value() { sum_value_size += val.len(); } From 29c4f76020f4fd47af59a48ef52a10b73af3c502 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Mon, 2 Nov 2026 09:53:24 +0100 Subject: [PATCH 3/4] fixes after merging recent master --- benchtop/src/backend.rs | 5 +++-- benchtop/src/custom_workload.rs | 1 + benchtop/src/main.rs | 4 ++-- benchtop/src/nomt.rs | 10 +++++----- benchtop/src/transfer_workload.rs | 2 +- benchtop/src/workload.rs | 1 + nomt/tests/witness_check.rs | 2 +- 7 files changed, 14 insertions(+), 11 deletions(-) diff --git a/benchtop/src/backend.rs b/benchtop/src/backend.rs index 3c101ff131..0e7dc2e7e5 100644 --- a/benchtop/src/backend.rs +++ b/benchtop/src/backend.rs @@ -21,6 +21,7 @@ impl Backend { // If reset is true, then erase any previous backend's database // and restart from an empty database. // Otherwise, use the already present database. + #[allow(clippy::too_many_arguments)] pub fn instantiate( &self, reset: bool, @@ -93,7 +94,7 @@ impl DB { while !workload.is_done() { if timeout .as_ref() - .map_or(false, |t| std::time::Instant::now() > *t) + .is_some_and(|t| std::time::Instant::now() > *t) { break; } @@ -121,7 +122,7 @@ impl DB { while workloads.iter().any(|w| !w.is_done()) { if timeout .as_ref() - .map_or(false, |t| std::time::Instant::now() > *t) + .is_some_and(|t| std::time::Instant::now() > *t) { break; } diff --git a/benchtop/src/custom_workload.rs b/benchtop/src/custom_workload.rs index 90341edcb8..7dbdeb92d0 100644 --- a/benchtop/src/custom_workload.rs +++ b/benchtop/src/custom_workload.rs @@ -48,6 +48,7 @@ fn encode_id(id: u64) -> [u8; 8] { } /// Build N `RwWorkload`s, one for each thread. +#[allow(clippy::too_many_arguments)] pub fn build( reads: u8, writes: u8, diff --git a/benchtop/src/main.rs b/benchtop/src/main.rs index 63ac58ea74..8672e32126 100644 --- a/benchtop/src/main.rs +++ b/benchtop/src/main.rs @@ -29,7 +29,7 @@ pub fn main() -> Result<()> { pub fn init(params: InitParams) -> Result<()> { let workload_params = params.workload; - let (mut init, _) = workload::parse(&workload_params, u64::max_value(), 0)?; + let (mut init, _) = workload::parse(&workload_params, u64::MAX, 0)?; let mut db = params.backend.instantiate( true, @@ -57,7 +57,7 @@ pub fn run(params: RunParams) -> Result<()> { ); let (mut init, mut workloads) = workload::parse( &workload_params, - params.limits.ops.unwrap_or(u64::max_value()), + params.limits.ops.unwrap_or(u64::MAX), seeder.random(), )?; diff --git a/benchtop/src/nomt.rs b/benchtop/src/nomt.rs index 3dde9ec2da..5b1c279c6a 100644 --- a/benchtop/src/nomt.rs +++ b/benchtop/src/nomt.rs @@ -19,6 +19,7 @@ pub struct NomtDB { } impl NomtDB { + #[allow(clippy::too_many_arguments)] pub fn open( reset: bool, commit_concurrency: usize, @@ -99,7 +100,7 @@ impl NomtDB { } let _timer_guard_total = timer.as_mut().map(|t| t.record_span("workload")); - self.commit_overlay(&mut overlay_window, timer.as_mut().map(|t| &mut **t)); + self.commit_overlay(&mut overlay_window, timer.as_deref_mut()); let session_params = SessionParams::default().witness_mode(WitnessMode::read_write()); @@ -152,7 +153,7 @@ impl NomtDB { let _timer_guard_total = timer.as_mut().map(|t| t.record_span("workload")); - self.commit_overlay(&mut overlay_window, timer.as_mut().map(|t| &mut **t)); + self.commit_overlay(&mut overlay_window, timer.as_deref_mut()); let session_params = SessionParams::default().witness_mode(WitnessMode::read_write()); @@ -166,7 +167,7 @@ impl NomtDB { let use_timer = timer.is_some(); thread_pool.in_place_scope(|scope| { - for (workload, result) in workloads.into_iter().zip(results.iter_mut()) { + for (workload, result) in workloads.iter_mut().zip(results.iter_mut()) { let session = &session; scope.spawn(move |_| { let mut workload_timer = if use_timer { @@ -196,8 +197,7 @@ impl NomtDB { let mut actual_access: Vec<_> = results .into_iter() .flatten() - .map(|(access, _)| access) - .flatten() + .flat_map(|(access, _)| access) .collect(); actual_access.sort_by_key(|(k, _)| *k); diff --git a/benchtop/src/transfer_workload.rs b/benchtop/src/transfer_workload.rs index af21e85a08..5c9b6bd6fd 100644 --- a/benchtop/src/transfer_workload.rs +++ b/benchtop/src/transfer_workload.rs @@ -134,7 +134,7 @@ impl Workload for TransferWorkload { } else { // odds of two threads generating the same random account here are // incredibly low. - rng.random_range(self.num_accounts..u64::max_value()) + rng.random_range(self.num_accounts..u64::MAX) }; let send_balance = decode_balance( diff --git a/benchtop/src/workload.rs b/benchtop/src/workload.rs index a2af466a20..160b211990 100644 --- a/benchtop/src/workload.rs +++ b/benchtop/src/workload.rs @@ -28,6 +28,7 @@ pub trait Workload: Send { fn is_done(&self) -> bool; } +#[allow(clippy::type_complexity)] pub fn parse( workload_params: &WorkloadParams, op_limit: u64, diff --git a/nomt/tests/witness_check.rs b/nomt/tests/witness_check.rs index 3c5bc49905..865ec2c677 100644 --- a/nomt/tests/witness_check.rs +++ b/nomt/tests/witness_check.rs @@ -281,7 +281,7 @@ fn witness_validity_with_concurrent_workers() { .iter() .map(|p| { p.inner - .verify::(&p.path.path(), prev_root.into_inner()) + .verify::(p.path.path(), prev_root.into_inner()) .unwrap() }) .collect::>(); From b6bbd5561128bf068ecaa88f99488c472d78d1da Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Wed, 25 Nov 2026 10:01:47 +0100 Subject: [PATCH 4/4] Fix CI checks after rebasing onto master --- core/src/proof/multi_proof.rs | 2 +- core/src/trie_pos.rs | 2 +- fuzz/fuzz_targets/overlay.rs | 2 +- fuzz/fuzz_targets/proof_decode.rs | 2 +- nomt/src/beatree/iterator.rs | 15 +++++------- nomt/src/bitbox/ht_file.rs | 4 +-- nomt/src/io/linux.rs | 4 +-- nomt/src/merkle/page_walker.rs | 1 + nomt/src/merkle/worker.rs | 4 +-- nomt/src/rollback/reverse_delta_worker.rs | 1 + nomt/src/store/mod.rs | 11 ++------- nomt/src/task.rs | 2 +- trickfs/src/lib.rs | 30 ++++++++++------------- 13 files changed, 33 insertions(+), 47 deletions(-) diff --git a/core/src/proof/multi_proof.rs b/core/src/proof/multi_proof.rs index ca0b21caed..a8f3c6d3ff 100644 --- a/core/src/proof/multi_proof.rs +++ b/core/src/proof/multi_proof.rs @@ -812,7 +812,7 @@ pub fn verify_update( } // ingest the currently updated terminal. - let ops = std::mem::take(&mut working_ops); + let ops = core::mem::take(&mut working_ops); working_ops.push((key, op)); let terminal = &proof.inner[updated_index]; diff --git a/core/src/trie_pos.rs b/core/src/trie_pos.rs index 68b69ad276..9b8f3e3d04 100644 --- a/core/src/trie_pos.rs +++ b/core/src/trie_pos.rs @@ -10,7 +10,7 @@ use bitvec::prelude::*; /// /// Deserialization rejects positions that no constructor could produce: a depth beyond 256, or a /// node index that does not match the path and depth. -#[derive(Clone)] +#[derive(Clone, Default)] #[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub struct TriePosition { diff --git a/fuzz/fuzz_targets/overlay.rs b/fuzz/fuzz_targets/overlay.rs index 520ad736d9..9d01384c5d 100644 --- a/fuzz/fuzz_targets/overlay.rs +++ b/fuzz/fuzz_targets/overlay.rs @@ -226,7 +226,7 @@ fn commit_overlay(u: &mut Unstructured, state: &mut State) -> Result<()> { let slot = &mut state.slots[i]; let parent_ok = slot .parent - .map_or(true, |p| state.last_committed_overlay == Some(p)); + .is_none_or(|p| state.last_committed_overlay == Some(p)); let expect_ok = parent_ok && slot.prev_root == state.db.root().into_inner(); // A commit attempt consumes the overlay, whether or not it succeeds. diff --git a/fuzz/fuzz_targets/proof_decode.rs b/fuzz/fuzz_targets/proof_decode.rs index e617c593c4..77281ee221 100644 --- a/fuzz/fuzz_targets/proof_decode.rs +++ b/fuzz/fuzz_targets/proof_decode.rs @@ -211,7 +211,7 @@ fn honest_witness(run: &Run) -> Witness { let position = position(*key, proof.siblings.len() as u16); if paths .last() - .map_or(true, |(_, p)| p.path() != position.path()) + .is_none_or(|(_, p)| p.path() != position.path()) { paths.push((proof, position)); } diff --git a/nomt/src/beatree/iterator.rs b/nomt/src/beatree/iterator.rs index 94477ddddd..79b252fa1f 100644 --- a/nomt/src/beatree/iterator.rs +++ b/nomt/src/beatree/iterator.rs @@ -169,15 +169,11 @@ impl CurrentLeaf { } fn is_in_range(&self, end: Option<&Key>) -> bool { - end.is_none_or(|end| { - super::key_cmp(&self.leaf.key(self.index), end).is_lt() - }) + end.is_none_or(|end| super::key_cmp(&self.leaf.key(self.index), end).is_lt()) } fn is_last_output_in_range(&self, end: Option<&Key>) -> bool { - end.is_none_or(|end| { - super::key_cmp(&self.leaf.key(self.index - 1), end).is_lt() - }) + end.is_none_or(|end| super::key_cmp(&self.leaf.key(self.index - 1), end).is_lt()) } fn last_output(&self) -> IterOutput<'_> { @@ -245,9 +241,10 @@ impl LeafIterator { LeafIteratorState::Proceeding { current, .. } => { let next = current.index + 1; next < current.leaf.n() - && self.end.as_ref().is_none_or(|end| { - super::key_cmp(¤t.leaf.key(next), end).is_lt() - }) + && self + .end + .as_ref() + .is_none_or(|end| super::key_cmp(¤t.leaf.key(next), end).is_lt()) } _ => false, }; diff --git a/nomt/src/bitbox/ht_file.rs b/nomt/src/bitbox/ht_file.rs index 6d847dca15..3cf4edbed5 100644 --- a/nomt/src/bitbox/ht_file.rs +++ b/nomt/src/bitbox/ht_file.rs @@ -118,13 +118,13 @@ pub(super) fn resize_and_prealloc( // To preallocate on Linux systems, try using fallocate with ZERO_RANGE first as it's more // efficient. fallocate sets the file size as well, so ftruncate (aka file.set_len()) is // not needed. - if crate::sys::linux::fs_check(ht_file).map_or(false, |fsck| fsck.is_tmpfs()) { + if crate::sys::linux::fs_check(ht_file).is_ok_and(|fsck| fsck.is_tmpfs()) { // Skip preallocation for tmpfs. It doesn't support fallocate and it's // memory-backed anyway. ftruncate and bail. ht_file.set_len(len)?; return Ok(()); } - if let Err(_) = crate::sys::linux::falloc_zero_file(ht_file, len) { + if crate::sys::linux::falloc_zero_file(ht_file, len).is_err() { // If fallocate fails, fall back to zeroing the file with write. resize_and_zero_file(ht_file, len)?; } diff --git a/nomt/src/io/linux.rs b/nomt/src/io/linux.rs index a9796bacf1..0b511ca89b 100644 --- a/nomt/src/io/linux.rs +++ b/nomt/src/io/linux.rs @@ -86,7 +86,7 @@ fn run_worker(page_pool: PagePool, command_rx: Receiver) { // 1. process completions. if !pending.is_empty() { complete_queue.sync(); - while let Some(completion_event) = complete_queue.next() { + for completion_event in complete_queue.by_ref() { if pending.get(completion_event.user_data() as usize).is_none() { continue; } @@ -203,7 +203,7 @@ fn submission_entry(command: &mut IoCommand) -> squeue::Entry { .build() } IoKind::WriteArc(fd, page_index, ref page) => { - let page: &[u8] = &*page; + let page: &[u8] = page; opcode::Write::new(types::Fd(fd), page.as_ptr(), PAGE_SIZE as u32) .offset(page_index * PAGE_SIZE as u64) .build() diff --git a/nomt/src/merkle/page_walker.rs b/nomt/src/merkle/page_walker.rs index 063187704e..b93d7cd854 100644 --- a/nomt/src/merkle/page_walker.rs +++ b/nomt/src/merkle/page_walker.rs @@ -841,6 +841,7 @@ fn count_leaves(page: &PageMut) -> u64 { /// otherwise, for each reconstructed page: its page_id, the page, the PageDiff of all nodes /// written, the number of leaves in the page and the number in its child pages. /// Every reconstructed page records its child pages as elided. +#[allow(clippy::type_complexity)] pub fn reconstruct_pages( page: &Page, page_id: PageId, diff --git a/nomt/src/merkle/worker.rs b/nomt/src/merkle/worker.rs index db579b2bb7..ea63cd704a 100644 --- a/nomt/src/merkle/worker.rs +++ b/nomt/src/merkle/worker.rs @@ -549,9 +549,7 @@ fn subtrie_ops(read_write: &[(KeyPath, KeyReadWrite)]) -> Vec<(KeyPath, Option { - Some((*key, *val)) - } + KeyReadWrite::Write(val) | KeyReadWrite::ReadThenWrite(_, val) => Some((*key, *val)), KeyReadWrite::Read(_) => None, }) .collect::>() diff --git a/nomt/src/rollback/reverse_delta_worker.rs b/nomt/src/rollback/reverse_delta_worker.rs index 54dce29ef3..cc871e1a0f 100644 --- a/nomt/src/rollback/reverse_delta_worker.rs +++ b/nomt/src/rollback/reverse_delta_worker.rs @@ -63,6 +63,7 @@ pub(super) enum DeltaBuilderCommand { /// finalized or dropped. /// /// The worker's result is the priors gathered since the last `Join`. +#[allow(clippy::type_complexity)] pub(super) fn start( store: impl LoadValueAsync, ) -> ( diff --git a/nomt/src/store/mod.rs b/nomt/src/store/mod.rs index 061196ec26..d06bf643a3 100644 --- a/nomt/src/store/mod.rs +++ b/nomt/src/store/mod.rs @@ -73,15 +73,8 @@ impl Store { cfg_if::cfg_if! { if #[cfg(target_os = "linux")] { // O_DIRECT is not supported on tmpfs. - let o_direct: bool; - match crate::sys::linux::fs_check(&db_dir_fd) { - Ok(fsck) => { - o_direct = !fsck.is_tmpfs(); - }, - Err(_) => { - o_direct = false; - }, - } + let o_direct = crate::sys::linux::fs_check(&db_dir_fd) + .is_ok_and(|fsck| !fsck.is_tmpfs()); } } diff --git a/nomt/src/task.rs b/nomt/src/task.rs index ff4e480a18..361e060baa 100644 --- a/nomt/src/task.rs +++ b/nomt/src/task.rs @@ -29,7 +29,7 @@ where std::thread::Builder::new() .name(name.to_string()) .spawn(move || { - let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| task())); + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(task)); let _ = tx.send(res); }) .expect("failed to spawn thread"); diff --git a/trickfs/src/lib.rs b/trickfs/src/lib.rs index 2944c0afb2..51cc7e41fd 100644 --- a/trickfs/src/lib.rs +++ b/trickfs/src/lib.rs @@ -693,28 +693,24 @@ impl TrickState { .get(&ino) .unwrap_or_else(|| panic!("{ino:?} is not in tree")); let standard = &[(DOT.as_os_str(), ino), (DOTDOT.as_os_str(), parent)]; - let mut iter = standard + let iter = standard .iter() .copied() .chain(container.iter()) .enumerate() .skip(offset as usize); - loop { - if let Some((offset, (name, ino))) = iter.next() { - let inode = self - .lookup_inode(ino) - .unwrap_or_else(|| panic!("{ino:?} cannot be found")); - let offset = offset + 1; - let buf_is_filled = reply.add( - INodeNo(ino.0), - offset.try_into().unwrap(), - inode.kind(), - name, - ); - if buf_is_filled { - break; - } - } else { + for (offset, (name, ino)) in iter { + let inode = self + .lookup_inode(ino) + .unwrap_or_else(|| panic!("{ino:?} cannot be found")); + let offset = offset + 1; + let buf_is_filled = reply.add( + INodeNo(ino.0), + offset.try_into().unwrap(), + inode.kind(), + name, + ); + if buf_is_filled { break; } }