connections 0.1.0

Galois connections as first-class values: lawful numeric casts, Q-format / IEEE / time ladders
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
//! Connections among **Rust core/std primitive types** —
//! `iN`/`uN` std integers, IEEE floats (`f16`/`f32`/`f64`), `bool`,
//! `char`, and [`core::num::NonZero<T>`]. The crate's only top-level
//! domain split is between this module (Conns whose endpoints all
//! ship in `core` / `std`) and `crate::fixed` (Conns where at least
//! one endpoint is a [`fixed`]-crate Q-format wrapper).
//!
//! [`fixed`]: https://docs.rs/fixed
//! [`core::num::NonZero<T>`]: https://doc.rust-lang.org/core/num/struct.NonZero.html
//!
//! ## Submodules
//!
//! - [`mod@i008`] / [`mod@i016`] / [`mod@i032`] / [`mod@i064`] / [`mod@i128`] —
//!   signed-source std-int Conns plus `NonZeroI<N>` host surfaces.
//! - [`mod@u008`] / [`mod@u016`] / [`mod@u032`] / [`mod@u064`] / [`mod@u128`] —
//!   unsigned-source std-int Conns plus `NonZeroU<N>` host surfaces.
//! - `f016` (gated on `f16`) / [`mod@f032`] / [`mod@f064`] —
//!   IEEE-float Conns; the [`N5<T>`](crate::float::N5)
//!   wrapper and float-only infrastructure live in [`crate::float`].
//! - [`mod@char`] — `Extended<u32> → Extended<char>` codepoint projection.
//! - [`mod@bool`] — bool ↔ `[u8;1]` / `LE<1>` projections.
//! - [`mod@usize`] — `usize → u8`/`u16`/`u32`/`u64`/`u128` pointer-width
//!   saturating casts (portable via `TryFrom`).
//! - [`mod@isize`] — `isize → i8`/`i16`/`i128` pointer-width casts
//!   (`→ i32`/`→ i64` deferred; direction flips with pointer width).
//!
//! ## Conn-name prefix conventions
//!
//! The prefix letter alone tells you which world a side belongs to:
//!
//! | Prefix | Shape | Side meaning                                            |
//! |--------|-------|---------------------------------------------------------|
//! | `I`    | 1L+3D | signed std primitive (`iN`). Digits = bit-width.        |
//! | `U`    | 1L+3D | unsigned std primitive (`uN`). Digits = bit-width.      |
//! | `F`    | 1L+3D | IEEE binary float (`f16`/`f32`/`f64`). Digits = bit-width. |
//! | `N`    | 1L+3D | `NonZero<iN>` / `NonZero<uN>`. Sign implicit by module path; digits = bit-width. |
//! | `BE`/`LE` | 2L+2D | big-/little-endian byte array (`[u8; N]`, [`LE`], [`B2`], [`L2`]). Digits = byte count. |
//! | `USZE` | 4L+0D | pointer-width `usize` source ([`mod@usize`]). Whole side is the mnemonic; no digits. |
//! | `ISZE` | 4L+0D | pointer-width `isize` source ([`mod@isize`]). Whole side is the mnemonic; no digits. |
//!
//! Cross-module name collisions are allowed and resolved by qualified import.
//!
//! ## Macros
//!
//! Nine macro families generate the std-int Conns; all live in this
//! parent module and are `pub(crate)`-imported by the per-primitive
//! submodules:
//!
//! | macro | direction | Galois | constructor |
//! |---|---|---|---|
//! | `uint_uint!`        | U→U widening    | left  | `new_l` |
//! | `int_uint!`         | I→U widening    | left  | `new_l` |
//! | `ext_int!`          | I→I, U→I widening (Extended source) | left  | `new_l` |
//! | `int_int_narrow!`   | I→I narrowing   | left  | `new_l` |
//! | `uint_uint_narrow!` | U→U narrowing   | left  | `new_l` |
//! | `int_uint_narrow!`  | I→U narrowing   | left  | `new_l` |
//! | `uint_int_sat!`     | U→I non-widening | right | `new_r` |
//! | `nz_int_ext!`       | `iN ↔ NonZero<iN>`  | adjoint triple | both |
//! | `nz_uint_ext!`      | `uN ↔ NonZero<uN>`  | left | `new_l` |
//!
//! The four narrowing/non-widening macros use a **FINE_MAX
//! boundary fixup** in `inner` (`inner(Coarse::MAX) =
//! Source::MAX`) so the relevant Galois bi-implication holds at
//! the source-side saturation plateau. The right-Galois
//! `uint_int_sat!` macro doesn't need the fixup: its plateau lives
//! on the target side.

/// Little-endian byte array wrapper with numeric-sort ordering.
///
/// Plain `[u8; N]` uses lexicographic order from index 0 upward, which
/// makes big-endian byte arrays sortable but breaks little-endian numeric
/// order for multi-byte widths. `LE<N>` keeps the little-endian storage
/// shape while ordering from the most-significant byte down to the
/// least-significant byte.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct LE<const N: usize>(pub [u8; N]);

