Skip to main content

nami_core/
id.rs

1//! Item identity: the [`Identifiable`] trait and its wrappers.
2//!
3//! Ported from `waterui-core` (`core/src/foundation/id.rs`) so that `WaterUI`
4//! can re-export these items from `nami` instead of defining its own. The
5//! only difference is that `Identifiable::Id` needs `Ord + Clone` but not
6//! `Hash`: collections align ids by ordering, so no hasher is involved.
7//!
8//! - [`Identifiable`]: a type that knows its own id, such as a record with a
9//!   key field.
10//! - [`SelfId`]: a value that is its own id, such as a tag `String`.
11//! - [`UseId`]: a value whose id is computed by a function.
12//! - [`IdentifiableExt`]: `.self_id()` / `.use_id(..)` shorthands.
13
14use core::ops::Deref;
15
16/// Defines an interface for types that can be uniquely identified.
17///
18/// Implementors provide a specific id type and a way to retrieve the id from
19/// an instance. The id should come from the data (a record's key field), not
20/// from its position, so that it survives reordering, whole-list
21/// replacement, persistence and sync.
22///
23/// ```rust
24/// use nami_core::Identifiable;
25///
26/// struct Todo {
27///     id: u32,
28///     title: String,
29/// }
30///
31/// impl Identifiable for Todo {
32///     type Id = u32;
33///
34///     fn id(&self) -> u32 {
35///         self.id
36///     }
37/// }
38/// ```
39#[diagnostic::on_unimplemented(
40    message = "`{Self}` has no stable identity",
41    label = "expected a type implementing `Identifiable`",
42    note = "collections such as `nami::collection::List` diff items by id, so each item needs `Identifiable`: implement it for your type, or, for a type you do not own, wrap the value with `SelfId::new(..)` / `.self_id()` (the value is its own id) or `UseId::new(..)` / `.use_id(..)`"
43)]
44pub trait Identifiable {
45    /// The type of id to use. `Ord` is all alignment needs.
46    type Id: Ord + Clone;
47
48    /// Retrieves the unique identifier for this instance.
49    fn id(&self) -> Self::Id;
50}
51
52/// A wrapper that provides identity to a value through a function.
53///
54/// This allows attaching identity behavior to any type by providing a
55/// function to extract an id from the wrapped value.
56#[derive(Debug, Clone, Copy)]
57pub struct UseId<T, F> {
58    /// The wrapped value.
59    value: T,
60    /// Function to extract an id from the value.
61    f: F,
62}
63
64impl<T, F> UseId<T, F> {
65    /// Creates a new [`UseId`] instance wrapping the given value and function.
66    pub const fn new(value: T, f: F) -> Self {
67        Self { value, f }
68    }
69
70    /// Consumes the wrapper and returns the inner value.
71    pub fn into_inner(self) -> T {
72        self.value
73    }
74}
75
76impl<T, F> Deref for UseId<T, F> {
77    type Target = T;
78
79    fn deref(&self) -> &Self::Target {
80        &self.value
81    }
82}
83
84impl<T: PartialEq, F> PartialEq for UseId<T, F> {
85    /// Compares the wrapped values; the id function is not compared.
86    fn eq(&self, other: &Self) -> bool {
87        self.value == other.value
88    }
89}
90
91impl<T, F, Id> Identifiable for UseId<T, F>
92where
93    F: Fn(&T) -> Id,
94    Id: Ord + Clone,
95{
96    type Id = Id;
97
98    /// Applies the stored function to the wrapped value to generate an id.
99    fn id(&self) -> Self::Id {
100        (self.f)(&self.value)
101    }
102}
103
104/// A wrapper that uses the value itself as its own identifier.
105///
106/// This is useful for types that are already suitable as identifiers, such
107/// as a list of tag strings: `List<SelfId<String>>`. Equal values are the
108/// same item.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
110pub struct SelfId<T>(T);
111
112impl<T> SelfId<T> {
113    /// Creates a new [`SelfId`] instance wrapping the given value.
114    pub const fn new(value: T) -> Self {
115        Self(value)
116    }
117
118    /// Consumes the wrapper and returns the inner value.
119    pub fn into_inner(self) -> T {
120        self.0
121    }
122}
123
124impl<T: Ord + Clone> Identifiable for SelfId<T> {
125    type Id = T;
126
127    /// Returns a clone of the wrapped value as the identifier.
128    fn id(&self) -> Self::Id {
129        self.0.clone()
130    }
131}
132
133impl<T> Deref for SelfId<T> {
134    type Target = T;
135
136    fn deref(&self) -> &Self::Target {
137        &self.0
138    }
139}
140
141/// Extension trait that provides convenient methods for making types
142/// identifiable.
143pub trait IdentifiableExt: Sized {
144    /// Wraps the value in a [`UseId`] with the provided identification function.
145    fn use_id<F, Id>(self, f: F) -> UseId<Self, F>
146    where
147        F: Fn(&Self) -> Id,
148        Id: Ord + Clone,
149    {
150        UseId { value: self, f }
151    }
152
153    /// Wraps the value in a [`SelfId`], making the value serve as its own
154    /// identifier.
155    fn self_id(self) -> SelfId<Self> {
156        SelfId(self)
157    }
158}
159
160impl<T> IdentifiableExt for T {}