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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
#![deny(unsafe_code)]
use core::{
    clone::Clone,
    fmt::{self, Debug, Formatter},
    future::Future,
    pin::Pin,
    sync::atomic::{AtomicBool, Ordering},
    task::{Context, Poll, Waker},
};
use std::{
    error::Error,
    sync::{Condvar, Mutex},
};
use std::{sync::Arc, thread};

struct State<S, R>
where
    S: Send,
    R: Send,
{
    activated: AtomicBool,
    result_ready: AtomicBool,
    channel_present: AtomicBool,
    mtx: Mutex<(Option<S>, Option<R>, Option<String>)>,
    cvar: Condvar,
    canceled: AtomicBool,
}

impl<S, R> Debug for State<S, R>
where
    S: Debug + Send,
    R: Debug + Send,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("State")
            .field("result_ready", &self.result_ready)
            .field("channel_present", &self.channel_present)
            .field("mtx", &self.mtx)
            .field("cvar", &self.cvar)
            .field("canceled", &self.canceled)
            .field("activated", &self.activated)
            .finish()
    }
}

impl<S, R> Drop for State<S, R>
where
    S: Send,
    R: Send,
{
    fn drop(&mut self) {}
}

/// Flow loosely and gracefully.
///
/// Where:
///
/// S = type of sender (channel) value
///
/// R = type of Ok value of the Result (Result<'R', String>, and Err value always return String)
///
/// # Quick Example:
///
///```
///use flowync::Flower;
///type TestFlower = Flower<u32, String>;
///
///fn _main() {
///    let flower: TestFlower = Flower::new(1);
///    std::thread::spawn({
///        let handle = flower.handle();
///        // Activate
///        handle.activate();
///        move || {
///            for i in 0..10 {
///                // Send current value through channel, will block the spawned thread
///                // until the option value successfully being polled in the main thread.
///                handle.send(i);
///                // or handle.send_async(i).await; can be used from any multithreaded async runtime,
///                
///                // Return error if the job is failure, for example:
///                // if i >= 3 {
///                //    return handle.error("Err");
///                // }
///            }
///            // And return if the job successfully completed.
///            handle.success("Ok".to_string());
///        }
///    });
///
///    let mut exit = false;
///
///    loop {
///        // Check if the flower is_active()
///        // and will deactivate itself if the result value successfully received.
///        if flower.is_active() {
///            // Another logic goes here...
///            // e.g:
///            // notify_loading_fn();
///
///            flower
///                .extract(|channel| {
///                     // Poll channel
///                     if let Some(value) = channel {
///                         println!("{}", value);
///                     }
///                 })
///                .finalize(|result| {
///                    match result {
///                        Ok(value) => println!("{}", value),
///                        Err(err_msg) => println!("{}", err_msg),
///                    }
///
///                    // Exit if completed
///                    exit = true;
///                });
///        }
///
///        if exit {
///            break;
///        }
///    }
///}
/// ```
pub struct Flower<S, R>
where
    S: Send,
    R: Send,
{
    state: Arc<State<S, R>>,
    awaiting: Arc<(Mutex<Option<Waker>>, AtomicBool)>,
    id: usize,
}

pub struct Extracted<'a, S: Send, R: Send>(&'a Flower<S, R>);

impl<S, R> Extracted<'_, S, R>
where
    S: Send,
    R: Send,
{
    /// Try finalize result of the flower.
    pub fn finalize(self, f: impl FnOnce(Result<R, String>)) {
        let _self = self.0;
        if _self.state.result_ready.load(Ordering::Relaxed) {
            let catch = move || {
                let mut result_value = _self.state.mtx.lock().unwrap();
                let (_, ok, error) = &mut *result_value;
                _self.state.result_ready.store(false, Ordering::Relaxed);
                _self.state.activated.store(false, Ordering::Relaxed);
                (ok.take(), error.take())
            };

            let (ok, err) = catch();
            if let Some(value) = ok {
                f(Ok(value));
            } else if let Some(value) = err {
                f(Err(value));
            }
        }
    }
}

impl<S, R> Flower<S, R>
where
    S: Send,
    R: Send,
{
    pub fn new(id: usize) -> Self {
        Self {
            state: Arc::new(State {
                activated: AtomicBool::new(false),
                result_ready: AtomicBool::new(false),
                channel_present: AtomicBool::new(false),
                mtx: Mutex::new((None, None, None)),
                cvar: Condvar::new(),
                canceled: AtomicBool::new(false),
            }),
            awaiting: Arc::new((Mutex::new(None), AtomicBool::new(false))),
            id,
        }
    }

    /// Get ID of the flower.
    pub fn id(&self) -> usize {
        self.id
    }

    /// Get handle of the flower.
    pub fn handle(&self) -> Handle<S, R> {
        self.state.canceled.store(false, Ordering::Relaxed);
        Handle {
            state: Clone::clone(&self.state),
            awaiting: Clone::clone(&self.awaiting),
            id: self.id,
        }
    }

    /// Cancel current flower handle.
    ///
    /// will do nothing if not explicitly configured.
    pub fn cancel(&self) {
        self.state.canceled.store(true, Ordering::Relaxed);
    }

    /// Check if the flower is canceled
    pub fn is_canceled(&self) -> bool {
        self.state.canceled.load(Ordering::Relaxed)
    }

    /// Check if the current flower is active
    pub fn is_active(&self) -> bool {
        self.state.activated.load(Ordering::Relaxed)
    }

    /// Check if result value of the flower is ready
    pub fn result_is_ready(&self) -> bool {
        self.state.result_ready.load(Ordering::Relaxed)
    }

    /// Check if channel value of the flower is present
    pub fn channel_is_present(&self) -> bool {
        self.state.channel_present.load(Ordering::Relaxed)
    }

    /// Get the result of the flower and ignore channel value (if any).
    ///
    /// **Warning!** don't use this fn if channel value is important, use `extract fn` and then use `finalize fn` instead.
    pub fn result(&self, f: impl FnOnce(Result<R, String>)) {
        if self.state.result_ready.load(Ordering::Relaxed) {
            {
                if self.state.channel_present.load(Ordering::Relaxed) {
                    let _ = self.state.mtx.lock().unwrap().0.take();
                    self.state.cvar.notify_all();
                }
            }

            let _self = self;
            let catch = move || {
                let mut result_value = _self.state.mtx.lock().unwrap();
                let (_, ok, error) = &mut *result_value;
                _self.state.result_ready.store(false, Ordering::Relaxed);
                _self.state.activated.store(false, Ordering::Relaxed);
                (ok.take(), error.take())
            };

            let (ok, err) = catch();
            if let Some(value) = ok {
                f(Ok(value));
            } else if let Some(value) = err {
                f(Err(value));
            }
        }
    }

    /// Try extract channel value of the flower if available, and then `finalize` (must_use)
    pub fn extract(&self, f: impl FnOnce(Option<S>)) -> Extracted<'_, S, R> {
        if self.state.channel_present.load(Ordering::Relaxed) {
            let catch = move || {
                let value = self.state.mtx.lock().unwrap().0.take();
                self.state.channel_present.store(false, Ordering::Relaxed);
                if self.awaiting.1.load(Ordering::Relaxed) {
                    let mut mg_opt_waker = self.awaiting.0.lock().unwrap();
                    self.awaiting.1.store(false, Ordering::Relaxed);
                    if let Some(waker) = mg_opt_waker.take() {
                        waker.wake();
                    }
                } else {
                    self.state.cvar.notify_all();
                }
                value
            };
            let value = catch();
            f(value)
        } else {
            f(None)
        }

        Extracted(self)
    }
}

impl<S, R> Debug for Flower<S, R>
where
    S: Debug + Send,
    R: Debug + Send,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("Flower")
            .field("state", &self.state)
            .field("awaiting", &self.awaiting)
            .field("id", &self.id)
            .finish()
    }
}

impl<S, R> Clone for Flower<S, R>
where
    S: Send,
    R: Send,
{
    fn clone(&self) -> Self {
        Self {
            state: Clone::clone(&self.state),
            awaiting: Clone::clone(&self.awaiting),
            id: self.id,
        }
    }
}

impl<S, R> Drop for Flower<S, R>
where
    S: Send,
    R: Send,
{
    fn drop(&mut self) {
        if thread::panicking() {
            self.state.activated.store(false, Ordering::Relaxed)
        }
    }
}

/// A handle for the Flower
pub struct Handle<S, R>
where
    S: Send,
    R: Send,
{
    state: Arc<State<S, R>>,
    awaiting: Arc<(Mutex<Option<Waker>>, AtomicBool)>,
    id: usize,
}

impl<S, R> Handle<S, R>
where
    S: Send,
    R: Send,
{
    /// Get ID of the flower.
    pub fn id(&self) -> usize {
        self.id
    }

    /// Activate current flower
    pub fn activate(&self) {
        self.state.activated.store(true, Ordering::Relaxed);
    }

    /// Check if the current flower is active
    pub fn is_active(&self) -> bool {
        self.state.activated.load(Ordering::Relaxed)
    }

    /// Check if the current flower should be canceled
    pub fn should_cancel(&self) -> bool {
        self.state.canceled.load(Ordering::Relaxed)
    }

    /// Send current progress value
    pub fn send(&self, s: S) {
        let mut mtx = self.state.mtx.lock().unwrap();
        {
            mtx.0 = Some(s);
            self.state.channel_present.store(true, Ordering::Relaxed);
            self.awaiting.1.store(false, Ordering::Relaxed);
        }
        let _ = self.state.cvar.wait(mtx);
    }

    /// Send current progress value asynchronously.
    pub async fn send_async(&self, s: S) {
        {
            self.state.mtx.lock().unwrap().0 = Some(s);
            self.awaiting.1.store(true, Ordering::Relaxed);
            self.state.channel_present.store(true, Ordering::Relaxed);
        }
        AsyncSuspender {
            awaiting: self.awaiting.clone(),
        }
        .await
    }

    /// Set the Ok value of the result.
    pub fn success(&self, r: R) {
        {
            let mut result = self.state.mtx.lock().unwrap();
            let (_, ok, error) = &mut *result;
            *ok = Some(r);
            *error = None;
        }
        self.state.result_ready.store(true, Ordering::Relaxed);
    }

    /// Set the Err value of the result.
    pub fn error(&self, e: impl ToString) {
        {
            let mut result = self.state.mtx.lock().unwrap();
            let (_, ok, error) = &mut *result;
            *error = Some(e.to_string());
            *ok = None;
        }
        self.state.result_ready.store(true, Ordering::Relaxed);
    }
}

struct AsyncSuspender {
    awaiting: Arc<(Mutex<Option<Waker>>, AtomicBool)>,
}

impl Future for AsyncSuspender {
    type Output = ();
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut mtx = self.awaiting.0.lock().unwrap();
        if !self.awaiting.1.load(Ordering::Relaxed) {
            Poll::Ready(())
        } else {
            *mtx = Some(cx.waker().clone());
            Poll::Pending
        }
    }
}

impl<S, R> Clone for Handle<S, R>
where
    S: Send,
    R: Send,
{
    fn clone(&self) -> Self {
        Self {
            state: Clone::clone(&self.state),
            awaiting: Clone::clone(&self.awaiting),
            id: self.id,
        }
    }
}

impl<S, R> Drop for Handle<S, R>
where
    S: Send,
    R: Send,
{
    fn drop(&mut self) {
        if thread::panicking() && !self.state.result_ready.load(Ordering::Relaxed) {
            self.error(format!(
                "the flower handle with id: {} error, the thread panicked maybe?",
                self.id
            ));
        }
    }
}

impl<S, R> Debug for Handle<S, R>
where
    S: Debug + Send,
    R: Debug + Send,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("Handle")
            .field("state", &self.state)
            .field("awaiting", &self.awaiting)
            .field("id", &self.id)
            .finish()
    }
}

pub type OIError = Box<dyn Error>;

/// A trait to convert option into `Result`.
pub trait IntoResult<T> {
    /// Convert `Option` into `Result`
    fn catch(self, error_msg: impl ToString) -> Result<T, Box<dyn Error>>;
}

impl<T> IntoResult<T> for Option<T> {
    fn catch(self, error_msg: impl ToString) -> Result<T, Box<dyn Error>> {
        let message: String = error_msg.to_string();
        match self {
            Some(val) => Ok(val),
            None => Err(message.into()),
        }
    }
}