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
//! Configurations related to the
//! [dihedral group _D_<sub>8</sub>](https://en.wikipedia.org/wiki/Examples_of_groups#dihedral_group_of_order_8).
//!
//! 8 different transformations correspond to 8 elements of _D_<sub>8</sub>.
//!
//! 10 different symmetries correspond to 10 subgroups of _D_<sub>8</sub>.

use super::{Config, Coord};
use std::{
    cmp::Ordering,
    fmt::{self, Display, Formatter},
    matches,
    ops::Mul,
    str::FromStr,
    vec,
};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Transformations (rotations and reflections) after the last generation
/// in a period.
///
/// After the last generation in a period, the pattern will return to
/// the first generation, applying this transformation first,
/// and then the translation defined by `dx` and `dy`.
///
/// 8 different values correspond to 8 elements of the dihedral group
/// _D_<sub>8</sub>.
///
/// `Id` is the identity transformation.
///
/// `R` means rotations around the center of the world.
/// The number after it is the counterclockwise rotation angle in degrees.
///
/// `F` means reflections (flips).
/// The symbol after it is the axis of reflection.
///
/// Some of the transformations are only valid when the world is square.
/// and some are only valid when the world has no diagonal width.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Transform {
    /// `Id`.
    ///
    /// Identity transformation.
    #[default]
    Id,
    /// `R90`.
    ///
    /// 90° rotation counterclockwise.
    ///
    /// Requires the world to be square and have no diagonal width.
    #[cfg_attr(feature = "serde", serde(rename(serialize = "R90")))]
    #[cfg_attr(feature = "serde", serde(alias = "R90"))]
    Rotate90,
    /// `R180`.
    ///
    /// 180° rotation counterclockwise.
    #[cfg_attr(feature = "serde", serde(rename(serialize = "R180")))]
    #[cfg_attr(feature = "serde", serde(alias = "R180"))]
    Rotate180,
    /// `R270`.
    ///
    /// 270° rotation counterclockwise.
    ///
    /// Requires the world to be square and have no diagonal width.
    #[cfg_attr(feature = "serde", serde(rename(serialize = "R270")))]
    #[cfg_attr(feature = "serde", serde(alias = "R270"))]
    Rotate270,
    /// `F-`.
    ///
    /// Reflection across the middle row.
    ///
    /// Requires the world to have no diagonal width.
    #[cfg_attr(feature = "serde", serde(rename(serialize = "F-")))]
    #[cfg_attr(feature = "serde", serde(alias = "F-"))]
    FlipRow,
    /// `F|`.
    ///
    /// Reflection across the middle column.
    ///
    /// Requires the world to have no diagonal width.
    #[cfg_attr(feature = "serde", serde(rename(serialize = "F|")))]
    #[cfg_attr(feature = "serde", serde(alias = "F|"))]
    FlipCol,
    /// `F\`.
    ///
    /// Reflection across the diagonal.
    ///
    /// Requires the world to be square.
    #[cfg_attr(feature = "serde", serde(rename(serialize = "F\\")))]
    #[cfg_attr(feature = "serde", serde(alias = "F\\"))]
    FlipDiag,
    /// `F/`.
    ///
    /// Reflection across the antidiagonal.
    ///
    /// Requires the world to be square.
    #[cfg_attr(feature = "serde", serde(rename(serialize = "F/")))]
    #[cfg_attr(feature = "serde", serde(alias = "F/"))]
    FlipAntidiag,
}

impl FromStr for Transform {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "Id" => Ok(Self::Id),
            "R90" => Ok(Self::Rotate90),
            "R180" => Ok(Self::Rotate180),
            "R270" => Ok(Self::Rotate270),
            "F-" => Ok(Self::FlipRow),
            "F|" => Ok(Self::FlipCol),
            "F\\" => Ok(Self::FlipDiag),
            "F/" => Ok(Self::FlipAntidiag),
            _ => Err(String::from("Invalid Transform")),
        }
    }
}

