• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2023 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 pub(crate) mod c_wrapper;
15 pub(crate) mod common_event;
16 pub(crate) mod form_item;
17 use std::collections::HashMap;
18 use std::future::Future;
19 use std::io::Write;
20 use std::sync::Once;
21 use std::time::{Duration, SystemTime, UNIX_EPOCH};
22 
23 pub(crate) use common_event::{
24     subscribe_common_event, CommonEventSubscriber, Want as CommonEventWant,
25 };
26 pub(crate) use ffi::PublishStateChangeEvent;
27 
28 cfg_oh! {
29     pub(crate) mod url_policy;
30     #[cfg(not(test))]
31     pub(crate) use ffi::GetForegroundAbilities;
32 }
33 
34 pub(crate) mod task_event_count;
35 pub(crate) mod task_id_generator;
36 use ylong_runtime::sync::oneshot::Receiver;
37 use ylong_runtime::task::JoinHandle;
38 
39 pub(crate) struct Recv<T> {
40     rx: Receiver<T>,
41 }
42 
43 impl<T> Recv<T> {
new(rx: Receiver<T>) -> Self44     pub(crate) fn new(rx: Receiver<T>) -> Self {
45         Self { rx }
46     }
47 
get(self) -> Option<T>48     pub(crate) fn get(self) -> Option<T> {
49         // Here `self.rx` can never be hung up.
50         ylong_runtime::block_on(self.rx).ok()
51     }
52 }
53 
build_vec<A, B, C>(ptr: *const A, len: usize, func: C) -> Vec<B> where C: Fn(&A) -> B,54 pub(crate) fn build_vec<A, B, C>(ptr: *const A, len: usize, func: C) -> Vec<B>
55 where
56     C: Fn(&A) -> B,
57 {
58     if ptr.is_null() || len == 0 {
59         return Vec::<B>::new();
60     }
61     let slice = unsafe { std::slice::from_raw_parts(ptr, len) };
62     slice.iter().map(func).collect()
63 }
64 
get_current_timestamp() -> u6465 pub(crate) fn get_current_timestamp() -> u64 {
66     match SystemTime::now().duration_since(UNIX_EPOCH) {
67         Ok(n) => n.as_millis() as u64,
68         Err(_) => panic!("SystemTime before UNIX EPOCH!"),
69     }
70 }
71 
get_current_duration() -> Duration72 pub(crate) fn get_current_duration() -> Duration {
73     match SystemTime::now().duration_since(UNIX_EPOCH) {
74         Ok(dur) => dur,
75         Err(_) => panic!("SystemTime before UNIX EPOCH!"),
76     }
77 }
78 
hashmap_to_string(map: &HashMap<String, String>) -> String79 pub(crate) fn hashmap_to_string(map: &HashMap<String, String>) -> String {
80     let mut res = Vec::new();
81     for (n, (k, v)) in map.iter().enumerate() {
82         if n != 0 {
83             let _ = write!(res, "\r\n");
84         }
85         let _ = write!(res, "{k}\t{v}");
86     }
87     unsafe { String::from_utf8_unchecked(res) }
88 }
89 
string_to_hashmap(str: &mut str) -> HashMap<String, String>90 pub(crate) fn string_to_hashmap(str: &mut str) -> HashMap<String, String> {
91     let mut map = HashMap::<String, String>::new();
92     if str.is_empty() {
93         return map;
94     }
95     for item in str.split("\r\n") {
96         let (k, v) = item.split_once('\t').unwrap();
97         map.insert(k.into(), v.into());
98     }
99     map
100 }
101 
split_string(str: &mut str) -> std::str::Split<'_, &str>102 pub(crate) fn split_string(str: &mut str) -> std::str::Split<'_, &str> {
103     let pat: &[_] = &['[', ']'];
104     str.trim_matches(pat).split(", ")
105 }
106 
call_once<F: FnOnce()>(once: &Once, func: F)107 pub(crate) fn call_once<F: FnOnce()>(once: &Once, func: F) {
108     once.call_once(Box::new(func) as Box<dyn FnOnce()>)
109 }
110 
runtime_spawn<F: Future<Output = ()> + Send + Sync + 'static>( fut: F, ) -> JoinHandle<()>111 pub(crate) fn runtime_spawn<F: Future<Output = ()> + Send + Sync + 'static>(
112     fut: F,
113 ) -> JoinHandle<()> {
114     ylong_runtime::spawn(Box::into_pin(
115         Box::new(fut) as Box<dyn Future<Output = ()> + Send + Sync>
116     ))
117 }
118 
119 #[cfg(feature = "oh")]
query_calling_bundle() -> String120 pub(crate) fn query_calling_bundle() -> String {
121     let token_id = ipc::Skeleton::calling_full_token_id();
122     ffi::GetCallingBundle(token_id)
123 }
124 
125 #[cfg(feature = "oh")]
is_system_api() -> bool126 pub(crate) fn is_system_api() -> bool {
127     let token_id = ipc::Skeleton::calling_full_token_id();
128     ffi::IsSystemAPI(token_id)
129 }
130 
131 #[cfg(feature = "oh")]
check_permission(permission: &str) -> bool132 pub(crate) fn check_permission(permission: &str) -> bool {
133     let token_id = ipc::Skeleton::calling_full_token_id();
134     ffi::CheckPermission(token_id, permission)
135 }
136 
137 #[cfg(feature = "oh")]
update_policy(any_tasks: bool) -> i32138 pub(crate) fn update_policy(any_tasks: bool) -> i32 {
139     ffi::UpdatePolicy(any_tasks)
140 }
141 
142 #[allow(unused)]
143 #[cxx::bridge(namespace = "OHOS::Request")]
144 mod ffi {
145 
146     unsafe extern "C++" {
147         include!("request_utils.h");
148 
PublishStateChangeEvent(bundleName: &str, taskId: u32, state: i32, uid: i32) -> bool149         fn PublishStateChangeEvent(bundleName: &str, taskId: u32, state: i32, uid: i32) -> bool;
GetForegroundAbilities(uid: &mut Vec<i32>) -> i32150         fn GetForegroundAbilities(uid: &mut Vec<i32>) -> i32;
GetCallingBundle(token_id: u64) -> String151         fn GetCallingBundle(token_id: u64) -> String;
IsSystemAPI(token_id: u64) -> bool152         fn IsSystemAPI(token_id: u64) -> bool;
CheckPermission(token_id: u64, permission: &str) -> bool153         fn CheckPermission(token_id: u64, permission: &str) -> bool;
UpdatePolicy(any_tasks: bool) -> i32154         fn UpdatePolicy(any_tasks: bool) -> i32;
155     }
156 }
157 
158 #[cfg(feature = "oh")]
159 #[cfg(test)]
160 mod ut_mod {
161     include!("../../tests/ut/utils/ut_mod.rs");
162 }
163