1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
use std::sync::{Arc, Mutex}; type Cb<T, E> = Box<Fn(&Result<T, E>) -> () + Send + Sync>; type RunCb<T, E> = Box<Fn(&Thunky<T, E>) -> () + Send + Sync>; pub struct Thunky<T, E> { run: RunCb<T, E>, state: Mutex<Option<Box<State<T, E> + Send + Sync>>>, stack: Mutex<Vec<Cb<T, E>>>, cache: Mutex<Option<Result<T, E>>> } impl<T, E> Thunky<T, E> { /// Create a thunky instance with a function which take a reference of thunky as parameters, /// /// So we can call `thunky.cache()` in this function. /// # Examples /// /// ``` /// // test: run_only_once /// extern crate thunky; /// use thunky::*; /// use std::sync::Mutex; /// /// let v = Mutex::new(0); /// /// let run = move |thunk: &Thunky<u32, &str>| { /// *v.lock().unwrap() += 1; /// thunk.cache(Ok(*v.lock().unwrap())); /// }; /// /// let thunk = Thunky::new(Box::new(run)); /// /// thunk.run(Box::new(|arg: &Result<u32, &str>| -> () { /// assert_eq!(1, arg.unwrap()); /// })); /// /// thunk.run(Box::new(|arg: &Result<u32, &str>| -> () { /// assert_eq!(1, arg.unwrap()); /// })); /// /// thunk.run(Box::new(|arg: &Result<u32, &str>| -> () { /// assert_eq!(1, arg.unwrap()); /// })); /// ``` pub fn new (run: RunCb<T, E>) -> Arc<Thunky<T, E>> { Arc::new(Thunky { run, state: Mutex::new(Some(Box::new(Run {}))), stack: Mutex::new(Vec::new()), cache: Mutex::new(None) }) } /// Set cache, if incoming is `Ok(T)`, cahce will be preserved, and ignore the following `thunk.cache()`. /// /// otherwise cache will be reset by next calling to `thunk.cache()` /// /// # Examples /// /// ``` /// // test: re_run_on_error /// /// extern crate thunky; /// use std::sync::Mutex; /// use thunky::*; /// /// /// let v = Mutex::new(0); /// /// let run = move |thunk: &Thunky<u32, &str>| { /// *v.lock().unwrap() += 1; /// /// if *v.lock().unwrap() == 1 { /// thunk.cache(Err("stop")) /// } else if *v.lock().unwrap() == 2 { /// thunk.cache(Err("stop")) /// } else if *v.lock().unwrap() == 3 { /// thunk.cache(Ok(*v.lock().unwrap())) /// } else if *v.lock().unwrap() == 4 { /// thunk.cache(Ok(*v.lock().unwrap())) /// } /// }; /// /// let thunk = Thunky::new(Box::new(run)); /// /// thunk.run(Box::new(|arg: &Result<u32, &str>| -> () { /// assert_eq!("stop", arg.unwrap_err()); /// })); /// /// thunk.run(Box::new(|arg: &Result<u32, &str>| -> () { /// assert_eq!("stop", arg.unwrap_err()); /// })); /// /// thunk.run(Box::new(|arg: &Result<u32, &str>| -> () { /// assert_eq!(3, arg.unwrap()); /// })); /// /// thunk.run(Box::new(|arg: &Result<u32, &str>| -> () { /// assert_eq!(3, arg.unwrap()); /// })); /// ``` pub fn cache(&self, a: Result<T, E>) -> () { while self.stack.lock().unwrap().len() > 0 { let cb = self.stack.lock().unwrap().pop().unwrap(); cb(&a); } #[allow(unused_assignments)] let mut is_cached = false; match self.cache.lock().unwrap().as_ref() { Some(v) => { if v.is_ok() { is_cached = true } else { is_cached = false } }, None => { is_cached = false } } if !is_cached { *self.cache.lock().unwrap() = Some(a); } } /// Call `run()` of the current state of thunky. There're three private inner states in thunky: /// /// ` Run {} `: initial state, and after set the cache to `Err(E)`, state turns back to `Run`. /// /// ` Wait {} `: after call `run()` of `Run`, before set the cache, state stays `Wait`. /// /// ` Finish {} `: after set the cache to `Ok(T)`, state turns to `Finish` forever. /// /// /// # Examples /// /// ``` /// // test: run only once async /// /// extern crate thunky; /// extern crate tokio; /// /// use std::sync::{ Arc, Mutex }; /// use std::time::{Duration, Instant}; /// use tokio::prelude::*; /// use tokio::timer::Delay; /// use thunky::*; /// /// let run = move |_thunk: &Thunky<u32, &str>| {}; /// /// let thunk = Thunky::new(Box::new(run)); /// /// let v = Mutex::new(0); /// let thunk_clone = Arc::clone(&thunk); /// let when = Instant::now() + Duration::from_millis(1000); /// let task = Delay::new(when) /// .and_then(move |_| { /// *v.lock().unwrap() += 1; /// thunk_clone.cache(Ok(*v.lock().unwrap())); /// Ok(()) /// }) /// .map_err(|e| panic!("delay errored; err={:?}", e)); /// /// thunk.run(Box::new(|arg: &Result<u32, &str>| -> () { /// assert_eq!(1, arg.unwrap()); /// })); /// /// thunk.run(Box::new(|arg: &Result<u32, &str>| -> () { /// assert_ne!(2, arg.unwrap()); /// })); /// /// thunk.run(Box::new(|arg: &Result<u32, &str>| -> () { /// assert_eq!(1, arg.unwrap()); /// })); /// /// tokio::run(task); /// ``` pub fn run(&self, callback: Cb<T, E>) -> () { let state = self.state.lock().unwrap().take().unwrap(); state.run(self, callback) } } trait State<T, E> { fn run(&self, thunky: &Thunky<T, E>, callback: Cb<T, E>) -> (); } struct Run {} impl<T, E> State<T, E> for Run { fn run (&self, thunky: &Thunky<T, E>, callback: Cb<T, E>) -> () { thunky.stack.lock().unwrap().push(callback); (thunky.run)(thunky); match thunky.cache.lock().unwrap().as_ref() { Some(cache) => { if cache.is_ok() { *thunky.state.lock().unwrap() = Some(Box::new(Finish {})); } else if cache.is_err() { *thunky.state.lock().unwrap() = Some(Box::new(Run {})); } }, None => { *thunky.state.lock().unwrap() = Some(Box::new(Wait {})); } } } } struct Wait {} impl<T, E> State<T, E> for Wait { fn run (&self, thunky: &Thunky<T, E>, callback: Cb<T, E>) -> () { thunky.stack.lock().unwrap().push(callback); *thunky.state.lock().unwrap() = Some(Box::new(Wait {})); } } struct Finish {} impl<T, E> State<T, E> for Finish { fn run (&self, thunky: &Thunky<T, E>, callback: Cb<T, E>) -> () { while thunky.stack.lock().unwrap().len() > 0 { let cb = thunky.stack.lock().unwrap().pop().unwrap(); cb(thunky.cache.lock().unwrap().as_ref().unwrap()); } callback(thunky.cache.lock().unwrap().as_ref().unwrap()); *thunky.state.lock().unwrap() = Some(Box::new(Finish {})); } }