sigma_types/
sigma.rs

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
//! Type that maintains a given invariant.

#![expect(
    clippy::arbitrary_source_item_ordering,
    reason = "macros must be defined before they're used"
)]

use {
    crate::{
        CanBeInfinite, Finite, Negative, NonNegative, NonPositive, NonZero, OnUnit, One, Positive,
        Zero,
    },
    core::{
        borrow::Borrow,
        cmp::Ordering,
        fmt,
        hash::{Hash, Hasher},
        marker::PhantomData,
        ops,
    },
};

#[cfg(test)]
use {paste::paste, quickcheck::TestResult, quickcheck_macros::quickcheck};

#[cfg(feature = "std")]
use std::env;

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

#[cfg(all(any(test, feature = "quickcheck"), not(feature = "std")))]
use alloc::boxed::Box;

/// Implement a unary operation.
macro_rules! impl_op_1 {
    ($op:ident, $fn:ident, $lhs:ident, $out:ident $(, $($bound:ident),* $(,)?)?) => {
        impl<
            L: $($($bound +)*)? fmt::Debug + ops::$op<Output: $($($bound +)*)? fmt::Debug>,
        > ops::$op for $lhs<L>
        {
            type Output = $out<<L as ops::$op>::Output>;

            #[inline]
            fn $fn(self) -> Self::Output {
                self.map(|lhs| lhs.$fn())
            }
        }

        #[cfg(test)]
        paste! {
            #[cfg(test)]
            #[expect(trivial_casts, clippy::as_conversions, reason = "must be an implementation detail of `quickcheck`")]
            mod [< $lhs:snake _ $fn >] {
                use super::*;

                #[quickcheck]
                fn doesnt_panic(lhs: $lhs</* L */ f64>) -> TestResult {
                    if lhs.abs() > 1e64_f64 { return TestResult::discard() }
                    _ = <$lhs</* L */ f64> as ops::$op>::$fn(lhs);
                    TestResult::passed()
                }
            }
        }
    };
}

