Skip to main content

waft_foundation/
key.rs

1//! Flutter counterpart: `foundation/key.dart`.
2
3use std::any::{Any, TypeId};
4use std::fmt::{self, Debug};
5use std::hash::{Hash, Hasher};
6use std::sync::atomic::{AtomicU64, Ordering};
7
8/// A [`Key`] is an identifier for widgets, elements and semantics nodes.
9///
10/// A new widget will only be used to update an existing element if its key is
11/// the same as the key of the current widget associated with the element.
12///
13/// Typically, if no key is provided, the default value is `None`, meaning the
14/// widget is considered unkeyed. In this case, Flutter matches widgets based
15/// on their type and position in the tree during rebuilds.
16///
17/// Keys must be unique amongst the elements with the same parent.
18///
19/// Implementors of [`Key`] should either implement [`LocalKey`] or `GlobalKey`.
20///
21/// A common mistake is to rebuild the widget tree in such a way that Flutter
22/// attaches the incorrect state object to an unkeyed stateful widget. This can
23/// often be solved by using an appropriate [`Key`] on the stateful widget.
24///
25/// See [`ValueKey`], which explains how that type can be used as a solution to a
26/// common case of this problem.
27pub trait Key: Any + Debug {
28    /// Flutter's `operator ==`. Must return false when `other` is a different
29    /// concrete key type, even if the two carry the same value.
30    fn eq_key(&self, other: &dyn Key) -> bool;
31
32    /// Flutter's `hashCode`. Must mix in the concrete key type so that two key
33    /// types carrying the same value do not collide.
34    fn hash_key(&self, state: &mut dyn Hasher);
35}
36
37impl PartialEq for dyn Key {
38    fn eq(&self, other: &dyn Key) -> bool {
39        self.eq_key(other)
40    }
41}
42
43impl Eq for dyn Key {}
44
45impl Hash for dyn Key {
46    fn hash<H: Hasher>(&self, state: &mut H) {
47        self.hash_key(state);
48    }
49}
50
51impl dyn Key {
52    /// Construct a [`ValueKey<String>`] with the given string.
53    ///
54    /// This is the simplest way to create keys.
55    ///
56    /// Dart: `const factory Key(String value) = ValueKey<String>`.
57    #[expect(
58        clippy::new_ret_no_self,
59        reason = "Dart's Key factory returns ValueKey<String>, not the trait object"
60    )]
61    pub fn new(value: impl Into<String>) -> ValueKey<String> {
62        ValueKey::new(value.into())
63    }
64}
65
66/// A key that is not a `GlobalKey`.
67///
68/// Keys must be unique amongst the elements with the same parent. By
69/// contrast, `GlobalKey`s must be unique across the entire app.
70pub trait LocalKey: Key {}
71
72/// A key that is only equal to itself.
73///
74/// This cannot be created with a const constructor because that implies that
75/// all instantiated keys would be the same instance and therefore not be unique.
76#[derive(Clone, Copy, PartialEq, Eq, Hash)]
77pub struct UniqueKey {
78    id: u64,
79}
80
81impl UniqueKey {
82    /// Creates a key that is equal only to itself.
83    #[expect(
84        clippy::new_without_default,
85        reason = "each call creates a distinct key; Default would suggest a neutral value"
86    )]
87    pub fn new() -> UniqueKey {
88        static NEXT: AtomicU64 = AtomicU64::new(0);
89        UniqueKey {
90            id: NEXT.fetch_add(1, Ordering::Relaxed),
91        }
92    }
93}
94
95impl Key for UniqueKey {
96    fn eq_key(&self, other: &dyn Key) -> bool {
97        (other as &dyn Any)
98            .downcast_ref::<UniqueKey>()
99            .is_some_and(|other| other.id == self.id)
100    }
101
102    fn hash_key(&self, mut state: &mut dyn Hasher) {
103        TypeId::of::<UniqueKey>().hash(&mut state);
104        self.id.hash(&mut state);
105    }
106}
107
108impl LocalKey for UniqueKey {}
109
110impl Debug for UniqueKey {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        write!(f, "[#{:05x}]", self.id & 0xF_FFFF)
113    }
114}
115
116/// A key that uses a value of a particular type to identify itself.
117///
118/// A [`ValueKey`] is equal to another [`ValueKey`] if, and only if, their values
119/// are equal.
120///
121/// This type can be wrapped to create value keys that will not be equal to
122/// other value keys that happen to use the same value. If the wrapper is
123/// private, this results in a value key type that cannot collide with keys from
124/// other sources. This is useful when keys are used as fallbacks in the same
125/// scope as keys supplied from another widget.
126///
127/// When building widgets from a collection of data, especially when that
128/// collection can change over time (e.g., items being inserted, removed, or
129/// reordered), keys are used to preserve the association between a widget and
130/// the underlying data.
131///
132/// Without keys, the framework may have no way to distinguish between a change
133/// in the data of an existing widget and a structural change in the list. As a
134/// result, widgets may be incorrectly updated, and state held by stateful
135/// widgets can be reused for a different piece of data.
136///
137/// Assigning a key ties the widget subtree to a specific piece of data,
138/// allowing the framework to correctly match old and new widgets and preserve
139/// state as expected.
140///
141/// In such cases, a [`ValueKey`] is typically appropriate, using a value that is
142/// stable and unique for each item, such as an identifier from the data model.
143#[derive(Clone, PartialEq, Eq, Hash)]
144pub struct ValueKey<T> {
145    /// The value to which this key delegates its equality.
146    pub value: T,
147}
148
149impl<T> ValueKey<T> {
150    /// Creates a key that delegates its equality to the given value.
151    pub const fn new(value: T) -> ValueKey<T> {
152        ValueKey { value }
153    }
154}
155
156impl<T: PartialEq + Hash + Debug + 'static> Key for ValueKey<T> {
157    fn eq_key(&self, other: &dyn Key) -> bool {
158        (other as &dyn Any)
159            .downcast_ref::<ValueKey<T>>()
160            .is_some_and(|other| other.value == self.value)
161    }
162
163    fn hash_key(&self, mut state: &mut dyn Hasher) {
164        TypeId::of::<ValueKey<T>>().hash(&mut state);
165        self.value.hash(&mut state);
166    }
167}
168
169impl<T: PartialEq + Hash + Debug + 'static> LocalKey for ValueKey<T> {}
170
171/// Dart's `ValueKey.toString`: `[<'title'>]` for a string, `[<3>]` for anything else.
172impl<T: Debug + 'static> Debug for ValueKey<T> {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        let value = &self.value as &dyn Any;
175        if let Some(text) = value.downcast_ref::<String>() {
176            write!(f, "[<'{text}'>]")
177        } else if let Some(text) = value.downcast_ref::<&str>() {
178            write!(f, "[<'{text}'>]")
179        } else {
180            write!(f, "[<{:?}>]", self.value)
181        }
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use std::collections::HashMap;
188    use std::sync::Arc;
189
190    use super::*;
191
192    #[derive(Debug, PartialEq, Eq, Hash)]
193    struct SaltedKey(ValueKey<u32>);
194
195    impl Key for SaltedKey {
196        fn eq_key(&self, other: &dyn Key) -> bool {
197            (other as &dyn Any)
198                .downcast_ref::<SaltedKey>()
199                .is_some_and(|other| other.0 == self.0)
200        }
201
202        fn hash_key(&self, mut state: &mut dyn Hasher) {
203            TypeId::of::<SaltedKey>().hash(&mut state);
204            self.0.hash(&mut state);
205        }
206    }
207
208    impl LocalKey for SaltedKey {}
209
210    fn erase(key: impl Key) -> Arc<dyn Key> {
211        Arc::new(key)
212    }
213
214    #[test]
215    fn value_keys_are_equal_when_their_values_are() {
216        assert_eq!(&*erase(ValueKey::new(3)), &*erase(ValueKey::new(3)));
217        assert_ne!(&*erase(ValueKey::new(3)), &*erase(ValueKey::new(4)));
218        assert_eq!(
219            &*erase(ValueKey::new("a".to_owned())),
220            &*erase(ValueKey::new("a".to_owned()))
221        );
222    }
223
224    #[test]
225    fn value_keys_of_different_types_are_never_equal() {
226        assert_ne!(&*erase(ValueKey::new(3u32)), &*erase(ValueKey::new(3u64)));
227        assert_ne!(
228            &*erase(ValueKey::new(3u32)),
229            &*erase(SaltedKey(ValueKey::new(3)))
230        );
231    }
232
233    #[test]
234    fn unique_keys_are_equal_only_to_themselves() {
235        let key = UniqueKey::new();
236        assert_eq!(&*erase(key), &*erase(key));
237        assert_ne!(&*erase(UniqueKey::new()), &*erase(UniqueKey::new()));
238    }
239
240    #[test]
241    fn keys_of_different_types_share_one_map() {
242        let mut elements: HashMap<Arc<dyn Key>, &str> = HashMap::new();
243        elements.insert(erase(ValueKey::new(3u32)), "value");
244        elements.insert(erase(SaltedKey(ValueKey::new(3))), "salted");
245
246        assert_eq!(elements.len(), 2);
247        assert_eq!(elements.get(&erase(ValueKey::new(3u32))), Some(&"value"));
248        assert_eq!(
249            elements.get(&erase(SaltedKey(ValueKey::new(3)))),
250            Some(&"salted")
251        );
252    }
253
254    #[test]
255    fn debug_matches_flutter_to_string() {
256        assert_eq!(format!("{:?}", ValueKey::new(3)), "[<3>]");
257        assert_eq!(format!("{:?}", ValueKey::new("a")), "[<'a'>]");
258        assert_eq!(format!("{:?}", ValueKey::new("a".to_string())), "[<'a'>]");
259        assert_eq!(format!("{:?}", UniqueKey { id: 0x1_2345 }), "[#12345]");
260        assert_eq!(format!("{:?}", UniqueKey { id: 0x7 }), "[#00007]");
261    }
262
263    #[test]
264    fn dyn_key_new_is_a_string_value_key() {
265        assert_eq!(
266            &*erase(<dyn Key>::new("x")),
267            &*erase(ValueKey::new("x".to_owned()))
268        );
269    }
270}