• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 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 //! This module is used to Asset service counter.
17 
18 /// Manages the count.
19 use std::sync::{Arc, Mutex};
20 
21 /// Count asset service use times
22 pub struct Counter {
23     count: u32,
24     is_stop: bool,
25 }
26 
27 impl Counter {
new() -> Self28     fn new() -> Self {
29         Self { count: 0, is_stop: false }
30     }
31 
32     /// Get the single instance of Counter.
get_instance() -> Arc<Mutex<Counter>>33     pub fn get_instance() -> Arc<Mutex<Counter>> {
34         static mut INSTANCE: Option<Arc<Mutex<Counter>>> = None;
35         unsafe { INSTANCE.get_or_insert_with(|| Arc::new(Mutex::new(Counter::new()))).clone() }
36     }
37 
38     /// Increase count
increase_count(&mut self)39     pub fn increase_count(&mut self) {
40         self.count += 1;
41     }
42 
43     /// Decrease count
decrease_count(&mut self)44     pub fn decrease_count(&mut self) {
45         if self.count > 0 {
46             self.count -= 1;
47         }
48     }
49 
50     /// get count.
count(&self) -> u3251     pub fn count(&self) -> u32 {
52         self.count
53     }
54 
55     /// get is_stop.
is_stop(&self) -> bool56     pub fn is_stop(&self) -> bool {
57         self.is_stop
58     }
59 
60     /// set service stop
stop(&mut self)61     pub fn stop(&mut self) {
62         self.is_stop = true
63     }
64 }
65 
66 /// Auto count asset service use times
67 #[derive(Default)]
68 pub struct AutoCounter;
69 
70 impl AutoCounter {
71     /// New auto counter instance and add count
new() -> Self72     pub fn new() -> Self {
73         let counter = Counter::get_instance();
74         counter.lock().unwrap().increase_count();
75         Self {}
76     }
77 }
78 
79 impl Drop for AutoCounter {
80     // Finish use counter.
drop(&mut self)81     fn drop(&mut self) {
82         let counter = Counter::get_instance();
83         counter.lock().unwrap().decrease_count();
84     }
85 }
86