impl Display for Transform {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
        let s = match self {
            Self::Id => "Id",
            Self::Rotate90 => "R90",
            Self::Rotate180 => "R180",
            Self::Rotate270 => "R270",
            Self::FlipRow => "F-",
            Self::FlipCol => "F|",
            Self::FlipDiag => "F\\",
            Self::FlipAntidiag => "F/",
        };
        write!(f, "{s}")?;
        Ok(())
    }
}

impl Mul for Transform {
    type Output = Self;

    fn mul(self, rhs: Self) -> Self {
        match (self, rhs) {
            (Self::Id, Self::Id)
            | (Self::Rotate90, Self::Rotate270)
            | (Self::Rotate180, Self::Rotate180)
            | (Self::Rotate270, Self::Rotate90)
            | (Self::FlipRow, Self::FlipRow)
            | (Self::FlipCol, Self::FlipCol)
            | (Self::FlipDiag, Self::FlipDiag)
            | (Self::FlipAntidiag, Self::FlipAntidiag) => Self::Id,
            (Self::Id, Self::Rotate90)
            | (Self::Rotate90, Self::Id)
            | (Self::Rotate180, Self::Rotate270)
            | (Self::Rotate270, Self::Rotate180)
            | (Self::FlipRow, Self::FlipAntidiag)
            | (Self::FlipCol, Self::FlipDiag)
            | (Self::FlipDiag, Self::FlipRow)
            | (Self::FlipAntidiag, Self::FlipCol) => Self::Rotate90,
            (Self::Id, Self::Rotate180)
            | (Self::Rotate90, Self::Rotate90)
            | (Self::Rotate180, Self::Id)
            | (Self::Rotate270, Self::Rotate270)
            | (Self::FlipRow, Self::FlipCol)
            | (Self::FlipCol, Self::FlipRow)
            | (Self::FlipDiag, Self::FlipAntidiag)
            | (Self::FlipAntidiag, Self::FlipDiag) => Self::Rotate180,
            (Self::Id, Self::Rotate270)
            | (Self::Rotate90, Self::Rotate180)
            | (Self::Rotate180, Self::Rotate90)
            | (Self::Rotate270, Self::Id)
            | (Self::FlipRow, Self::FlipDiag)
            | (Self::FlipCol, Self::FlipAntidiag)
            | (Self::FlipDiag, Self::FlipCol)
            | (Self::FlipAntidiag, Self::FlipRow) => Self::Rotate270,
            (Self::Id, Self::FlipRow)
            | (Self::Rotate90, Self::FlipAntidiag)
            | (Self::Rotate180, Self::FlipCol)
            | (Self::Rotate270, Self::FlipDiag)
            | (Self::FlipRow, Self::Id)
            | (Self::FlipCol, Self::Rotate180)
            | (Self::FlipDiag, Self::Rotate90)
            | (Self::FlipAntidiag, Self::Rotate270) => Self::FlipRow,
            (Self::Id, Self::FlipCol)
            | (Self::Rotate90, Self::FlipDiag)
            | (Self::Rotate180, Self::FlipRow)
            | (Self::Rotate270, Self::FlipAntidiag)
            | (Self::FlipRow, Self::Rotate180)
            | (Self::FlipCol, Self::Id)
            | (Self::FlipDiag, Self::Rotate270)
            | (Self::FlipAntidiag, Self::Rotate90) => Self::FlipCol,
            (Self::Id, Self::FlipDiag)
            | (Self::Rotate90, Self::FlipRow)
            | (Self::Rotate180, Self::FlipAntidiag)
            | (Self::Rotate270, Self::FlipCol)
            | (Self::FlipRow, Self::Rotate270)
            | (Self::FlipCol, Self::Rotate90)
            | (Self::FlipDiag, Self::Id)
            | (Self::FlipAntidiag, Self::Rotate180) => Self::FlipDiag,
            (Self::Id, Self::FlipAntidiag)
            | (Self::Rotate90, Self::FlipCol)
            | (Self::Rotate180, Self::FlipDiag)
            | (Self::Rotate270, Self::FlipRow)
            | (Self::FlipRow, Self::Rotate90)
            | (Self::FlipCol, Self::Rotate270)
            | (Self::FlipDiag, Self::Rotate180)
            | (Self::FlipAntidiag, Self::Id) => Self::FlipAntidiag,
        }
    }
}

