* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::sync::{Arc, Mutex, OnceLock};
use asset_log::logw;
pub struct Counter {
count: u32,
is_stop: bool,
}
impl Counter {
fn new() -> Self {
Self { count: 0, is_stop: false }
}
pub fn get_instance() -> Arc<Mutex<Counter>> {
static INSTANCE: OnceLock<Arc<Mutex<Counter>>> = OnceLock::new();
INSTANCE.get_or_init(|| {
logw!("Create instance for Counter.");
Arc::new(Mutex::new(Counter::new()))
}).clone()
}
pub fn increase_count(&mut self) {
self.count += 1;
}
pub fn decrease_count(&mut self) {
if self.count > 0 {
self.count -= 1;
}
}
pub fn count(&self) -> u32 {
self.count
}
pub fn is_stop(&self) -> bool {
self.is_stop
}
pub fn stop(&mut self) {
self.is_stop = true
}
}
#[derive(Default)]
pub struct AutoCounter;
impl AutoCounter {
pub fn new() -> Self {
let counter = Counter::get_instance();
counter.lock().unwrap().increase_count();
Self {}
}
}
impl Drop for AutoCounter {
fn drop(&mut self) {
let counter = Counter::get_instance();
counter.lock().unwrap().decrease_count();
}
}