Skip to content

Commit 7270b0b

Browse files
authored
Add GetByKey trait and get_by_key_type macro. (#304)
* Add GetByKey trait and get_by_key_type macro. * Renaming. Add docs. * Make clippy happy.
1 parent c1addc7 commit 7270b0b

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

traits/src/get_by_key.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/// A trait for querying a value by a key.
2+
pub trait GetByKey<Key, Value> {
3+
/// Return the value.
4+
fn get(k: &Key) -> Value;
5+
}
6+
7+
/// Create new implementations of the `GetByKey` trait.
8+
///
9+
/// The implementation is typically used like a map or set.
10+
///
11+
/// Example:
12+
/// ```ignore
13+
/// use primitives::CurrencyId;
14+
/// parameter_type_with_key! {
15+
/// pub Rates: |currency_id: CurrencyId| -> u32 {
16+
/// match currency_id {
17+
/// CurrencyId::DOT => 1,
18+
/// CurrencyId::KSM => 2,
19+
/// _ => 3,
20+
/// }
21+
/// }
22+
/// }
23+
/// ```
24+
#[macro_export]
25+
macro_rules! parameter_type_with_key {
26+
(
27+
pub $name:ident: |$k:ident: $key:ty| -> $value:ty $body:block;
28+
) => {
29+
pub struct $name;
30+
impl $crate::get_by_key::GetByKey<$key, $value> for $name {
31+
fn get($k: &$key) -> $value {
32+
$body
33+
}
34+
}
35+
};
36+
}
37+
38+
#[cfg(test)]
39+
mod tests {
40+
use super::*;
41+
42+
parameter_type_with_key! {
43+
pub Test: |k: u32| -> u32 {
44+
match k {
45+
1 => 1,
46+
_ => 2,
47+
}
48+
};
49+
}
50+
51+
#[test]
52+
fn get_by_key_should_work() {
53+
assert_eq!(Test::get(&1), 1);
54+
assert_eq!(Test::get(&2), 2);
55+
assert_eq!(Test::get(&3), 2);
56+
}
57+
}

traits/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,15 @@ pub use currency::{
1616
LockIdentifier, MultiCurrency, MultiCurrencyExtended, MultiLockableCurrency, MultiReservableCurrency, OnReceived,
1717
};
1818
pub use data_provider::{DataFeeder, DataProvider, DataProviderExtended};
19+
pub use get_by_key::GetByKey;
1920
pub use price::{DefaultPriceProvider, PriceProvider};
2021
pub use rewards::RewardHandler;
2122

2223
pub mod arithmetic;
2324
pub mod auction;
2425
pub mod currency;
2526
pub mod data_provider;
27+
pub mod get_by_key;
2628
pub mod price;
2729
pub mod rewards;
2830

0 commit comments

Comments
 (0)