/// Implement a binary operation.
macro_rules! impl_op_2 {
    ($op:ident, $fn:ident, $lhs:ident, $rhs:ident, $out:ident, $reject:expr $(, $($bound:ident),* $(,)?)?) => {
        impl<
            L: $($($bound +)*)? fmt::Debug + ops::$op<R, Output: $($($bound +)*)? fmt::Debug>,
            R: $($($bound +)*)? fmt::Debug,
        > ops::$op<$rhs<R>> for $lhs<L>
        {
            type Output = $out<<L as ops::$op<R>>::Output>;

            #[inline]
            fn $fn(self, rhs: $rhs<R>) -> Self::Output {
                self.map(|lhs| lhs.$fn(rhs.get()))
            }
        }

        #[cfg(test)]
        paste! {
            #[cfg(test)]
            #[expect(trivial_casts, clippy::as_conversions, reason = "must be an implementation detail of `quickcheck`")]
            mod [< $lhs:snake _ $fn _ $rhs:snake >] {
                use super::*;

                #[quickcheck]
                fn doesnt_panic(lhs: $lhs</* L */ f64>, rhs: $rhs</* R */ f64>) -> TestResult {
                    if lhs.abs() > 1e64_f64 { return TestResult::discard() }
                    if rhs.abs() > 1e64_f64 { return TestResult::discard() }
                    let toss: fn(&$lhs</* L */ f64>, &$rhs</* R */ f64>) -> bool = $reject;
                    if toss(&lhs, &rhs) { return TestResult::discard() }
                    _ = <$lhs</* L */ f64> as ops::$op<$rhs</* R */ f64>>>::$fn(lhs, rhs);
                    TestResult::passed()
                }
            }
        }

        impl<
            'rhs,
            L: $($($bound +)*)? fmt::Debug + ops::$op<&'rhs R, Output: $($($bound +)*)? fmt::Debug>,
            R: $($($bound +)*)? fmt::Debug,
        > ops::$op<&'rhs $rhs<R>> for $lhs<L>
        {
            type Output = $out<<L as ops::$op<&'rhs R>>::Output>;

            #[inline]
            fn $fn(self, rhs: &'rhs $rhs<R>) -> Self::Output {
                self.map(|lhs| lhs.$fn(rhs.get_ref()))
            }
        }

        #[cfg(test)]
        paste! {
            #[cfg(test)]
            #[expect(trivial_casts, clippy::as_conversions, reason = "must be an implementation detail of `quickcheck`")]
            mod [< $lhs:snake _ $fn _ $rhs:snake _ref >] {
                use super::*;

                #[quickcheck]
                fn doesnt_panic(lhs: $lhs</* L */ f64>, rhs: $rhs</* R */ f64>) -> TestResult {
                    if lhs.abs() > 1e64_f64 { return TestResult::discard() }
                    if rhs.abs() > 1e64_f64 { return TestResult::discard() }
                    let toss: fn(&$lhs</* L */ f64>, &$rhs</* R */ f64>) -> bool = $reject;
                    if toss(&lhs, &rhs) { return TestResult::discard() }
                    _ = <$lhs</* L */ f64> as ops::$op<&$rhs</* R */ f64>>>::$fn(lhs, &rhs);
                    TestResult::passed()
                }
            }
        }

        /*
        impl<
            'lhs,
            L: $($($bound +)*)? fmt::Debug,
            R: $($($bound +)*)? fmt::Debug,
        > ops::$op<$rhs<R>> for &'lhs $lhs<L>
        where
            &'lhs L: ops::$op<R, Output: $($($bound +)*)? fmt::Debug>,
        {
            type Output = $out<<&'lhs L as ops::$op<R>>::Output>;

            #[inline]
            fn $fn(self, rhs: $rhs<R>) -> Self::Output {
                self.map_ref(|lhs| lhs.$fn(rhs.get()))
            }
        }

        #[cfg(test)]
        #[quickcheck]
        fn [< doesnt_panic_ $lhs:snake _ $fn _ $rhs:snake >] {
            fn doesnt_panic(lhs: $lhs</* L */ f64>, rhs: $rhs</* R */ f64>) -> TestResult {
            _ = <$lhs</* L */ f64> as ops::$ops>::$fn(lhs, rhs);
            TestResult::passed()
        }

        impl<
            'lhs,
            'rhs,
            L: $($($bound +)*)? fmt::Debug,
            R: $($($bound +)*)? fmt::Debug,
        > ops::$op<&'rhs $rhs<R>> for &'lhs $lhs<L>
        where
            &'lhs L: ops::$op<&'rhs R, Output: $($($bound +)*)? fmt::Debug>,
        {
            type Output = $out<<&'lhs L as ops::$op<&'rhs R>>::Output>;

            #[inline]
            fn $fn(self, rhs: &'rhs $rhs<R>) -> Self::Output {
                self.map_ref(|lhs| lhs.$fn(rhs.get_ref()))
            }
        }

        #[cfg(test)]
        #[quickcheck]
        fn [< doesnt_panic_ $lhs:snake _ $fn _ $rhs:snake _ref >] {
            fn doesnt_panic(lhs: $lhs</* L */ f64>, rhs: $rhs</* R */ f64>) -> TestResult {
            _ = <$lhs</* L */ f64> as ops::$ops>::$fn(lhs, rhs);
            TestResult::passed()
        }
        */
    };
}

/// Implement a unary assignment operator.
macro_rules! impl_op_assign {
    ($op:ident, $fn:ident, $lhs:ident, $rhs:ident, $reject:expr $(, $($bound:ident),* $(,)?)?) => {
        impl<
            L: $($($bound +)*)? fmt::Debug + ops::$op<R>,
            R: $($($bound +)*)? fmt::Debug,
        > ops::$op<$rhs<R>> for $lhs<L>
        {
            #[inline]
            fn $fn(&mut self, rhs: $rhs<R>) {
                self.map_mut(|lhs| lhs.$fn(rhs.get()))
            }
        }

        #[cfg(test)]
        paste! {
            #[cfg(test)]
            #[expect(trivial_casts, clippy::as_conversions, reason = "must be an implementation detail of `quickcheck`")]
            mod [< $lhs:snake _ $fn _ $rhs:snake >] {
                use super::*;

                #[quickcheck]
                fn doesnt_panic(mut lhs: $lhs</* L */ f64>, rhs: $rhs</* R */ f64>) -> TestResult {
                    if lhs.abs() > 1e64_f64 { return TestResult::discard() }
                    if rhs.abs() > 1e64_f64 { return TestResult::discard() }
                    let toss: fn(&$lhs</* L */ f64>, &$rhs</* R */ f64>) -> bool = $reject;
                    if toss(&lhs, &rhs) { return TestResult::discard() }
                    _ = <$lhs</* L */ f64> as ops::$op<$rhs</* R */ f64>>>::$fn(&mut lhs, rhs);
                    TestResult::passed()
                }
            }
        }

        impl<
            'rhs,
            L: $($($bound +)*)? fmt::Debug + ops::$op<&'rhs R>,
            R: $($($bound +)*)? fmt::Debug,
        > ops::$op<&'rhs $rhs<R>> for $lhs<L>
        {
            #[inline]
            fn $fn(&mut self, rhs: &'rhs $rhs<R>) {
                self.map_mut(|lhs| lhs.$fn(rhs.get_ref()))
            }
        }

        #[cfg(test)]
        paste! {
            #[cfg(test)]
            #[expect(trivial_casts, clippy::as_conversions, reason = "must be an implementation detail of `quickcheck`")]
            mod [< $lhs:snake _ $fn _ $rhs:snake _ref >] {
                use super::*;

                #[quickcheck]
                fn doesnt_panic(mut lhs: $lhs</* L */ f64>, rhs: $rhs</* R */ f64>) -> TestResult {
                    if lhs.abs() > 1e64_f64 { return TestResult::discard() }
                    if rhs.abs() > 1e64_f64 { return TestResult::discard() }
                    let toss: fn(&$lhs</* L */ f64>, &$rhs</* R */ f64>) -> bool = $reject;
                    if toss(&lhs, &rhs) { return TestResult::discard() }
                    _ = <$lhs</* L */ f64> as ops::$op<&$rhs</* R */ f64>>>::$fn(&mut lhs, &rhs);
                    TestResult::passed()
                }
            }
        }
    };
}

