From 1e2cee55a59190c9a9079bc130e450499ca65331 Mon Sep 17 00:00:00 2001 From: viridian Date: Fri, 10 May 2024 13:02:53 +0200 Subject: [PATCH] Allow subtraction to underflow --- src/main.rs | 66 +++++++++++++++++++++++++++++------------------------ 1 file changed, 36 insertions(+), 30 deletions(-) diff --git a/src/main.rs b/src/main.rs index 8f81ff5..9e5ae6e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,5 @@ use std::{ + io::Read, ops::{Add, Sub}, process::exit, usize, @@ -56,7 +57,7 @@ fn main() { } } -#[derive(Debug)] +#[derive(Debug, Clone)] struct Machine { instruction_pointer: usize, data_pointer: usize, @@ -64,8 +65,7 @@ struct Machine { instructions: Vec, } - -#[derive(Debug, Default, Clone, Copy, PartialEq)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] struct Cell { value: u8, } @@ -91,6 +91,7 @@ impl Machine { fn step(&mut self) -> MachineState { let instruction = self.instructions.get(self.instruction_pointer).unwrap(); + match instruction { Instruction::BINC => self.binc(), Instruction::BDEC => self.bdec(), @@ -178,12 +179,10 @@ impl Machine { fn inp(&mut self) { let mut input = String::new(); - std::io::stdin().read_line(&mut input).unwrap(); - - let value = *input.into_bytes().first().unwrap(); + std::io::stdin().take(1).read_to_string(&mut input).unwrap(); + let value = input.as_bytes().first().unwrap().to_owned(); let cell = Cell { value }; - self.data[self.data_pointer] = cell; } @@ -230,25 +229,36 @@ impl Machine { std::io::stdin().read_line(&mut input).unwrap(); let repetitions: usize = input.trim().parse().unwrap(); - - let bar = indicatif::ProgressBar::new(repetitions as u64); - bar.set_style( - ProgressStyle::with_template( - "{bar:40} | {human_pos}/{human_len} | {eta_precise} | {elapsed_precise}", - ) - .unwrap(), - ); - for _ in 0..repetitions { - bar.inc(1); - match self.step() { - MachineState::Ok => continue, - MachineState::EOI => { - self.instruction_pointer -= 1; - break; + if repetitions > 10000000 { + let bar = indicatif::ProgressBar::new(repetitions as u64); + bar.set_style( + ProgressStyle::with_template( + "{bar:40} | {human_pos}/{human_len} | {eta_precise} | {elapsed_precise} | {per_sec}", + ) + .unwrap(), + ); + for _ in 0..repetitions { + bar.inc(1); + match self.step() { + MachineState::Ok => continue, + MachineState::EOI => { + self.instruction_pointer -= 1; + break; + } + } + } + bar.finish(); + } else { + for _ in 0..repetitions { + match self.step() { + MachineState::Ok => continue, + MachineState::EOI => { + self.instruction_pointer -= 1; + break; + } } } } - bar.finish(); } } @@ -266,17 +276,13 @@ impl Sub for Cell { type Output = Cell; fn sub(self, rhs: Self) -> Self::Output { - if self.value == 0 { - Cell { value: 0 } - } else { - Cell { - value: self.value - rhs.value, - } + Cell { + value: self.value - rhs.value, } } } #[allow(clippy::upper_case_acronyms)] -#[derive(PartialEq, Eq, Debug)] +#[derive(PartialEq, Eq, Debug, Clone)] enum Instruction { PINC, // > PDEC, // <