feat!: add error handling in eval function
authorMA Beaudet <ma@beaudet.xyz>
Mon, 8 Nov 2021 17:20:30 +0000 (18:20 +0100)
committerMA Beaudet <ma@beaudet.xyz>
Mon, 8 Nov 2021 17:20:30 +0000 (18:20 +0100)
src/evaluator.rs
src/lib.rs

index 66efc98..5c6606c 100644 (file)
@@ -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<usize, u16> {
+    pub fn eval(&mut self) -> Result<HashMap<usize, u16>, MyError> {
+        let hands: Vec<Cards> = 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 {
index fc09bd2..9627e1e 100644 (file)
@@ -26,7 +26,9 @@ pub enum MyError {
     InvalidLength,
     InvalidRank,
     InvalidSuit,
-    IndexError
+    IndexError,
+    NoHands,
+    NoTable,
 }
 
 impl std::error::Error for MyError {}