gear_common/storage/complicated/counter.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 counter implementation.
20//!
21//! Counter provides API for step-by-step changing of the value.
22//! Could be used to count amount of some parameter.
23
24use crate::storage::ValueStorage;
25use core::marker::PhantomData;
26
27/// Represents logic of managing step-by-step changeable value.
28pub trait Counter {
29 /// Counter stored type.
30 type Value;
31
32 /// Decreases stored value.
33 ///
34 /// Should be safe from overflow.
35 fn decrease();
36
37 /// Returns stored value, if present, or default/starting value.
38 fn get() -> Self::Value;
39
40 /// Increases stored value.
41 ///
42 /// Should be safe from overflow.
43 fn increase();
44
45 /// Resets stored value by setting default/starting value.
46 fn reset();
47}
48
49/// `Counter` implementation based on `ValueStorage`.
50///
51/// Generic parameter `T` presents inner storing type.
52pub struct CounterImpl<T, VS: ValueStorage<Value = T>>(PhantomData<VS>);
53
54/// Crate local macro for repeating `Counter` implementation
55/// over `ValueStorage` with Rust's numeric types.
56macro_rules! impl_counter {
57 ($($t: ty), +) => { $(
58 impl<VS: ValueStorage<Value = $t>> Counter for CounterImpl<$t, VS> {
59 type Value = VS::Value;
60
61 fn decrease() {
62 VS::mutate(|opt_val| {
63 if let Some(val) = opt_val {
64 *val = val.saturating_sub(1);
65 }
66 });
67 }
68
69 fn get() -> Self::Value {
70 VS::get().unwrap_or(0)
71 }
72
73 fn increase() {
74 VS::mutate(|opt_val| {
75 if let Some(val) = opt_val {
76 *val = val.saturating_add(1);
77 } else {
78 *opt_val = Some(1)
79 }
80 });
81 }
82
83 fn reset() {
84 VS::put(0);
85 }
86 }
87 ) + };
88}
89
90// Implementation for unsigned integers.
91impl_counter!(u8, u16, u32, u64, u128);
92
93// Implementation for signed integers.
94impl_counter!(i8, i16, i32, i64, i128);