iced_core/widget/
id.rs

1use std::borrow;
2use std::sync::atomic::{self, AtomicUsize};
3
4static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
5
6/// The identifier of a generic widget.
7#[derive(Debug, Clone, PartialEq, Eq, Hash)]
8pub struct Id(Internal);
9
10impl Id {
11    /// Creates a custom [`Id`].
12    pub fn new(id: impl Into<borrow::Cow<'static, str>>) -> Self {
13        Self(Internal::Custom(id.into()))
14    }
15
16    /// Creates a unique [`Id`].
17    ///
18    /// This function produces a different [`Id`] every time it is called.
19    pub fn unique() -> Self {
20        let id = NEXT_ID.fetch_add(1, atomic::Ordering::Relaxed);
21
22        Self(Internal::Unique(id))
23    }
24}
25
26#[derive(Debug, Clone, PartialEq, Eq, Hash)]
27enum Internal {
28    Unique(usize),
29    Custom(borrow::Cow<'static, str>),
30}
31
32#[cfg(test)]
33mod tests {
34    use super::Id;
35
36    #[test]
37    fn unique_generates_different_ids() {
38        let a = Id::unique();
39        let b = Id::unique();
40
41        assert_ne!(a, b);
42    }
43}