impl Transform {
    pub const ALL: [Self; 8] = [
        Self::Id,
        Self::Rotate90,
        Self::Rotate180,
        Self::Rotate270,
        Self::FlipRow,
        Self::FlipCol,
        Self::FlipDiag,
        Self::FlipAntidiag,
    ];

    /// Whether this transformation requires the world to be square.
    ///
    /// Returns `true` for `R90`, `R270`, `F\` and `F/`.
    pub const fn require_square_world(self) -> bool {
        !self.is_in(Symmetry::D4Ortho)
    }

    /// Whether this transformation requires the world to have no diagonal width.
    ///
    /// Returns `true` for `R90`, `R270`, `F-` and `F|`.
    pub const fn require_no_diagonal_width(self) -> bool {
        !self.is_in(Symmetry::D4Diag)
    }

    /// The order of this transformation in the symmetry group.
    pub const fn order(self) -> u8 {
        match self {
            Self::Id => 1,
            Self::Rotate90 | Self::Rotate270 => 4,
            _ => 2,
        }
    }

    /// The inverse of this transformation.
    pub const fn inverse(self) -> Self {
        match self {
            Self::Rotate90 => Self::Rotate270,
            Self::Rotate270 => Self::Rotate90,
            x => x,
        }
    }

    /// Whether the transformation is a member of the symmetry group,
    /// i.e., whether patterns with this symmetry are invariant under
    /// this transformation.
    pub const fn is_in(self, sym: Symmetry) -> bool {
        matches!(
            (self, sym),
            (Self::Id, _)
                | (_, Symmetry::D8)
                | (Self::Rotate90 | Self::Rotate270, Symmetry::C4)
                | (
                    Self::Rotate180,
                    Symmetry::C2 | Symmetry::C4 | Symmetry::D4Ortho | Symmetry::D4Diag
                )
                | (Self::FlipRow, Symmetry::D2Row | Symmetry::D4Ortho)
                | (Self::FlipCol, Symmetry::D2Col | Symmetry::D4Ortho)
                | (Self::FlipDiag, Symmetry::D2Diag | Symmetry::D4Diag)
                | (Self::FlipAntidiag, Symmetry::D2Antidiag | Symmetry::D4Diag),
        )
    }

    /// Apply the transformation on a coordinate.
    pub const fn act_on(self, coord: Coord, width: i32, height: i32) -> Coord {
        let (x, y, t) = coord;
        match self {
            Self::Id => (x, y, t),
            Self::Rotate90 => (y, width - 1 - x, t),
            Self::Rotate180 => (width - 1 - x, height - 1 - y, t),
            Self::Rotate270 => (height - 1 - y, x, t),
            Self::FlipRow => (x, height - 1 - y, t),
            Self::FlipCol => (width - 1 - x, y, t),
            Self::FlipDiag => (y, x, t),
            Self::FlipAntidiag => (height - 1 - y, width - 1 - x, t),
        }
    }
}

