sokoban-elements 0.2.0

Parsing and writing Sokoban, Hexoban, Trioban and Octoban file formats.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
use itertools::Itertools;

use super::edges::{HorizontalEdge, VerticalEdge};
use super::errors::{BoardSyntaxError, BoardSyntaxErrorKind};
use crate::rle::Rle;
use crate::utilities::is_blank;
use crate::{Tessellation, TileKind};

/// row-major: outer `Vec` is rows (`y`), inner is columns (`x`). Origin `(0, 0)` is top-left, `y`
/// grows downward.
pub(super) type ParsedBoard = Vec<Vec<TileKind>>;

pub struct ParserCommon;

impl ParserCommon {
    pub const BOX: char = '$';
    pub const BOX_ALT1: char = 'b';
    pub const BOX_ON_GOAL: char = '*';
    pub const BOX_ON_GOAL_ALT1: char = 'B';
    pub const FLOOR: char = ' ';
    pub const VISIBLE_FLOOR: char = '-';
    pub const VISIBLE_FLOOR_ALT1: char = '_';
    pub const GOAL: char = '.';
    pub const GOAL_ALT1: char = 'o';
    pub const PUSHER: char = '@';
    pub const PUSHER_ALT1: char = 'p';
    pub const PUSHER_ALT2: char = 'm';
    pub const PUSHER_ON_GOAL: char = '+';
    pub const PUSHER_ON_GOAL_ALT1: char = 'P';
    pub const PUSHER_ON_GOAL_ALT2: char = 'M';
    pub const WALL: char = '#';
    // pub const PUSHER_ON_BOX: char = '!';

    pub const RLE_GROUP_START: char = Rle::GROUP_START;
    pub const RLE_GROUP_END: char = Rle::GROUP_END;
    pub const RLE_EOL: char = Rle::EOL;

    /// Checks if character represents board cell having pusher on it
    pub const fn is_pusher(ch: char) -> bool {
        (ch == Self::PUSHER)
            || (ch == Self::PUSHER_ALT1)
            || (ch == Self::PUSHER_ALT2)
            || (ch == Self::PUSHER_ON_GOAL)
            || (ch == Self::PUSHER_ON_GOAL_ALT1)
            || (ch == Self::PUSHER_ON_GOAL_ALT2)
    }

    /// Checks if character represents board cell having box on it
    pub const fn is_box(ch: char) -> bool {
        (ch == Self::BOX)
            || (ch == Self::BOX_ALT1)
            || (ch == Self::BOX_ON_GOAL)
            || (ch == Self::BOX_ON_GOAL_ALT1)
    }

    /// Checks if character represents board cell having goal on it
    pub const fn is_goal(ch: char) -> bool {
        (ch == Self::GOAL)
            || (ch == Self::GOAL_ALT1)
            || (ch == Self::BOX_ON_GOAL)
            || (ch == Self::BOX_ON_GOAL_ALT1)
            || (ch == Self::PUSHER_ON_GOAL)
            || (ch == Self::PUSHER_ON_GOAL_ALT1)
            || (ch == Self::PUSHER_ON_GOAL_ALT2)
    }

    /// Checks if character represents empty floor board cell
    pub const fn is_empty_floor(ch: char) -> bool {
        (ch == Self::FLOOR) || (ch == Self::VISIBLE_FLOOR) || (ch == Self::VISIBLE_FLOOR_ALT1)
    }

    /// Checks if character represents wall board cell
    pub const fn is_wall(ch: char) -> bool { ch == Self::WALL }
}

/// Tests if `input` contains only characters that are valid in game board strings.
///
/// This method doesn't test if `input` is a valid game board. The only way to do that is
/// to actually [`parse`](GameBoard::parsed()) it.
pub(crate) fn is_board_line(line: &str) -> bool {
    !line
        .chars()
        .all(|c| c.is_whitespace() || c.is_ascii_digit())
        && line.chars().all(|c| {
            c.is_whitespace()
                || c.is_ascii_digit()
                || ParserCommon::is_pusher(c)
                || ParserCommon::is_box(c)
                || ParserCommon::is_goal(c)
                || ParserCommon::is_empty_floor(c)
                || ParserCommon::is_wall(c)
                || (c == ParserCommon::RLE_EOL)
                || (c == ParserCommon::RLE_GROUP_START)
                || (c == ParserCommon::RLE_GROUP_END)
        })
}

/// Asserts the board data invariant that all rows are of equal length.
///
/// Board editing primitives rely on it and are only ever reachable through
/// [`GameBoard`](crate::GameBoard), which upholds it.
pub(super) fn assert_width_normalized(body: &ParsedBoard) {
    assert!(
        body.iter().map(std::vec::Vec::len).all_equal(),
        "expects width-normalized board data"
    );
}

/// Collapses board data that has rows but no columns into the empty board.
///
/// Editing primitives are free to produce rows of zero length on their way to a final result (ie.
/// removing more columns than there are, or adding rows to an empty board). Such data is not a
/// valid [`GameBoard`](crate::GameBoard): a board with no columns is the empty board. See
/// `GameBoard` docs.
///
/// Board data is width-normalized, so testing the first row is enough.
pub(super) fn normalize_dimensions(body: &mut ParsedBoard) {
    assert_width_normalized(body);

    if body.first().is_some_and(Vec::is_empty) {
        body.clear();
    }
}

