Skip to main content

perspective_viewer/utils/
completion.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
3// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
4// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
5// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
6// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
8// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9// ┃ This file is part of the Perspective library, distributed under the terms ┃
10// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
13use std::future::Future;
14
15use futures::channel::oneshot;
16use perspective_js::utils::*;
17
18pub struct Completion(Option<oneshot::Sender<ApiResult<()>>>);
19
20impl Completion {
21    #[allow(clippy::new_ret_no_self)]
22    pub fn new() -> (Self, oneshot::Receiver<ApiResult<()>>) {
23        let (sender, receiver) = oneshot::channel();
24        (Self(Some(sender)), receiver)
25    }
26
27    /// Resolve this completion with `run`'s result when it settles. The
28    /// caller relinquishes the handle — one run, one resolution.
29    pub fn resolve_after(mut self, run: impl Future<Output = ApiResult<()>> + 'static) {
30        let sender = self.0.take().unwrap();
31        ApiFuture::spawn(async move {
32            let _ = sender.send(run.await);
33            Ok(())
34        });
35    }
36}
37
38impl std::fmt::Debug for Completion {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("Completion").finish()
41    }
42}
43
44impl Drop for Completion {
45    fn drop(&mut self) {
46        if let Some(sender) = self.0.take() {
47            let _ = sender.send(Err(ApiError::new("Cancelled")));
48        }
49    }
50}