Merge pull request #2419 from jurvis/2023-03-interactivetxs
[rust-lightning] / lightning / src / util / atomic_counter.rs
1 //! A simple atomic counter that uses AtomicUsize to give a u64 counter.
2
3 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
4 compile_error!("We need at least 32-bit pointers for atomic counter (and to have enough memory to run LDK)");
5
6 use core::sync::atomic::{AtomicUsize, Ordering};
7
8 #[derive(Debug)]
9 pub(crate) struct AtomicCounter {
10         // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
11         // bits we will never realistically count into high:
12         counter_low: AtomicUsize,
13         counter_high: AtomicUsize,
14 }
15
16 impl AtomicCounter {
17         pub(crate) fn new() -> Self {
18                 Self {
19                         counter_low: AtomicUsize::new(0),
20                         counter_high: AtomicUsize::new(0),
21                 }
22         }
23         pub(crate) fn get_increment(&self) -> u64 {
24                 let low = self.counter_low.fetch_add(1, Ordering::AcqRel) as u64;
25                 let high = if low == 0 {
26                         self.counter_high.fetch_add(1, Ordering::AcqRel) as u64
27                 } else {
28                         self.counter_high.load(Ordering::Acquire) as u64
29                 };
30                 (high << 32) | low
31         }
32 }