grid1d 0.4.0

A mathematically rigorous, type-safe Rust library for 1D grid operations and interval partitions, supporting both native and arbitrary-precision numerics.
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
#![deny(rustdoc::broken_intra_doc_links)]

//! Topology and index spaces for one-dimensional grids and partitions.
//!
//! This module defines the topological types used to model connectivity and
//! adjacency in a one-dimensional partition:
//!
//! - [`Topology1D`]: topological model (`RealLine` or `Circle`).
//! - [`Side`] and [`IntervalSide`]: left/right side and identification of a
//!   specific interval boundary.
//! - [`IndexSpace1D`] and [`Adjacency1D`]: abstractions for cardinality and
//!   neighbor queries.
//! - [`IntervalIndexSpace1D`] and [`PointIndexSpace1D`]: concrete index spaces
//!   for intervals and vertices.
//! - [`Grid1DIndexSpaces`]: consistent container for both grid index spaces.
//!
//! # Topological Semantics
//!
//! - [`Topology1D::RealLine`]: boundary elements have no external neighbors.
//! - [`Topology1D::Circle`]: boundary elements are connected periodically
//!   (wrap-around).
//!
//! # Example
//!
//! ```rust
//! use grid1d::{Adjacency1D, Grid1D, IntervalPartition, intervals::*, scalars::NumIntervals};
//! use try_create::TryNew;
//!
//! let grid = Grid1D::uniform(IntervalClosed::new(0.0, 1.0), NumIntervals::try_new(4).unwrap());
//! let interval_space = grid.index_spaces().interval_index_space();
//!
//! assert_eq!(interval_space.left_neighbor(&0), None);
//! assert_eq!(interval_space.right_neighbor(&0), Some(1));
//! ```

use crate::scalars::{NumIntervals, PositiveIntTrait, PositiveNumPoints1D};
use duplicate::duplicate_item;
use serde::{Deserialize, Serialize};
use try_create::TryNew;

//----------------------------------------------------------------------------------------------
pub(crate) mod sealed {
    use crate::intervals::{IntervalLowerClosedUpperOpen, IntervalLowerOpenUpperClosed};
    use num_valid::RealScalar;

    pub trait SupportsCircularTopology {}
    impl<T: RealScalar> SupportsCircularTopology for IntervalLowerClosedUpperOpen<T> {}
    impl<T: RealScalar> SupportsCircularTopology for IntervalLowerOpenUpperClosed<T> {}
}
//----------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------------------------------------
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Runtime topology model for one-dimensional grids.
///
/// [`Topology1D::RealLine`] represents a non-periodic domain with boundary
/// endpoints, while [`Topology1D::Circle`] represents periodic connectivity
/// where the first and last intervals are neighbors.
pub enum Topology1D {
    /// Non-periodic topology on the real line.
    RealLine,
    /// Periodic topology on a circle.
    Circle,
}

impl Topology1D {
    /// Returns `true` if this topology is periodic.
    pub fn is_periodic(&self) -> bool {
        matches!(self, Topology1D::Circle)
    }
}
//------------------------------------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
/// Side of an interval with respect to a reference position.
///
/// This enum is primarily used by [`IntervalPartition`](crate::traits::IntervalPartition) neighbor APIs
/// to select the left or right adjacent interval.
pub enum Side {
    /// Left side.
    Left,
    /// Right side.
    Right,
}

impl Side {
    /// Returns `true` if the side is [`Side::Left`].
    #[inline(always)]
    pub fn is_left(&self) -> bool {
        matches!(&self, Side::Left)
    }

    /// Returns `true` if the side is [`Side::Right`].
    #[inline(always)]
    pub fn is_right(&self) -> bool {
        matches!(&self, Side::Right)
    }
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------------------------------------
/// Trait for types that carry a [`Side`] — i.e. a lower/upper boundary specifier
/// for a fixed normal dimension.
///
/// Implemented by:
/// - [`Side`] itself (the side *is* the data),
/// - [`IntervalSide`] (bundles an interval index with a side).
pub trait HasSide: Copy + Clone + std::fmt::Debug + PartialEq + Eq {
    /// Returns the [`Side`] for this normal dimension.
    fn side(&self) -> Side;
}

impl HasSide for Side {
    #[inline(always)]
    fn side(&self) -> Side {
        *self
    }
}
//------------------------------------------------------------------------------------------------------------------------------

// ================================================================================================
// IntervalSide
// ================================================================================================

/// Bundles an interval index with a [`Side`], identifying one boundary of a specific interval.
///
/// Used to reference a particular boundary point of a grid interval: either the
/// lower vertex ([`Side::Left`]) or the upper vertex ([`Side::Right`]).
///
/// # Coordinate Convention
///
/// Given element index `k` along a normal axis:
///
/// | `side`                | point coordinate (`coord_index`) |
/// |-----------------------|----------------------------------|
/// | [`Side::Left`]  | `k`                              |
/// | [`Side::Right`]  | `k + 1`                          |
///
/// # Example
///
/// ```rust
/// use grid1d::{Side, IntervalSide};
///
/// let left = IntervalSide::new(3, Side::Left);
/// assert_eq!(left.interval_index(), 3);
/// assert_eq!(left.coord_index(), 3); // lower vertex of interval 3
///
/// let right = IntervalSide::new(3, Side::Right);
/// assert_eq!(right.interval_index(), 3);
/// assert_eq!(right.coord_index(), 4); // upper vertex of interval 3
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct IntervalSide {
    /// The interval index along this normal dimension.
    pub interval_index: usize,
    /// Which boundary of interval `interval_index` the restriction touches.
    pub side: Side,
}

impl IntervalSide {
    /// Creates a new [`IntervalSide`] from an interval (interval) index and a [`Side`].
    ///
    /// # Parameters
    ///
    /// - `interval_index`: zero-based interval index along the normal dimension.
    /// - `side`: which boundary of that interval the restriction touches.
    #[inline(always)]
    pub fn new(interval_index: usize, side: Side) -> Self {
        Self {
            interval_index,
            side,
        }
    }

    /// Returns the point (vertex) coordinate index for this restriction along this dimension.
    ///
    /// - [`Side::Left`] → `interval_index` (lower vertex of interval `k`).
    /// - [`Side::Right`] → `interval_index + 1` (upper vertex of interval `k`).
    #[inline(always)]
    pub fn coord_index(&self) -> usize {
        match self.side {
            Side::Left => self.interval_index,
            Side::Right => self.interval_index + 1,
        }
    }

    /// Returns the zero-based interval index along this normal dimension.
    #[inline(always)]
    pub fn interval_index(&self) -> usize {
        self.interval_index
    }
}

impl HasSide for IntervalSide {
    #[inline(always)]
    fn side(&self) -> Side {
        self.side
    }
}
//------------------------------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------
/// Left and right neighbors of an element in a 1D index space.
///
/// Returned by [`Adjacency1D::neighbors`]. Each field is `None` when the
/// element has no neighbor in that direction (boundary of a
/// [`Topology1D::RealLine`] index space), or `Some(id)` with the wrapped
/// neighbor index (always present for [`Topology1D::Circle`]).
///
/// # Example
///
/// ```rust
/// use grid1d::{Grid1D, Adjacency1D, IndexSpace1D, IntervalPartition, intervals::*, scalars::NumIntervals};
/// use try_create::TryNew;
///
/// let grid = Grid1D::uniform(IntervalClosed::new(0.0, 1.0), NumIntervals::try_new(4).unwrap());
/// let neighbors = grid.index_spaces().interval_index_space().neighbors(&2);
/// assert_eq!(neighbors.left(), Some(1));
/// assert_eq!(neighbors.right(), Some(3));
///
/// // Boundary element: no left neighbor on the real line
/// let boundary = grid.index_spaces().interval_index_space().neighbors(&0);
/// assert_eq!(boundary.left(), None);
/// assert_eq!(boundary.right(), Some(1));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Neighbors1D {
    /// The left neighbor index, or `None` if there is no left neighbor (boundary).
    left: Option<usize>,

    /// The right neighbor index, or `None` if there is no right neighbor (boundary).
    right: Option<usize>,
}

impl Neighbors1D {
    /// Returns the left neighbor, if it exists.
    pub fn left(&self) -> Option<usize> {
        self.left
    }

