From 8e09b3068da2985e7ee37d15d1f8d8934723d835 Mon Sep 17 00:00:00 2001 From: MA Beaudet Date: Mon, 8 Nov 2021 18:20:30 +0100 Subject: [PATCH] feat!: add error handling in eval function --- src/evaluator.rs | 30 +++++++++++++++++++++++++++--- src/lib.rs | 4 +++- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/evaluator.rs b/src/evaluator.rs index 66efc98..5c6606c 100644 --- a/src/evaluator.rs +++ b/src/evaluator.rs @@ -3,7 +3,7 @@ use std::{collections::HashMap, rc::Rc}; use crate::{ card::{Card, Cards}, constants::{FLUSHES, HASH_ADJUST, HASH_VALUES, PERM7, UNIQUE5}, - Algorithm, Rules, + Algorithm, MyError, Rules, }; #[derive(Debug)] @@ -57,7 +57,31 @@ impl Evaluator { self } - pub fn eval(&self) -> HashMap { + pub fn eval(&mut self) -> Result, MyError> { + let hands: Vec = self + .hands + .clone() + .into_iter() + .map(|h| Cards(h.as_ref().0.clone())) + .collect(); + if hands.is_empty() { + return Err(MyError::NoHands); + } + let table = &self.table.as_ref().0.clone(); + if hands.len() == 5 && matches!(self.rules, Rules::Holdem) { + println!("Warning: card number in hands does not match the given Poker rules"); + println!("Switching rules to classic"); + self.rules = Rules::Classic; + } + let hand = &hands.get(0).unwrap().0; + if hand.len() == 2 && matches!(self.rules, Rules::Classic) { + println!("Warning: card number in hands does not match the given Poker rules"); + println!("Switching rules to holdem"); + self.rules = Rules::Holdem; + } + if matches!(self.rules, Rules::Holdem) && table.len() == 0 { + return Err(MyError::NoTable); + } let result = match self.rules { Rules::Classic => self .hands @@ -86,7 +110,7 @@ impl Evaluator { .enumerate() .collect(), }; - result + Ok(result) } pub fn eval_5hand(&self, cards: &[Card; 5]) -> u16 { diff --git a/src/lib.rs b/src/lib.rs index fc09bd2..9627e1e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,7 +26,9 @@ pub enum MyError { InvalidLength, InvalidRank, InvalidSuit, - IndexError + IndexError, + NoHands, + NoTable, } impl std::error::Error for MyError {} -- 2.20.1