尹耀德asset arc change
495e6d32创建于 4月7日历史提交
/*
 * 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.
 */

//! This module is used to Asset service counter.

/// Manages the count.
use std::sync::{Arc, Mutex, OnceLock};

use asset_log::logw;

/// Count asset service use times
pub struct Counter {
    count: u32,
    is_stop: bool,
}

impl Counter {
    fn new() -> Self {
        Self { count: 0, is_stop: false }
    }

    /// Get the single instance of Counter.
    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()
    }

    /// Increase count
    pub fn increase_count(&mut self) {
        self.count += 1;
    }

    /// Decrease count
    pub fn decrease_count(&mut self) {
        if self.count > 0 {
            self.count -= 1;
        }
    }

    /// get count.
    pub fn count(&self) -> u32 {
        self.count
    }

    /// get is_stop.
    pub fn is_stop(&self) -> bool {
        self.is_stop
    }

    /// set service stop
    pub fn stop(&mut self) {
        self.is_stop = true
    }
}

/// Auto count asset service use times
#[derive(Default)]
pub struct AutoCounter;

impl AutoCounter {
    /// New auto counter instance and add count
    pub fn new() -> Self {
        let counter = Counter::get_instance();
        counter.lock().unwrap().increase_count();
        Self {}
    }
}

impl Drop for AutoCounter {
    // Finish use counter.
    fn drop(&mut self) {
        let counter = Counter::get_instance();
        counter.lock().unwrap().decrease_count();
    }
}