Skip to content

Commit 32aa7bc

Browse files
Centralize index checking
1 parent 6e2afc4 commit 32aa7bc

File tree

1 file changed

+22
-23
lines changed
  • minesweeper/src/minesweeper_logic

1 file changed

+22
-23
lines changed

minesweeper/src/minesweeper_logic/table.rs

Lines changed: 22 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -187,18 +187,14 @@ impl FieldVisiter {
187187
row: SizeType,
188188
col: SizeType,
189189
) -> Result<FieldVisiter, &'static str> {
190-
if row >= height || col >= width {
191-
Err(INVALID_INDEX_ERROR)
192-
} else {
193-
let mut fields_to_visit = IndexSet::new();
194-
fields_to_visit.insert((row, col));
195-
Ok(FieldVisiter {
196-
height,
197-
width,
198-
fields_to_visit,
199-
visited_fields: HashSet::new(),
200-
})
201-
}
190+
let mut fields_to_visit = IndexSet::new();
191+
fields_to_visit.insert((row, col));
192+
Ok(FieldVisiter {
193+
height,
194+
width,
195+
fields_to_visit,
196+
visited_fields: HashSet::new(),
197+
})
202198
}
203199

204200
fn extend_with_unvisited_neighbors(&mut self, row: SizeType, col: SizeType) {
@@ -530,6 +526,14 @@ impl BasicTable {
530526
}
531527
Ok(number_of_flagged_neighbors)
532528
}
529+
530+
fn validate_indices(&self, row: SizeType, col: SizeType) -> Result<(), &'static str> {
531+
if row < 0 || row >= self.height || col < 0 || col >= self.width {
532+
Err(INVALID_INDEX_ERROR)
533+
} else {
534+
Ok(())
535+
}
536+
}
533537
}
534538

535539
impl Table for BasicTable {
@@ -542,9 +546,8 @@ impl Table for BasicTable {
542546
}
543547

544548
fn open_field(&mut self, row: SizeType, col: SizeType) -> Result<OpenInfo, &'static str> {
545-
if row >= self.height || col >= self.width {
546-
return Err(INVALID_INDEX_ERROR);
547-
}
549+
self.validate_indices(row, col)?;
550+
548551
if self.fields[row as usize][col as usize]
549552
.get_field_state()
550553
.is_flagged()
@@ -566,9 +569,7 @@ impl Table for BasicTable {
566569
}
567570

568571
fn open_neighbors(&mut self, row: SizeType, col: SizeType) -> Result<OpenInfo, &'static str> {
569-
if row >= self.height || col >= self.width {
570-
return Err(INVALID_INDEX_ERROR);
571-
}
572+
self.validate_indices(row, col)?;
572573

573574
let empty_open_info = OpenInfo {
574575
result: OpenResult::Ok,
@@ -593,11 +594,9 @@ impl Table for BasicTable {
593594
}
594595

595596
fn toggle_flag(&mut self, row: SizeType, col: SizeType) -> Result<FlagResult, &'static str> {
596-
if row >= self.height || col >= self.width {
597-
Err(INVALID_INDEX_ERROR)
598-
} else {
599-
Ok(self.fields[row as usize][col as usize].toggle_flag())
600-
}
597+
self.validate_indices(row, col)?;
598+
599+
Ok(self.fields[row as usize][col as usize].toggle_flag())
601600
}
602601
}
603602

0 commit comments

Comments
 (0)