Skip to main content

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    ($(#[$meta:meta])* $vis:vis const $name:ident: $ty:ty = $key:literal) => {
29        $(#[$meta])*
30        $vis const $name: $crate::settings::Key<$ty> = $crate::settings::Key::new($key);
31    };
32}
33
34/// Type-safe key for settings storage.
35///
36/// Associates a string key name with a value type at compile time,
37/// preventing type mismatches while maintaining ergonomic usage.
38///
39/// Use the [`register_setting_key!`](crate::register_setting_key) macro to create keys.
40///
41/// # Example
42/// ```rust
43/// use bitwarden_state::register_setting_key;
44/// use serde::{Deserialize, Serialize};
45///
46/// #[derive(Serialize, Deserialize)]
47/// struct AppConfig {
48///     theme: String,
49///     auto_save: bool,
50/// }
51///
52/// register_setting_key!(pub const CONFIG: AppConfig = "app_config");
53/// ```
54#[derive(Debug, Clone, Copy)]
55pub struct Key<T> {
56    pub(crate) name: &'static str,
57    _marker: PhantomData<T>,
58}
59
60impl<T> Key<T> {
61    /// Create a new type-safe key with the given storage name.
62    #[doc(hidden)]
63    pub const fn new(name: &'static str) -> Self {
64        Self {
65            name,
66            _marker: PhantomData,
67        }
68    }
69}