/// Addition only (and -assignment).
macro_rules! impl_add {
    ($lhs:ident, $rhs:ident, $out:ident $(, $($bound:ident),* $(,)?)?) => {
        impl_op_2!(Add, add, $lhs, $rhs, $out, |_, _| false $(, $($bound,)*)?);
        impl_op_assign!(AddAssign, add_assign, $lhs, $rhs, |_, _| false $(, $($bound,)*)?);
    };
}

/// Subtraction only (and -assignment).
macro_rules! impl_sub {
    ($lhs:ident, $rhs:ident, $out:ident $(, $($bound:ident),* $(,)?)?) => {
        impl_op_2!(Sub, sub, $lhs, $rhs, $out, |_, _| false $(, $($bound,)*)?);
        impl_op_assign!(SubAssign, sub_assign, $lhs, $rhs, |_, _| false $(, $($bound,)*)?);
    };
}

/// All multiplicative traits (e.g. multiplication, division, ...).
macro_rules! impl_mul {
    ($lhs:ident, $rhs:ident, $out:ident $(, $($bound:ident),* $(,)?)?) => {
        impl_op_2!(Div, div, $lhs, $rhs, $out, |_, rhs| rhs.get() == 0_f64 $(, $($bound,)*)?);
        impl_op_2!(Mul, mul, $lhs, $rhs, $out, |_, _| false $(, $($bound,)*)?);
    };
}

/// All multiplicative traits (e.g. multiplication, division, ...).
macro_rules! impl_mul_assign {
    ($lhs:ident, $rhs:ident $(, $($bound:ident),* $(,)?)?) => {
        impl_op_assign!(DivAssign, div_assign, $lhs, $rhs, |_, rhs| rhs.get() == 0_f64 $(, $($bound,)*)?);
        impl_op_assign!(MulAssign, mul_assign, $lhs, $rhs, |_, _| false $(, $($bound,)*)?);
    };
}

impl<Z: CanBeInfinite + One + fmt::Debug> One for Finite<Z> {
    const ONE: Self = Self {
        phantom: PhantomData,
        raw: Z::ONE,
    };
}

impl<Z: CanBeInfinite + Zero + fmt::Debug> Zero for Finite<Z> {
    const ZERO: Self = Self {
        phantom: PhantomData,
        raw: Z::ZERO,
    };
}

impl_add!(Finite, Finite, Finite, CanBeInfinite);
impl_sub!(Finite, Finite, Finite, CanBeInfinite);
impl_mul!(Finite, Finite, Finite, CanBeInfinite);
impl_mul_assign!(Finite, Finite, CanBeInfinite);
impl_op_1!(Neg, neg, Finite, Finite, CanBeInfinite);