    /// Returns the right neighbor, if it exists.
    pub fn right(&self) -> Option<usize> {
        self.right
    }
}
//--------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------
/// An index space along one dimension: associates a count of elements with a [`Topology1D`].
///
/// Implemented by [`PointIndexSpace1D`] (for grid vertices) and
/// [`IntervalIndexSpace1D`] (for grid intervals).
pub trait IndexSpace1D {
    /// The newtype counter for this index space (e.g. [`PositiveNumPoints1D`] or [`NumIntervals`]).
    type Counter: PositiveIntTrait;

    /// Returns the topology of this index space.
    fn topology(&self) -> &Topology1D;

    /// Returns the number of elements in this index space.
    fn count(&self) -> &Self::Counter;
}
//--------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------
/// Neighbor queries for a one-dimensional index space.
///
/// Provides [`left_neighbor`](Adjacency1D::left_neighbor),
/// [`right_neighbor`](Adjacency1D::right_neighbor) and the combined
/// [`neighbors`](Adjacency1D::neighbors) query.
/// Boundary behaviour depends on the [`Topology1D`]:
/// - [`Topology1D::RealLine`]: returns `None` at the boundaries.
/// - [`Topology1D::Circle`]: wraps around (periodic).
pub trait Adjacency1D: IndexSpace1D {
    /// Returns the neighbor of `id` on the given `side`, or `None` if out of bounds.
    fn neighbor(&self, id: &usize, side: &Side) -> Option<usize> {
        match side {
            Side::Left => self.left_neighbor(id),
            Side::Right => self.right_neighbor(id),
        }
    }

    /// Returns the left neighbor of `id`, or `None` if `id` is the leftmost
    /// element in a [`Topology1D::RealLine`] topology.
    ///
    /// For [`Topology1D::Circle`], wraps around: the left neighbor of `0` is `n-1`.
    ///
    /// # Panics (debug only)
    ///
    /// Panics if `id >= count` — callers are responsible for passing valid IDs.
    fn left_neighbor(&self, id: &usize) -> Option<usize> {
        let n = *self.count().as_ref();
        more_asserts::debug_assert_lt!(*id, n, "ID {} out of bounds for count {}", id, n);

        if *id == 0 {
            match self.topology() {
                Topology1D::RealLine => None,
                Topology1D::Circle => Some(n - 1),
            }
        } else {
            Some(id - 1)
        }
    }

    /// Returns the right neighbor of `id`, or `None` if `id` is the rightmost
    /// element in a [`Topology1D::RealLine`] topology.
    ///
    /// For [`Topology1D::Circle`], wraps around: the right neighbor of `n-1` is `0`.
    ///
    /// # Panics (debug only)
    ///
    /// Panics if `id >= count` — callers are responsible for passing valid IDs.
    fn right_neighbor(&self, id: &usize) -> Option<usize> {
        let n = *self.count().as_ref();
        more_asserts::debug_assert_lt!(*id, n, "ID {} out of bounds for count {}", id, n);

        if *id == n - 1 {
            match self.topology() {
                Topology1D::RealLine => None,
                Topology1D::Circle => Some(0),
            }
        } else {
            Some(id + 1)
        }
    }

    /// Returns both neighbors of `id` as a [`Neighbors1D`].
    ///
    /// Equivalent to calling [`left_neighbor`](Adjacency1D::left_neighbor) and
    /// [`right_neighbor`](Adjacency1D::right_neighbor) individually.
    ///
    /// # Panics (debug only)
    ///
    /// Panics if `id >= count` — callers are responsible for passing valid IDs.
    fn neighbors(&self, id: &usize) -> Neighbors1D {
        Neighbors1D {
            left: self.left_neighbor(id),
            right: self.right_neighbor(id),
        }
    }
}
//--------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
/// Index space for grid points (vertices) in one dimension.
///
/// Stores the number of points and the [`Topology1D`] used to interpret
/// adjacency queries on point indices.
pub struct PointIndexSpace1D {
    /// The topology of this index space, which determines adjacency behavior.
    topology: Topology1D,

    /// The number of points (vertices) in this index space.
    count: PositiveNumPoints1D,
}

