Skip to main content

starweaver_context/
notes.rs

1//! Serializable note store carried by context state.
2
3use std::collections::BTreeMap;
4
5use serde::{Deserialize, Serialize};
6
7/// Serializable note store carried by context state.
8#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
9pub struct NoteStore {
10    notes: BTreeMap<String, String>,
11}
12
13impl NoteStore {
14    /// Create an empty note store.
15    #[must_use]
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    /// Set a note value.
21    pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
22        self.notes.insert(key.into(), value.into());
23    }
24
25    /// Get a note value.
26    #[must_use]
27    pub fn get(&self, key: &str) -> Option<&str> {
28        self.notes.get(key).map(String::as_str)
29    }
30
31    /// Delete a note value and return whether it existed.
32    pub fn delete(&mut self, key: &str) -> bool {
33        self.notes.remove(key).is_some()
34    }
35
36    /// Return all notes sorted by key.
37    #[must_use]
38    pub fn entries(&self) -> Vec<(String, String)> {
39        self.notes
40            .iter()
41            .map(|(key, value)| (key.clone(), value.clone()))
42            .collect()
43    }
44
45    /// Return a serializable copy of all notes.
46    #[must_use]
47    pub fn to_map(&self) -> BTreeMap<String, String> {
48        self.notes.clone()
49    }
50
51    /// Restore notes from exported data.
52    #[must_use]
53    pub const fn from_map(notes: BTreeMap<String, String>) -> Self {
54        Self { notes }
55    }
56
57    /// Return whether the store has no notes.
58    #[must_use]
59    pub fn is_empty(&self) -> bool {
60        self.notes.is_empty()
61    }
62}