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
//! A representation of a stage, with human-friendly `const`s and display names.

use std::{
    convert::TryFrom,
    fmt::{Debug, Display, Formatter},
    ops::{Add, Sub},
};

#[cfg(feature = "serde")]
use serde_crate::{
    de::{Error, Visitor},
    Deserialize, Deserializer, Serialize, Serializer,
};

use crate::{RowBuf, SameStageVec};
// Imports used solely by doc comments
#[allow(unused_imports)]
use crate::{Bell, Method, Row};

/// A newtype over [`u8`] that represents a stage.  All `Stage`s must contain at least one
/// [`Bell`]; zero-bell `Stage`s cannot be created without using incorrect `unsafe` code.
///
/// To create a new `Stage`, you can either create it directly with [`Stage::try_from`] (which
/// returns a [`Result`]) or with [`Stage::new`] (which panics if passed `0`).
///
/// If you want a specific small `Stage`, then you can use the constants for the human name for
/// each `Stage`:
/// ```
/// use bellframe::Stage;
///
/// // Converting from numbers is the same as using the constants
/// assert_eq!(Stage::SINGLES, Stage::new(3));
/// assert_eq!(Stage::MAJOR, Stage::new(8));
/// assert_eq!(Stage::CINQUES, Stage::new(11));
/// assert_eq!(Stage::SIXTEEN, Stage::new(16));
/// // We can use `Stage::from` to generate `Stage`s that don't have names
/// assert_eq!(Stage::new(100).num_bells(), 100);
/// assert_eq!(Stage::new(254).num_bells(), 254);
/// ```
///
/// `Stage`s with human-friendly names are [`Display`]ed as their names:
/// ```
/// # use bellframe::Stage;
/// #
/// assert_eq!(Stage::MAXIMUS.to_string(), "Maximus");
/// assert_eq!(Stage::new(9).to_string(), "Caters");
/// assert_eq!(Stage::new(50).to_string(), "50 bells");
/// ```
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(transparent)]
pub struct Stage(u8);

impl Stage {
    /// Creates a new `Stage` representing a given number of [`Bell`]s.
    ///
    /// # Panics
    ///
    /// Panics if `num_bells` is zero.
    #[track_caller]
    pub fn new(num_bells: u8) -> Stage {
        Self::try_from(num_bells).expect("Can't create a `Stage` of zero bells")
    }

    /// The number of [`Bell`]s in this [`Stage`].  This is guaranteed to be non-zero.
    ///
    /// # Example
    /// ```
    /// use bellframe::Stage;
    ///
    /// assert_eq!(Stage::DOUBLES.num_bells(), 5);
    /// assert_eq!(Stage::MAXIMUS.num_bells(), 12);
    /// ```
    #[inline(always)]
    pub fn num_bells(self) -> usize {
        self.0 as usize
    }

    /// The number of [`Bell`]s in this [`Stage`] as a [`u8`].  This is guaranteed to be non-zero.
    ///
    /// # Example
    /// ```
    /// use bellframe::Stage;
    ///
    /// assert_eq!(Stage::DOUBLES.num_bells(), 5);
    /// assert_eq!(Stage::MAXIMUS.num_bells(), 12);
    /// ```
    #[inline(always)]
    pub fn num_bells_u8(self) -> u8 {
        self.0
    }

    /// Returns the highest numbered [`Bell`] in this `Stage`
    pub fn tenor(self) -> Bell {
        Bell::tenor(self)
    }

    /// Gets an [`Iterator`] over the [`Bell`]s contained within this `Stage`, in increasing order.
    pub fn bells(self) -> impl DoubleEndedIterator<Item = Bell> {
        (0..self.num_bells_u8()).map(Bell::from_index)
    }

    /// Returns `true` if a given [`Bell`] is contained in this `Stage`.
    pub fn contains(self, bell: Bell) -> bool {
        bell.number() <= self.num_bells_u8()
    }

    /// Returns true if this `Stage` denotes an even number of [`Bell`]s
    #[inline(always)]
    pub fn is_even(self) -> bool {
        self.num_bells() % 2 == 0
    }

    /// Creates a [`Stage`] from the lower case version of the human-friendly name (e.g.
    /// `"royal"`, `"triples"` or `"twenty-two"`).
    pub fn from_lower_case_name(name: &str) -> Option<Stage> {
        Some(match name {
            "one" => Stage::ONE,
            "two" => Stage::TWO,
            "singles" => Stage::SINGLES,
            "minimus" => Stage::MINIMUS,

            "doubles" => Stage::DOUBLES,
            "minor" => Stage::MINOR,
            "triples" => Stage::TRIPLES,
            "major" => Stage::MAJOR,

            "caters" => Stage::CATERS,
            "royal" => Stage::ROYAL,
            "cinques" => Stage::CINQUES,
            "maximus" => Stage::MAXIMUS,

            "sextuples" => Stage::SEXTUPLES,
            "fourteen" => Stage::FOURTEEN,
            "septuples" => Stage::SEPTUPLES,
            "sixteen" => Stage::SIXTEEN,

            "octuples" => Stage(17),
            "eighteen" => Stage(18),
            "nonuples" => Stage(19),
            "twenty" => Stage(20),

            "decuples" => Stage(21),
            "twenty-two" => Stage(22),

            _ => return None,
        })
    }

    /// Gets the human-friendly name of this [`Stage`], as would be used in [`Method`] names (or
    /// `None` if `self` is too big to have a name).
    pub fn name(self) -> Option<&'static str> {
        Some(match self.0 {
            1 => "One",
            2 => "Two",
            3 => "Singles",
            4 => "Minimus",

            5 => "Doubles",
            6 => "Minor",
            7 => "Triples",
            8 => "Major",

            9 => "Caters",
            10 => "Royal",
            11 => "Cinques",
            12 => "Maximus",

            13 => "Sextuples",
            14 => "Fourteen",
            15 => "Septuples",
            16 => "Sixteen",

            17 => "Octuples",
            18 => "Eighteen",
            19 => "Nonuples",
            20 => "Twenty",

            21 => "Decuples",
            22 => "Twenty-two",

            _ => return None,
        })
    }

    pub fn checked_add(self, rhs: u8) -> Option<Self> {
        self.0.checked_add(rhs).map(Self)
    }

    pub fn checked_sub(self, rhs: u8) -> Option<Self> {
        let new_num_bells = self.0.checked_sub(rhs)?;
        (new_num_bells > 0).then_some(Self(new_num_bells))
    }

    /// Returns a [`SameStageVec`] containing one copy of every [`Row`] possible in this [`Stage`]
    /// in some arbitrary order.
    // TODO: Make this an iterator
    pub fn extent(self) -> SameStageVec {
        let self_minus_one = match self.checked_sub(1) {
            Some(self_minus_one) => self_minus_one,
            // Base case: if stage is one, then there's only one possible row
            None => return SameStageVec::from_row_buf(RowBuf::rounds(self)),
        };

        // Construct this extent recursively by taking every row of one stage lower and inserting
        // the new tenor into every position.  So, for example, converting 2 bells -> 3 bells:
        // ```
        // prev_row = 12 -> [3]12, 1[3]2, 12[3] -> 312, 132, 123
        // prev_row = 21 -> [3]21, 2[3]1, 21[3] -> 321, 231, 213
        // ```
        let mut new_extent_bell_vec = Vec::new();
        for prev_row in &self_minus_one.extent() {
            for split_idx in 0..self.num_bells() {
                let (bells_before, bells_after) = prev_row.slice().split_at(split_idx);
                new_extent_bell_vec.extend_from_slice(bells_before);
                new_extent_bell_vec.push(self.tenor());
                new_extent_bell_vec.extend_from_slice(bells_after)
            }
        }
        // SAFETY: We generated the rows by inserting the new tenor into an already valid `Row`.
        unsafe { SameStageVec::from_bell_vec_unchecked(new_extent_bell_vec, self) }
    }
}

/// User-friendly constants for commonly used `Stage`s.
///
/// # Example
/// ```
/// use bellframe::Stage;
///
/// assert_eq!(Stage::MINIMUS, Stage::new(4));
/// assert_eq!(Stage::MINOR, Stage::new(6));
/// assert_eq!(Stage::TRIPLES, Stage::new(7));
/// assert_eq!(Stage::FOURTEEN, Stage::new(14));
/// assert_eq!(Stage::SEPTUPLES, Stage::new(15));
/// ```
impl Stage {
    /// A `Stage` with `1` 'working' bell
    pub const ONE: Stage = Stage(1);

    /// A `Stage` with `2` working bells
    pub const TWO: Stage = Stage(2);

    /// A `Stage` with `3` working bells
    pub const SINGLES: Stage = Stage(3);

    /// A `Stage` with `4` working bells
    pub const MINIMUS: Stage = Stage(4);

    /// A `Stage` with `5` working bells
    pub const DOUBLES: Stage = Stage(5);

    /// A `Stage` with `6` working bells
    pub const MINOR: Stage = Stage(6);

