udoprog / leaky-bucket

A token-based rate limiter based on the leaky bucket algorithm.
Apache License 2.0
93 stars 10 forks source link

How to call in Future #15

Closed caobug closed 2 years ago

caobug commented 2 years ago

Hello, I tried adding limit.acquire(8192).await; to "copy.rs poll" but it always prompts me "only allowed inside async functions and blocks", which I know means what.

So I modified some code, but it seems that cx.wake is never called. what should I do to make it work properly.?

let acquire = limit.acquire(8192);
tokio::pin!(acquire);
if acquire.as_mut().poll(cx).is_pending() {
    println!("Pending");
    return Poll::Pending;
}

Add to here:

https://github.com/tokio-rs/tokio/blob/d32ba2cf9d9b7eac3a904f558e5fe4397cc83e89/tokio/src/io/util/copy.rs#L91

udoprog commented 2 years ago

You need to run your code in an async function, like:

#[tokio::main]
async fn main() {
    let limit = /* your set up limiter */;
    limit.acquire(8192).await;
    // this will happen after the limit has been acquired.
}