/// Symmetries of the pattern.
///
/// For each symmetry, its [symmetry group](https://en.wikipedia.org/wiki/Symmetry_group)
/// is a subgroup of the dihedral group _D_<sub>8</sub>.
/// 10 different symmetries correspond to 10 subgroups of _D_<sub>8</sub>.
///
/// The notations are stolen from Oscar Cunningham's
/// [Logic Life Search](https://github.com/OscarCunningham/logic-life-search).
/// Please see the [Life Wiki](https://conwaylife.com/wiki/Static_symmetry#Reflectional) for details.
///
/// Some of the symmetries are only valid when the world is square,
/// and some are only valid when the world has no diagonal width.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Symmetry {
    /// `C1`.
    ///
    /// No symmetry at all.
    #[default]
    C1,
    /// `C2`.
    ///
    /// Symmetry under 180° rotation.
    C2,
    /// `C4`.
    ///
    /// Symmetry under 90° rotation.
    ///
    /// Requires the world to be square and have no diagonal width.
    C4,
    /// `D2-`.
    ///
    /// Symmetry under reflection across the middle row.
    ///
    /// Requires the world to have no diagonal width.
    #[cfg_attr(feature = "serde", serde(rename(serialize = "D2-")))]
    #[cfg_attr(feature = "serde", serde(alias = "D2-"))]
    D2Row,
    /// `D2|`.
    ///
    /// Symmetry under reflection across the middle column.
    ///
    /// Requires the world to have no diagonal width.
    #[cfg_attr(feature = "serde", serde(rename(serialize = "D2|")))]
    #[cfg_attr(feature = "serde", serde(alias = "D2|"))]
    D2Col,
    /// `D2\`.
    ///
    /// Symmetry under reflection across the diagonal.
    ///
    /// Requires the world to be square.
    #[cfg_attr(feature = "serde", serde(rename(serialize = "D2\\")))]
    #[cfg_attr(feature = "serde", serde(alias = "D2\\"))]
    D2Diag,
    /// `D2/`.
    ///
    /// Symmetry under reflection across the antidiagonal.
    ///
    /// Requires the world to be square.
    #[cfg_attr(feature = "serde", serde(rename(serialize = "D2/")))]
    #[cfg_attr(feature = "serde", serde(alias = "D2/"))]
    D2Antidiag,
    /// `D4+`.
    ///
    /// Symmetry under reflections across the middle row
    /// and the middle column.
    ///
    /// Requires the world to have no diagonal width.
    #[cfg_attr(feature = "serde", serde(rename(serialize = "D4+")))]
    #[cfg_attr(feature = "serde", serde(alias = "D4+"))]
    D4Ortho,
    /// `D4X`.
    ///
    /// Symmetry under reflections across the diagonal
    /// and the antidiagonal.
    ///
    /// Requires the world to be square.
    #[cfg_attr(feature = "serde", serde(rename(serialize = "D4X")))]
    #[cfg_attr(feature = "serde", serde(alias = "D4X"))]
    D4Diag,
    /// `D8`.
    ///
    /// Symmetry under all 8 transformations.
    ///
    /// Requires the world to be square and have no diagonal width.
    D8,
}

impl FromStr for Symmetry {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "C1" => Ok(Self::C1),
            "C2" => Ok(Self::C2),
            "C4" => Ok(Self::C4),
            "D2-" => Ok(Self::D2Row),
            "D2|" => Ok(Self::D2Col),
            "D2\\" => Ok(Self::D2Diag),
            "D2/" => Ok(Self::D2Antidiag),
            "D4+" => Ok(Self::D4Ortho),
            "D4X" => Ok(Self::D4Diag),
            "D8" => Ok(Self::D8),
            _ => Err(String::from("invalid Self")),
        }
    }
}

impl Display for Symmetry {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
        let s = match self {
            Self::C1 => "C1",
            Self::C2 => "C2",
            Self::C4 => "C4",
            Self::D2Row => "D2-",
            Self::D2Col => "D2|",
            Self::D2Diag => "D2\\",
            Self::D2Antidiag => "D2/",
            Self::D4Ortho => "D4+",
            Self::D4Diag => "D4X",
            Self::D8 => "D8",
        };
        write!(f, "{s}")?;
        Ok(())
    }
}

impl PartialOrd for Symmetry {
    /// We say that symmetry `a` is smaller than symmetry `b`,
    /// when the symmetry group of `a` is a subgroup of that of `b`,
    /// i.e., all patterns with symmetry `b` also have symmetry `a`.
    ///
    /// For example, `Symmetry::C1` is smaller than all other symmetries.
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        if self == other {
            Some(Ordering::Equal)
        } else if self.is_subgroup_of(*other) {
            Some(Ordering::Less)
        } else if other.is_subgroup_of(*self) {
            Some(Ordering::Greater)
        } else {
            None
        }
    }
}

impl Symmetry {
    pub const ALL: [Self; 10] = [
        Self::C1,
        Self::C2,
        Self::C4,
        Self::D2Col,
        Self::D2Row,
        Self::D2Diag,
        Self::D2Antidiag,
        Self::D4Diag,
        Self::D4Ortho,
        Self::D8,
    ];