impl<const N: usize> Ord for LE<N> {
    #[inline]
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.0.iter().rev().cmp(other.0.iter().rev())
    }
}

impl<const N: usize> PartialOrd for LE<N> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<const N: usize> From<[u8; N]> for LE<N> {
    #[inline]
    fn from(bytes: [u8; N]) -> Self {
        Self(bytes)
    }
}

impl<const N: usize> From<LE<N>> for [u8; N] {
    #[inline]
    fn from(bytes: LE<N>) -> Self {
        bytes.0
    }
}

impl<const N: usize> AsRef<[u8; N]> for LE<N> {
    #[inline]
    fn as_ref(&self) -> &[u8; N] {
        &self.0
    }
}

/// Big-endian two's-complement byte array wrapper with signed numeric-sort ordering.
///
/// Plain `[u8; N]` uses lexicographic order from index 0 upward, which
/// makes unsigned big-endian byte arrays sortable but breaks signed
/// two's-complement order because negative values have the sign bit set.
/// `B2<N>` keeps the big-endian storage shape while ordering by the
/// decoded signed value.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct B2<const N: usize>(pub [u8; N]);

impl<const N: usize> Ord for B2<N> {
    #[inline]
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        if N == 0 {
            return core::cmp::Ordering::Equal;
        }

        (self.0[0] ^ 0x80)
            .cmp(&(other.0[0] ^ 0x80))
            .then_with(|| self.0[1..].cmp(&other.0[1..]))
    }
}

impl<const N: usize> PartialOrd for B2<N> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<const N: usize> From<[u8; N]> for B2<N> {
    #[inline]
    fn from(bytes: [u8; N]) -> Self {
        Self(bytes)
    }
}

impl<const N: usize> From<B2<N>> for [u8; N] {
    #[inline]
    fn from(bytes: B2<N>) -> Self {
        bytes.0
    }
}

impl<const N: usize> AsRef<[u8; N]> for B2<N> {
    #[inline]
    fn as_ref(&self) -> &[u8; N] {
        &self.0
    }
}

/// Little-endian two's-complement byte array wrapper with signed numeric-sort ordering.
///
/// Plain `[u8; N]` uses lexicographic order from index 0 upward, which
/// makes unsigned big-endian byte arrays sortable but breaks both
/// little-endian byte order and signed two's-complement order. `L2<N>`
/// keeps the little-endian storage shape while ordering by the decoded
/// signed value.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct L2<const N: usize>(pub [u8; N]);

impl<const N: usize> Ord for L2<N> {
    #[inline]
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        let mut lhs = self.0.iter().rev();
        let mut rhs = other.0.iter().rev();

        let Some(&lhs_sign) = lhs.next() else {
            return core::cmp::Ordering::Equal;
        };
        let rhs_sign = *rhs.next().expect("matching const length");

        (lhs_sign ^ 0x80)
            .cmp(&(rhs_sign ^ 0x80))
            .then_with(|| lhs.cmp(rhs))
    }
}

impl<const N: usize> PartialOrd for L2<N> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<const N: usize> From<[u8; N]> for L2<N> {
    #[inline]
    fn from(bytes: [u8; N]) -> Self {
        Self(bytes)
    }
}

impl<const N: usize> From<L2<N>> for [u8; N] {
    #[inline]
    fn from(bytes: L2<N>) -> Self {
        bytes.0
    }
}

impl<const N: usize> AsRef<[u8; N]> for L2<N> {
    #[inline]
    fn as_ref(&self) -> &[u8; N] {
        &self.0
    }
}

/// Byte-array wrapper whose default-derived `Ord` is raw
/// lexicographic compare over the bytes.
///
/// `LX<N>` itself does no encoding or decoding — it just carries
/// the contract that comparison walks the bytes left-to-right.
/// Producers that want numeric-equivalent ordering ship Conns
/// (`IxxxLXxy` in `src/core/iNNN.rs`) that bias signed inputs by
/// `1 << (bits-1)` before big-endian encoding so the stored bytes
/// sort numerically; consumers that just want lex ordering over
/// arbitrary bytes can use the wrapper directly.
///
/// Typical consumers are byte-keyed stores (LMDB, RocksDB, sled,
/// etc.) that compare keys directly without consulting Rust's
/// `Ord`, and sorted in-memory containers where the lex contract
/// is explicit. For 2s-complement preservation use [`B2`] / [`L2`].
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct LX<const N: usize>(pub [u8; N]);

impl<const N: usize> From<[u8; N]> for LX<N> {
    #[inline]
    fn from(bytes: [u8; N]) -> Self {
        Self(bytes)
    }
}

impl<const N: usize> From<LX<N>> for [u8; N] {
    #[inline]
    fn from(bytes: LX<N>) -> Self {
        bytes.0
    }
}

impl<const N: usize> AsRef<[u8; N]> for LX<N> {
    #[inline]
    fn as_ref(&self) -> &[u8; N] {
        &self.0
    }
}

