gear_common/storage/primitives/callback.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 callback primitives.
20//!
21//! Callbacks represent some additional logic which
22//! should be done over the argument on some conditions.
23
24/// Represents callback action for cases `(&T) -> R`,
25/// where `R` is `()` by default.
26pub trait Callback<T, R = ()> {
27 /// Triggers the callback's logic.
28 fn call(arg: &T) -> R;
29}
30
31// Blank `Callback<T, ()>` implementation
32// for skipping callback type in parent traits.
33impl<T> Callback<T> for () {
34 fn call(_: &T) {}
35}
36
37/// Represents callback action for cases
38/// without input and output.
39pub trait EmptyCallback {
40 /// Triggers the callback's logic.
41 fn call();
42}
43
44// Blank `EmptyCallback` implementation
45// for skipping callback type in parent traits.
46impl EmptyCallback for () {
47 fn call() {}
48}
49
50/// Represents callback action for cases `(&T) -> Result<R, E>`,
51/// where `R` is `()` by default and `E` is associated type `Error`.
52pub trait FallibleCallback<T, R = ()> {
53 /// Returning error in callback's `Err` case.
54 type Error;
55
56 /// Triggers the callback's logic.
57 fn call(arg: &T) -> Result<R, Self::Error>;
58}
59
60/// Represents callback action for cases
61/// without input for getting some data.
62pub trait GetCallback<T> {
63 /// Returns value by callback's logic.
64 fn call() -> T;
65}
66
67// Blank `GetCallback` implementation
68// for returning default values.
69impl<T: Default> GetCallback<T> for () {
70 fn call() -> T {
71 Default::default()
72 }
73}
74
75/// Represents transposing callback
76/// for mutating values.
77pub trait TransposeCallback<T, R> {
78 /// Returns value by callback's logic.
79 fn call(arg: T) -> R;
80}
81
82// Blank `TransposeCallback` implementation
83// for returning value itself.
84impl<T> TransposeCallback<T, T> for () {
85 fn call(arg: T) -> T {
86 arg
87 }
88}