    /// Whether the symmetry group of `self` is a subgroup of that of `other`,
    /// i.e., all patterns with symmetry `other` also have symmetry `self`.
    ///
    /// For example, the symmetry group of `Symmetry::C1` is a subgroup of
    /// that of all other symmetries.
    pub const fn is_subgroup_of(self, other: Self) -> bool {
        matches!(
            (self, other),
            (Self::C1, _)
                | (_, Self::D8)
                | (Self::C2, Self::C2 | Self::C4 | Self::D4Ortho | Self::D4Diag)
                | (Self::C4, Self::C4)
                | (Self::D2Row, Self::D2Row | Self::D4Ortho)
                | (Self::D2Col, Self::D2Col | Self::D4Ortho)
                | (Self::D2Diag, Self::D2Diag | Self::D4Diag)
                | (Self::D2Antidiag, Self::D2Antidiag | Self::D4Diag)
                | (Self::D4Ortho, Self::D4Ortho)
                | (Self::D4Diag, Self::D4Diag)
        )
    }

    /// Whether this symmetry requires the world to be square.
    ///
    /// Returns `true` for `C4`, `D2\`, `D2/`, `D4X` and `D8`.
    pub const fn require_square_world(self) -> bool {
        !self.is_subgroup_of(Self::D4Ortho)
    }

    /// Whether this transformation requires the world to have no diagonal width.
    ///
    /// Returns `true` for `C4`, `D2-`, `D2|`, `D4+` and `D8`.
    pub const fn require_no_diagonal_width(self) -> bool {
        !self.is_subgroup_of(Self::D4Diag)
    }

    /// Transformations contained in the symmetry group.
    pub fn members(self) -> Vec<Transform> {
        match self {
            Self::C1 => vec![Transform::Id],
            Self::C2 => vec![Transform::Id, Transform::Rotate180],
            Self::C4 => vec![
                Transform::Id,
                Transform::Rotate90,
                Transform::Rotate180,
                Transform::Rotate270,
            ],
            Self::D2Row => vec![Transform::Id, Transform::FlipRow],
            Self::D2Col => vec![Transform::Id, Transform::FlipCol],
            Self::D2Diag => vec![Transform::Id, Transform::FlipDiag],
            Self::D2Antidiag => vec![Transform::Id, Transform::FlipAntidiag],
            Self::D4Ortho => vec![
                Transform::Id,
                Transform::FlipRow,
                Transform::FlipCol,
                Transform::Rotate180,
            ],
            Self::D4Diag => vec![
                Transform::Id,
                Transform::FlipDiag,
                Transform::FlipAntidiag,
                Transform::Rotate180,
            ],
            Self::D8 => vec![
                Transform::Id,
                Transform::Rotate90,
                Transform::Rotate180,
                Transform::Rotate270,
                Transform::FlipRow,
                Transform::FlipCol,
                Transform::FlipDiag,
                Transform::FlipAntidiag,
            ],
        }
    }

    /// A list of coset representatives,
    /// seeing the symmetry group as a subgroup of _D_<sub>8</sub>.
    ///
    /// The first element in the result is always [`Transform::Id`].
    pub fn cosets(self) -> Vec<Transform> {
        match self {
            Self::C1 => vec![
                Transform::Id,
                Transform::Rotate90,
                Transform::Rotate180,
                Transform::Rotate270,
                Transform::FlipRow,
                Transform::FlipCol,
                Transform::FlipDiag,
                Transform::FlipAntidiag,
            ],
            Self::C2 => vec![
                Transform::Id,
                Transform::Rotate90,
                Transform::FlipRow,
                Transform::FlipDiag,
            ],
            Self::C4 => vec![Transform::Id, Transform::FlipRow],
            Self::D2Row => vec![
                Transform::Id,
                Transform::FlipCol,
                Transform::FlipDiag,
                Transform::FlipAntidiag,
            ],
            Self::D2Col => vec![
                Transform::Id,
                Transform::FlipRow,
                Transform::FlipDiag,
                Transform::FlipAntidiag,
            ],
            Self::D2Diag => vec![
                Transform::Id,
                Transform::FlipRow,
                Transform::FlipCol,
                Transform::FlipAntidiag,
            ],
            Self::D2Antidiag => vec![
                Transform::Id,
                Transform::FlipRow,
                Transform::FlipCol,
                Transform::FlipDiag,
            ],
            Self::D4Ortho => vec![Transform::Id, Transform::FlipDiag],
            Self::D4Diag => vec![Transform::Id, Transform::FlipRow],
            Self::D8 => vec![Transform::Id],
        }
    }

