dioxus_sdk_storage/client_storage/
memory.rs

1use std::any::Any;
2use std::cell::RefCell;
3use std::collections::HashMap;
4use std::ops::{Deref, DerefMut};
5use std::rc::Rc;
6use std::sync::Arc;
7
8use dioxus::core::{consume_context_from_scope, provide_root_context};
9
10use crate::StorageBacking;
11
12#[derive(Clone)]
13pub struct SessionStorage;
14
15impl StorageBacking for SessionStorage {
16    type Key = String;
17
18    fn set<T: Clone + 'static>(key: String, value: &T) {
19        let session = SessionStore::get_current_session();
20        session.borrow_mut().insert(key, Arc::new(value.clone()));
21    }
22
23    fn get<T: Clone + 'static>(key: &String) -> Option<T> {
24        let session = SessionStore::get_current_session();
25        let read_binding = session.borrow();
26        let value_any = read_binding.get(key)?;
27        value_any.downcast_ref::<T>().cloned()
28    }
29}
30
31/// An in-memory session store that is tied to the current Dioxus root context.
32#[derive(Clone)]
33struct SessionStore {
34    /// The underlying map of session data.
35    map: Rc<RefCell<HashMap<String, Arc<dyn Any>>>>,
36}
37
38impl SessionStore {
39    fn new() -> Self {
40        Self {
41            map: Rc::new(RefCell::new(HashMap::<String, Arc<dyn Any>>::new())),
42        }
43    }
44
45    /// Get the current session store from the root context, or create a new one if it doesn't exist.
46    fn get_current_session() -> Self {
47        consume_context_from_scope::<Self>(dioxus::prelude::ScopeId::ROOT).map_or_else(
48            || {
49                let session = Self::new();
50                provide_root_context(session.clone());
51                session
52            },
53            |s| s,
54        )
55    }
56}
57
58impl Deref for SessionStore {
59    type Target = Rc<RefCell<HashMap<String, Arc<dyn Any>>>>;
60
61    fn deref(&self) -> &Self::Target {
62        &self.map
63    }
64}
65
66impl DerefMut for SessionStore {
67    fn deref_mut(&mut self) -> &mut Self::Target {
68        &mut self.map
69    }
70}