impl PointIndexSpace1D {
    /// Creates a new [`PointIndexSpace1D`] with the given topology and vertex count.
    pub fn new(topology: Topology1D, count: PositiveNumPoints1D) -> Self {
        Self { topology, count }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
/// Index space for grid intervals (cells) in one dimension.
///
/// Stores the number of intervals and the [`Topology1D`] used to interpret
/// adjacency queries on interval indices.
pub struct IntervalIndexSpace1D {
    /// The topology of this index space, which determines adjacency behavior.
    topology: Topology1D,

    /// The number of intervals in this index space.
    count: NumIntervals,
}

impl IntervalIndexSpace1D {
    /// Creates a new [`IntervalIndexSpace1D`] with the given topology and interval count.
    pub fn new(topology: Topology1D, count: NumIntervals) -> Self {
        Self { topology, count }
    }
}

#[duplicate_item(
    T counter;
    [PointIndexSpace1D]    [PositiveNumPoints1D];
    [IntervalIndexSpace1D] [NumIntervals];
)]
impl IndexSpace1D for T {
    type Counter = counter;

    /// Returns the topology of this index space (the topology determines adjacency behavior).
    fn topology(&self) -> &Topology1D {
        &self.topology
    }

    /// Returns the number of elements in this index space.
    fn count(&self) -> &Self::Counter {
        &self.count
    }
}

impl Adjacency1D for PointIndexSpace1D {}
impl Adjacency1D for IntervalIndexSpace1D {}
//--------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------
/// Bundles the [`IntervalIndexSpace1D`] and [`PointIndexSpace1D`] for a 1D grid.
///
/// A 1D grid with `n` intervals has `n+1` points; this struct keeps both
/// index spaces consistent and derived from the same topology.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Grid1DIndexSpaces {
    /// The interval index space for this grid.
    interval_index_space: IntervalIndexSpace1D,

    /// The point (vertex) index space for this grid.
    point_index_space: PointIndexSpace1D,
}

impl Grid1DIndexSpaces {
    /// Creates a [`Grid1DIndexSpaces`] for a grid with `num_intervals` intervals and
    /// the given `topology`.
    ///
    /// The point index space is automatically set to `num_intervals + 1` points.
    pub(crate) fn new(num_intervals: NumIntervals, topology: Topology1D) -> Self {
        let interval_index_space = IntervalIndexSpace1D::new(topology, num_intervals);
        let point_index_space = PointIndexSpace1D::new(
            topology,
            PositiveNumPoints1D::try_new(*num_intervals.as_ref() + 1).unwrap(),
        );
        Self {
            interval_index_space,
            point_index_space,
        }
    }

    /// Returns the interval index space for this grid.
    pub fn interval_index_space(&self) -> &IntervalIndexSpace1D {
        &self.interval_index_space
    }

    /// Returns the point (vertex) index space for this grid.
    pub fn point_index_space(&self) -> &PointIndexSpace1D {
        &self.point_index_space
    }
}
//--------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------
#[cfg(test)]
mod tests {
    use super::*;
    use crate::scalars::NumIntervals;
    use try_create::TryNew;

    // ── helpers ──────────────────────────────────────────────────────────────

    fn point_space(topology: Topology1D, n: usize) -> PointIndexSpace1D {
        PointIndexSpace1D {
            topology,
            count: PositiveNumPoints1D::try_new(n).unwrap(),
        }
    }

    fn interval_space(topology: Topology1D, n: usize) -> IntervalIndexSpace1D {
        IntervalIndexSpace1D {
            topology,
            count: NumIntervals::try_new(n).unwrap(),
        }
    }

    mod side {
        use super::*;

        #[test]
        fn side_equality() {
            assert_eq!(Side::Left, Side::Left);
            assert_eq!(Side::Right, Side::Right);
            assert_ne!(Side::Right, Side::Left);
        }

        #[test]
        fn is_left() {
            assert!(Side::Left.is_left());
            assert!(!Side::Right.is_left());
        }

        #[test]
        fn is_right() {
            assert!(Side::Right.is_right());
            assert!(!Side::Left.is_right());
        }

        #[test]
        fn has_side_for_side_returns_self() {
            assert_eq!(Side::Left.side(), Side::Left);
            assert_eq!(Side::Right.side(), Side::Right);
        }

        #[test]
        fn left_point_index() {
            let data_3 = IntervalSide::new(3, Side::Left);
            assert_eq!(data_3.coord_index(), 3);

            let data_0 = IntervalSide::new(0, Side::Left);
            assert_eq!(data_0.coord_index(), 0);
        }

