@@ -187,18 +187,14 @@ impl FieldVisiter {
187
187
row : SizeType ,
188
188
col : SizeType ,
189
189
) -> 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
+ } )
202
198
}
203
199
204
200
fn extend_with_unvisited_neighbors ( & mut self , row : SizeType , col : SizeType ) {
@@ -530,6 +526,14 @@ impl BasicTable {
530
526
}
531
527
Ok ( number_of_flagged_neighbors)
532
528
}
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
+ }
533
537
}
534
538
535
539
impl Table for BasicTable {
@@ -542,9 +546,8 @@ impl Table for BasicTable {
542
546
}
543
547
544
548
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
+
548
551
if self . fields [ row as usize ] [ col as usize ]
549
552
. get_field_state ( )
550
553
. is_flagged ( )
@@ -566,9 +569,7 @@ impl Table for BasicTable {
566
569
}
567
570
568
571
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) ?;
572
573
573
574
let empty_open_info = OpenInfo {
574
575
result : OpenResult :: Ok ,
@@ -593,11 +594,9 @@ impl Table for BasicTable {
593
594
}
594
595
595
596
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 ( ) )
601
600
}
602
601
}
603
602
0 commit comments