Skip to main content

hydracache_core/
options.rs

1use std::time::Duration;
2
3use crate::TagSet;
4
5/// Per-entry cache behavior.
6///
7/// Options are passed to `put`, `get_or_load`, and loader helper methods.
8///
9/// # Example
10///
11/// ```rust
12/// use std::time::Duration;
13///
14/// use hydracache_core::CacheOptions;
15///
16/// let options = CacheOptions::new()
17///     .ttl(Duration::from_secs(60))
18///     .tags(["users", "user:42"]);
19///
20/// assert_eq!(options.ttl_value(), Some(Duration::from_secs(60)));
21/// assert_eq!(options.tags_value(), &["users".to_owned(), "user:42".to_owned()]);
22/// ```
23#[derive(Debug, Clone, Default, PartialEq, Eq)]
24pub struct CacheOptions {
25    ttl: Option<Duration>,
26    tags: Vec<String>,
27}
28
29impl CacheOptions {
30    /// Create empty cache options.
31    pub fn new() -> Self {
32        Self::default()
33    }
34
35    /// Set a per-entry TTL.
36    pub fn ttl(mut self, ttl: Duration) -> Self {
37        self.ttl = Some(ttl);
38        self
39    }
40
41    /// Attach one tag used by `invalidate_tag`.
42    pub fn tag(mut self, tag: impl Into<String>) -> Self {
43        self.tags.push(tag.into());
44        self
45    }
46
47    /// Attach tags used by `invalidate_tag`.
48    pub fn tags<I, S>(mut self, tags: I) -> Self
49    where
50        I: IntoIterator<Item = S>,
51        S: Into<String>,
52    {
53        self.tags = tags.into_iter().map(Into::into).collect();
54        self
55    }
56
57    /// Replace tags from a [`TagSet`].
58    pub fn tag_set(mut self, tags: TagSet) -> Self {
59        self.tags = tags.into_vec();
60        self
61    }
62
63    /// Return the configured TTL, if any.
64    pub fn ttl_value(&self) -> Option<Duration> {
65        self.ttl
66    }
67
68    /// Return tags attached to this entry.
69    pub fn tags_value(&self) -> &[String] {
70        &self.tags
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77    use crate::TagSet;
78
79    #[test]
80    fn cache_options_tag_set_replaces_existing_tags() {
81        let options = CacheOptions::new()
82            .tag("old")
83            .tag_set(TagSet::new().tag("new").entity("user", 42));
84
85        assert_eq!(
86            options.tags_value(),
87            &["new".to_owned(), "user:42".to_owned()]
88        );
89    }
90}