summaryrefslogtreecommitdiff
path: root/src/state_file.rs
blob: ca7ed342f18a7301ba24f563fdc5dfd59a8f3f3c (plain)
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
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;

use crate::exercise::Exercise;

#[derive(Serialize, Deserialize)]
pub struct StateFile {
    next_exercise_ind: usize,
    progress: Vec<bool>,
}

impl StateFile {
    fn read(exercises: &[Exercise]) -> Option<Self> {
        let file_content = fs::read(".rustlings.json").ok()?;

        let slf: Self = serde_json::de::from_slice(&file_content).ok()?;

        if slf.progress.len() != exercises.len() || slf.next_exercise_ind >= exercises.len() {
            return None;
        }

        Some(slf)
    }

    pub fn read_or_default(exercises: &[Exercise]) -> Self {
        Self::read(exercises).unwrap_or_else(|| Self {
            next_exercise_ind: 0,
            progress: vec![false; exercises.len()],
        })
    }

    fn write(&self) -> Result<()> {
        // TODO: Capacity
        let mut buf = Vec::with_capacity(1024);
        serde_json::ser::to_writer(&mut buf, self).context("Failed to serialize the state")?;

        Ok(())
    }

    #[inline]
    pub fn next_exercise_ind(&self) -> usize {
        self.next_exercise_ind
    }

    pub fn set_next_exercise_ind(&mut self, ind: usize) -> Result<()> {
        if ind >= self.progress.len() {
            bail!("The next exercise index is higher than the number of exercises");
        }

        self.next_exercise_ind = ind;
        self.write()
    }

    #[inline]
    pub fn progress(&self) -> &[bool] {
        &self.progress
    }
}