Skip to main content

kova_native_core/
id.rs

1//! Identifiers for elements and resources.
2
3use crate::SharedString;
4use std::hash::{Hash, Hasher};
5
6/// A user supplied, stable identity for an element.
7///
8/// Ids are used to preserve element state (scroll offsets, text editing
9/// state) across rebuilds of a reactive region, and to address elements
10/// programmatically (e.g. to focus them).
11#[derive(Clone, Debug, PartialEq, Eq, Hash)]
12pub enum ElementId {
13    Name(SharedString),
14    Integer(u64),
15    /// A name scoped by an index, handy for list items: `("row", 3)`.
16    NamedInteger(SharedString, u64),
17}
18
19impl ElementId {
20    /// A 64-bit hash of the id (stable within a process run).
21    pub fn hash64(&self) -> u64 {
22        let mut h = rustc_hash::FxHasher::default();
23        self.hash(&mut h);
24        h.finish()
25    }
26}
27
28impl From<&'static str> for ElementId {
29    fn from(s: &'static str) -> Self {
30        ElementId::Name(s.into())
31    }
32}
33
34impl From<String> for ElementId {
35    fn from(s: String) -> Self {
36        ElementId::Name(s.into())
37    }
38}
39
40impl From<SharedString> for ElementId {
41    fn from(s: SharedString) -> Self {
42        ElementId::Name(s)
43    }
44}
45
46macro_rules! integer_ids {
47    ($($t:ty),*) => {$(
48        impl From<$t> for ElementId {
49            fn from(v: $t) -> Self {
50                ElementId::Integer(v as u64)
51            }
52        }
53
54        impl From<(&'static str, $t)> for ElementId {
55            fn from((s, i): (&'static str, $t)) -> Self {
56                ElementId::NamedInteger(s.into(), i as u64)
57            }
58        }
59
60        impl From<(SharedString, $t)> for ElementId {
61            fn from((s, i): (SharedString, $t)) -> Self {
62                ElementId::NamedInteger(s, i as u64)
63            }
64        }
65    )*};
66}
67
68// Negative integers wrap; ids only need to be distinct and stable.
69integer_ids!(u8, u16, u32, u64, usize, i32, i64);
70
71/// Defines a process-unique id newtype backed by an atomic counter.
72#[macro_export]
73macro_rules! unique_id {
74    ($(#[$meta:meta])* $vis:vis struct $name:ident;) => {
75        $(#[$meta])*
76        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
77        $vis struct $name(pub u64);
78
79        impl $name {
80            /// Allocates a new, never before used id.
81            pub fn next() -> Self {
82                static COUNTER: ::std::sync::atomic::AtomicU64 = ::std::sync::atomic::AtomicU64::new(1);
83                Self(COUNTER.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed))
84            }
85        }
86    };
87}
88
89unique_id! {
90    /// Identifies a decoded image or rasterizable vector asset.
91    pub struct ImageId;
92}