        #[test]
        fn right_point_index() {
            let data_3 = IntervalSide::new(3, Side::Right);
            assert_eq!(data_3.coord_index(), 4);

            let data_0 = IntervalSide::new(0, Side::Right);
            assert_eq!(data_0.coord_index(), 1);
        }

        #[test]
        fn interval_side_interval_index_getter() {
            let s = IntervalSide::new(7, Side::Left);
            assert_eq!(s.interval_index(), 7);

            let s2 = IntervalSide::new(0, Side::Right);
            assert_eq!(s2.interval_index(), 0);
        }

        #[test]
        fn has_side_for_interval_side() {
            let left = IntervalSide::new(2, Side::Left);
            assert_eq!(left.side(), Side::Left);

            let right = IntervalSide::new(5, Side::Right);
            assert_eq!(right.side(), Side::Right);
        }
    }

    // ── Topology1D ───────────────────────────────────────────────────────────
    mod topology {
        use super::*;
        #[test]
        fn topology1d_real_line_eq_self() {
            assert_eq!(Topology1D::RealLine, Topology1D::RealLine);
        }

        #[test]
        fn topology1d_circle_eq_self() {
            assert_eq!(Topology1D::Circle, Topology1D::Circle);
        }

        #[test]
        fn topology1d_real_line_ne_circle() {
            assert_ne!(Topology1D::RealLine, Topology1D::Circle);
        }

        #[test]
        fn topology1d_copy() {
            let t = Topology1D::Circle;
            let t2 = t; // Copy
            assert_eq!(t, t2);
        }

        #[test]
        fn is_periodic_real_line_is_false() {
            assert!(!Topology1D::RealLine.is_periodic());
        }

        #[test]
        fn is_periodic_circle_is_true() {
            assert!(Topology1D::Circle.is_periodic());
        }
    }

    // ── Neighbors1D ──────────────────────────────────────────────────────────
    mod neighbors1d {
        use super::*;

        #[test]
        fn neighbors1d_construction_and_eq() {
            let a = Neighbors1D {
                left: Some(0),
                right: Some(2),
            };
            let b = Neighbors1D {
                left: Some(0),
                right: Some(2),
            };
            assert_eq!(a, b);
        }

        #[test]
        fn neighbors1d_none_variants() {
            let a = Neighbors1D {
                left: None,
                right: None,
            };
            assert_eq!(
                a,
                Neighbors1D {
                    left: None,
                    right: None
                }
            );
        }

        #[test]
        fn neighbors1d_copy() {
            let a = Neighbors1D {
                left: Some(1),
                right: None,
            };
            let b = a; // Copy
            assert_eq!(a, b);
        }
    }

    // ── IndexSpace1D / count / topology ──────────────────────────────────────

    #[test]
    fn point_index_space_topology_and_count() {
        let s = point_space(Topology1D::RealLine, 5);
        assert_eq!(*s.topology(), Topology1D::RealLine);
        assert_eq!(*s.count().as_ref(), 5);
    }

    #[test]
    fn interval_index_space_topology_and_count() {
        let s = interval_space(Topology1D::Circle, 4);
        assert_eq!(*s.topology(), Topology1D::Circle);
        assert_eq!(*s.count().as_ref(), 4);
    }

    // ── Adjacency1D::left_neighbor — Open ────────────────────────────────────

    #[test]
    fn left_neighbor_open_first_element_is_none() {
        let s = point_space(Topology1D::RealLine, 5);
        assert_eq!(s.left_neighbor(&0), None);
    }

    #[test]
    fn left_neighbor_open_middle() {
        let s = point_space(Topology1D::RealLine, 5);
        assert_eq!(s.left_neighbor(&3), Some(2));
    }

    #[test]
    fn left_neighbor_open_last_element() {
        let s = point_space(Topology1D::RealLine, 5);
        assert_eq!(s.left_neighbor(&4), Some(3));
    }

    // ── Adjacency1D::left_neighbor — Periodic ────────────────────────────────

    #[test]
    fn left_neighbor_periodic_first_element_wraps() {
        let s = interval_space(Topology1D::Circle, 5);
        assert_eq!(s.left_neighbor(&0), Some(4));
    }

