Skip to content

Change to WakeCounter API proposal #1384

@Thomasdezeeuw

Description

@Thomasdezeeuw

I would like to propose a breaking change in API for the WakerCounter type in the futures-test crate. The current API has the counter and LocalWaker implementation in the same WakerCounter type, which can be limiting. I propose an API that splits it into two types. Since it's not a lot of code I have a working implementation below.

/// Create a new `LocalWaker` that counts the number of times it's awoken.
pub fn new_count_waker() -> (LocalWaker, AwokenCount) {
    let inner = Arc::new(WakerInner { count: AtomicUsize::new(0) });
    (local_waker_from_nonlocal(inner.clone()), AwokenCount { inner })
}

/// Number of times the waker was awoken.
///
/// See [`new_count_waker`].
pub struct AwokenCount {
    inner: Arc<WakerInner>,
}

impl AwokenCount {
    /// Get the number of times the waker was awoken.
    pub fn get(&self) -> usize {
        self.inner.count.load(Ordering::SeqCst)
    }
}

struct WakerInner {
    count: AtomicUsize,
}

impl Wake for WakerInner {
    fn wake(arc_self: &Arc<Self>) {
        let _ = arc_self.count.fetch_add(1, Ordering::SeqCst);
    }
}

And the usage.

let (waker, count) = new_count_waker();

// Polling is easy since we just have a `LocalWaker`.
let future = // ...
future.poll(&waker);

// And elsewhere we can check the wake count.
assert_eq!(count.get(), 1);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions