Skip to main content

gear_common/storage/primitives/
callback.rs

1// Copyright (C) Gear Technologies Inc.
2// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
3
4//! Module for callback primitives.
5//!
6//! Callbacks represent some additional logic which
7//! should be done over the argument on some conditions.
8
9/// Represents callback action for cases `(&T) -> R`,
10/// where `R` is `()` by default.
11pub trait Callback<T, R = ()> {
12    /// Triggers the callback's logic.
13    fn call(arg: &T) -> R;
14}
15
16// Blank `Callback<T, ()>` implementation
17// for skipping callback type in parent traits.
18impl<T> Callback<T> for () {
19    fn call(_: &T) {}
20}
21
22/// Represents callback action for cases
23/// without input and output.
24pub trait EmptyCallback {
25    /// Triggers the callback's logic.
26    fn call();
27}
28
29// Blank `EmptyCallback` implementation
30// for skipping callback type in parent traits.
31impl EmptyCallback for () {
32    fn call() {}
33}
34
35/// Represents callback action for cases `(&T) -> Result<R, E>`,
36/// where `R` is `()` by default and `E` is associated type `Error`.
37pub trait FallibleCallback<T, R = ()> {
38    /// Returning error in callback's `Err` case.
39    type Error;
40
41    /// Triggers the callback's logic.
42    fn call(arg: &T) -> Result<R, Self::Error>;
43}
44
45/// Represents callback action for cases
46/// without input for getting some data.
47pub trait GetCallback<T> {
48    /// Returns value by callback's logic.
49    fn call() -> T;
50}
51
52// Blank `GetCallback` implementation
53// for returning default values.
54impl<T: Default> GetCallback<T> for () {
55    fn call() -> T {
56        Default::default()
57    }
58}
59
60/// Represents transposing callback
61/// for mutating values.
62pub trait TransposeCallback<T, R> {
63    /// Returns value by callback's logic.
64    fn call(arg: T) -> R;
65}
66
67// Blank `TransposeCallback` implementation
68// for returning value itself.
69impl<T> TransposeCallback<T, T> for () {
70    fn call(arg: T) -> T {
71        arg
72    }
73}