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