#[cfg(test)]
mod le_tests {
    use super::{B2, L2, LE};

    #[test]
    fn le_order_compares_most_significant_byte_first() {
        assert!(LE([1]) < LE([2]));
        assert!(LE([1, 0]) < LE([2, 0]));
        assert!(LE([255, 0]) < LE([0, 1]));
        assert!(LE([255, 255, 0, 0]) < LE([0, 0, 1, 0]));
    }

    #[test]
    fn le_equality_matches_inner_bytes() {
        assert_eq!(LE([1, 2, 3, 4]), LE([1, 2, 3, 4]));
        assert_ne!(LE([1, 2, 3, 4]), LE([1, 2, 3, 5]));
    }

    #[test]
    fn b2_order_compares_as_signed_big_endian() {
        assert!(B2([0x80]) < B2([0x00]));
        assert!(B2([0xFF]) < B2([0x00]));
        assert!(B2([0x80, 0x00]) < B2([0xFF, 0xFF]));
        assert!(B2([0xFF, 0xFF]) < B2([0x00, 0x00]));
        assert!(B2([0x00, 0x00]) < B2([0x7F, 0xFF]));
    }

    #[test]
    fn b2_equality_matches_inner_bytes() {
        assert_eq!(B2([1, 2, 3, 4]), B2([1, 2, 3, 4]));
        assert_ne!(B2([1, 2, 3, 4]), B2([1, 2, 3, 5]));
    }

    #[test]
    fn l2_order_compares_as_signed_little_endian() {
        assert!(L2([0x80]) < L2([0x00]));
        assert!(L2([0xFF]) < L2([0x00]));
        assert!(L2([0x00, 0x80]) < L2([0xFF, 0xFF]));
        assert!(L2([0xFF, 0xFF]) < L2([0x00, 0x00]));
        assert!(L2([0x01, 0x00]) < L2([0x00, 0x01]));
        assert!(L2([0x00, 0x00]) < L2([0xFF, 0x7F]));
    }

    #[test]
    fn l2_equality_matches_inner_bytes() {
        assert_eq!(L2([1, 2, 3, 4]), L2([1, 2, 3, 4]));
        assert_ne!(L2([1, 2, 3, 4]), L2([1, 2, 3, 5]));
    }
}

// ── std-int Conn macros ────────────────────────────────────────────

/// `Conn<u_N, u_M>` widening (`bits(u_N) < bits(u_M)`).
///
/// `ceil` is the lossless `as`-upcast; `inner` saturates targets
/// above `u_N::MAX` down to `u_N::MAX` before downcasting.
#[cfg_attr(feature = "macros", macro_export)]
macro_rules! uint_uint {
    ($NAME:ident, $A:ty, $B:ty) => {
        #[doc = concat!("`", stringify!($A), "", stringify!($B), "` saturating cast.")]
        pub const $NAME: $crate::conn::Conn<$A, $B> = {
            fn ceil(x: $A) -> $B {
                x as $B
            }
            fn inner(x: $B) -> $A {
                let cap = <$A>::MAX as $B;
                let clipped = if x > cap { cap } else { x };
                clipped as $A
            }
            $crate::conn::Conn::new_l(ceil, inner)
        };
    };
}
pub(crate) use uint_uint;

/// `Conn<i_N, u_M>` widening or same-width cross-sign
/// (`bits(i_N) ≤ bits(u_M)`).
///
/// `ceil` clips negatives to `0` then upcasts (lossless on the
/// non-negative half by the bit-width constraint); `inner`
/// saturates targets above `i_N::MAX` down to `i_N::MAX`.
#[cfg_attr(feature = "macros", macro_export)]
macro_rules! int_uint {
    ($NAME:ident, $A:ty, $B:ty) => {
        // rustfmt's indent-instability bug with `#[doc = concat!(...)]`
        // means each fmt round pushes the args further right.
        // `#[rustfmt::skip]` pins the layout. See ext_int! below for
        // the same workaround.
#[rustfmt::skip]
        #[doc = concat!(
            "`",
            stringify!($A),
            "",
            stringify!($B),
            "` saturating cast: negatives clip to 0; `inner` saturates at source max."
        )]
        pub const $NAME: $crate::conn::Conn<$A, $B> = {
            fn ceil(x: $A) -> $B {
                if x < 0 { 0 } else { x as $B }
            }
            fn inner(x: $B) -> $A {
                let cap = <$A>::MAX as $B;
                let clipped = if x > cap { cap } else { x };
                clipped as $A
            }
            $crate::conn::Conn::new_l(ceil, inner)
        };
    };
}
pub(crate) use int_uint;

/// `Conn<Extended<$A>, $B>` widening with Extended source (left-Galois).
/// Covers both `I??I??` (signed widening) and `U??I??`
/// (unsigned-into-signed widening) — the body is identical, only
/// the source's `MIN`/`MAX` differ.
///
/// Constraints (verified at the call site, not at compile time):
/// - `(<$A>::MIN as $B) - 1` and `(<$A>::MAX as $B) + 1` must fit
///   in `$B` — guaranteed by `bits($A) < bits($B)` (signed source)
///   or `bits($A) ≤ bits($B) - 1` (unsigned source, equivalent).
/// - `<$B>::MIN < BELOW` and `<$B>::MAX > ABOVE` (i.e. target has
///   room beyond the source range so saturation values are
///   distinct).
///
/// **One-sided.** `_inner` collapses every rung value `≤ BELOW` onto
/// `Extended::NegInf` and every rung value `≥ ABOVE` onto
/// `Extended::PosInf` — non-injective at the saturation regions, so
/// not order-reflecting, so no true adjoint triple exists. The
/// L-Galois adjunction `ceil ⊣ inner` holds on the full domain;
/// shipped as `ConnL` accordingly. (Plan 32.)
#[cfg_attr(feature = "macros", macro_export)]
macro_rules! ext_int {
    ($NAME:ident, $A:ty, $B:ty) => {
#[rustfmt::skip]
        #[doc = concat!(
            "`Extended<",
            stringify!($A),
            "> → ",
            stringify!($B),
            "` left-Galois widening."
        )]
        pub const $NAME: $crate::conn::Conn<$crate::extended::Extended<$A>, $B> = {
            const BELOW: $B = (<$A>::MIN as $B) - 1;
            const ABOVE: $B = (<$A>::MAX as $B) + 1;
            fn ceil(x: $crate::extended::Extended<$A>) -> $B {
                match x {
                    $crate::extended::Extended::NegInf => <$B>::MIN,
                    $crate::extended::Extended::Finite(a) => a as $B,
                    $crate::extended::Extended::PosInf => ABOVE,
                }
            }
            fn inner(x: $B) -> $crate::extended::Extended<$A> {
                if x <= BELOW {
                    $crate::extended::Extended::NegInf
                } else if x >= ABOVE {
                    $crate::extended::Extended::PosInf
                } else {
                    $crate::extended::Extended::Finite(x as $A)
                }
            }

            $crate::conn::Conn::new_l(ceil, inner)
        };
    };
}
pub(crate) use ext_int;

// ── Narrowing macros ───────────────────────────────────────────────

/// `Conn<i_N, i_M>` narrowing (`bits(i_N) > bits(i_M)`).
///
/// **Constraint** (verified at the call site, not at compile time):
/// `bits($A) > bits($B)`. The macro's `ceil` casts `<$B>::MAX as $A`
/// and `<$B>::MIN as $A` for its threshold checks; both must fit
/// losslessly in `$A` for the saturation logic to be correct.
/// Mirrors the `ext_int!` constraint a few lines up.
///
/// `ceil` saturates at both `i_M::MIN` and `i_M::MAX`; `inner` is
/// the lossless widen with the high-end FINE_MAX fixup
/// (`inner(i_M::MAX) = i_N::MAX`).
///
/// **Why no FINE_MIN fixup?** The low-end plateau holds for
/// `galois_l` without one. The plateau covers source values
/// `a < i_M::MIN as i_N` (everything `ceil` collapses onto
/// `i_M::MIN`). For these, `ceil(a) = i_M::MIN ≤ b` is true for
/// every `b ∈ i_M`, so the law's LHS is always true, and the RHS
/// (`a ≤ inner(b)`) is also always true because
/// `inner(b) ≥ i_M::MIN as i_N > a` (since
/// `i_M::MIN as i_N > i_N::MIN ≥ a` by the bit-width
/// constraint). Both sides match without fiddling. Compare the
/// high end, where `ceil` collapsing onto `i_M::MAX` does require
/// the fixup so `a ≤ inner(i_M::MAX) = i_N::MAX` holds.
#[cfg_attr(feature = "macros", macro_export)]
macro_rules! int_int_narrow {
    ($NAME:ident, $A:ty, $B:ty) => {
        #[doc = concat!("`", stringify!($A), "", stringify!($B), "` saturating narrow.")]
        pub const $NAME: $crate::conn::Conn<$A, $B> = {
            fn ceil(x: $A) -> $B {
                if x > <$B>::MAX as $A {
                    <$B>::MAX
                } else if x < <$B>::MIN as $A {
                    <$B>::MIN
                } else {
                    x as $B
                }
            }
            fn inner(x: $B) -> $A {
                if x == <$B>::MAX { <$A>::MAX } else { x as $A }
            }
            $crate::conn::Conn::new_l(ceil, inner)
        };
    };
}
pub(crate) use int_int_narrow;

