Skip to content

Commit

Permalink
Refactor next function
Browse files Browse the repository at this point in the history
  • Loading branch information
mikhailUshakoff committed Oct 9, 2024
1 parent 940708a commit 8ea7dd2
Showing 1 changed file with 11 additions and 19 deletions.
30 changes: 11 additions & 19 deletions Node/src/node/l2_block_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -87,5 +80,4 @@ mod tests {
l2_block_id.update(5);
assert_eq!(l2_block_id.block_id.load(Ordering::SeqCst), 13);
}

}

0 comments on commit 8ea7dd2

Please sign in to comment.