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 new [`Id`] from a static `str`.
12    pub const fn new(id: &'static str) -> Self {
13        Self(Internal::Custom(borrow::Cow::Borrowed(id)))
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
26impl From<&'static str> for Id {
27    fn from(value: &'static str) -> Self {
28        Self::new(value)
29    }
30}
31
32impl From<String> for Id {
33    fn from(value: String) -> Self {
34        Self(Internal::Custom(borrow::Cow::Owned(value)))
35    }
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, Hash)]
39enum Internal {
40    Unique(usize),
41    Custom(borrow::Cow<'static, str>),
42}
43
44#[cfg(test)]
45mod tests {
46    use super::Id;
47
48    #[test]
49    fn unique_generates_different_ids() {
50        let a = Id::unique();
51        let b = Id::unique();
52
53        assert_ne!(a, b);
54    }
55}