summaryrefslogtreecommitdiff
path: root/src/state.rs
blob: 60f6a3795fd6148062558493e1f0b9024d11f848 (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
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;

use crate::exercise::Exercise;

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

impl State {
    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() {
            return None;
        }

        Some(slf)
    }

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

    pub fn write(&self) -> Result<()> {
        // TODO: Capacity
        let mut buf = Vec::with_capacity(1 << 12);
        serde_json::ser::to_writer(&mut buf, self).context("Failed to serialize the state")?;
        dbg!(buf.len());
        Ok(())
    }
}