Skip to main content

teloxide/dispatching/dialogue/storage/
in_mem_storage.rs

1use super::{DialogueKey, Storage, StorageKeys};
2use futures::future::BoxFuture;
3use std::{
4    collections::{HashMap, HashSet},
5    convert::Infallible,
6    sync::Arc,
7};
8use thiserror::Error;
9use tokio::sync::Mutex;
10
11/// An error returned from [`InMemStorage`].
12#[derive(Debug, Error)]
13pub enum InMemStorageError {
14    /// Returned from [`InMemStorage::remove_dialogue`].
15    #[error("row not found")]
16    DialogueNotFound,
17}
18
19/// A dialogue storage based on [`std::collections::HashMap`].
20///
21/// ## Note
22/// All your dialogues will be lost after you restart your bot. If you need to
23/// store them somewhere on a drive, you should use e.g.
24/// [`super::SqliteStorage`] or implement your own.
25#[derive(Debug)]
26pub struct InMemStorage<D> {
27    map: Mutex<HashMap<DialogueKey, D>>,
28}
29
30impl<S> InMemStorage<S> {
31    #[must_use]
32    pub fn new() -> Arc<Self> {
33        Arc::new(Self { map: Mutex::new(HashMap::new()) })
34    }
35}
36
37impl<D> Storage<D> for InMemStorage<D>
38where
39    D: Clone,
40    D: Send + 'static,
41{
42    type Error = InMemStorageError;
43
44    fn remove_dialogue(
45        self: Arc<Self>,
46        key: DialogueKey,
47    ) -> BoxFuture<'static, Result<(), Self::Error>>
48    where
49        D: Send + 'static,
50    {
51        Box::pin(async move {
52            self.map
53                .lock()
54                .await
55                .remove(&key)
56                .map_or(Err(InMemStorageError::DialogueNotFound), |_| Ok(()))
57        })
58    }
59
60    fn update_dialogue(
61        self: Arc<Self>,
62        key: DialogueKey,
63        dialogue: D,
64    ) -> BoxFuture<'static, Result<(), Self::Error>>
65    where
66        D: Send + 'static,
67    {
68        Box::pin(async move {
69            self.map.lock().await.insert(key, dialogue);
70            Ok(())
71        })
72    }
73
74    fn get_dialogue(
75        self: Arc<Self>,
76        key: DialogueKey,
77    ) -> BoxFuture<'static, Result<Option<D>, Self::Error>> {
78        Box::pin(async move { Ok(self.map.lock().await.get(&key).cloned()) })
79    }
80
81    fn get_or_insert_dialogue(
82        self: Arc<Self>,
83        key: DialogueKey,
84        default: fn() -> D,
85        _reset_incompatible: bool,
86    ) -> BoxFuture<'static, Result<D, Self::Error>> {
87        Box::pin(
88            async move { Ok(self.map.lock().await.entry(key).or_insert_with(default).clone()) },
89        )
90    }
91}
92
93impl<D: Send + 'static> StorageKeys for InMemStorage<D> {
94    type Error = Infallible;
95
96    fn keys(self: Arc<Self>) -> BoxFuture<'static, Result<HashSet<DialogueKey>, Self::Error>> {
97        Box::pin(async move { Ok(self.map.lock().await.keys().cloned().collect()) })
98    }
99}