/// Extends board data to at least `width` columns and `height` rows with
/// [`TileKind::Floor`](crate::TileKind::Floor).
///
/// Callers pass targets already maximized against the current size, so rows are never truncated.
/// The empty board is grown too: it has no rows to widen, and every row it then gains is built at
/// the wanted width.
///
/// This needs no [`BoardResizer`] and no [`Tessellation`] dispatch. Only the Top and Left edges
/// shift existing content, so only they can break tile geometry; growing right and down is
/// dimension-local in every tessellation and never needs a perpendicular padding line.
pub(super) fn grown(body: &mut ParsedBoard, width: usize, height: usize) {
    assert_width_normalized(body);

    for row in body.iter_mut() {
        row.resize(width, TileKind::Floor);
    }

    let missing_rows = height.saturating_sub(body.len());
    body.extend(std::iter::repeat_n(vec![TileKind::Floor; width], missing_rows));
}

pub(super) trait BoardParser {
    fn parse(board: &str) -> Result<ParsedBoard, BoardSyntaxError> {
        if is_blank(board) {
            return Ok(ParsedBoard::new());
        }

        let lines: Vec<String> = match Rle::decode(board, false) {
            Ok(v) => v,
            Err(e) => {
                return Err(BoardSyntaxError::new_with_source(
                    BoardSyntaxErrorKind::RleDecodingFailed,
                    Some(e),
                ));
            }
        }
        .trim_start_matches('\n')
        .trim_end()
        .split('\n')
        .map(str::to_owned)
        .collect();
        let max_width = lines.iter().map(|s| s.chars().count()).max().unwrap_or(0);

        // A board with no columns is the empty board. Reachable for input that is not blank, but
        // RLE-decodes to nothing, ie. "|" or "3 ". No character validation is skipped here:
        // `max_width` of zero means every decoded line was empty.
        if max_width == 0 {
            return Ok(ParsedBoard::new());
        }

        let mut body: ParsedBoard = Vec::with_capacity(lines.len());
        for (row_idx, line) in lines.iter().enumerate() {
            let mut row: Vec<TileKind> = Vec::with_capacity(max_width);
            for (col_idx, ch) in line.chars().enumerate() {
                row.push(Self::tile_kind_from_char(ch, row_idx, col_idx)?);
            }
            // Board data is always width-normalized: shorter rows are padded with floor tiles. See
            // `GameBoard` docs.
            row.resize(max_width, TileKind::Floor);
            body.push(row);
        }

        Ok(body)
    }

    fn tile_kind_from_char(
        c: char, row_idx: usize, col_idx: usize,
    ) -> Result<TileKind, BoardSyntaxError> {
        if c == ParserCommon::BOX || c == ParserCommon::BOX_ALT1 {
            Ok(TileKind::Box)
        } else if c == ParserCommon::BOX_ON_GOAL || c == ParserCommon::BOX_ON_GOAL_ALT1 {
            Ok(TileKind::BoxOnGoal)
        } else if c == ParserCommon::FLOOR
            || c == ParserCommon::VISIBLE_FLOOR
            || c == ParserCommon::VISIBLE_FLOOR_ALT1
        {
            Ok(TileKind::Floor)
        } else if c == ParserCommon::GOAL || c == ParserCommon::GOAL_ALT1 {
            Ok(TileKind::Goal)
        } else if c == ParserCommon::PUSHER
            || c == ParserCommon::PUSHER_ALT1
            || c == ParserCommon::PUSHER_ALT2
        {
            Ok(TileKind::Pusher)
        } else if c == ParserCommon::PUSHER_ON_GOAL
            || c == ParserCommon::PUSHER_ON_GOAL_ALT1
            || c == ParserCommon::PUSHER_ON_GOAL_ALT2
        {
            Ok(TileKind::PusherOnGoal)
        } else if c == ParserCommon::WALL {
            Ok(TileKind::Wall)
        } else {
            Err(BoardSyntaxError::new(BoardSyntaxErrorKind::IllegalCharacter {
                input: c,
                x:     col_idx,
                y:     row_idx,
            }))
        }
    }
}

pub(super) trait BoardPrinter {
    /// # Todo
    ///
    /// If there are empty rows or empty columns in the board, they should always be printed using
    /// visible (non-blank) floor character! Check that this also applies to all types currently
    /// implementing this trait. Can it be enforced in implementors? At least document what
    /// implementors of this method are expected to do.
    fn print(parsed_board: &ParsedBoard, use_visible_floor: bool) -> String {
        let retv: String = parsed_board
            .iter()
            .map(|tiles_vec| -> String {
                tiles_vec
                    .iter()
                    .map(|tile| Self::tile_kind_to_char(*tile, use_visible_floor))
                    .collect()
            })
            .map(|s| -> String {
                if use_visible_floor {
                    s
                } else {
                    s.trim_end_matches(ParserCommon::FLOOR).to_string()
                }
            })
            .collect::<Vec<String>>()
            .join("\n");

        retv
    }