    /// A `Stage` with `7` working bells
    pub const TRIPLES: Stage = Stage(7);

    /// A `Stage` with `8` working bells
    pub const MAJOR: Stage = Stage(8);

    /// A `Stage` with `9` working bells
    pub const CATERS: Stage = Stage(9);

    /// A `Stage` with `10` working bells
    pub const ROYAL: Stage = Stage(10);

    /// A `Stage` with `11` working bells
    pub const CINQUES: Stage = Stage(11);

    /// A `Stage` with `12` working bells
    pub const MAXIMUS: Stage = Stage(12);

    /// A `Stage` with `13` working bells
    pub const SEXTUPLES: Stage = Stage(13);

    /// A `Stage` with `14` working bells
    pub const FOURTEEN: Stage = Stage(14);

    /// A `Stage` with `15` working bells
    pub const SEPTUPLES: Stage = Stage(15);

    /// A `Stage` with `16` working bells
    pub const SIXTEEN: Stage = Stage(16);
}

impl Debug for Stage {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let const_name = match self.0 {
            0 => unreachable!(),
            1 => "ONE",
            2 => "TWO",
            3 => "SINGLES",
            4 => "MINIMUS",
            5 => "DOUBLES",
            6 => "MINOR",
            7 => "TRIPLES",
            8 => "MAJOR",
            9 => "CATERS",
            10 => "ROYAL",
            11 => "CINQUES",
            12 => "MAXIMUS",
            13 => "SEXTUPLES",
            14 => "FOURTEEN",
            15 => "SEPTUPLES",
            16 => "SIXTEEN",
            num_bells => return write!(f, "Stage({})", num_bells),
        };
        write!(f, "Stage::{}", const_name)
    }
}

impl Display for Stage {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self.name() {
            Some(n) => write!(f, "{}", n),
            None => write!(f, "{} bells", self.0),
        }
    }
}

impl TryFrom<u8> for Stage {
    type Error = ZeroStageError;

    fn try_from(num_bells: u8) -> Result<Self, Self::Error> {
        match num_bells {
            0 => Err(ZeroStageError),
            _ => Ok(Stage(num_bells)),
        }
    }
}

/// An error created when attempting to create a [`Stage`] of zero [`Bell`]s.
#[derive(Debug, Clone, Copy)]
pub struct ZeroStageError;

impl Display for ZeroStageError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "Can't create a `Stage` of zero bells")
    }
}

impl Add<u8> for Stage {
    type Output = Stage;

    fn add(self, rhs: u8) -> Self::Output {
        self.checked_add(rhs)
            .expect("`u8` overflowed whilst adding to a `Stage`")
    }
}

impl Sub<u8> for Stage {
    type Output = Stage;

    fn sub(self, rhs: u8) -> Self::Output {
        self.checked_sub(rhs)
            .expect("`u8` underflowed whilst adding to a `Stage`")
    }
}

//////////////////////////
// `IncompatibleStages` //
//////////////////////////

/// An error created when a [`Row`] was used to permute something with the wrong length
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct IncompatibleStages {
    /// The [`Stage`] of the [`Row`] that was being permuted
    pub(crate) lhs_stage: Stage,
    /// The [`Stage`] of the [`Row`] that was doing the permuting
    pub(crate) rhs_stage: Stage,
}

impl IncompatibleStages {
    /// Compares two [`Stage`]s, returning `Ok(())` if they are equal and returning the appropriate
    /// `IncompatibleStages` error if not.
    pub fn test_err(lhs_stage: Stage, rhs_stage: Stage) -> Result<(), Self> {
        if lhs_stage == rhs_stage {
            Ok(())
        } else {
            Err(IncompatibleStages {
                lhs_stage,
                rhs_stage,
            })
        }
    }

    /// Compares an `Option<Stage>` to a [`Stage`], overwriting the `Option` if it's `None` but
    /// otherwise checking the [`Stage`]s for validity.  This is useful if you have a sequence of
    /// [`Row`]s and you want to verify that all the [`Stage`]s are equal without treating the
    /// first [`Row`] as a special case.
    pub fn test_err_opt(opt: &mut Option<Stage>, stage: Stage) -> Result<(), Self> {
        match opt {
            None => {
                *opt = Some(stage);
                Ok(())
            }
            Some(s) => Self::test_err(*s, stage),
        }
    }
}

impl Display for IncompatibleStages {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Incompatible stages: {} (lhs), {} (rhs)",
            self.lhs_stage, self.rhs_stage
        )
    }
}