impl_add!(Negative, Negative, Negative, PartialOrd, Zero);
impl_sub!(Negative, NonNegative, Negative, PartialOrd, Zero);
impl_add!(Negative, NonPositive, Negative, PartialOrd, Zero);
impl_sub!(Negative, Positive, Negative, PartialOrd, Zero);
impl_mul!(Negative, Negative, Positive, PartialOrd, Zero);
impl_mul!(Negative, NonNegative, NonPositive, PartialOrd, Zero);
impl_mul!(Negative, NonPositive, NonNegative, PartialOrd, Zero);
impl_mul!(Negative, Positive, Negative, PartialOrd, Zero);
impl_mul_assign!(Negative, Positive, PartialOrd, Zero);
impl_op_1!(Neg, neg, Negative, Positive, PartialOrd, Zero);

impl<T: One + PartialOrd + Zero + fmt::Debug> One for NonNegative<T> {
    const ONE: Self = Self {
        phantom: PhantomData,
        raw: T::ONE,
    };
}

impl<Z: PartialOrd + Zero + fmt::Debug> Zero for NonNegative<Z> {
    const ZERO: Self = Self {
        phantom: PhantomData,
        raw: Z::ZERO,
    };
}

impl_sub!(NonNegative, Negative, Positive, PartialOrd, Zero);
impl_add!(NonNegative, NonNegative, NonNegative, PartialOrd, Zero);
impl_sub!(NonNegative, NonPositive, NonNegative, PartialOrd, Zero);
impl_add!(NonNegative, Positive, Positive, PartialOrd, Zero);
impl_mul!(NonNegative, Negative, NonPositive, PartialOrd, Zero);
impl_mul!(NonNegative, NonNegative, NonNegative, PartialOrd, Zero);
impl_mul!(NonNegative, NonPositive, NonPositive, PartialOrd, Zero);
impl_mul!(NonNegative, Positive, NonNegative, PartialOrd, Zero);
impl_mul_assign!(NonNegative, NonNegative, PartialOrd, Zero);
impl_mul_assign!(NonNegative, Positive, PartialOrd, Zero);
impl_op_1!(Neg, neg, NonNegative, NonPositive, PartialOrd, Zero);

impl_add!(NonPositive, Negative, Negative, PartialOrd, Zero);
impl_sub!(NonPositive, NonNegative, NonPositive, PartialOrd, Zero);
impl_add!(NonPositive, NonPositive, NonPositive, PartialOrd, Zero);
impl_sub!(NonPositive, Positive, Negative, PartialOrd, Zero);
impl_mul!(NonPositive, Negative, NonNegative, PartialOrd, Zero);
impl_mul!(NonPositive, NonNegative, NonPositive, PartialOrd, Zero);
impl_mul!(NonPositive, NonPositive, NonNegative, PartialOrd, Zero);
impl_mul!(NonPositive, Positive, NonPositive, PartialOrd, Zero);
impl_mul_assign!(NonPositive, NonNegative, PartialOrd, Zero);
impl_mul_assign!(NonPositive, Positive, PartialOrd, Zero);
impl_op_1!(Neg, neg, NonPositive, NonNegative, PartialOrd, Zero);

impl_mul!(NonZero, NonZero, NonZero, PartialEq, Zero);
impl_op_1!(Neg, neg, NonZero, NonZero, PartialEq, Zero);

impl<T: One + PartialOrd + Zero + fmt::Debug, const INCLUSIVE_AT_ZERO: bool> One
    for OnUnit<T, INCLUSIVE_AT_ZERO, true>
{
    const ONE: Self = Self {
        phantom: PhantomData,
        raw: T::ONE,
    };
}

impl<Z: One + PartialOrd + Zero + fmt::Debug, const INCLUSIVE_AT_ONE: bool> Zero
    for OnUnit<Z, true, INCLUSIVE_AT_ONE>
{
    const ZERO: Self = Self {
        phantom: PhantomData,
        raw: Z::ZERO,
    };
}

impl_sub!(Positive, Negative, Positive, PartialOrd, Zero);
impl_add!(Positive, NonNegative, Positive, PartialOrd, Zero);
impl_sub!(Positive, NonPositive, Positive, PartialOrd, Zero);
impl_add!(Positive, Positive, Positive, PartialOrd, Zero);
impl_mul!(Positive, Negative, Negative, PartialOrd, Zero);
impl_mul!(Positive, NonNegative, NonNegative, PartialOrd, Zero);
impl_mul!(Positive, NonPositive, NonPositive, PartialOrd, Zero);
impl_mul!(Positive, Positive, Positive, PartialOrd, Zero);
impl_mul_assign!(Positive, Positive, PartialOrd, Zero);
impl_op_1!(Neg, neg, Positive, NonPositive, PartialOrd, Zero);

impl<T: One + PartialOrd + Zero + fmt::Debug> One for Positive<T> {
    const ONE: Self = Self {
        phantom: PhantomData,
        raw: T::ONE,
    };
}

/// Type that maintains a given invariant.
#[repr(transparent)]
pub struct Sigma<Raw: fmt::Debug, Invariant: crate::Test<Raw, 1>> {
    /// Only to silence compiler errors.
    phantom: PhantomData<Invariant>,
    /// Internal type (to which this type will reduce in release builds).
    raw: Raw,
}

impl<Raw: fmt::Debug, Invariant: crate::Test<Raw, 1>> Sigma<Raw, Invariant> {
    /// Check all elements of an array.
    #[inline]
    pub fn all<const N: usize>(array: &[Raw; N]) -> &[Self; N] {
        let pointer: *const [Raw; N] = array;
        let cast: *const [Self; N] = pointer.cast();
        // SAFETY:
        // `repr(transparent)`
        let provisional = unsafe { &*cast };
        for element in provisional {
            element.check();
        }
        provisional
    }

    /// Without changing its internal value,
    /// view one sigma-typed value as implementing another sigma type
    /// by checking the latter invariant at runtime (iff debug assertions are enabled).
    /// # Panics
    /// If the latter invariant does not hold.
    #[inline(always)]
    pub fn also<OtherInvariant: crate::Test<Raw, 1>>(self) -> Sigma<Raw, OtherInvariant> {
        Sigma::new(self.get())
    }

    /// Without changing its internal value,
    /// view one sigma-typed value as implementing another sigma type
    /// by checking the latter invariant at runtime (iff debug assertions are enabled).
    /// # Panics
    /// If the latter invariant does not hold.
    #[inline]
    #[cfg(debug_assertions)]
    pub fn also_ref<OtherInvariant: crate::Test<Raw, 1>>(&self) -> &Sigma<Raw, OtherInvariant> {
        let ptr: *const Self = self;
        // SAFETY:
        // Pointer reinterpretation. See `repr(transparent)` above.
        // All non-zero-sized fields are identical across the cast.
        let transmuted: &Sigma<Raw, OtherInvariant> = unsafe { &*ptr.cast() };
        transmuted.check();
        transmuted
    }

    /// Without changing its internal value,
    /// view one sigma-typed value as implementing another sigma type
    /// by checking the latter invariant at runtime (iff debug assertions are enabled).
    #[inline]
    #[cfg(not(debug_assertions))]
    pub const fn also_ref<OtherInvariant: crate::Test<Raw, 1>>(
        &self,
    ) -> &Sigma<Raw, OtherInvariant> {
        let ptr: *const Self = self;
        // SAFETY:
        // Pointer reinterpretation. See `repr(transparent)` above.
        // All non-zero-sized fields are identical across the cast.
        unsafe { &*ptr.cast() }
    }

