1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
use crate::quote::Quote;
use anyhow::{ensure, Result};
use std::collections::VecDeque;
use std::path::PathBuf;

pub struct QuoteManager {
    /// Quotes
    quotes: VecDeque<Quote>,
    /// Path to quotes file.
    path: PathBuf,
    /// Maximum number of quotes to store.
    max_quotes: usize,
}

impl QuoteManager {
    /// Create new QuoteManager instance.
    ///
    /// This constructor does not load quotes from the specified file path, but uses the provided
    /// quotes deque. To load from a quotes file, use `QuoteManager::load` instead.
    ///
    /// # Errors
    /// An error is returned if `max_quotes` is less than 1.
    pub fn new(
        quotes: impl Into<VecDeque<Quote>>,
        path: impl Into<PathBuf>,
        max_quotes: usize,
    ) -> Result<Self> {
        ensure!(
            max_quotes > 0,
            "Maximum number of quotes must be greater than 0"
        );
        let mut quotes = quotes.into();
        quotes.truncate(max_quotes);
        Ok(Self {
            quotes: quotes.into(),
            path: path.into(),
            max_quotes: max_quotes,
        })
    }

    /// Load quotes from file.
    ///
    /// If the quotes file does not exist, initialize the QuoteManager with an empty quote deque.
    ///
    /// # Errors
    /// An error is returned if `max_quotes` is less than 1.
    pub fn load(path: impl Into<PathBuf>, max_quotes: usize) -> Result<Self> {
        let path: PathBuf = path.into();
        let quotes = match std::fs::read_to_string(&path) {
            Ok(data) => VecDeque::from(
                serde_json::from_str::<Vec<Quote>>(&data)?
                    .into_iter()
                    .rev()
                    .take(max_quotes)
                    .collect::<Vec<Quote>>(),
            ),
            Err(_) => VecDeque::new(),
        };
        Self::new(quotes, path, max_quotes)
    }

    /// Save quotes to file.
    pub fn save(&self) -> Result<()> {
        if let Some(parent_dir) = self.path.parent() {
            std::fs::create_dir_all(parent_dir)?;
        }
        let quotes: Vec<&Quote> = self.quotes.iter().rev().collect();
        std::fs::write(&self.path, serde_json::to_string_pretty(&quotes)?)?;
        Ok(())
    }

    /// Push quote, truncating the quote deque if it exceeds the maximum number of quotes.
    pub fn push(&mut self, quote: Quote) {
        self.quotes.truncate(self.max_quotes - 1);
        self.quotes.push_front(quote);
    }

    /// List quotes, ordered from most recent to least recent.
    pub fn list(&self) -> &VecDeque<Quote> {
        &self.quotes
    }

    /// Get latest quote.
    pub fn get(&self) -> Option<&Quote> {
        self.quotes.front()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::DateTime;

    fn make_quote(quote: &str) -> Quote {
        Quote {
            quote: quote.to_owned(),
            author: "Test Author".to_owned(),
            url: None,
            vendor: "testvendor".to_owned(),
            fetch_time: DateTime::parse_from_rfc3339("2021-01-01T10:00:00Z")
                .unwrap()
                .into(),
        }
    }

    #[test]
    fn new() {
        assert!(QuoteManager::new(vec![make_quote("Quote 1")], "/dev/null", 3,).is_ok());
    }

    #[test]
    fn new_max_queues_too_small() {
        assert!(QuoteManager::new(vec![make_quote("Quote 1")], "/dev/null", 0,).is_err());
    }

    #[test]
    fn list() {
        let quotes = vec![make_quote("Quote 1"), make_quote("Quote 2")];
        let manager = QuoteManager::new(quotes.clone(), "/dev/null", 3).unwrap();
        assert!(manager.list().iter().eq(quotes.iter()));
    }

    #[test]
    fn new_truncates() {
        let quotes = vec![make_quote("Quote 1"), make_quote("Quote 2")];
        let max_quotes = 1;
        // `max_quotes` must be less than number of quotes for the test to be meaningful.
        assert!(max_quotes < quotes.len());
        let manager = QuoteManager::new(quotes.clone(), "/dev/null", max_quotes).unwrap();
        assert!(manager.list().iter().eq(quotes.iter().take(max_quotes)));
    }

    #[test]
    fn get() {
        let quotes = vec![make_quote("Quote 1"), make_quote("Quote 2")];
        let manager = QuoteManager::new(quotes.clone(), "/dev/null", 3).unwrap();
        assert_eq!(manager.get().unwrap().to_owned(), quotes[0]);
    }

    #[test]
    fn push() {
        let mut manager = QuoteManager::new(vec![], "/dev/null", 2).unwrap();
        manager.push(make_quote("Quote 1"));
        assert!(manager.list().iter().eq(vec![make_quote("Quote 1")].iter()));
        manager.push(make_quote("Quote 2"));
        assert!(manager
            .list()
            .iter()
            .eq(vec![make_quote("Quote 2"), make_quote("Quote 1")].iter()));
        manager.push(make_quote("Quote 3"));
        assert!(manager
            .list()
            .iter()
            .eq(vec![make_quote("Quote 3"), make_quote("Quote 2")].iter()));
    }
}