1 // Copyright (C) 2024 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 cfg_oh! {
15     use std::sync::atomic::{AtomicU32, Ordering};
16     use std::time::{SystemTime, UNIX_EPOCH};
17     use crate::manage::database::RequestDb;
18 }
19 
20 pub(crate) struct TaskIdGenerator;
21 
22 impl TaskIdGenerator {
23     #[cfg(feature = "oh")]
generate() -> u3224     pub(crate) fn generate() -> u32 {
25         loop {
26             debug!("generate task_id");
27             let task_id = match SystemTime::now().duration_since(UNIX_EPOCH) {
28                 Ok(time) => time.subsec_nanos(),
29                 Err(e) => {
30                     static ID: AtomicU32 = AtomicU32::new(0);
31                     error!("Generate task id from system time failed {:?}", e);
32                     ID.fetch_add(1, Ordering::Relaxed)
33                 }
34             };
35             if !RequestDb::get_instance().contains_task(task_id) {
36                 return task_id;
37             }
38         }
39     }
40     #[cfg(not(feature = "oh"))]
generate() -> u3241     pub(crate) fn generate() -> u32 {
42         rand::random()
43     }
44 }
45