Advertisement
Brord

client wrap example

May 8th, 2023 (edited)
1,296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.12 KB | None | 0 0
  1. use std::sync::{Mutex, MutexGuard};
  2.  
  3. struct Wallet {
  4.     lock: Mutex<()>,
  5.     client: Client,
  6. }
  7.  
  8. struct Client {
  9.     // ...
  10. }
  11.  
  12. impl Wallet {
  13.     fn new(client: Client) -> Self {
  14.         Self { lock: Mutex::new(()), client }
  15.     }
  16.  
  17.     async fn async_with_lock<F, R>(&self, f: F) -> R
  18.     where
  19.         F: FnOnce(&mut Client) -> R + Send,
  20.         R: Send,
  21.     {
  22.         let mut lock: MutexGuard<()> = self.lock.lock().await;
  23.         f(&mut self.client)
  24.     }
  25.  
  26.     async fn my_locked_method(&self) {
  27.         my_macro!(client, my_client_method);
  28.     }
  29.  
  30.     fn my_regular_method(&self) {
  31.         client.my_other_client_method();
  32.     }
  33. }
  34.  
  35. impl Client {
  36.     fn my_client_method(&mut self) {
  37.         // ...
  38.     }
  39. }
  40.  
  41. macro_rules! my_macro {
  42.     ($wallet:expr, $method:ident) => {
  43.         {
  44.             $wallet.async_with_lock(|client| async move {
  45.                 client.$method().await;
  46.             }).await;
  47.         }
  48.     }
  49. }
  50.  
  51. async fn main() {
  52.     let client = Client { /* ... */ };
  53.     let wallet = Wallet::new(client);
  54.  
  55.     wallet.my_locked_method().await;
  56.     wallet.my_regular_method();
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement