soliterm-model 0.1.0

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

use super::Stock;
use crate::piles::{Cards, Pile as _, PileMut as _};
use crate::{action, undo};

#[derive(Debug)]
pub struct Action(pub usize);

#[derive(Debug)]
pub struct Value {
    drawn: Cards,
}

impl Value {
    pub fn drawn(&self) -> &Cards {
        &self.drawn
    }
}

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

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

impl action::Target<Action> for Stock {
    fn update(&mut self, Action(max_count): Action, _: ()) -> Result<Value, Error> {
        if self.pile.is_empty() {
            return Err(Error::Empty);
        }

        let cards = self.pile.take_at_most(max_count).flipped();

        Ok(Value { drawn: cards })
    }
}

impl undo::Target<Value> for Stock {
    fn revert(&mut self, value: Value) {
        let cards = value.drawn.flipped();
        self.pile.place(cards);
    }
}