Created
November 12, 2025 15:32
-
-
Save aliakakis/d73b0ec9bf816b7117daa7a1fdfa80d7 to your computer and use it in GitHub Desktop.
Rust dynamic queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Usage | |
| async fn t0() { | |
| tokio::time::sleep(std::time::Duration::from_secs(2)).await; | |
| println!("Hello"); | |
| } | |
| async fn t1() { | |
| tokio::time::sleep(std::time::Duration::from_secs(2)).await; | |
| println!("World"); | |
| } | |
| #[tokio::main] | |
| async fn main() { | |
| env_logger::init(); // Log to stderr (if you run with `RUST_LOG=debug`). | |
| let mut queue = Queue::new(); | |
| queue.en_queue(task!(t0())); | |
| queue.en_queue(task!(t1())); | |
| queue.run().await; | |
| } | |
| */ | |
| use std::future::Future; | |
| use std::pin::Pin; | |
| type AsyncFn = Pin<Box<dyn Future<Output=()>>>; | |
| macro_rules! task { | |
| ($function:expr) => { | |
| Box::pin($function) | |
| }; | |
| } | |
| struct Queue { | |
| tasks: Vec<AsyncFn>, | |
| } | |
| impl Queue { | |
| fn new() -> Self { | |
| Self { tasks: Vec::new() } | |
| } | |
| fn en_queue(&mut self, task: AsyncFn) { | |
| self.tasks.insert(0, task); | |
| } | |
| async fn run(&mut self) { | |
| while let Some(func) = self.tasks.pop() { | |
| func.await; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment