bitwarden_state/settings/
key.rs

1//! Type-safe keys for settings storage.
2
3use std::marker::PhantomData;
4
5/// Register a type-safe settings key.
6///
7/// This macro is the primary way to create settings keys. It associates
8/// a string key name with a value type at compile time.
9///
10/// **Important:** The key name must be globally unique across the entire application.
11/// Using the same key name for different settings will cause conflicts.
12///
13/// # Example
14/// ```rust
15/// use bitwarden_state::register_setting_key;
16/// use serde::{Deserialize, Serialize};
17///
18/// #[derive(Serialize, Deserialize)]
19/// struct AppConfig {
20///     theme: String,
21///     auto_save: bool,
22/// }
23///
24/// register_setting_key!(pub const CONFIG: AppConfig = "app_config");
25/// ```
26#[macro_export]
27macro_rules! register_setting_key {
28    ($vis:vis const $name:ident: $ty:ty = $key:literal) => {
29        $vis const $name: $crate::settings::Key<$ty> = $crate::settings::Key::new($key);
30    };
31}
32
33/// Type-safe key for settings storage.
34///
35/// Associates a string key name with a value type at compile time,
36/// preventing type mismatches while maintaining ergonomic usage.
37///
38/// Use the [`register_setting_key!`](crate::register_setting_key) macro to create keys.
39///
40/// # Example
41/// ```rust
42/// use bitwarden_state::register_setting_key;
43/// use serde::{Deserialize, Serialize};
44///
45/// #[derive(Serialize, Deserialize)]
46/// struct AppConfig {
47///     theme: String,
48///     auto_save: bool,
49/// }
50///
51/// register_setting_key!(pub const CONFIG: AppConfig = "app_config");
52/// ```
53#[derive(Debug, Clone, Copy)]
54pub struct Key<T> {
55    pub(crate) name: &'static str,
56    _marker: PhantomData<T>,
57}
58
59impl<T> Key<T> {
60    /// Create a new type-safe key with the given storage name.
61    #[doc(hidden)]
62    pub const fn new(name: &'static str) -> Self {
63        Self {
64            name,
65            _marker: PhantomData,
66        }
67    }
68}