    #[test]
    fn left_neighbor_periodic_middle() {
        let s = interval_space(Topology1D::Circle, 5);
        assert_eq!(s.left_neighbor(&2), Some(1));
    }

    #[test]
    fn left_neighbor_periodic_last_element() {
        let s = interval_space(Topology1D::Circle, 5);
        assert_eq!(s.left_neighbor(&4), Some(3));
    }

    // ── Adjacency1D::right_neighbor — Open ───────────────────────────────────

    #[test]
    fn right_neighbor_open_first_element() {
        let s = point_space(Topology1D::RealLine, 5);
        assert_eq!(s.right_neighbor(&0), Some(1));
    }

    #[test]
    fn right_neighbor_open_middle() {
        let s = point_space(Topology1D::RealLine, 5);
        assert_eq!(s.right_neighbor(&2), Some(3));
    }

    #[test]
    fn right_neighbor_open_last_element_is_none() {
        let s = point_space(Topology1D::RealLine, 5);
        assert_eq!(s.right_neighbor(&4), None);
    }

    // ── Adjacency1D::right_neighbor — Periodic ───────────────────────────────

    #[test]
    fn right_neighbor_periodic_first_element() {
        let s = interval_space(Topology1D::Circle, 5);
        assert_eq!(s.right_neighbor(&0), Some(1));
    }

    #[test]
    fn right_neighbor_periodic_middle() {
        let s = interval_space(Topology1D::Circle, 5);
        assert_eq!(s.right_neighbor(&2), Some(3));
    }

    #[test]
    fn right_neighbor_periodic_last_element_wraps() {
        let s = interval_space(Topology1D::Circle, 5);
        assert_eq!(s.right_neighbor(&4), Some(0));
    }

    // ── Adjacency1D::neighbors — combined ────────────────────────────────────

    #[test]
    fn neighbors_open_interior() {
        let s = point_space(Topology1D::RealLine, 5);
        assert_eq!(
            s.neighbors(&2),
            Neighbors1D {
                left: Some(1),
                right: Some(3)
            }
        );
    }

    #[test]
    fn neighbors_open_left_boundary() {
        let s = point_space(Topology1D::RealLine, 5);
        assert_eq!(
            s.neighbors(&0),
            Neighbors1D {
                left: None,
                right: Some(1)
            }
        );
    }

    #[test]
    fn neighbors_open_right_boundary() {
        let s = point_space(Topology1D::RealLine, 5);
        assert_eq!(
            s.neighbors(&4),
            Neighbors1D {
                left: Some(3),
                right: None
            }
        );
    }

    #[test]
    fn neighbors_periodic_wraps_at_boundaries() {
        let s = interval_space(Topology1D::Circle, 5);
        assert_eq!(
            s.neighbors(&0),
            Neighbors1D {
                left: Some(4),
                right: Some(1)
            }
        );
        assert_eq!(
            s.neighbors(&4),
            Neighbors1D {
                left: Some(3),
                right: Some(0)
            }
        );
    }

    // ── Edge cases: n = 1 ────────────────────────────────────────────────────

    #[test]
    fn neighbors_open_single_element_both_none() {
        let s = point_space(Topology1D::RealLine, 1);
        assert_eq!(
            s.neighbors(&0),
            Neighbors1D {
                left: None,
                right: None
            }
        );
    }

    #[test]
    fn neighbors_periodic_single_element_wraps_to_itself() {
        let s = interval_space(Topology1D::Circle, 1);
        assert_eq!(
            s.neighbors(&0),
            Neighbors1D {
                left: Some(0),
                right: Some(0)
            }
        );
    }

    // ── Adjacency1D::neighbor dispatch ───────────────────────────────────────

    #[test]
    fn neighbor_dispatch_left_and_right_open() {
        let s = point_space(Topology1D::RealLine, 5);
        assert_eq!(s.neighbor(&2, &Side::Left), s.left_neighbor(&2));
        assert_eq!(s.neighbor(&2, &Side::Right), s.right_neighbor(&2));
        // boundary cases
        assert_eq!(s.neighbor(&0, &Side::Left), None);
        assert_eq!(s.neighbor(&4, &Side::Right), None);
    }

