summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authormo8it <mo8it@proton.me>2024-04-06 01:46:22 +0200
committermo8it <mo8it@proton.me>2024-04-06 01:46:22 +0200
commitde9a0ed5221934b43a27921455f484e006c3ec20 (patch)
treec48ff118df32ebd7d7b8e101f26194af2e9ab670 /src
parent06e7216c833f46299c0314bbab47f8df9fc355a3 (diff)
Update state
Diffstat (limited to 'src')
-rw-r--r--src/state.rs34
1 files changed, 20 insertions, 14 deletions
diff --git a/src/state.rs b/src/state.rs
index e3e3299..60f6a37 100644
--- a/src/state.rs
+++ b/src/state.rs
@@ -1,31 +1,37 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
-use std::{fs, io, path::PathBuf};
+use std::fs;
-#[derive(Serialize, Deserialize)]
-pub struct ExerciseState {
- pub path: PathBuf,
- pub done: bool,
-}
+use crate::exercise::Exercise;
#[derive(Serialize, Deserialize)]
pub struct State {
- pub progress: Vec<ExerciseState>,
+ pub progress: Vec<bool>,
}
impl State {
- pub fn read() -> Result<Self> {
- let file_content =
- fs::read(".rustlings.json").context("Failed to read the file `.rustlings.json`")?;
+ 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)
+ }
- serde_json::de::from_slice(&file_content)
- .context("Failed to deserialize the file `.rustlings.json`")
+ pub fn read_or_default(exercises: &[Exercise]) -> Self {
+ Self::read(exercises).unwrap_or_else(|| Self {
+ progress: vec![false; exercises.len()],
+ })
}
- pub fn write(&self) -> io::Result<()> {
+ 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");
+ serde_json::ser::to_writer(&mut buf, self).context("Failed to serialize the state")?;
dbg!(buf.len());
Ok(())
}