mirror of
https://github.com/rust-lang/rustlings.git
synced 2024-11-08 09:09:17 +01:00
Update state
This commit is contained in:
parent
06e7216c83
commit
de9a0ed522
34
src/state.rs
34
src/state.rs
@ -1,31 +1,37 @@
|
|||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::{fs, io, path::PathBuf};
|
use std::fs;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
use crate::exercise::Exercise;
|
||||||
pub struct ExerciseState {
|
|
||||||
pub path: PathBuf,
|
|
||||||
pub done: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct State {
|
pub struct State {
|
||||||
pub progress: Vec<ExerciseState>,
|
pub progress: Vec<bool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl State {
|
impl State {
|
||||||
pub fn read() -> Result<Self> {
|
fn read(exercises: &[Exercise]) -> Option<Self> {
|
||||||
let file_content =
|
let file_content = fs::read(".rustlings.json").ok()?;
|
||||||
fs::read(".rustlings.json").context("Failed to read the file `.rustlings.json`")?;
|
|
||||||
|
|
||||||
serde_json::de::from_slice(&file_content)
|
let slf: Self = serde_json::de::from_slice(&file_content).ok()?;
|
||||||
.context("Failed to deserialize the file `.rustlings.json`")
|
|
||||||
|
if slf.progress.len() != exercises.len() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(slf)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn write(&self) -> io::Result<()> {
|
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
|
// TODO: Capacity
|
||||||
let mut buf = Vec::with_capacity(1 << 12);
|
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());
|
dbg!(buf.len());
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user