1/*
2 * Copyright (C) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16//! Implementation of task handle.
17
18use fusion_utils_rust::{ FusionErrorCode, FusionResult };
19use ylong_runtime::task::JoinHandle;
20
21/// Representation of task handle.
22pub struct TaskHandle<R> {
23    join_handle: Option<JoinHandle<R>>,
24}
25
26impl<R> From<JoinHandle<R>> for TaskHandle<R> {
27    fn from(value: JoinHandle<R>) -> Self
28    {
29        Self {
30            join_handle: Some(value),
31        }
32    }
33}
34
35impl<R> TaskHandle<R> {
36    /// Cancel this task.
37    pub fn cancel(&mut self)
38    {
39        if let Some(join_handle) = self.join_handle.take() {
40            join_handle.cancel();
41        }
42    }
43
44    /// Get result of this task.
45    pub fn result(&mut self) -> FusionResult<R>
46    {
47        if let Some(join_handle) = self.join_handle.take() {
48            if let Ok(ret) = ylong_runtime::block_on(join_handle) {
49                Ok(ret)
50            } else {
51                Err(FusionErrorCode::Fail)
52            }
53        } else {
54            Err(FusionErrorCode::Fail)
55        }
56    }
57}
58