    /// The symmetry group "generated by" the given symmetry and the transformation.
    /// i.e., the smallest symmetry group which is larger than the given symmetry
    /// group and contains that transformation.
    pub const fn generated_with(self, transform: Transform) -> Self {
        match (self, transform) {
            (sym, Transform::Id) => sym,
            (Self::C1, Transform::Rotate90 | Transform::Rotate270) => Self::C4,
            (Self::C1, Transform::Rotate180) => Self::C2,
            (Self::C1, Transform::FlipRow) => Self::D2Row,
            (Self::C1, Transform::FlipCol) => Self::D2Col,
            (Self::C1, Transform::FlipDiag) => Self::D2Diag,
            (Self::C1, Transform::FlipAntidiag) => Self::D2Antidiag,
            (Self::C2, Transform::Rotate90 | Transform::Rotate270) => Self::C4,
            (Self::C2, Transform::Rotate180) => Self::C2,
            (Self::C2, Transform::FlipRow | Transform::FlipCol) => Self::D4Ortho,
            (Self::C2, Transform::FlipDiag | Transform::FlipAntidiag) => Self::D4Diag,
            (Self::C4, Transform::Rotate90 | Transform::Rotate180 | Transform::Rotate270) => {
                Self::C4
            }
            (Self::D2Row, Transform::Rotate180 | Transform::FlipCol) => Self::D4Ortho,
            (Self::D2Row, Transform::FlipRow) => Self::D2Row,
            (Self::D2Col, Transform::Rotate180 | Transform::FlipRow) => Self::D4Ortho,
            (Self::D2Col, Transform::FlipCol) => Self::D2Col,
            (Self::D2Diag, Transform::Rotate180 | Transform::FlipAntidiag) => Self::D4Diag,
            (Self::D2Diag, Transform::FlipDiag) => Self::D2Diag,
            (Self::D2Antidiag, Transform::Rotate180 | Transform::FlipDiag) => Self::D4Diag,
            (Self::D2Antidiag, Transform::FlipAntidiag) => Self::D2Antidiag,
            (Self::D4Ortho, Transform::Rotate180 | Transform::FlipRow | Transform::FlipCol) => {
                Self::D4Ortho
            }
            (
                Self::D4Diag,
                Transform::Rotate180 | Transform::FlipDiag | Transform::FlipAntidiag,
            ) => Self::D4Diag,
            _ => Self::D8,
        }
    }

    /// The symmetry group generated by the given transformations,
    /// i.e., the smallest symmetry group containing all these transformations.
    pub fn generated_by(transforms: impl IntoIterator<Item = Transform>) -> Self {
        transforms
            .into_iter()
            .fold(Self::C1, |sym, transform| sym.generated_with(transform))
    }
}