/// `Conn<u_N, u_M>` narrowing (`bits(u_N) > bits(u_M)`).
///
/// `ceil` saturates source values above `u_M::MAX` down to
/// `u_M::MAX` before downcasting. There is **no** low-end branch
/// (no `MIN` saturation arm) because both endpoints are unsigned —
/// the source range starts at `0 = u_N::MIN ≥ u_M::MIN = 0`, so no
/// source value can fall below the target's minimum. Compare
/// `int_int_narrow!`, which needs both arms because signed sources
/// can dip below the target's `MIN`.
///
/// `inner` is the lossless `as`-widen with a FINE_MAX fixup
/// (`inner(u_M::MAX) = u_N::MAX`). The fixup is required for
/// left-Galois to hold at the source-side saturation plateau
/// (mirrors the same pattern in the per-primitive `fix_fix_uN!`
/// macros).
#[cfg_attr(feature = "macros", macro_export)]
macro_rules! uint_uint_narrow {
    ($NAME:ident, $A:ty, $B:ty) => {
        #[doc = concat!("`", stringify!($A), "", stringify!($B), "` saturating narrow.")]
        pub const $NAME: $crate::conn::Conn<$A, $B> = {
            fn ceil(x: $A) -> $B {
                if x > <$B>::MAX as $A {
                    <$B>::MAX
                } else {
                    x as $B
                }
            }
            fn inner(x: $B) -> $A {
                if x == <$B>::MAX { <$A>::MAX } else { x as $A }
            }
            $crate::conn::Conn::new_l(ceil, inner)
        };
    };
}
pub(crate) use uint_uint_narrow;

/// `Conn<u_N, i_M>` non-widening cross-sign (`bits(u_N) ≥ bits(i_M)`).
///
/// **Constraint** (verified at the call site, not at compile time):
/// `bits($A) ≥ bits($B)`. `floor` casts `<$B>::MAX as $A`, which
/// must fit in `$A` losslessly — guaranteed by the bit-width
/// constraint since `$B::MAX > 0` and unsigned `$A` can hold any
/// positive value up to `$A::MAX ≥ $B::MAX`. `inner` casts
/// non-negative `$B` values to `$A`, also lossless under the
/// same constraint. Mirrors the `ext_int!` constraint pattern.
///
/// **Right-Galois single-sided** (uses [`Conn::new_r`](crate::conn::Conn::new_r)). The
/// saturation plateau lives on the target side: `inner` clips
/// `i_M`'s negative half to `0_u_N`. `floor` saturates `u_N` values
/// above `i_M::MAX` down to `i_M::MAX`.
///
/// No FINE_MAX fixup needed: `inner`'s image is exactly
/// `[0, i_M::MAX as u_N]`, and `floor`'s collapse at the high
/// plateau aligns the target-side fiber with the source identity at
/// `i_M::MAX`.
#[cfg_attr(feature = "macros", macro_export)]
macro_rules! uint_int_sat {
    ($(#[$attr:meta])* $NAME:ident, $A:ty, $B:ty) => {
        #[doc = concat!("`", stringify!($A), "", stringify!($B), "` saturating cast (right-Galois).")]
        $(#[$attr])*
        pub const $NAME: $crate::conn::Conn<$A, $B, $crate::conn::R> = {
            fn floor(x: $A) -> $B {
                if x > <$B>::MAX as $A {
                    <$B>::MAX
                } else {
                    x as $B
                }
            }
            fn inner(x: $B) -> $A {
                if x < 0 { 0 } else { x as $A }
            }
            $crate::conn::Conn::new_r(inner, floor)
        };
    };
}
pub(crate) use uint_int_sat;

/// `Conn<i<N>, NonZero<i<N>>>` — saturate `iN` onto `NonZero<iN>` with
/// asymmetric rounding at zero. Source is the bare primitive (not
/// `Extended<iN>`) so there are no infinities at the source-side
/// plateau to break the Galois law: every `iN` value other than 0 is
/// itself a `NonZero<iN>`, and 0 sandwiches between `NonZero(-1)` and
/// `NonZero(+1)`.
///
/// Forward (`ceil` / `floor`): `iN → NonZero<iN>`.
///
/// - `floor(0) = NonZero(-1)`  (largest NonZero ≤ 0)
/// - `ceil(0)  = NonZero(+1)`  (smallest NonZero ≥ 0)
/// - For `v != 0`: `ceil(v) = floor(v) = NonZero(v)` (lossless).
///
/// Back (`inner`): trivial total embedding
/// `NonZero<iN> → iN::get()`.
///
/// Both Galois laws (`galois_l` and `galois_r`) hold: the
/// asymmetric `floor`/`ceil` lift the target's puncture at zero to a
/// [-1, +1] sandwich on the source side, exactly bracketing the
/// missing value.
#[cfg_attr(feature = "macros", macro_export)]
macro_rules! nz_int_ext {
    ($NAME:ident, $A:ty, $NZ:ty) => {
#[rustfmt::skip]
        #[doc = concat!(
            "`",
            stringify!($A),
            "",
            stringify!($NZ),
            "` (signed; floor/ceil split 0 between -1 and +1)."
        )]
        #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)]
        pub struct $NAME;

        impl $NAME {
            const fn _ceil(v: $A) -> $NZ {
                let r: $A = if v == 0 { 1 } else { v };
                match <$NZ>::new(r) {
                    Some(nz) => nz,
                    None => panic!("nz_int_ext::ceil produced zero"),
                }
            }
            const fn _floor(v: $A) -> $NZ {
                let r: $A = if v == 0 { -1 } else { v };
                match <$NZ>::new(r) {
                    Some(nz) => nz,
                    None => panic!("nz_int_ext::floor produced zero"),
                }
            }
            const fn _inner(nz: $NZ) -> $A {
                nz.get()
            }
        }

        impl $NAME {
            /// The L-view. `const`-projectable.
            #[allow(dead_code)]
            #[inline]
            #[must_use]
            pub const fn view_l(self) -> $crate::conn::Conn<$A, $NZ, $crate::conn::L> {
                $crate::conn::Conn::new_l($NAME::_ceil, $NAME::_inner)
            }
            /// The R-view. `const`-projectable.
            #[allow(dead_code)]
            #[inline]
            #[must_use]
            pub const fn view_r(self) -> $crate::conn::Conn<$A, $NZ, $crate::conn::R> {
                $crate::conn::Conn::new_r($NAME::_inner, $NAME::_floor)
            }
            /// The swapped L-view. `const`-projectable.
            #[allow(dead_code)]
            #[inline]
            #[must_use]
            pub const fn swap_l(self) -> $crate::conn::Conn<$NZ, $A, $crate::conn::R> {
                self.view_l().swap_l()
            }
            /// The swapped R-view. `const`-projectable.
            #[allow(dead_code)]
            #[inline]
            #[must_use]
            pub const fn swap_r(self) -> $crate::conn::Conn<$NZ, $A, $crate::conn::L> {
                self.view_r().swap_r()
            }
        }
        impl $crate::conn::ConnL for $NAME {
            type A = $A;
            type B = $NZ;
            #[inline]
            fn swap_l(&self) -> $crate::conn::Conn<$NZ, $A, $crate::conn::R> {
                // Inherent `const fn swap_l` (path call), not the trait
                // `view_l` default — the `&self` receiver would recurse.
                $NAME::swap_l(*self)
            }
        }
        impl $crate::conn::ConnR for $NAME {
            type A = $A;
            type B = $NZ;
            #[inline]
            fn swap_r(&self) -> $crate::conn::Conn<$NZ, $A, $crate::conn::L> {
                $NAME::swap_r(*self)
            }
        }
    };
}
pub(crate) use nz_int_ext;

/// `Conn<u<N>, NonZero<u<N>>>` — unsigned counterpart of
/// [`nz_int_ext!`]. `floor` and `ceil` collapse identically at 0
/// because there is no NonZero ≤ 0 on the unsigned side: both pick
/// `NonZero(1)`, the smallest representable NonZero. Single-sided
/// left-Galois ([`Conn::new_l`]) — `floor = ceil`. The
/// right-Galois law fails at `(NonZero(1), 0)` (no NonZero strictly
/// below 1 to act as the "previous" rounding target).
///
/// [`Conn::new_l`]: crate::conn::Conn::new_l
#[cfg_attr(feature = "macros", macro_export)]
macro_rules! nz_uint_ext {
    ($NAME:ident, $A:ty, $NZ:ty) => {
#[rustfmt::skip]
        #[doc = concat!(
            "`",
            stringify!($A),
            "",
            stringify!($NZ),
            "` (unsigned; 0 saturates to NonZero(1); single-sided left-Galois)."
        )]
        pub const $NAME: $crate::conn::Conn<$A, $NZ> = {
            fn ceil(v: $A) -> $NZ {
                let r: $A = if v == 0 { 1 } else { v };
                match <$NZ>::new(r) {
                    Some(nz) => nz,
                    None => panic!("nz_uint_ext::ceil produced zero"),
                }
            }
            fn inner(nz: $NZ) -> $A {
                nz.get()
            }

            $crate::conn::Conn::new_l(ceil, inner)
        };
    };
}
pub(crate) use nz_uint_ext;

