soliterm-model 0.1.0

Shared model types for soliterm
Documentation
use derive_more::{Display, Error};

use super::Waste;
use crate::card::Card;
use crate::piles::{Pile as _, PileMut as _};
use crate::{action, undo};

#[derive(Debug)]
pub struct Action;

#[derive(Debug)]
pub struct Value {
    taken: Card,
    previous_stack_len: usize,
}

impl Value {
    pub fn taken(&self) -> Card {
        self.taken
    }
}

#[derive(Debug, Display, Error)]
pub enum Error {
    #[display(fmt = "The waste is empty")]
    Empty,
}

impl action::Action for Action {
    type State<'s> = ();
    type Value = Value;
    type Error = Error;
}

impl action::Target<Action> for Waste {
    fn update(&mut self, _: Action, _: ()) -> Result<Value, Error> {
        let previous_stack_len = self.pile.left().len();
        let card = self.pile.take_at_most_one().ok_or(Error::Empty)?;

        Ok(Value {
            taken: card,
            previous_stack_len,
        })
    }
}

impl undo::Target<Value> for Waste {
    fn revert(&mut self, value: Value) {
        self.pile.place_one(value.taken);
        self.pile.set_left_length(value.previous_stack_len);
    }
}