Merge pull request #43 from T-Dark0/T-Dark_fix_brainfuck_overflows

Fixed integer overflows. Why did I even write `checked_add` in the first place?
This commit is contained in:
Erin 2021-10-19 23:37:47 +02:00 committed by GitHub
commit 0f198a2554

View file

@ -110,14 +110,14 @@ impl<'a, I: BootlegRead> Interpreter<'a, I> {
let val = self let val = self
.get_or_resize_tape_mut() .get_or_resize_tape_mut()
.ok_or(ProgramError::TapeSizeExceededLimit)?; .ok_or(ProgramError::TapeSizeExceededLimit)?;
*val = val.checked_add(1).ok_or(ProgramError::IntegerOverflow)?; *val = val.wrapping_add(1)
} }
b'-' => { b'-' => {
let val = self let val = self
.get_or_resize_tape_mut() .get_or_resize_tape_mut()
.ok_or(ProgramError::TapeSizeExceededLimit)?; .ok_or(ProgramError::TapeSizeExceededLimit)?;
*val = val.checked_sub(1).ok_or(ProgramError::IntegerUnderflow)?; *val = val.wrapping_sub(1)
} }
b'.' => { b'.' => {
@ -282,8 +282,6 @@ pub enum IoStatus {
/// An error that occurred while the interpreter was advancing /// An error that occurred while the interpreter was advancing
pub enum ProgramError { pub enum ProgramError {
DataPointerUnderflow, DataPointerUnderflow,
IntegerOverflow,
IntegerUnderflow,
InputReadError, InputReadError,
UnmatchedOpeningBracket, UnmatchedOpeningBracket,
UnmatchedClosingBracket, UnmatchedClosingBracket,
@ -297,8 +295,6 @@ impl Display for ProgramError {
"{}", "{}",
match self { match self {
ProgramError::DataPointerUnderflow => "data pointer underflow", ProgramError::DataPointerUnderflow => "data pointer underflow",
ProgramError::IntegerOverflow => "integer overflow",
ProgramError::IntegerUnderflow => "integer underflow",
ProgramError::InputReadError => "input read error", ProgramError::InputReadError => "input read error",
ProgramError::UnmatchedOpeningBracket => "unmatched `[`", ProgramError::UnmatchedOpeningBracket => "unmatched `[`",
ProgramError::UnmatchedClosingBracket => "unmatched `]`", ProgramError::UnmatchedClosingBracket => "unmatched `]`",
@ -442,4 +438,14 @@ mod tests {
)) ))
); );
} }
#[test]
fn positive_integer_overflow() {
interpret_with_io(b"+[+]", std::io::empty(), std::io::sink()).unwrap();
}
#[test]
fn negative_integer_overflow() {
interpret_with_io(b"-", std::io::empty(), std::io::sink()).unwrap();
}
} }