/// `Conn<NonZero<u_N>, NonZero<u_M>>` widening
/// (`bits(u_N) < bits(u_M)`).
///
/// Mirrors [`uint_uint!`] at the [`NonZero`](core::num) layer.
/// `ceil` lossless-widens via `n.get() as $UM`; the result is never
/// zero because `NonZero<u_N>.get() ≥ 1`. `inner` saturates targets
/// above `u_N::MAX` down to `NonZero<u_N>::new(u_N::MAX)`. The zero
/// gap of [`nz_uint_ext!`] doesn't appear here — `NonZero<u_M>.get()
/// ≥ 1`, so the clipped value is always `≥ 1` after the saturation,
/// and `NonZero<u_N>::new` succeeds without panic.
///
/// Single-sided left-Galois ([`Conn::new_l`]) — the saturation
/// plateau at `NonZero<u_N>::MAX` lives on the source side.
///
/// [`Conn::new_l`]: crate::conn::Conn::new_l
/// [`uint_uint!`]: crate::uint_uint
/// [`nz_uint_ext!`]: crate::nz_uint_ext
#[cfg_attr(feature = "macros", macro_export)]
macro_rules! nz_uint_widen {
    ($NAME:ident, $NZN:ty, $UN:ty, $NZM:ty, $UM:ty) => {
#[rustfmt::skip]
        #[doc = concat!(
            "`",
            stringify!($NZN),
            "",
            stringify!($NZM),
            "` lossless widening; `inner` saturates at `",
            stringify!($NZN),
            "::MAX`."
        )]
        pub const $NAME: $crate::conn::Conn<$NZN, $NZM> = {
            fn ceil(n: $NZN) -> $NZM {
                match <$NZM>::new(n.get() as $UM) {
                    Some(nz) => nz,
                    // unreachable: NZN::get() ≥ 1, cast preserves value
                    None => panic!("nz_uint_widen::ceil produced zero"),
                }
            }
            fn inner(m: $NZM) -> $NZN {
                let cap = <$UN>::MAX as $UM;
                let val = m.get();
                let clipped = if val > cap { cap } else { val };
                match <$NZN>::new(clipped as $UN) {
                    Some(nz) => nz,
                    // unreachable: clipped ≥ NZM::get() ≥ 1, cap ≥ 1
                    None => panic!("nz_uint_widen::inner produced zero"),
                }
            }
            $crate::conn::Conn::new_l(ceil, inner)
        };
    };
}
pub(crate) use nz_uint_widen;

// No `nz_int_widen!`. Signed `NonZero<i_N> → NonZero<i_M>` (N < M)
// cannot be expressed as a bare `Conn<NonZero<i_N>, NonZero<i_M>>`:
// the target side has plateaus on *both* ends (values in
// `[i_M::MIN, i_N::MIN as i_M - 1]` below the source range, and
// `[i_N::MAX as i_M + 1, i_M::MAX]` above it). Closing the lower
// plateau requires a `-Inf` sentinel on the source — which
// `NonZero<i_N>` does not provide — so no `inner` choice satisfies
// L-Galois on the lower plateau. R-Galois fails symmetrically on the
// upper plateau. Compare `nz_uint_widen!`, where the unsigned lower
// bound `u_N::MIN = 0 < 1 = NonZero<u_M>::MIN` makes the lower
// plateau empty and saturation is sound. Use `nz_int_ext!` +
// `ext_int!` to widen via `i_N -> Extended<i_N> -> i_M ->
// NonZero<i_M>` when needed.

/// `Conn<i_N, u_M>` narrowing (`bits(i_N) > bits(u_M)`).
///
/// `ceil` clips negatives to `0` and saturates positives at
/// `u_M::MAX`; `inner` is the lossless `as`-widen with a FINE_MAX
/// fixup (`inner(u_M::MAX) = i_N::MAX`). The negative half of the
/// source has no plateau issue (it collapses on `ceil`, the
/// source-side fiber compatible with left-Galois).
#[cfg_attr(feature = "macros", macro_export)]
macro_rules! int_uint_narrow {
    ($NAME:ident, $A:ty, $B:ty) => {
        #[doc = concat!("`", stringify!($A), "", stringify!($B), "` saturating narrow.")]
        pub const $NAME: $crate::conn::Conn<$A, $B> = {
            fn ceil(x: $A) -> $B {
                if x < 0 {
                    0
                } else if x > <$B>::MAX as $A {
                    <$B>::MAX
                } else {
                    x as $B
                }
            }
            fn inner(x: $B) -> $A {
                if x == <$B>::MAX { <$A>::MAX } else { x as $A }
            }
            $crate::conn::Conn::new_l(ceil, inner)
        };
    };
}
pub(crate) use int_uint_narrow;

