identity_core/common/
key_comparable.rs

1// Copyright 2020-2022 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4/// A trait for comparing types only by a certain key.
5pub trait KeyComparable {
6  /// Key type for comparisons.
7  type Key: PartialEq + ?Sized;
8
9  /// Returns a reference to the key.
10  fn key(&self) -> &Self::Key;
11}
12
13/// Macro to implement the `KeyComparable` trait for primitive types.
14///
15/// This approach is used to avoid conflicts from a blanket implementation where the type is the
16/// key itself.
17macro_rules! impl_key_comparable {
18    ($($t:ty)*) => ($(
19        impl KeyComparable for $t {
20            type Key = $t;
21            #[inline]
22            fn key(&self) -> &Self::Key { self }
23        }
24    )*)
25}
26
27impl_key_comparable! {
28    str bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
29}
30
31impl KeyComparable for &str {
32  type Key = str;
33
34  fn key(&self) -> &Self::Key {
35    self
36  }
37}
38
39impl KeyComparable for String {
40  type Key = str;
41
42  fn key(&self) -> &Self::Key {
43    self
44  }
45}