diff --git a/Node/src/node/l2_block_id.rs b/Node/src/node/l2_block_id.rs index 9e8dd5b..5b4937a 100644 --- a/Node/src/node/l2_block_id.rs +++ b/Node/src/node/l2_block_id.rs @@ -19,28 +19,21 @@ impl L2BlockId { // Returns the next block ID // The next block ID is computed as the maximum value between current_block_id + 1 and new_block_id + 1 pub fn next(&self, block_id: u64) -> u64 { - // Get the current value of current_block_id - let mut current_block_id = self.block_id.load(Ordering::Acquire); - // Initialize new_block_id - let mut new_block_id = block_id + 1; - + // Get the current value of self.block_id + let mut current = self.block_id.load(Ordering::Acquire); loop { - // Get next block ID + // Get next block ID // It is the maximum value between current_block_id + 1 and new_block_id + 1 - new_block_id = new_block_id.max(current_block_id + 1); - + let next = current.max(block_id) + 1; // Attempt to update the block ID using a compare-exchange operation match self.block_id.compare_exchange( - current_block_id, - new_block_id, + current, + next, Ordering::Release, Ordering::Acquire, ) { - Ok(_) => return new_block_id, // Return immediately on success - Err(previous) => { - current_block_id = previous; - // new_block_id gets recalculated at the start of the loop - } + Ok(_) => return next, // Return immediately on success + Err(previous) => current = previous, // next gets recalculated at the start of the loop } } } @@ -53,7 +46,7 @@ mod tests { #[test] fn test_next() { let l2_block_id = L2BlockId::new(); - + assert_eq!(l2_block_id.next(1), 2); assert_eq!(l2_block_id.next(0), 3); assert_eq!(l2_block_id.next(1), 4); @@ -65,7 +58,7 @@ mod tests { #[test] fn test_update() { let l2_block_id = L2BlockId::new(); - + l2_block_id.update(1); assert_eq!(l2_block_id.block_id.load(Ordering::SeqCst), 1); l2_block_id.update(10); @@ -77,7 +70,7 @@ mod tests { #[test] fn test_update_next() { let l2_block_id = L2BlockId::new(); - + l2_block_id.update(1); assert_eq!(l2_block_id.block_id.load(Ordering::SeqCst), 1); l2_block_id.update(10); @@ -87,5 +80,4 @@ mod tests { l2_block_id.update(5); assert_eq!(l2_block_id.block_id.load(Ordering::SeqCst), 13); } - }