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 } 25 26 impl Counter { new() -> Self27 fn new() -> Self { 28 Self { count: 0 } 29 } 30 31 /// Get the single instance of Counter. get_instance() -> Arc<Mutex<Counter>>32 pub fn get_instance() -> Arc<Mutex<Counter>> { 33 static mut INSTANCE: Option<Arc<Mutex<Counter>>> = None; 34 unsafe { INSTANCE.get_or_insert_with(|| Arc::new(Mutex::new(Counter::new()))).clone() } 35 } 36 37 /// Increase count increase_count(&mut self)38 pub fn increase_count(&mut self) { 39 self.count += 1; 40 } 41 42 /// Decrease count decrease_count(&mut self)43 pub fn decrease_count(&mut self) { 44 if self.count > 0 { 45 self.count -= 1; 46 } 47 } 48 49 /// get count. count(&mut self) -> u3250 pub fn count(&mut self) -> u32 { 51 self.count 52 } 53 } 54 55 /// Auto count asset service use times 56 #[derive(Default)] 57 pub struct AutoCounter; 58 59 impl AutoCounter { 60 /// New auto counter instance and add count new() -> Self61 pub fn new() -> Self { 62 let counter = Counter::get_instance(); 63 counter.lock().unwrap().increase_count(); 64 Self {} 65 } 66 } 67 68 impl Drop for AutoCounter { 69 // Finish use counter. drop(&mut self)70 fn drop(&mut self) { 71 let counter = Counter::get_instance(); 72 counter.lock().unwrap().decrease_count(); 73 } 74 } 75