    /// Check an invariant if and only if debug assertions are enabled.
    /// # Panics
    /// If the invariant does not hold ***and*** debug assertions are enabled.
    #[inline]
    #[cfg(debug_assertions)]
    pub fn check(&self) {
        #[expect(
            clippy::panic,
            reason = "Returning a result would break API in release builds"
        )]
        match Invariant::test([&self.raw]) {
            Ok(()) => {}
            Err(message) => {
                panic!("{:#?} is not {}: {message}", self.raw, Invariant::ADJECTIVE);
            }
        }
    }

    /// Do nothing (since debug assertions are disabled).
    #[inline]
    #[cfg(not(debug_assertions))]
    pub const fn check(&self) {}

    /// Unwrap the internal value that satisfies the invariant.
    /// If you're using this to create another value that should
    /// also maintain an invariant, use `map` instead.
    #[inline(always)]
    pub fn get(self) -> Raw {
        self.raw
    }

    /// Unwrap the internal value that satisfies the invariant.
    /// If you're using this to create another value that should
    /// also maintain an invariant, use `map` instead.
    #[inline(always)]
    #[expect(clippy::allow_attributes, reason = "Edition 2021 only")]
    #[allow(tail_expr_drop_order, reason = "just for miri")]
    pub fn get_by<Y, F: FnOnce(Raw) -> Y>(self, f: F) -> Y {
        f(self.get())
    }

    /// Unwrap the internal value that satisfies the invariant.
    /// If you're using this to create another value that should
    /// also maintain an invariant, use `map` instead.
    #[inline(always)]
    pub fn get_by_mut<Y, F: FnOnce(&mut Raw) -> Y>(&mut self, f: F) -> Y {
        f(self.get_mut())
    }

    /// Unwrap the internal value that satisfies the invariant.
    /// If you're using this to create another value that should
    /// also maintain an invariant, use `map` instead.
    #[inline(always)]
    pub fn get_by_ref<Y, F: FnOnce(&Raw) -> Y>(&self, f: F) -> Y {
        f(self)
    }

    /// Unwrap the internal value that satisfies the invariant.
    /// If you're using this to create another value that should
    /// also maintain an invariant, use `map` instead.
    #[inline(always)]
    pub const fn get_mut(&mut self) -> &mut Raw {
        &mut self.raw
    }

    /// Unwrap the internal value that satisfies the invariant.
    /// If you're using this to create another value that should
    /// also maintain an invariant, use `map` instead.
    #[inline(always)]
    pub const fn get_ref(&self) -> &Raw {
        &self.raw
    }

    /// Apply a function to a term that implements a given invariant (say, A),
    /// then check the output for a (possibly different) invariant (say, B).
    #[inline]
    #[expect(clippy::allow_attributes, reason = "Edition 2021 only")]
    #[allow(tail_expr_drop_order, reason = "just for miri")]
    pub fn map<
        OtherRaw: fmt::Debug,
        OtherInvariant: crate::Test<OtherRaw, 1>,
        F: FnOnce(Raw) -> OtherRaw,
    >(
        self,
        f: F,
    ) -> Sigma<OtherRaw, OtherInvariant> {
        Sigma::new(f(self.get()))
    }

    /// Apply a function that mutates this value,
    /// then check that the operation maintained this invariant.
    #[inline]
    pub fn map_mut<Y, F: FnOnce(&mut Raw) -> Y>(&mut self, f: F) -> Y {
        let raw = self.get_mut();
        let y = f(raw);
        self.check();
        y
    }

    /// Apply a function to a term that implements a given invariant (say, A),
    /// then check the output for a (possibly different) invariant (say, B).
    #[inline]
    #[expect(clippy::allow_attributes, reason = "Edition 2021 only")]
    #[allow(tail_expr_drop_order, reason = "just for miri")]
    pub fn map_ref<
        OtherRaw: fmt::Debug,
        OtherInvariant: crate::Test<OtherRaw, 1>,
        F: FnOnce(&Raw) -> OtherRaw,
    >(
        &self,
        f: F,
    ) -> Sigma<OtherRaw, OtherInvariant> {
        Sigma::new(f(self))
    }

    /// Create a new sigma type instance by checking an invariant.
    /// # Panics
    /// If the invariant does not hold ***and*** debug assertions are enabled.
    #[inline]
    #[cfg(debug_assertions)]
    pub fn new(raw: Raw) -> Self {
        let provisional = Self {
            phantom: PhantomData,
            raw,
        };
        provisional.check();
        provisional
    }

    /// Create a new sigma type instance by checking an invariant.
    /// # Panics
    /// If the invariant does not hold ***and*** debug assertions are enabled.
    #[inline]
    #[cfg(not(debug_assertions))]
    pub const fn new(raw: Raw) -> Self {
        Self {
            phantom: PhantomData,
            raw,
        }
    }

    /// Without changing its internal value,
    /// try to view one sigma-typed value as implementing another sigma type
    /// by checking the latter invariant at runtime.
    /// # Errors
    /// If the latter invariant does not hold.
    #[inline]
    pub fn try_also<OtherInvariant: crate::Test<Raw, 1>>(
        self,
    ) -> Option<Sigma<Raw, OtherInvariant>> {
        Sigma::try_new(self.get())
    }

    /// Without changing its internal value,
    /// try to view one sigma-typed value as implementing another sigma type
    /// by checking the latter invariant at runtime.
    /// # Errors
    /// If the latter invariant does not hold.
    #[inline]
    pub fn try_also_ref<OtherInvariant: crate::Test<Raw, 1>>(
        &self,
    ) -> Result<&Sigma<Raw, OtherInvariant>, OtherInvariant::Error<'_>> {
        let ptr: *const Self = self;
        // SAFETY:
        // Pointer reinterpretation. See `repr(transparent)` above.
        // All non-zero-sized fields are identical across the cast.
        let transmuted: &Sigma<Raw, OtherInvariant> = unsafe { &*ptr.cast() };
        transmuted.try_check()?;
        Ok(transmuted)
    }

    /// Check an invariant without panicking.
    /// # Errors
    /// If the invariant does not hold.
    #[inline(always)]
    pub fn try_check(&self) -> Result<(), Invariant::Error<'_>> {
        Invariant::test([&self.raw])
    }

    /// Create a new sigma type instance by checking an invariant.
    /// # Errors
    /// If the invariant does not hold.
    #[inline]
    pub fn try_new(raw: Raw) -> Option<Self> {
        let provisional = Self {
            phantom: PhantomData,
            raw,
        };
        provisional.try_check().ok()?;
        Some(provisional)
    }

    /// Wrap a reference through pointer reinterpretation magic.
    #[inline(always)]
    #[cfg(debug_assertions)]
    pub fn wrap(reference: &Raw) -> &Self {
        let raw_pointer: *const _ = reference;
        let sigma_pointer = raw_pointer.cast::<Self>();
        // SAFETY:
        // `repr(transparent)`
        let wrapped = unsafe { &*sigma_pointer };
        wrapped.check();
        wrapped
    }

    /// Wrap a reference through pointer reinterpretation magic.
    #[inline(always)]
    #[cfg(not(debug_assertions))]
    pub const fn wrap(reference: &Raw) -> &Self {
        let raw_pointer: *const _ = reference;
        let sigma_pointer = raw_pointer.cast::<Self>();
        // SAFETY:
        // `repr(transparent)`
        unsafe { &*sigma_pointer }
    }

    /// Wrap a reference through pointer reinterpretation magic.
    #[inline(always)]
    pub fn wrap_mut(reference: &mut Raw) -> &mut Self {
        let raw_pointer: *mut _ = reference;
        let sigma_pointer = raw_pointer.cast::<Self>();
        // SAFETY:
        // `repr(transparent)`
        let wrapped = unsafe { &mut *sigma_pointer };
        wrapped.check();
        wrapped
    }
}

