2021-02-08 18:37:25 +11:00
|
|
|
//! This implements a "database" for our Todos app. It makes the assumption that we're only ever
|
|
|
|
//! doing this stuff on the main thread; in a more complicated app, you'd probably make different
|
|
|
|
//! choices.
|
|
|
|
|
|
|
|
use std::cell::RefCell;
|
2022-07-16 00:14:02 +10:00
|
|
|
use std::rc::Rc;
|
2021-02-08 18:37:25 +11:00
|
|
|
|
|
|
|
/// The status of a Todo.
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum TodoStatus {
|
|
|
|
/// Yet to be completed.
|
|
|
|
Incomplete,
|
|
|
|
|
|
|
|
/// Completed. ;P
|
2022-08-19 07:45:19 +10:00
|
|
|
Complete
|
2021-02-08 18:37:25 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
/// A Todo. Represents... something to do.
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct Todo {
|
|
|
|
/// The title of this todo.
|
|
|
|
pub title: String,
|
|
|
|
|
|
|
|
/// The status of this todo.
|
2022-08-19 07:45:19 +10:00
|
|
|
pub status: TodoStatus
|
2021-02-08 18:37:25 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
/// A single-threaded Todos "database".
|
|
|
|
#[derive(Debug, Default)]
|
|
|
|
pub struct Todos(Rc<RefCell<Vec<Todo>>>);
|
|
|
|
|
|
|
|
impl Todos {
|
|
|
|
/// Insert a new Todo.
|
|
|
|
pub fn insert(&self, title: String) {
|
|
|
|
let mut stack = self.0.borrow_mut();
|
|
|
|
|
|
|
|
let mut todos = vec![Todo {
|
|
|
|
title: title,
|
2022-08-19 07:45:19 +10:00
|
|
|
status: TodoStatus::Incomplete
|
2021-02-08 18:37:25 +11:00
|
|
|
}];
|
|
|
|
|
|
|
|
todos.append(&mut stack);
|
|
|
|
|
|
|
|
*stack = todos;
|
|
|
|
}
|
2022-07-11 01:15:29 +10:00
|
|
|
|
2021-02-08 18:37:25 +11:00
|
|
|
/// Edit a Todo at the row specified.
|
|
|
|
pub fn with_mut<F>(&self, row: usize, handler: F)
|
|
|
|
where
|
2022-08-19 07:45:19 +10:00
|
|
|
F: Fn(&mut Todo)
|
2021-02-08 18:37:25 +11:00
|
|
|
{
|
|
|
|
let mut stack = self.0.borrow_mut();
|
|
|
|
|
|
|
|
if let Some(todo) = stack.get_mut(row) {
|
|
|
|
handler(todo);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Run a block with the given Todo.
|
|
|
|
pub fn with<F>(&self, row: usize, mut handler: F)
|
|
|
|
where
|
2022-08-19 07:45:19 +10:00
|
|
|
F: FnMut(&Todo)
|
2021-02-08 18:37:25 +11:00
|
|
|
{
|
|
|
|
let stack = self.0.borrow();
|
|
|
|
|
|
|
|
if let Some(todo) = stack.get(row) {
|
|
|
|
handler(todo);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the total number of Todos.
|
|
|
|
pub fn len(&self) -> usize {
|
|
|
|
let stack = self.0.borrow();
|
|
|
|
stack.len()
|
|
|
|
}
|
|
|
|
}
|