impl Config {
    /// Applies the transformation and translation to a coord.
    pub(crate) const fn translate(&self, coord: Coord) -> Coord {
        let mut coord = coord;
        while coord.2 < 0 {
            coord = self
                .transform
                .inverse()
                .act_on(coord, self.width, self.height);
            coord.0 -= self.dx;
            coord.1 -= self.dy;
            coord.2 += self.period;
        }
        while coord.2 >= self.period {
            coord.0 += self.dx;
            coord.1 += self.dy;
            coord.2 -= self.period;
            coord = self.transform.act_on(coord, self.width, self.height);
        }
        coord
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::{thread_rng, Rng};
    use std::collections::HashSet;

    #[test]
    fn test_sym_tran_names() {
        for sym in Symmetry::ALL {
            assert!(Symmetry::from_str(&sym.to_string()) == Ok(sym))
        }
        for trans in Transform::ALL {
            assert!(Transform::from_str(&trans.to_string()) == Ok(trans))
        }
    }

    #[test]
    fn test_symmetry_group_member() {
        for sym in Symmetry::ALL {
            let members = sym.members();
            for tran in Transform::ALL {
                assert_eq!(tran.is_in(sym), members.contains(&tran));
            }
        }
    }

    #[test]
    fn test_symmetry_subgroup() {
        for sym in Symmetry::ALL {
            for sub_sym in Symmetry::ALL {
                let is_subgroup = sub_sym.members().into_iter().all(|tran| tran.is_in(sym));
                assert_eq!(sub_sym <= sym, is_subgroup);
            }
        }
    }

    #[test]
    fn test_symmetry_coset() {
        let group = Transform::ALL.iter().copied().collect::<HashSet<_>>();
        for sym in Symmetry::ALL {
            let all_cosets = sym
                .cosets()
                .into_iter()
                .flat_map(|coset| sym.members().into_iter().map(move |elem| elem * coset))
                .collect::<HashSet<_>>();
            assert_eq!(all_cosets, group);
        }
    }

    #[test]
    fn test_generating() {
        for sym in Symmetry::ALL {
            let members = sym.members();
            assert_eq!(sym, Symmetry::generated_by(members));

            let generated_with_cosets = sym
                .cosets()
                .iter()
                .cloned()
                .fold(sym, Symmetry::generated_with);
            assert_eq!(generated_with_cosets, Symmetry::D8);

            for transform in Transform::ALL {
                let generated_with = sym.generated_with(transform);
                if transform.is_in(sym) {
                    assert_eq!(generated_with, sym);
                } else {
                    assert!(generated_with > sym);
                }
            }
        }
    }

    #[test]
    fn test_transform_inverse() {
        let width = 16;
        let height = 16;
        let mut rng = thread_rng();
        for _ in 0..10 {
            let x = rng.gen_range(0..width);
            let y = rng.gen_range(0..height);
            let coord = (x, y, 0);

            for tran in Transform::ALL {
                assert_eq!(
                    coord,
                    tran.inverse()
                        .act_on(tran.act_on(coord, width, height), width, height),
                    "{} ^ -1 != {}",
                    tran,
                    tran.inverse()
                )
            }
        }
    }

    #[test]
    fn test_transform_mul() {
        let width = 16;
        let height = 16;
        let mut rng = thread_rng();
        for _ in 0..10 {
            let x = rng.gen_range(0..width);
            let y = rng.gen_range(0..height);
            let coord = (x, y, 0);

            for tran0 in Transform::ALL {
                for tran1 in Transform::ALL {
                    assert_eq!(
                        (tran0 * tran1).act_on(coord, width, height),
                        tran1.act_on(tran0.act_on(coord, width, height), width, height),
                        "{} * {} != {}",
                        tran0,
                        tran1,
                        tran0 * tran1
                    )
                }
            }
        }
    }

    #[test]
    fn test_world_condition() {
        for tran in Transform::ALL {
            assert_eq!(
                tran.require_square_world(),
                matches!(
                    tran,
                    Transform::Rotate90
                        | Transform::Rotate270
                        | Transform::FlipDiag
                        | Transform::FlipAntidiag
                )
            );
            assert_eq!(
                tran.require_no_diagonal_width(),
                matches!(
                    tran,
                    Transform::Rotate90
                        | Transform::Rotate270
                        | Transform::FlipRow
                        | Transform::FlipCol
                )
            );
        }
        for sym in Symmetry::ALL {
            assert_eq!(
                sym.require_square_world(),
                matches!(
                    sym,
                    Symmetry::C4
                        | Symmetry::D2Diag
                        | Symmetry::D2Antidiag
                        | Symmetry::D4Diag
                        | Symmetry::D8
                )
            );
            assert_eq!(
                sym.require_no_diagonal_width(),
                matches!(
                    sym,
                    Symmetry::C4
                        | Symmetry::D2Row
                        | Symmetry::D2Col
                        | Symmetry::D4Ortho
                        | Symmetry::D8
                )
            );
        }
    }
}