Skip to main content

lgui_core/core/foundation/
id.rs

1use std::{borrow::Cow, fmt};
2
3#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4pub struct StaticUiId(&'static str);
5
6#[derive(Clone, Debug, PartialEq, Eq, Hash)]
7pub struct UiId(Cow<'static, str>);
8
9impl UiId {
10    pub fn new(value: &'static str) -> Self {
11        Self(Cow::Borrowed(value))
12    }
13
14    pub fn owned(value: impl Into<String>) -> Self {
15        Self(Cow::Owned(value.into()))
16    }
17
18    pub fn from_parts(parts: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
19        let mut value = String::new();
20        for part in parts {
21            if !value.is_empty() {
22                value.push('.');
23            }
24            value.push_str(part.as_ref());
25        }
26        Self::owned(value)
27    }
28
29    pub fn child(&self, segment: impl AsRef<str>) -> Self {
30        Self::from_parts([self.as_str(), segment.as_ref()])
31    }
32
33    pub fn as_str(&self) -> &str {
34        &self.0
35    }
36}
37
38impl From<&'static str> for UiId {
39    fn from(value: &'static str) -> Self {
40        Self::new(value)
41    }
42}
43
44impl From<StaticUiId> for UiId {
45    fn from(value: StaticUiId) -> Self {
46        Self::new(value.0)
47    }
48}
49
50impl fmt::Display for UiId {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        f.write_str(self.as_str())
53    }
54}
55
56#[derive(Clone, Debug, Default, PartialEq, Eq)]
57pub struct UiIdPath {
58    segments: Vec<Cow<'static, str>>,
59}
60
61impl UiIdPath {
62    pub fn new(root: &'static str) -> Self {
63        Self {
64            segments: vec![Cow::Borrowed(root)],
65        }
66    }
67
68    pub fn child(&self, segment: impl Into<Cow<'static, str>>) -> Self {
69        let mut segments = self.segments.clone();
70        segments.push(segment.into());
71        Self { segments }
72    }
73
74    pub fn segments(&self) -> &[Cow<'static, str>] {
75        &self.segments
76    }
77
78    pub fn id(&self, leaf: impl AsRef<str>) -> UiId {
79        let mut parts: Vec<&str> = self
80            .segments
81            .iter()
82            .map(|segment| segment.as_ref())
83            .collect();
84        parts.push(leaf.as_ref());
85        UiId::from_parts(parts)
86    }
87}