#[cfg(any(test, feature = "quickcheck"))]
impl<Raw: Arbitrary + fmt::Debug, Invariant: 'static + crate::Test<Raw, 1>> Arbitrary
    for Sigma<Raw, Invariant>
{
    #[inline]
    fn arbitrary(g: &mut Gen) -> Self {
        loop {
            let raw: Raw = Arbitrary::arbitrary(g);
            if let Some(sigma) = Self::try_new(raw) {
                return sigma;
            }
        }
    }

    #[inline]
    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        let Self {
            phantom: PhantomData,
            ref raw,
        } = *self;
        Box::new(raw.shrink().filter_map(Self::try_new))
    }
}

impl<Raw: fmt::Debug, Invariant: crate::Test<Raw, 1>> AsRef<Raw> for Sigma<Raw, Invariant> {
    #[inline(always)]
    fn as_ref(&self) -> &Raw {
        &self.raw
    }
}

impl<Raw: fmt::Debug, Invariant: crate::Test<Raw, 1>> Borrow<Raw> for Sigma<Raw, Invariant> {
    #[inline(always)]
    fn borrow(&self) -> &Raw {
        &self.raw
    }
}

impl<Raw: CanBeInfinite + fmt::Debug, Invariant: crate::Test<Raw>> CanBeInfinite
    for Sigma<Raw, Invariant>
{
    #[inline(always)]
    fn check_finite(&self) -> bool {
        self.raw.check_finite()
    }
}

impl<Raw: Clone + fmt::Debug, Invariant: crate::Test<Raw, 1>> Clone for Sigma<Raw, Invariant> {
    #[inline(always)]
    fn clone(&self) -> Self {
        Self::new(self.raw.clone())
    }

    #[inline(always)]
    fn clone_from(&mut self, source: &Self) {
        self.raw.clone_from(&source.raw);
        self.check();
    }
}

impl<Raw: Copy + fmt::Debug, Invariant: crate::Test<Raw, 1>> Copy for Sigma<Raw, Invariant> {}

impl<Raw: Default + fmt::Debug, Invariant: crate::Test<Raw, 1>> Default for Sigma<Raw, Invariant> {
    #[inline(always)]
    fn default() -> Self {
        Self::new(Raw::default())
    }
}

impl<Raw: Eq + fmt::Debug, Invariant: crate::Test<Raw, 1>> Eq for Sigma<Raw, Invariant> {
    #[inline(always)]
    fn assert_receiver_is_total_eq(&self) {
        self.raw.assert_receiver_is_total_eq();
    }
}

