gear_common/storage/complicated/
limiter.rs

1// This file is part of Gear.
2
3// Copyright (C) 2022-2025 Gear Technologies Inc.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! Module for limiter implementation.
20//!
21//! Limiter provides API for continually descending value.
22//! Could be used to prevent (limit) some value from overflow.
23
24use crate::storage::ValueStorage;
25use core::marker::PhantomData;
26
27/// Represents logic of limiting value decreasing.
28pub trait Limiter {
29    /// Limiter stored type.
30    type Value;
31
32    /// Decreases stored value.
33    ///
34    /// Should be safe from overflow.
35    fn decrease(value: Self::Value);
36
37    /// Returns stored value, if present,
38    /// or default/nullable value.
39    fn get() -> Self::Value;
40
41    /// Puts given value into stored, to start from
42    /// new one for future decreasing.
43    fn put(value: Self::Value);
44}
45
46/// `Limiter` implementation based on `ValueStorage`.
47///
48/// Generic parameter `T` represents inner storing type.
49pub struct LimiterImpl<T, VS: ValueStorage<Value = T>>(PhantomData<VS>);
50
51/// Crate local macro for repeating `Limiter` implementation
52/// over `ValueStorage` with Rust's numeric types.
53macro_rules! impl_limiter {
54    ($($t: ty), +) => { $(
55        impl<VS: ValueStorage<Value = $t>> Limiter for LimiterImpl<$t, VS> {
56            type Value = VS::Value;
57
58            fn decrease(value: Self::Value) {
59                VS::mutate(|opt_val| {
60                    if let Some(val) = opt_val {
61                        *val = val.saturating_sub(value);
62                    }
63                });
64            }
65
66            fn get() -> Self::Value {
67                VS::get().unwrap_or(0)
68            }
69
70            fn put(value: Self::Value) {
71                VS::put(value);
72            }
73        }
74    ) + };
75}
76
77// Implementation for unsigned integers.
78impl_limiter!(u8, u16, u32, u64, u128);
79
80// Implementation for signed integers.
81impl_limiter!(i8, i16, i32, i64, i128);