gear_common/storage/primitives/key.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 map's key generation primitives.
20//!
21//! Key generator primitives might be used to prevent
22//! manual specifying of the key for cases,
23//! when data stored in map.
24
25use crate::Origin;
26use core::marker::PhantomData;
27use gear_core::{
28 ids::{ActorId, MessageId},
29 message::{StoredDispatch, UserStoredMessage},
30};
31
32/// Represents logic of providing key as specified
33/// (associated) type for given as specified
34/// (associated) type value by reference.
35pub trait KeyFor {
36 /// Generated key type.
37 type Key;
38 /// Value over which key should be generated type.
39 type Value;
40
41 /// Generates key for given by reference Value.
42 fn key_for(value: &Self::Value) -> Self::Key;
43}
44
45/// Key generator for `gear`'s mailbox implementation.
46pub struct MailboxKeyGen<T>(PhantomData<T>);
47
48// `MailboxKeyGen` stores `StoredMessage` under it's
49// `MessageId` id parameter and the generic `T: Origin`
50// (represented with `Substrate`'s 32-byte `AccountId`)
51// destination parameter.
52impl<T: Origin> KeyFor for MailboxKeyGen<T> {
53 type Key = (T, MessageId);
54 type Value = UserStoredMessage;
55
56 fn key_for(value: &Self::Value) -> Self::Key {
57 (value.destination().cast(), value.id())
58 }
59}
60
61/// Key generator for `gear`'s message queue implementation.
62pub struct QueueKeyGen;
63
64// `QueueKeyGen` stores `StoredDispatch` under
65// it's `MessageId` id parameter.
66impl KeyFor for QueueKeyGen {
67 type Key = MessageId;
68 type Value = StoredDispatch;
69
70 fn key_for(value: &Self::Value) -> Self::Key {
71 value.id()
72 }
73}
74
75/// Key generator for `gear`'s waitlist implementation.
76pub struct WaitlistKeyGen;
77
78// `WaitlistKeyGen` stores `StoredDispatch` under it's destination
79// `ActorId` and `MessageId` id parameters.
80impl KeyFor for WaitlistKeyGen {
81 type Key = (ActorId, MessageId);
82 type Value = StoredDispatch;
83
84 fn key_for(value: &Self::Value) -> Self::Key {
85 (value.destination(), value.id())
86 }
87}