impl std::error::Error for IncompatibleStages {}

/* Allow [`Stage`]s to be serialised and deserialised with `serde` */

// Serialise as a u64
#[cfg(feature = "serde")]
impl Serialize for Stage {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u64(self.0 as u64)
    }
}

///////////
// SERDE //
///////////

// Stage by default will deserialise from either a name (i.e. a string) or a non-negative number.
// If types are not known (e.g. when using Bincode), it will deserialise as a u64 to make sure that
// deserialisation is always an inverse of serialisation.
#[cfg(feature = "serde")]
struct StageVisitor;

#[cfg(feature = "serde")]
impl<'de> Visitor<'de> for StageVisitor {
    type Value = Stage;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a non-negative integer, or a stage name")
    }

    fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
    where
        E: Error,
    {
        try_parse_stage_u(v as u64)
    }

    fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>
    where
        E: Error,
    {
        try_parse_stage(v as i64)
    }

    fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>
    where
        E: Error,
    {
        try_parse_stage_u(v as u64)
    }

    fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
    where
        E: Error,
    {
        try_parse_stage(v as i64)
    }

    fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
    where
        E: Error,
    {
        try_parse_stage_u(v as u64)
    }

    fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
    where
        E: Error,
    {
        try_parse_stage(v)
    }

    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
    where
        E: Error,
    {
        try_parse_stage_u(v)
    }

    /// Attempt to parse a [`Stage`] from a string.  This matches standard [`Stage`] names on up to
    /// 16 bells, and is not case sensitive.
    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: Error,
    {
        let lower_str = v.to_lowercase();
        Stage::from_lower_case_name(&lower_str)
            .ok_or_else(|| E::custom(format!("'{}' is not a stage name", v)))
    }
}

/// Helper function to attempt to parse a [`Stage`] from a [`u64`]
#[cfg(feature = "serde")]
#[inline(always)]
fn try_parse_stage_u<E: Error>(val: u64) -> Result<Stage, E> {
    let val_u8: u8 = val
        .try_into()
        .map_err(|_| E::custom(format!("stage is too large: {}", val)))?;
    Stage::try_from(val_u8).map_err(|_| E::custom("Can't have a Stage of zero bells"))
}

/// Helper function to attempt to parse a [`Stage`] from an [`i64`]
#[cfg(feature = "serde")]
#[inline(always)]
fn try_parse_stage<E: Error>(val: i64) -> Result<Stage, E> {
    try_parse_stage_u(
        val.try_into()
            .map_err(|_| E::custom(format!("negative stage: {}", val)))?,
    )
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Stage {
    fn deserialize<D>(deserializer: D) -> Result<Stage, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_u64(StageVisitor)
    }
}

//////////////////
// TESTING CODE //
//////////////////

#[cfg(test)]
use quickcheck::{Arbitrary, Gen};

#[cfg(test)]
impl Arbitrary for Stage {
    fn arbitrary(gen: &mut Gen) -> Self {
        let num_bells = u8::arbitrary(gen);
        // Convert all zero-size `Stage`s to `Stage::ONE`.  This means that `Stage::arbitrary` is
        // not uniform (since `Stage::ONE` will be generated twice as much as any other value) but
        // I think this is fine - the point here is not to be fair, but rather to generate useful
        // test cases.
        let num_bells = num_bells.max(1);
        Self::new(num_bells)
    }
}

#[cfg(test)]
mod tests {
    use itertools::Itertools;

    use crate::{Row, RowBuf};

    use super::Stage;

    #[test]
    #[rustfmt::skip]
    fn extent() {
        #[track_caller]
        fn check(stage: Stage, exp_extent: &[&str]) {
            let mut extent = stage.extent().iter().map(Row::to_owned).collect_vec();
            let mut expected_extent = exp_extent.iter().map(|s| RowBuf::parse(s).unwrap()).collect_vec();
            // Sort both extents so that we guarantee they'll be in the same order
            extent.sort();
            expected_extent.sort();
            assert_eq!(extent, expected_extent);
        }

        check(Stage::ONE, &["1"]);
        check(Stage::TWO, &["12", "21"]);
        check(Stage::SINGLES, &["123", "132", "213", "231", "312", "321"]);
        check(
            Stage::MINIMUS,
            &[
                "1234", "1243", "1324", "1342", "1423", "1432",
                "2134", "2143", "2314", "2341", "2413", "2431",
                "3124", "3142", "3214", "3241", "3412", "3421",
                "4123", "4132", "4213", "4231", "4312", "4321",
            ]
        );
    }
}