    fn tile_kind_to_char(tile: TileKind, use_visible_floor: bool) -> char {
        match tile {
            TileKind::Box => ParserCommon::BOX,
            TileKind::BoxOnGoal => ParserCommon::BOX_ON_GOAL,
            TileKind::Pusher => ParserCommon::PUSHER,
            TileKind::PusherOnGoal => ParserCommon::PUSHER_ON_GOAL,
            TileKind::Goal => ParserCommon::GOAL,
            TileKind::Wall => ParserCommon::WALL,
            TileKind::Floor => {
                if use_visible_floor {
                    ParserCommon::VISIBLE_FLOOR
                } else {
                    ParserCommon::FLOOR
                }
            }
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(super) struct BoardRect {
    pub(super) left:   usize,
    pub(super) top:    usize,
    pub(super) width:  usize,
    pub(super) height: usize,
}

fn to_i64(value: usize) -> i64 { i64::try_from(value).unwrap_or(i64::MAX) }

fn copied_rect(
    body: &ParsedBoard, source: BoardRect, destination_left: usize, destination_top: usize,
) -> ParsedBoard {
    assert_width_normalized(body);
    let body_width = body.first().map_or(0, Vec::len);
    assert!(source.left.saturating_add(source.width) <= body_width);
    assert!(source.top.saturating_add(source.height) <= body.len());

    if source.width == 0 || source.height == 0 {
        return ParsedBoard::new();
    }

    let destination_width = destination_left.saturating_add(source.width);
    let destination_height = destination_top.saturating_add(source.height);
    let mut destination = vec![vec![TileKind::Floor; destination_width]; destination_height];

    for (source_row, destination_row) in body
        .iter()
        .skip(source.top)
        .take(source.height)
        .zip(destination.iter_mut().skip(destination_top))
    {
        destination_row[destination_left..destination_left + source.width]
            .copy_from_slice(&source_row[source.left..source.left + source.width]);
    }

    destination
}

fn best_crop_offset(tessellation: Tessellation, source: BoardRect) -> (usize, usize) {
    let mut best: Option<(usize, usize, usize)> = None;

    for (extra_left, extra_top) in [(0_usize, 0_usize), (1, 0), (0, 1), (1, 1)] {
        let dx = to_i64(extra_left) - to_i64(source.left);
        let dy = to_i64(extra_top) - to_i64(source.top);
        if !tessellation.is_rigid_translation(dx, dy) {
            continue;
        }

        let area = source
            .width
            .saturating_add(extra_left)
            .saturating_mul(source.height.saturating_add(extra_top));
        if best.is_none_or(|(_, _, best_area)| area < best_area) {
            best = Some((extra_left, extra_top, area));
        }
    }

    // Every supported integer translation lattice has period at most two on each axis.
    best.map_or((0, 0), |(extra_left, extra_top, _)| (extra_left, extra_top))
}

/// Resizes boards in one batch while preserving the tessellation's tile geometry.
pub(super) trait BoardResizer {
    const TESSELLATION: Tessellation;

    fn width(body: &ParsedBoard) -> usize {
        assert_width_normalized(body);
        if body.is_empty() { 0 } else { body[0].len() }
    }

    fn height(body: &ParsedBoard) -> usize {
        assert_width_normalized(body);

        body.len()
    }

    fn add_rows_top(body: &mut ParsedBoard, count: usize) {
        let source = BoardRect {
            left:   0,
            top:    0,
            width:  Self::width(body),
            height: Self::height(body),
        };
        let extra_left = usize::from(!Self::TESSELLATION.is_rigid_translation(0, to_i64(count)));
        *body = copied_rect(body, source, extra_left, count);
    }

    fn add_rows_bottom(body: &mut ParsedBoard, count: usize) {
        let width = Self::width(body);
        body.extend(std::iter::repeat_n(vec![TileKind::Floor; width], count));
    }

    fn add_columns_left(body: &mut ParsedBoard, count: usize) {
        let source = BoardRect {
            left:   0,
            top:    0,
            width:  Self::width(body),
            height: Self::height(body),
        };
        let extra_top = usize::from(!Self::TESSELLATION.is_rigid_translation(to_i64(count), 0));
        *body = copied_rect(body, source, count, extra_top);
    }

    fn add_columns_right(body: &mut ParsedBoard, count: usize) {
        assert_width_normalized(body);
        let new_width = Self::width(body).saturating_add(count);
        for row in body {
            row.resize(new_width, TileKind::Floor);
        }
    }

    fn remove_rows_top(body: &mut ParsedBoard, count: usize) {
        let count = count.min(Self::height(body));
        if count == 0 {
            return;
        }
        let source = BoardRect {
            left:   0,
            top:    count,
            width:  Self::width(body),
            height: Self::height(body) - count,
        };
        let extra_left = usize::from(!Self::TESSELLATION.is_rigid_translation(0, -to_i64(count)));
        *body = copied_rect(body, source, extra_left, 0);
    }

    fn remove_rows_bottom(body: &mut ParsedBoard, count: usize) {
        assert_width_normalized(body);
        body.truncate(body.len().saturating_sub(count));
    }

    fn remove_columns_left(body: &mut ParsedBoard, count: usize) {
        let width = Self::width(body);
        let count = count.min(width);
        if count == 0 {
            return;
        }
        let source = BoardRect {
            left:   count,
            top:    0,
            width:  width.saturating_sub(count),
            height: Self::height(body),
        };
        let extra_top = usize::from(!Self::TESSELLATION.is_rigid_translation(-to_i64(count), 0));
        *body = copied_rect(body, source, 0, extra_top);
    }

    fn remove_columns_right(body: &mut ParsedBoard, count: usize) {
        assert_width_normalized(body);
        let new_width = Self::width(body).saturating_sub(count);
        for row in body {
            row.truncate(new_width);
        }
    }

    fn add_rows(body: &mut ParsedBoard, edge: HorizontalEdge, count: usize) -> usize {
        if Self::width(body) == 0 || count == 0 {
            return 0;
        }
        match edge {
            HorizontalEdge::Top => Self::add_rows_top(body, count),
            HorizontalEdge::Bottom => Self::add_rows_bottom(body, count),
        }
        count
    }

    /// Removing more rows than board has removes all of them.
    fn remove_rows(body: &mut ParsedBoard, edge: HorizontalEdge, count: usize) -> usize {
        let count = count.min(Self::height(body));
        if count == 0 {
            return 0;
        }
        match edge {
            HorizontalEdge::Top => Self::remove_rows_top(body, count),
            HorizontalEdge::Bottom => Self::remove_rows_bottom(body, count),
        }
        count
    }

    fn add_columns(body: &mut ParsedBoard, edge: VerticalEdge, count: usize) -> usize {
        if Self::height(body) == 0 || count == 0 {
            return 0;
        }
        match edge {
            VerticalEdge::Left => Self::add_columns_left(body, count),
            VerticalEdge::Right => Self::add_columns_right(body, count),
        }
        count
    }

    /// Removing more columns than board has removes all of them, leaving rows of zero length.
    /// [`GameBoard`](crate::GameBoard) collapses those into the empty board.
    fn remove_columns(body: &mut ParsedBoard, edge: VerticalEdge, count: usize) -> usize {
        let count = count.min(Self::width(body));
        if count == 0 {
            return 0;
        }
        match edge {
            VerticalEdge::Left => Self::remove_columns_left(body, count),
            VerticalEdge::Right => Self::remove_columns_right(body, count),
        }
        count
    }

    fn crop(body: &mut ParsedBoard, source: BoardRect) {
        let (extra_left, extra_top) = best_crop_offset(Self::TESSELLATION, source);
        *body = copied_rect(body, source, extra_left, extra_top);
    }

    fn trim(body: &mut ParsedBoard) {
        assert_width_normalized(body);

        let mut left = Self::width(body);
        let mut top = Self::height(body);
        let mut right = 0;
        let mut bottom = 0;
        let mut found = false;

        for (y, row) in body.iter().enumerate() {
            for (x, tile) in row.iter().enumerate() {
                if !tile.is_empty_floor() {
                    found = true;
                    left = left.min(x);
                    top = top.min(y);
                    right = right.max(x);
                    bottom = bottom.max(y);
                }
            }
        }

        if !found {
            body.clear();
            return;
        }

        Self::crop(
            body,
            BoardRect {
                left,
                top,
                width: right - left + 1,
                height: bottom - top + 1,
            },
        );
    }
}

#[cfg(test)]
mod tests {
    use std::collections::{HashMap, HashSet};

    use indoc::indoc;

    use super::*;
    use crate::{GameBoard, Size2D};

    /// Board data invariant: all rows have exactly `width()` tiles and a board with no columns is
    /// the empty board.
    fn assert_invariant(board: &GameBoard) {
        assert!(
            board.data.iter().all(|row| row.len() == board.width()),
            "rows are not width-normalized: {:?}",
            board.data
        );
        assert_eq!(
            board.width() == 0,
            board.height() == 0,
            "board is {}x{}, but a board with no columns must have no rows",
            board.width(),
            board.height()
        );
        assert_eq!(board.iter().count(), board.width() * board.height());
    }

    fn assert_empty(board: &GameBoard) {
        assert_invariant(board);
        assert_eq!(board.width(), 0);
        assert_eq!(board.height(), 0);
        assert!(board.data.is_empty());
        assert!(board.iter().next().is_none());
    }

    fn content_signature(board: &GameBoard) -> Vec<(usize, usize, TileKind)> {
        let non_floor: Vec<_> = board
            .iter()
            .filter(|(_, tile)| *tile != TileKind::Floor)
            .collect();
        let min_x = non_floor.iter().map(|((x, _), _)| *x).min().unwrap_or(0);
        let min_y = non_floor.iter().map(|((_, y), _)| *y).min().unwrap_or(0);
        non_floor
            .into_iter()
            .map(|((x, y), tile)| (x - min_x, y - min_y, tile))
            .collect()
    }

    fn adjacency_signature(
        board: &GameBoard, markers: &[TileKind],
    ) -> Vec<(TileKind, HashSet<TileKind>)> {
        markers
            .iter()
            .map(|marker| {
                let (position, _) = board.iter().find(|(_, tile)| *tile == *marker).unwrap();
                let neighbors = board
                    .tessellation()
                    .known_directions()
                    .iter()
                    .filter_map(|direction| {
                        board.tessellation().neighbor(
                            position.0,
                            position.1,
                            *direction,
                            board.width(),
                            board.height(),
                        )
                    })
                    .map(|neighbor| board[neighbor])
                    .filter(|tile| *tile != TileKind::Floor)
                    .collect();
                (*marker, neighbors)
            })
            .collect()
    }

    /// The default `BoardParser::parse` / `BoardPrinter::print` bodies, exercised through
    /// Sokoban - the tessellation that overrides nothing.
    mod test_parsing {
        use super::*;

        #[test]
        fn it_carefully_preserves_original_newlines() -> Result<(), BoardSyntaxError> {
            let src: String = [
                " ##########\n    \n\n",
                " ## @ *   #\n\n",
                "##  $ ####\n\n",
                "# $.+ #\n\n",
                "#######\n\n",
            ]
            .join("");

            let result = indoc! {"-##########
                              -----------
                              -----------
                              -##-@-*---#
                              -----------
                              ##--$-####-
                              -----------
                              #-$.+-#----
                              -----------
                              #######----"};

            let board = GameBoard::parsed(&src, Tessellation::Sokoban)?;
            assert_eq!(board.width(), 11);
            assert_eq!(board.height(), 10);
            assert_eq!(board.printed(true), result);

            Ok(())
        }

        #[test]
        fn it_correctly_parses_board_with_internal_blank_rows() -> Result<(), BoardSyntaxError> {
            // ```
            // ::   The first and the last non-empty square in each row  ::
            // ::   must be a wall or a box on a goal. An empty interior ::
            // ::   row is written with at least one "-" or "_".         ::
            // ```
            //
            // Notice that our parser is correct even without that one "-" or "_"

            let src1: String = [
                " ##########\n    \n",
                " ## @ *   #\n",
                "##  $ ####\n",
                "# $.+ #\n",
                "#######\n",
            ]
            .join("");

            let src2: String = [
                " ##########\n  - \n",
                " ## @ *   #\n",
                "##  $ ####\n",
                "# $.+ #\n",
                "#######\n",
            ]
            .join("");

            let result = indoc! {"-##########
                              -----------
                              -##-@-*---#
                              ##--$-####-
                              #-$.+-#----
                              #######----"};

            for src in [src1, src2] {
                let board = GameBoard::parsed(&src, Tessellation::Sokoban)?;
                assert_eq!(board.width(), 11);
                assert_eq!(board.height(), 6);
                assert_eq!(board.printed(true), result);
            }

            Ok(())
        }

        #[test]
        fn it_parses_rle_encoded_board() -> Result<(), BoardSyntaxError> {
            // ```
            // ::   The first and the last non-empty square in each row  ::
            // ::   must be a wall or a box on a goal. An empty interior ::
            // ::   row is written with at least one "-" or "_".         ::
            // ```
            //
            // Notice that our parser can go even without that on "-" or "_"

            let src1: String = [
                " ##########   |",
                " ## @ *   #|",
                "##  $ ####|",
                "# $.+ #|||",
                "#######   |",
            ]
            .join("");

            let src2: String = [
                " ##########   |",
                " ## @ *   #|",
                "##  $ ####|",
                "# $.+ #|||",
                "#######   |",
            ]
            .join("");

            let result = indoc! {"-##########---
                              -##-@-*---#---
                              ##--$-####----
                              #-$.+-#-------
                              --------------
                              --------------
                              #######-------"};

            for src in [src1, src2] {
                let board = GameBoard::parsed(&src, Tessellation::Sokoban)?;
                assert_eq!(board.width(), 14);
                assert_eq!(board.height(), 7);
                assert_eq!(board.printed(true), result);
            }

            Ok(())
        }
    }

    /// Return values of the `BoardResizer` entry points: additions apply `count` exactly,
    /// removals saturate at what is available.
    mod test_resizing {
        use super::*;

        #[test]
        fn top_and_left_resizing_applies_the_exact_count() {
            for tessellation in Tessellation::ALL {
                let mut rows = GameBoard::new(5, 5, tessellation);
                assert_eq!(rows.remove_rows(HorizontalEdge::Top, 1), 1, "{tessellation:?}");

                let mut columns = GameBoard::new(5, 5, tessellation);
                assert_eq!(columns.add_columns(VerticalEdge::Left, 1), 1, "{tessellation:?}");
            }
        }

        #[test]
        fn bottom_and_right_resizing_applies_the_exact_available_count() {
            let mut board = GameBoard::new(5, 5, Tessellation::Octoban);
            assert_eq!(board.add_rows(HorizontalEdge::Bottom, 1), 1);
            assert_eq!(board.add_columns(VerticalEdge::Right, 3), 3);
            assert_eq!(board.remove_rows(HorizontalEdge::Bottom, 2), 2);
            assert_eq!(board.remove_columns(VerticalEdge::Right, 42), 8);
        }

        #[test]
        fn saturated_removal_does_not_pad_an_empty_result() {
            for tessellation in Tessellation::ALL {
                let mut rows = GameBoard::new(3, 2, tessellation);
                assert_eq!(rows.remove_rows(HorizontalEdge::Top, 42), 2);
                assert_empty(&rows);

                let mut columns = GameBoard::new(3, 2, tessellation);
                assert_eq!(columns.remove_columns(VerticalEdge::Left, 42), 3);
                assert_empty(&columns);
            }
        }
    }

    /// A Top or Left edit shifts existing content, so on a parity-sensitive tiling it must be
    /// compensated with one perpendicular padding line. Trioban and Octoban share the rule -
    /// `is_rigid_translation` is `(dx + dy) % 2 == 0` for both - which is why these sweep the
    /// two together rather than living beside either tessellation.
    ///
    /// See `doc/dev-notes/board-geometry-and-transformations.md` sections 6 and 7.
    mod test_parity_padding {
        use super::*;

        #[test]
        fn odd_top_resizing_adds_one_left_column_on_trioban_and_octoban()
        -> Result<(), BoardSyntaxError> {
            let markers = [
                TileKind::Wall,
                TileKind::Pusher,
                TileKind::Box,
                TileKind::Goal,
            ];

            for tessellation in [Tessellation::Trioban, Tessellation::Octoban] {
                let mut added = GameBoard::parsed_from_tiles(&markers, 2, 2, tessellation)?;
                assert_eq!(added.add_rows(HorizontalEdge::Top, 1), 1);
                assert_eq!(added.size(), Size2D::new(3, 3));
                for y in 0..2 {
                    for x in 0..2 {
                        assert_eq!(added[(x + 1, y + 1)], markers[y * 2 + x]);
                    }
                }

                let mut removed = GameBoard::new(2, 3, tessellation);
                for (index, marker) in markers.iter().enumerate() {
                    removed[(index % 2, index / 2 + 1)] = *marker;
                }
                assert_eq!(removed.remove_rows(HorizontalEdge::Top, 1), 1);
                assert_eq!(removed.size(), Size2D::new(3, 2));
                for y in 0..2 {
                    for x in 0..2 {
                        assert_eq!(removed[(x + 1, y)], markers[y * 2 + x]);
                    }
                }
            }

            Ok(())
        }

        #[test]
        fn odd_left_resizing_adds_one_top_row_on_trioban_and_octoban()
        -> Result<(), BoardSyntaxError> {
            let markers = [
                TileKind::Wall,
                TileKind::Pusher,
                TileKind::Box,
                TileKind::Goal,
            ];

            for tessellation in [Tessellation::Trioban, Tessellation::Octoban] {
                let mut added = GameBoard::parsed_from_tiles(&markers, 2, 2, tessellation)?;
                assert_eq!(added.add_columns(VerticalEdge::Left, 1), 1);
                assert_eq!(added.size(), Size2D::new(3, 3));
                for y in 0..2 {
                    for x in 0..2 {
                        assert_eq!(added[(x + 1, y + 1)], markers[y * 2 + x]);
                    }
                }

                let mut removed = GameBoard::new(3, 2, tessellation);
                for (index, marker) in markers.iter().enumerate() {
                    removed[(index % 2 + 1, index / 2)] = *marker;
                }
                assert_eq!(removed.remove_columns(VerticalEdge::Left, 1), 1);
                assert_eq!(removed.size(), Size2D::new(2, 3));
                for y in 0..2 {
                    for x in 0..2 {
                        assert_eq!(removed[(x, y + 1)], markers[y * 2 + x]);
                    }
                }
            }

            Ok(())
        }

        #[test]
        fn even_top_and_left_resizing_needs_no_perpendicular_padding() {
            for tessellation in [Tessellation::Trioban, Tessellation::Octoban] {
                let mut rows = GameBoard::new(3, 2, tessellation);
                assert_eq!(rows.add_rows(HorizontalEdge::Top, 2), 2);
                assert_eq!(rows.size(), Size2D::new(3, 4));

                let mut columns = GameBoard::new(3, 2, tessellation);
                assert_eq!(columns.add_columns(VerticalEdge::Left, 2), 2);
                assert_eq!(columns.size(), Size2D::new(5, 2));
            }
        }

        #[test]
        fn even_batch_differs_from_two_odd_resizes_on_trioban_and_octoban()
        -> Result<(), BoardSyntaxError> {
            let markers = [
                TileKind::Wall,
                TileKind::Pusher,
                TileKind::Box,
                TileKind::Goal,
            ];

            for tessellation in [Tessellation::Trioban, Tessellation::Octoban] {
                let original = GameBoard::parsed_from_tiles(&markers, 2, 2, tessellation)?;
                let mut batched = original.clone();
                let mut sequential = original;

                batched.add_rows(HorizontalEdge::Top, 2);
                sequential.add_rows(HorizontalEdge::Top, 1);
                sequential.add_rows(HorizontalEdge::Top, 1);

                assert_eq!(batched.size(), Size2D::new(2, 4));
                assert_eq!(sequential.size(), Size2D::new(4, 4));
                assert_eq!(content_signature(&batched), content_signature(&sequential));

                let original = GameBoard::parsed_from_tiles(&markers, 2, 2, tessellation)?;
                let mut batched = original.clone();
                let mut sequential = original;
                batched.add_columns(VerticalEdge::Left, 2);
                sequential.add_columns(VerticalEdge::Left, 1);
                sequential.add_columns(VerticalEdge::Left, 1);

                assert_eq!(batched.size(), Size2D::new(4, 2));
                assert_eq!(sequential.size(), Size2D::new(4, 4));
                assert_eq!(content_signature(&batched), content_signature(&sequential));
            }

            Ok(())
        }

        #[test]
        fn perpendicular_padding_depends_on_dimensions_not_content() {
            for tessellation in [Tessellation::Trioban, Tessellation::Octoban] {
                let mut odd_rows = GameBoard::new(3, 2, tessellation);
                let mut even_rows = odd_rows.clone();
                let mut odd_columns = odd_rows.clone();

                odd_rows.add_rows(HorizontalEdge::Top, 1);
                even_rows.add_rows(HorizontalEdge::Top, 2);
                odd_columns.add_columns(VerticalEdge::Left, 1);

                assert_eq!(odd_rows.size(), Size2D::new(4, 3));
                assert_eq!(even_rows.size(), Size2D::new(3, 4));
                assert_eq!(odd_columns.size(), Size2D::new(4, 3));
                assert!(odd_rows.is_blank() && even_rows.is_blank() && odd_columns.is_blank());
            }
        }

        #[test]
        fn odd_resizing_still_compensates_when_one_source_dimension_is_one() {
            for tessellation in [Tessellation::Trioban, Tessellation::Octoban] {
                let mut added_rows = GameBoard::new(3, 1, tessellation);
                added_rows.add_rows(HorizontalEdge::Top, 1);
                assert_eq!(added_rows.size(), Size2D::new(4, 2));

                let mut removed_rows = GameBoard::new(3, 2, tessellation);
                removed_rows.remove_rows(HorizontalEdge::Top, 1);
                assert_eq!(removed_rows.size(), Size2D::new(4, 1));

                let mut added_columns = GameBoard::new(1, 3, tessellation);
                added_columns.add_columns(VerticalEdge::Left, 1);
                assert_eq!(added_columns.size(), Size2D::new(2, 4));

                let mut removed_columns = GameBoard::new(2, 3, tessellation);
                removed_columns.remove_columns(VerticalEdge::Left, 1);
                assert_eq!(removed_columns.size(), Size2D::new(1, 4));
            }
        }

        #[test]
        fn odd_batched_resizing_preserves_adjacency_and_tile_shapes() -> Result<(), BoardSyntaxError>
        {
            let markers = [
                TileKind::Wall,
                TileKind::Pusher,
                TileKind::Box,
                TileKind::Goal,
                TileKind::BoxOnGoal,
                TileKind::PusherOnGoal,
            ];

            for tessellation in [Tessellation::Trioban, Tessellation::Octoban] {
                let original = GameBoard::parsed_from_tiles(&markers, 3, 2, tessellation)?;
                let expected_adjacency = adjacency_signature(&original, &markers);
                let expected_shapes: Vec<_> = original
                    .iter()
                    .map(|((x, y), tile)| (tile, tessellation.tile_shape_from_pos(x, y)))
                    .collect();

                for add_top in [true, false] {
                    let mut resized = original.clone();
                    let operation = if add_top {
                        resized.add_rows(HorizontalEdge::Top, 1);
                        "Top"
                    } else {
                        resized.add_columns(VerticalEdge::Left, 1);
                        "Left"
                    };

                    let actual_shapes: Vec<_> = resized
                        .iter()
                        .filter(|(_, tile)| *tile != TileKind::Floor)
                        .map(|((x, y), tile)| (tile, tessellation.tile_shape_from_pos(x, y)))
                        .collect();
                    assert_eq!(actual_shapes, expected_shapes, "{tessellation:?} {operation}");
                    assert_eq!(
                        adjacency_signature(&resized, &markers),
                        expected_adjacency,
                        "{tessellation:?} {operation}"
                    );
                }
            }

            Ok(())
        }

        #[test]
        fn every_trioban_and_octoban_top_or_left_batch_is_rigid_and_injective() {
            #[derive(Debug, Copy, Clone)]
            enum Operation {
                AddTop,
                RemoveTop,
                AddLeft,
                RemoveLeft,
            }

            let sizes = [(1, 1), (1, 2), (2, 1), (3, 4), (4, 3)];
            let operations = [
                Operation::AddTop,
                Operation::RemoveTop,
                Operation::AddLeft,
                Operation::RemoveLeft,
            ];

            for tessellation in [Tessellation::Trioban, Tessellation::Octoban] {
                for (width, height) in sizes {
                    for count in [1, 2] {
                        for operation in operations {
                            let mut board = GameBoard::new(width, height, tessellation);
                            let mut positions = HashMap::new();

                            for y in 0..height {
                                for x in 0..width {
                                    let mapped = match operation {
                                        Operation::AddTop => Some((x + count % 2, y + count)),
                                        Operation::RemoveTop if y >= count.min(height) => {
                                            Some((x + count.min(height) % 2, y - count.min(height)))
                                        }
                                        Operation::AddLeft => Some((x + count, y + count % 2)),
                                        Operation::RemoveLeft if x >= count.min(width) => {
                                            Some((x - count.min(width), y + count.min(width) % 2))
                                        }
                                        Operation::RemoveTop | Operation::RemoveLeft => None,
                                    };
                                    if let Some(mapped) = mapped {
                                        positions.insert((x, y), mapped);
                                    }
                                }
                            }

                            match operation {
                                Operation::AddTop => {
                                    board.add_rows(HorizontalEdge::Top, count);
                                }
                                Operation::RemoveTop => {
                                    board.remove_rows(HorizontalEdge::Top, count);
                                }
                                Operation::AddLeft => {
                                    board.add_columns(VerticalEdge::Left, count);
                                }
                                Operation::RemoveLeft => {
                                    board.remove_columns(VerticalEdge::Left, count);
                                }
                            }

                            let image: HashSet<_> = positions.values().copied().collect();
                            assert_eq!(image.len(), positions.len());
                            for (source, destination) in &positions {
                                assert_eq!(
                                    tessellation.tile_shape_from_pos(source.0, source.1),
                                    tessellation.tile_shape_from_pos(destination.0, destination.1),
                                    "{tessellation:?} {width}x{height} {operation:?} {count}"
                                );

                                let mapped_neighbors: HashSet<_> = tessellation
                                    .known_directions()
                                    .iter()
                                    .filter_map(|direction| {
                                        tessellation
                                            .neighbor(source.0, source.1, *direction, width, height)
                                    })
                                    .filter_map(|neighbor| positions.get(&neighbor).copied())
                                    .collect();
                                let destination_neighbors: HashSet<_> = tessellation
                                    .known_directions()
                                    .iter()
                                    .filter_map(|direction| {
                                        tessellation.neighbor(
                                            destination.0,
                                            destination.1,
                                            *direction,
                                            board.width(),
                                            board.height(),
                                        )
                                    })
                                    .filter(|neighbor| image.contains(neighbor))
                                    .collect();
                                assert_eq!(
                                    mapped_neighbors, destination_neighbors,
                                    "{tessellation:?} {width}x{height} {operation:?} {count}: \
                                 {source:?} -> {destination:?}"
                                );
                            }
                        }
                    }
                }
            }
        }

        #[test]
        fn resized_trioban_and_octoban_round_trip_through_text() -> Result<(), BoardSyntaxError> {
            let markers = [
                TileKind::Wall,
                TileKind::Pusher,
                TileKind::Box,
                TileKind::Goal,
                TileKind::BoxOnGoal,
                TileKind::PusherOnGoal,
            ];

            for tessellation in [Tessellation::Trioban, Tessellation::Octoban] {
                let mut board = GameBoard::parsed_from_tiles(&markers, 3, 2, tessellation)?;
                board.add_rows(HorizontalEdge::Top, 1);
                board.add_columns(VerticalEdge::Left, 1);

                assert_eq!(GameBoard::parsed(&board.printed(true), tessellation)?, board);
            }

            Ok(())
        }
    }

    /// `BoardResizer::trim` crops all four edges together and picks the smallest rigid anchor,
    /// adding a column when the areas tie.
    mod test_trimming {
        use super::*;

        #[test]
        fn it_trims_empty_outer_rows_and_columns() -> Result<(), BoardSyntaxError> {
            let src = indoc! {"------------------------
                           ------------------------
                           ------#####-------------
                           ------#---#-------------
                           ------#$--#-------------
                           ----###--$##------------
                           ----#--$-$-#------------
                           --###-#-##-#---######---
                           --#---#-##-#####--..#---
                           --#-$--$----------..#---
                           --#####-###-#@##--..#---
                           ------#-----#########---
                           ------#######-----------
                           ------------------------
                           ------------------------
                           ------------------------"};

            let result = indoc! {"----#####----------
                              ----#---#----------
                              ----#$--#----------
                              --###--$##---------
                              --#--$-$-#---------
                              ###-#-##-#---######
                              #---#-##-#####--..#
                              #-$--$----------..#
                              #####-###-#@##--..#
                              ----#-----#########
                              ----#######--------"};

            let mut board = GameBoard::parsed(src, Tessellation::Sokoban)?;

            board.trim();

            assert_eq!(board.printed(true), result);
            assert_eq!(board.width(), 19);
            assert_eq!(board.height(), 11);

            Ok(())
        }

        #[test]
        fn trim_keeps_goal_only_and_pusher_only_edge_lines() -> Result<(), BoardSyntaxError> {
            // Every one of these is the whole board, so nothing may be cropped.
            for source in ["@--#", ".--#", "#--@", "#--.", "@", ".", "$", "*", "+"] {
                let mut board = GameBoard::parsed(source, Tessellation::Sokoban)?;
                board.trim();
                assert_eq!(board.printed(true), source, "{source}");
            }

            let source = indoc! {"--.--
                              -----
                              -###-
                              -----"};
            let result = indoc! {"-.-
                              ---
                              ###"};
            let mut board = GameBoard::parsed(source, Tessellation::Sokoban)?;
            board.trim();
            assert_eq!(board.printed(true), result);

            Ok(())
        }

        #[test]
        fn trim_preserves_tile_shapes_on_parity_sensitive_boards() {
            for tessellation in [Tessellation::Trioban, Tessellation::Octoban] {
                let mut board = GameBoard::new(6, 6, tessellation);
                board[(2, 2)] = TileKind::Wall;
                board[(3, 2)] = TileKind::Box;
                board[(2, 3)] = TileKind::BoxOnGoal;
                board[(4, 3)] = TileKind::Goal;
                board[(3, 4)] = TileKind::Pusher;
                let before: Vec<_> = board
                    .iter()
                    .filter(|(_, tile)| !tile.is_empty_floor())
                    .map(|((x, y), tile)| (tile, tessellation.tile_shape_from_pos(x, y)))
                    .collect();

                board.trim();

                let after: Vec<_> = board
                    .iter()
                    .filter(|(_, tile)| !tile.is_empty_floor())
                    .map(|((x, y), tile)| (tile, tessellation.tile_shape_from_pos(x, y)))
                    .collect();
                assert_eq!(after, before, "{tessellation:?}");
            }
        }

        #[test]
        fn trim_chooses_the_smallest_parity_compensation() {
            for tessellation in [Tessellation::Trioban, Tessellation::Octoban] {
                let mut wide = GameBoard::new(8, 4, tessellation);
                wide[(1, 0)] = TileKind::Wall;
                wide[(5, 1)] = TileKind::BoxOnGoal;
                let wide_shape = tessellation.tile_shape_from_pos(1, 0);
                wide.trim();
                assert_eq!(wide.size(), Size2D::new(6, 2));
                assert_eq!(wide[(1, 0)], TileKind::Wall);
                assert_eq!(tessellation.tile_shape_from_pos(1, 0), wide_shape);

                let mut tall = GameBoard::new(5, 8, tessellation);
                tall[(1, 0)] = TileKind::Wall;
                tall[(2, 4)] = TileKind::BoxOnGoal;
                let tall_shape = tessellation.tile_shape_from_pos(1, 0);
                tall.trim();
                assert_eq!(tall.size(), Size2D::new(2, 6));
                assert_eq!(tall[(0, 1)], TileKind::Wall);
                assert_eq!(tessellation.tile_shape_from_pos(0, 1), tall_shape);

                let mut tied = GameBoard::new(6, 5, tessellation);
                tied[(1, 0)] = TileKind::Wall;
                tied[(3, 2)] = TileKind::BoxOnGoal;
                tied.trim();
                assert_eq!(tied.size(), Size2D::new(4, 3));
                assert_eq!(tied[(1, 0)], TileKind::Wall);
            }
        }
    }
}