]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/util/atomic_counter.rs
Merge pull request #1738 from jkczyz/2022-09-invoice-request
[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 pub(crate) struct AtomicCounter {
9         // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
10         // bits we will never realistically count into high:
11         counter_low: AtomicUsize,
12         counter_high: AtomicUsize,
13 }
14
15 impl AtomicCounter {
16         pub(crate) fn new() -> Self {
17                 Self {
18                         counter_low: AtomicUsize::new(0),
19                         counter_high: AtomicUsize::new(0),
20                 }
21         }
22         pub(crate) fn get_increment(&self) -> u64 {
23                 let low = self.counter_low.fetch_add(1, Ordering::AcqRel) as u64;
24                 let high = if low == 0 {
25                         self.counter_high.fetch_add(1, Ordering::AcqRel) as u64
26                 } else {
27                         self.counter_high.load(Ordering::Acquire) as u64
28                 };
29                 (high << 32) | low
30         }
31 }