feat: improve tape peeking + tape peek display trait impl

This commit is contained in:
leonhard committed 2026-11-17 18:30:05 +01:00
1 parent e53b61904d
commit e0a7b7b9e8
2 files changed
+25 -3

No files matched your search

+7 -1
View File
@@ -2,7 +2,7 @@ use std::{collections::HashMap, fmt::Display, num::NonZeroUsize};
use crate::{ use crate::{
TuringMachineError, TuringMachineError,
tape::{Tape, TapeSymbol}, tape::{Tape, TapePeek, TapeSymbol},
}; };
pub struct TuringMachine { pub struct TuringMachine {
@@ -62,6 +62,12 @@ impl TuringMachine {
} }
} }
impl<'a> TuringMachine {
pub fn peek(&'a self, radius: usize) -> TapePeek<'a> {
self.tape.peek(radius)
}
}
const ALPHABET: [char; 26] = [ const ALPHABET: [char; 26] = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
+18 -2
View File
@@ -66,7 +66,7 @@ impl Tape {
} }
} }
pub fn peek(&self, radius: usize) -> Vec<&TapeSymbol> { pub fn peek(&self, radius: usize) -> TapePeek<'_> {
let mut fields = Vec::new(); let mut fields = Vec::new();
match self.head.side { match self.head.side {
TapeSide::Left => { TapeSide::Left => {
@@ -102,7 +102,23 @@ impl Tape {
fields.resize(fields.len() + right_overshoot, &TapeSymbol::Zero); fields.resize(fields.len() + right_overshoot, &TapeSymbol::Zero);
} }
} }
fields TapePeek(fields)
}
}
pub struct TapePeek<'a>(Vec<&'a TapeSymbol>);
impl Display for TapePeek<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let middle = self.0.len() / 2;
for (index, symbol) in self.0.iter().enumerate() {
if index == middle {
write!(f, "[{}]", symbol)?;
} else {
write!(f, " {} ", symbol)?;
}
}
Ok(())
} }
} }