/// `Conn<NonZero<i_N>, NonZero<i_M>>` narrowing
/// (`bits(i_N) > bits(i_M)`).
///
/// Mirrors [`int_int_narrow!`] at the signed [`NonZero`](core::num)
/// layer. `ceil` saturates source values above `i_M::MAX` to
/// `i_M::MAX` and below `i_M::MIN` to `i_M::MIN` (both nonzero, so
/// no zero gap reappears). `inner` is the lossless `as`-widen with a
/// FINE_MAX fixup (`inner(i_M::MAX) = i_N::MAX`).
///
/// **Why no FINE_MIN fixup?** Same argument as [`int_int_narrow!`]:
/// the low-end source plateau covers every `a < i_M::MIN as i_N`,
/// where `ceil(a) = i_M::MIN ≤ b` is always true and
/// `inner(b) ≥ i_M::MIN as i_N > a` is always true (since
/// `i_M::MIN as i_N > i_N::MIN ≥ a` by the bit-width constraint),
/// so the law's LHS and RHS match without a fixup. Compare the high
/// end, where `ceil` collapsing onto `i_M::MAX` does require the
/// fixup so `a ≤ inner(i_M::MAX) = i_N::MAX` holds.
///
/// Single-sided left-Galois ([`Conn::new_l`]).
///
/// [`Conn::new_l`]: crate::conn::Conn::new_l
/// [`int_int_narrow!`]: crate::int_int_narrow
#[cfg_attr(feature = "macros", macro_export)]
macro_rules! nz_int_narrow {
    ($NAME:ident, $NZN:ty, $IN:ty, $NZM:ty, $IM:ty) => {
#[rustfmt::skip]
        #[doc = concat!(
            "`",
            stringify!($NZN),
            "",
            stringify!($NZM),
            "` saturating narrow; `inner` widens with FINE_MAX fixup at `",
            stringify!($NZM),
            "::MAX`."
        )]
        pub const $NAME: $crate::conn::Conn<$NZN, $NZM> = {
            fn ceil(n: $NZN) -> $NZM {
                let val = n.get();
                let clipped = if val > <$IM>::MAX as $IN {
                    <$IM>::MAX
                } else if val < <$IM>::MIN as $IN {
                    <$IM>::MIN
                } else {
                    val as $IM
                };
                match <$NZM>::new(clipped) {
                    Some(nz) => nz,
                    // unreachable: IN value != 0, clipped takes IM::MIN / IM::MAX /
                    // (val as IM); IM::MIN < 0 < IM::MAX, and val in [IM::MIN, IM::MAX]
                    // preserves nonzero-ness.
                    None => panic!("nz_int_narrow::ceil produced zero"),
                }
            }
            fn inner(m: $NZM) -> $NZN {
                let v: $IN = if m.get() == <$IM>::MAX {
                    <$IN>::MAX
                } else {
                    m.get() as $IN
                };
                match <$NZN>::new(v) {
                    Some(nz) => nz,
                    // unreachable: m.get() != 0; widen preserves nonzero
                    None => panic!("nz_int_narrow::inner produced zero"),
                }
            }
            $crate::conn::Conn::new_l(ceil, inner)
        };
    };
}
pub(crate) use nz_int_narrow;

/// `Conn<NonZero<u_N>, NonZero<u_M>>` narrowing
/// (`bits(u_N) > bits(u_M)`).
///
/// Mirrors [`uint_uint_narrow!`] at the unsigned
/// [`NonZero`](core::num) layer. `ceil` saturates source values
/// above `u_M::MAX` to `u_M::MAX` (nonzero) before downcasting. No
/// low-end branch: source values start at `NonZero<u_N> ≥ 1`, and
/// `u_M::MIN = 0 < 1`, so no source value can fall below the target's
/// minimum representable. The zero gap of [`nz_uint_ext!`] doesn't
/// reappear here — both endpoints' NonZero range is `[1, ::MAX]`.
///
/// `inner` is the lossless `as`-widen with a FINE_MAX fixup
/// (`inner(u_M::MAX) = u_N::MAX`).
///
/// Single-sided left-Galois ([`Conn::new_l`]).
///
/// [`Conn::new_l`]: crate::conn::Conn::new_l
/// [`uint_uint_narrow!`]: crate::uint_uint_narrow
/// [`nz_uint_ext!`]: crate::nz_uint_ext
#[cfg_attr(feature = "macros", macro_export)]
macro_rules! nz_uint_narrow {
    ($NAME:ident, $NZN:ty, $UN:ty, $NZM:ty, $UM:ty) => {
#[rustfmt::skip]
        #[doc = concat!(
            "`",
            stringify!($NZN),
            "",
            stringify!($NZM),
            "` saturating narrow; `inner` widens with FINE_MAX fixup at `",
            stringify!($NZM),
            "::MAX`."
        )]
        pub const $NAME: $crate::conn::Conn<$NZN, $NZM> = {
            fn ceil(n: $NZN) -> $NZM {
                let val = n.get();
                let clipped = if val > <$UM>::MAX as $UN {
                    <$UM>::MAX
                } else {
                    val as $UM
                };
                match <$NZM>::new(clipped) {
                    Some(nz) => nz,
                    // unreachable: UN value ≥ 1, clipped ∈ [1, UM::MAX]
                    None => panic!("nz_uint_narrow::ceil produced zero"),
                }
            }
            fn inner(m: $NZM) -> $NZN {
                let v: $UN = if m.get() == <$UM>::MAX {
                    <$UN>::MAX
                } else {
                    m.get() as $UN
                };
                match <$NZN>::new(v) {
                    Some(nz) => nz,
                    // unreachable: m.get() ≥ 1; widen preserves nonzero
                    None => panic!("nz_uint_narrow::inner produced zero"),
                }
            }
            $crate::conn::Conn::new_l(ceil, inner)
        };
    };
}
pub(crate) use nz_uint_narrow;

// ── Per-primitive submodules ───────────────────────────────────────

pub mod i008;
pub mod i016;
pub mod i032;
pub mod i064;
pub mod i128;
pub mod u008;
pub mod u016;
pub mod u032;
pub mod u064;
pub mod u128;

#[cfg(feature = "f16")]
pub mod f016;
pub mod f032;
pub mod f064;

pub mod bool;
pub mod char;
pub mod isize;
pub mod usize;