Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. use std::future::Future;
  2.  
  3. fn main() {
  4. let mut conn = Connection;
  5. conn.transaction(|conn: &mut Connection| async move {
  6. conn.execute("Hi").await?;
  7. conn.execute("Hi2").await
  8. });
  9. }
  10.  
  11. struct Connection;
  12.  
  13. impl Connection {
  14. async fn execute(&mut self, s: &str) -> Result<(), ()> {
  15. println!("{}", s);
  16. Ok(())
  17. }
  18.  
  19. async fn transaction<F, T>(&mut self, f: F) -> Result<T, ()>
  20. where
  21. F: for<'a> AsyncFnOnceWithOurBounds<&'a mut Self, Output = Result<T, ()>>,
  22. {
  23. self.execute("BEGIN").await?;
  24. let res = f.async_call_once(self).await;
  25. if res.is_ok() {
  26. self.execute("COMMIT").await?;
  27. } else {
  28. self.execute("ROLLBACK").await?;
  29. }
  30. res
  31. }
  32. }
  33.  
  34. trait AsyncFnOnceWithOurBounds<Args> {
  35. type Output;
  36. type Future: Future<Output = Self::Output>;
  37.  
  38. fn async_call_once(self, args: Args) -> Self::Future;
  39. }
  40.  
  41. impl<'a, F, Args, Fut> AsyncFnOnceWithOurBounds<&'a mut Args> for F
  42. where
  43. F: FnOnce(&'a mut Args) -> Fut,
  44. Fut: Future + 'a,
  45. {
  46. type Output = Fut::Output;
  47. type Future = Fut;
  48.  
  49. fn async_call_once(self, args: &'a mut Args) -> Self::Future {
  50. self(args)
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement