|
| 1 | +use serde::{Deserialize, Serialize}; |
| 2 | +use std::error::Error; |
| 3 | +use std::fs; |
| 4 | +use std::path::Path; |
| 5 | + |
| 6 | +const TODO_FILE: &str = "data/day34_todo.json"; |
| 7 | + |
| 8 | +#[derive(Debug, Serialize, Deserialize, Clone)] |
| 9 | +struct TodoItem { |
| 10 | + id: u32, |
| 11 | + title: String, |
| 12 | + done: bool, |
| 13 | +} |
| 14 | + |
| 15 | +#[derive(Debug, Serialize, Deserialize, Default)] |
| 16 | +struct TodoStore { |
| 17 | + items: Vec<TodoItem>, |
| 18 | +} |
| 19 | + |
| 20 | +impl TodoStore { |
| 21 | + fn add_task(&mut self, title: impl Into<String>) { |
| 22 | + let next_id = self.items.last().map_or(1, |item| item.id + 1); |
| 23 | + self.items.push(TodoItem { |
| 24 | + id: next_id, |
| 25 | + title: title.into(), |
| 26 | + done: false, |
| 27 | + }); |
| 28 | + } |
| 29 | + |
| 30 | + fn mark_done(&mut self, id: u32) -> bool { |
| 31 | + if let Some(item) = self.items.iter_mut().find(|item| item.id == id) { |
| 32 | + item.done = true; |
| 33 | + true |
| 34 | + } else { |
| 35 | + false |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + fn load(path: &Path) -> Result<Self, Box<dyn Error>> { |
| 40 | + if !path.exists() { |
| 41 | + return Ok(Self::default()); |
| 42 | + } |
| 43 | + |
| 44 | + let content = fs::read_to_string(path)?; |
| 45 | + let store = serde_json::from_str(&content)?; |
| 46 | + Ok(store) |
| 47 | + } |
| 48 | + |
| 49 | + fn save(&self, path: &Path) -> Result<(), Box<dyn Error>> { |
| 50 | + if let Some(parent) = path.parent() { |
| 51 | + fs::create_dir_all(parent)?; |
| 52 | + } |
| 53 | + |
| 54 | + let json = serde_json::to_string_pretty(self)?; |
| 55 | + fs::write(path, json)?; |
| 56 | + Ok(()) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +pub fn run() -> Result<(), Box<dyn Error>> { |
| 61 | + println!("\nLesson: Build a tiny Todo with File I/O + JSON"); |
| 62 | + println!("Data file: {TODO_FILE}"); |
| 63 | + |
| 64 | + let path = Path::new(TODO_FILE); |
| 65 | + let mut store = TodoStore::load(path)?; |
| 66 | + |
| 67 | + if store.items.is_empty() { |
| 68 | + store.add_task("Read ownership chapter again"); |
| 69 | + store.add_task("Practice borrowing with 3 small exercises"); |
| 70 | + } |
| 71 | + |
| 72 | + if let Some(first_open_id) = store.items.iter().find(|item| !item.done).map(|item| item.id) { |
| 73 | + store.mark_done(first_open_id); |
| 74 | + } |
| 75 | + |
| 76 | + store.save(path)?; |
| 77 | + |
| 78 | + println!("Current tasks:"); |
| 79 | + for item in &store.items { |
| 80 | + let status = if item.done { "done" } else { "todo" }; |
| 81 | + println!("- [{}] #{} {}", status, item.id, item.title); |
| 82 | + } |
| 83 | + |
| 84 | + println!("Saved to {}", path.display()); |
| 85 | + Ok(()) |
| 86 | +} |
| 87 | + |
0 commit comments