    #[test]
    fn neighbor_dispatch_left_and_right_periodic() {
        let s = interval_space(Topology1D::Circle, 4);
        assert_eq!(s.neighbor(&0, &Side::Left), Some(3)); // wraps
        assert_eq!(s.neighbor(&0, &Side::Right), Some(1));
        assert_eq!(s.neighbor(&3, &Side::Right), Some(0)); // wraps
    }

    // ── Constructors ::new ───────────────────────────────────────────────────

    #[test]
    fn point_index_space_new_constructor() {
        let count = PositiveNumPoints1D::try_new(7).unwrap();
        let s = PointIndexSpace1D::new(Topology1D::Circle, count);
        assert_eq!(*s.topology(), Topology1D::Circle);
        assert_eq!(*s.count().as_ref(), 7);
    }

    #[test]
    fn interval_index_space_new_constructor() {
        let count = NumIntervals::try_new(3).unwrap();
        let s = IntervalIndexSpace1D::new(Topology1D::RealLine, count);
        assert_eq!(*s.topology(), Topology1D::RealLine);
        assert_eq!(*s.count().as_ref(), 3);
    }

    // ── Grid1DIndexSpaces ────────────────────────────────────────────────────

    mod grid1d_index_spaces {
        use super::*;

        fn make(n: usize, topology: Topology1D) -> Grid1DIndexSpaces {
            Grid1DIndexSpaces::new(NumIntervals::try_new(n).unwrap(), topology)
        }

        #[test]
        fn new_sets_correct_interval_count() {
            let g = make(4, Topology1D::RealLine);
            assert_eq!(*g.interval_index_space().count().as_ref(), 4);
        }

        #[test]
        fn new_sets_point_count_as_n_plus_1() {
            let g = make(4, Topology1D::RealLine);
            assert_eq!(*g.point_index_space().count().as_ref(), 5);
        }

        #[test]
        fn topology_is_propagated_to_both_spaces() {
            let g = make(3, Topology1D::Circle);
            assert_eq!(*g.interval_index_space().topology(), Topology1D::Circle);
            assert_eq!(*g.point_index_space().topology(), Topology1D::Circle);
        }

        #[test]
        fn interval_index_space_adjacency_uses_topology() {
            let g = make(4, Topology1D::Circle);
            // periodic: right of last interval (idx 3) wraps to 0
            assert_eq!(g.interval_index_space().right_neighbor(&3), Some(0));
        }

        #[test]
        fn point_index_space_adjacency_uses_topology() {
            let g = make(4, Topology1D::RealLine);
            // open: left of first point is None
            assert_eq!(g.point_index_space().left_neighbor(&0), None);
            // open: right of last point (idx 4) is None
            assert_eq!(g.point_index_space().right_neighbor(&4), None);
        }

        #[test]
        fn clone_and_equality() {
            let g1 = make(5, Topology1D::Circle);
            let g2 = g1.clone();
            assert_eq!(g1, g2);
        }
    }

    // ── debug_assert: out-of-bounds IDs ─────────────────────────────────────
    // These tests run only in debug mode (cargo test compiles with debug_assertions).
    // In release mode the assert is elided, so the tests are excluded via #[cfg].

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic]
    fn left_neighbor_panics_on_out_of_bounds_open() {
        let s = point_space(Topology1D::RealLine, 5);
        let _ = s.left_neighbor(&5); // id == count → debug_assert fires
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic]
    fn left_neighbor_panics_on_out_of_bounds_periodic() {
        let s = interval_space(Topology1D::Circle, 4);
        let _ = s.left_neighbor(&4); // id == count → debug_assert fires
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic]
    fn left_neighbor_panics_on_far_out_of_bounds() {
        let s = point_space(Topology1D::RealLine, 3);
        let _ = s.left_neighbor(&100);
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic]
    fn right_neighbor_panics_on_out_of_bounds_open() {
        let s = point_space(Topology1D::RealLine, 5);
        let _ = s.right_neighbor(&5); // id == count → debug_assert fires
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic]
    fn right_neighbor_panics_on_out_of_bounds_periodic() {
        let s = interval_space(Topology1D::Circle, 4);
        let _ = s.right_neighbor(&4); // id == count → debug_assert fires
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic]
    fn right_neighbor_panics_on_far_out_of_bounds() {
        let s = point_space(Topology1D::RealLine, 3);
        let _ = s.right_neighbor(&100);
    }
}