Last active
July 15, 2018 00:58
-
-
Save U007D/3e4a824f4077ced8de92b1689abbe7b1 to your computer and use it in GitHub Desktop.
evolution from iterative to functional validator for bgk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//does not work as intended :( | |
#[inline] | |
pub(super) fn validate_frame(roll: u8) -> Result<u8> { | |
let mut frame_validator = || -> Error { | |
for frame in Game::FIRST_FRAME..=Game::LAST_FRAME { | |
let first_roll = roll; | |
yield Ok(first_roll); | |
// this frame has a second roll if it's the last frame OR if first roll was not a strike | |
if frame == Game::LAST_FRAME || first_roll < Game::FRAME_MAX_VALUE { | |
let second_roll = roll; | |
match first_roll.saturating_add(second_roll) <= Game::FRAME_MAX_VALUE { | |
true => yield Ok(second_roll), | |
false => yield Err(Error::InvalidFrame(frame, vec![first_roll, second_roll])), | |
} | |
// this frame has a third roll iff it's the last frame AND is a strike or spare | |
if frame == Game::LAST_FRAME && first_roll.saturating_add(second_roll) >= Game::FRAME_MAX_VALUE { | |
let third_roll = roll; | |
yield Ok(third_roll); | |
} | |
} | |
}; | |
Error::TooManyRolls | |
}; | |
match unsafe { frame_validator.resume() } { | |
GeneratorState::Yielded(Ok(v)) => Ok(v), | |
GeneratorState::Yielded(Err(e)) | | |
GeneratorState::Complete(e) => Err(e), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment