Skip to main content

lite_strtab/types/
string_id.rs

1//! Typed string handles used to query a [`crate::StringTable`].
2//!
3//! [`StringId`] is returned by [`crate::StringTableBuilder::try_push`] and passed to
4//! lookup APIs such as [`crate::StringTable::get`]. It wraps a
5//! [`crate::StringIndex`] integer so ID storage can be tuned without changing
6//! call sites.
7
8use super::StringIndex;
9use core::fmt;
10
11/// Identifier for one string in a [`crate::StringTable`].
12///
13/// `I` is the backing integer type (default [`u16`]) and must implement
14/// [`crate::StringIndex`]. It limits how many strings a single table can hold,
15/// and it is what you store in your own structs to later refer to a string.
16#[repr(transparent)]
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
18pub struct StringId<I = u16>(I);
19
20impl<I> StringId<I> {
21    /// Creates a new ID from a raw value.
22    #[inline]
23    pub const fn new(raw: I) -> Self {
24        Self(raw)
25    }
26
27    /// Returns the raw index value.
28    #[inline]
29    pub fn into_raw(self) -> I {
30        self.0
31    }
32}
33
34impl<I: StringIndex> StringId<I> {
35    /// Returns the value as [`usize`].
36    #[inline]
37    pub fn into_usize(self) -> usize {
38        self.0.to_usize()
39    }
40}
41
42impl StringId<u32> {
43    /// Returns the raw [`u32`] value.
44    #[inline]
45    pub const fn into_u32(self) -> u32 {
46        self.0
47    }
48}
49
50impl<I> From<I> for StringId<I> {
51    #[inline]
52    fn from(value: I) -> Self {
53        Self(value)
54    }
55}
56
57/// Macro pattern:
58/// - `$($ty:ty),+` - One or more comma-separated types
59/// - `$(,)?` - Optional trailing comma
60/// - `$( ... )+` wrapper repeats the inner block for each type
61macro_rules! impl_raw_from_string_id {
62    ($($ty:ty),+ $(,)?) => {
63        $(
64            impl From<StringId<$ty>> for $ty {
65                #[inline]
66                fn from(value: StringId<$ty>) -> Self {
67                    value.0
68                }
69            }
70        )+
71    };
72}
73
74impl_raw_from_string_id!(u8, u16, u32, u64, usize);
75
76impl<I: fmt::Display> fmt::Display for StringId<I> {
77    #[inline]
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        self.0.fmt(f)
80    }
81}