impl<Raw: Hash + fmt::Debug, Invariant: crate::Test<Raw, 1>> Hash for Sigma<Raw, Invariant> {
    #[inline(always)]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.raw.hash(state);
    }

    #[inline(always)]
    fn hash_slice<H: Hasher>(data: &[Self], state: &mut H) {
        let ptr: *const [Self] = data;
        #[expect(clippy::as_conversions, reason = "marked `repr(transparent)` above")]
        let transparent = ptr as *const [Raw];
        // SAFETY:
        // Marked `repr(transparent)` above
        let reinterpreted: &[Raw] = unsafe { &*transparent };
        Raw::hash_slice(reinterpreted, state);
    }
}

impl<Raw: Ord + fmt::Debug, Invariant: crate::Test<Raw, 1>> Ord for Sigma<Raw, Invariant> {
    #[inline(always)]
    fn clamp(self, min: Self, max: Self) -> Self {
        Self::new(self.raw.clamp(min.raw, max.raw))
    }

    #[inline(always)]
    fn cmp(&self, other: &Self) -> Ordering {
        self.raw.cmp(&other.raw)
    }

    #[inline(always)]
    fn max(self, other: Self) -> Self {
        Self::new(self.raw.max(other.raw))
    }

    #[inline(always)]
    fn min(self, other: Self) -> Self {
        Self::new(self.raw.min(other.raw))
    }
}

impl<Raw: PartialEq + fmt::Debug, Invariant: crate::Test<Raw, 1>> PartialEq
    for Sigma<Raw, Invariant>
{
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        self.raw.eq(&other.raw)
    }

    #[inline(always)]
    #[expect(
        clippy::partialeq_ne_impl,
        reason = "arbitrary choice between competing lints"
    )]
    fn ne(&self, other: &Self) -> bool {
        self.raw.ne(&other.raw)
    }
}

impl<Raw: PartialOrd + fmt::Debug, Invariant: crate::Test<Raw, 1>> PartialOrd
    for Sigma<Raw, Invariant>
{
    #[inline(always)]
    fn ge(&self, other: &Self) -> bool {
        self.raw.ge(&other.raw)
    }

    #[inline(always)]
    fn gt(&self, other: &Self) -> bool {
        self.raw.gt(&other.raw)
    }

    #[inline(always)]
    fn le(&self, other: &Self) -> bool {
        self.raw.le(&other.raw)
    }

    #[inline(always)]
    fn lt(&self, other: &Self) -> bool {
        self.raw.lt(&other.raw)
    }

    #[inline(always)]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.raw.partial_cmp(&other.raw)
    }
}

impl<Raw: fmt::Debug, Invariant: crate::Test<Raw, 1>> fmt::Debug for Sigma<Raw, Invariant> {
    #[inline(always)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        #[cfg(feature = "std")]
        if env::var("DEBUG_SIGMA_TYPES").is_ok_and(|s| s != "0") {
            write!(f, "({}) ", Invariant::ADJECTIVE)?;
        }
        fmt::Debug::fmt(&self.raw, f)
    }
}

impl<Raw: fmt::Debug + fmt::Display, Invariant: crate::Test<Raw, 1>> fmt::Display
    for Sigma<Raw, Invariant>
{
    #[inline(always)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.raw, f)
    }
}

impl<Raw: fmt::Debug, Invariant: crate::Test<Raw, 1>> ops::Deref for Sigma<Raw, Invariant> {
    type Target = Raw;

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.raw
    }
}

#[cfg(feature = "serde")]
#[expect(clippy::missing_trait_methods, reason = "I'm no expert")]
impl<'de, Raw: fmt::Debug + serde::Deserialize<'de>, Invariant: crate::Test<Raw, 1>>
    serde::Deserialize<'de> for Sigma<Raw, Invariant>
{
    #[inline]
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use serde::de::Error;

        let raw = Raw::deserialize(deserializer)?;
        let provisional = Self {
            phantom: PhantomData,
            raw,
        };
        match provisional.try_check() {
            Ok(()) => {}
            Err(e) => return Err(Error::custom(e)),
        }
        Ok(provisional)
    }
}

#[cfg(feature = "serde")]
impl<Raw: fmt::Debug + serde::Serialize, Invariant: crate::Test<Raw, 1>> serde::Serialize
    for Sigma<Raw, Invariant>
{
    #[inline(always)]
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.raw.serialize(serializer)
    }
}