pyrucast 0.4.1

Finite-element library in Rust, inspired by cast3m, exposed to Python
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
//! Common trait for the "parent" containers (Mesh, FiniteElementSpace,
//! Model). Each is essentially a `Vec<Handle<Sub>>` and exposes the same
//! access grammar (`len`, `get`, indexing, iteration).
//!
//! Goals:
//! - factor out the access mechanics (zero duplicated `__getitem__`);
//! - guarantee uniform access: a sub-mesh from a mesh, a sub-space from an
//!   FE-space, or a sub-model from a model are iterated and indexed in
//!   strictly the same way.
//!
//! # Example
//!
//! ```
//! use pyrucast::aggregate::Aggregate;
//! use pyrucast::handle::Handle;
//!
//! #[derive(serde::Serialize, serde::Deserialize)]
//! struct Item(u32);
//!
//! #[derive(Default)]
//! struct Bag { items: Vec<Handle<Item>> }
//!
//! impl Aggregate for Bag {
//!     type Sub = Item;
//!     fn items(&self) -> &[Handle<Item>] { &self.items }
//!     fn items_mut(&mut self) -> &mut Vec<Handle<Item>> { &mut self.items }
//!     fn type_name() -> &'static str { "Bag" }
//! }
//!
//! let mut b = Bag::default();
//! assert!(b.is_empty());
//! b.push(Handle::new(Item(42)));
//! assert_eq!(b.len(), 1);
//! let h = b.get(0).unwrap();
//! assert_eq!(h.read().0, 42);
//! ```

use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use std::any::Any;

/// Typed container of objects held in the global store.
///
/// All access mechanics (length, indexing, iteration) are derived from the
/// two required methods [`Aggregate::items`] and [`Aggregate::items_mut`].
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::field::{Field, SubField};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// # let support = mesh::poi1_from_nodes(&n).unwrap();
/// # let temp = NodeField::from_submesh(&support.get(0).unwrap(),
/// #                                    vec!["T".into()]).unwrap();
/// # temp.get(0).unwrap().write().add_to_component("T", 4.0).unwrap();
/// // Toute la mécanique d'accès — longueur, indexation, itération, union —
/// // se dérive de deux méthodes seulement, `items` et `items_mut`. Un même
/// // vocabulaire vaut donc pour les maillages, les champs, les modèles et
/// // les matrices.
/// assert_eq!(maillage.len(), 1);
/// assert!(!maillage.is_empty());
/// assert_eq!(maillage.iter().count(), 1);
/// // Et l'union partage les zones plutôt que de les copier.
/// # use pyrucast::handle::Handle as H;
/// let deux = maillage.union(&support)?;
/// assert_eq!(deux.len(), 2);
/// assert!(H::same_object(&deux.get(0)?, &maillage.get(0)?));
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub trait Aggregate: Default {
    /// Type of the sub-object held (referenced via `Handle<Sub>`).
    type Sub: Any + Send + Sync;

    /// Reference to the internal list of handles.
    fn items(&self) -> &[Handle<Self::Sub>];

    /// Mutable reference to the internal list of handles.
    fn items_mut(&mut self) -> &mut Vec<Handle<Self::Sub>>;

    /// Human-readable name of this aggregate type (e.g. `"Mesh"`).
    /// Used by the default `Debug` and `Display` implementations.
    fn type_name() -> &'static str;

    /// Construct an empty aggregate (no sub-items). Equivalent to `Default::default()`.
    fn empty() -> Self
    where
        Self: Sized,
    {
        Self::default()
    }

    /// Plural label for the sub-item used by the default `Display`
    /// (e.g. `"submesh(es)"`). Defaults to `"item(s)"`.
    fn sub_display_name() -> &'static str {
        "item(s)"
    }

    /// Optional suffix appended by the default `Display` after the count
    /// (e.g. `", 12 cell(s) total"`). Defaults to nothing.
    fn display_extra(&self) -> Option<String> {
        None
    }

    /// Union of `self` and `other` into a fresh aggregate.
    ///
    /// Exposed to Rust as [`Aggregate::union`] and to Python as `a | b`.
    /// Sub-objects are deduplicated **by handle identity**
    /// ([`Handle::same_object`]): a sub already present (the same object) is
    /// not added twice. Order is first-seen. Domain constraints (e.g.
    /// `Coords` compatibility for `Mesh`) are enforced via
    /// [`Aggregate::try_extend_from`]. After the union, [`Aggregate::finalize`]
    /// runs — a no-op for most aggregates. The two field types override it
    /// **asymmetrically**: `NodeField` *fuses* zones sharing the same support
    /// (`node_field::consolidate`), whereas `ElementField` only *checks* that no
    /// component is carried by two zones on one support
    /// (`check_unique_component_per_support`) and leaves component-disjoint zones
    /// side by side — fuse them explicitly with `element_field::consolidate`.
    fn merge(&self, other: &Self) -> Result<Self>
    where
        Self: Sized,
    {
        let mut result = Self::default();
        result.try_extend_from(self)?;
        result.try_extend_from(other)?;
        result.finalize()?;
        Ok(result)
    }

    /// Union with another aggregate — the named Rust entry point for the
    /// composition operator (`a | b` in Python). Alias of
    /// [`Aggregate::merge`]; see it for the deduplication and finalization
    /// semantics.
    fn union(&self, other: &Self) -> Result<Self>
    where
        Self: Sized,
    {
        self.merge(other)
    }

    /// Union with a single sub-object `h`: a fresh aggregate holding
    /// `self`'s subs plus `h`, unless `h`'s slot is already present. The
    /// sub-handle is shared (refcount bump), then [`Aggregate::finalize`]
    /// runs. Python: `aggregate | sub`.
    fn union_sub(&self, h: &Handle<Self::Sub>) -> Result<Self>
    where
        Self: Sized,
    {
        let mut out = Self::default();
        out.try_extend_from(self)?;
        if !out.contains_handle(h) {
            out.add_sub(h.clone())?;
        }
        out.finalize()?;
        Ok(out)
    }

    /// Mirror of [`Aggregate::union_sub`] with the sub-object **first**: a
    /// fresh aggregate holding `h`, then `self`'s subs, skipping the one whose
    /// slot is `h`'s. Same sharing and finalization semantics; only the zone
    /// order differs. Python: `sub | aggregate`.
    fn union_sub_first(&self, h: &Handle<Self::Sub>) -> Result<Self>
    where
        Self: Sized,
    {
        let mut out = Self::default();
        out.add_sub(h.clone())?;
        out.try_extend_from(self)?;
        out.finalize()?;
        Ok(out)
    }

    /// Fresh aggregate holding the sub-objects at `indices` (already
    /// resolved against `len`, in the given order). Each handle is shared
    /// (refcount bump), not deep-copied. Backs Python slicing (`agg[i:j:k]`).
    ///
    /// Reuses [`Aggregate::add_sub`] — so [`Aggregate::check_push`] invariants
    /// (e.g. `Coords` compatibility for `Mesh`) still hold — then runs
    /// [`Aggregate::finalize`]. A slice yields distinct indices, so no handle
    /// is added twice; on an already-finalized source `finalize` is a no-op.
    fn subset<I: IntoIterator<Item = usize>>(&self, indices: I) -> Result<Self>
    where
        Self: Sized,
    {
        let mut out = Self::default();
        for i in indices {
            out.add_sub(self.get(i)?)?;
        }
        out.finalize()?;
        Ok(out)
    }

    /// Hook called at the end of [`Aggregate::merge`], once the union by
    /// handle is complete. Override to fuse/normalize sub-objects beyond
    /// handle identity (e.g. fields fusing two zones on the same support).
    /// The default is a no-op.
    fn finalize(&mut self) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }

    fn len(&self) -> usize {
        self.items().len()
    }

    fn is_empty(&self) -> bool {
        self.items().is_empty()
    }

    /// The sole sub-handle of a **unitary** aggregate (exactly one sub).
    ///
    /// This is the parent→sub coercion primitive (see `CONVENTIONS.md`,
    /// « Agrégats : un ou plusieurs ») used at the few boundaries that
    /// genuinely need a single sub — e.g. a `SubNodeField` support accepting
    /// a unitary `Mesh`. Errors with a clear message if the aggregate holds
    /// zero or more than one sub.
    fn unit(&self) -> Result<Handle<Self::Sub>> {
        match self.items() {
            [h] => Ok(h.clone()),
            items => Err(PyrucastError::Message(format!(
                "expected a unitary {} (exactly one {}), found {}",
                Self::type_name(),
                Self::sub_display_name(),
                items.len(),
            ))),
        }
    }

    /// Clone of the `i`-th handle. Explicit error if `i` is out of bounds.
    fn get(&self, i: usize) -> Result<Handle<Self::Sub>> {
        self.items().get(i).cloned().ok_or_else(|| {
            PyrucastError::Message(format!("index {} out of bounds (len={})", i, self.len()))
        })
    }

    /// Append a handle at the tail. Any extra validation (Coords
    /// compatibility, duplicates, ...) is the caller's responsibility.
    fn push(&mut self, h: Handle<Self::Sub>) {
        self.items_mut().push(h);
    }

    /// Iterator over the internal handles.
    fn iter(&self) -> std::slice::Iter<'_, Handle<Self::Sub>> {
        self.items().iter()
    }

    /// Append all handles from `other` into `self` (clone each handle).
    fn extend_from(&mut self, other: &Self) {
        for h in other.iter() {
            self.items_mut().push(h.clone());
        }
    }

    /// Whether a sub naming the same object as `h` is already held
    /// ([`Handle::same_object`]). Basis of the union's deduplication.
    fn contains_handle(&self, h: &Handle<Self::Sub>) -> bool {
        self.items().iter().any(|existing| existing.same_object(h))
    }

    /// Hook called before inserting a single handle. Override to enforce
    /// domain-specific constraints (e.g. same `Coords` for `Mesh`).
    /// The default accepts everything.
    fn check_push(&self, _h: &Handle<Self::Sub>) -> crate::error::Result<()> {
        Ok(())
    }

    /// Hook called after a handle has been successfully pushed. Override to
    /// perform side-effects such as cache invalidation.
    /// The default is a no-op.
    fn post_push(&mut self) {}

    /// Check compatibility (via [`Aggregate::check_push`]) then append a single handle.
    fn add_sub(&mut self, h: Handle<Self::Sub>) -> crate::error::Result<()> {
        self.check_push(&h)?;
        self.push(h);
        self.post_push();
        Ok(())
    }

    /// Check compatibility (via [`Aggregate::check_push`] on the first item of `other`)
    /// then append handles from `other` into `self`, **deduplicating by
    /// handle identity** ([`Handle::same_object`]): a sub already present is
    /// skipped. This is the union semantics of `|`.
    fn try_extend_from(&mut self, other: &Self) -> crate::error::Result<()> {
        if let Some(h) = other.items().first() {
            self.check_push(h)?;
        }
        for h in other.iter() {
            if self.contains_handle(h) {
                continue;
            }
            self.items_mut().push(h.clone());
            self.post_push();
        }
        Ok(())
    }
}

// ─── Debug helper: recurse into each sub-object ─────────────────────────────

/// Wraps an aggregate's handle slice so its `Debug` **dereferences** each
/// handle and prints the full `Debug` of the pointed-to sub-object, instead
/// of the handle's short tag.
///
/// Honours the alternate (`{:#?}`) flag, so the sub-objects are
/// pretty-printed and indented when the aggregate is.
///
/// Safe against the non-reentrant per-object lock: one read guard is held at
/// a time, on a different sub-object each turn, and every sub-object `Debug`
/// is itself lock-free.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::field::{Field, SubField};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// # let support = mesh::poi1_from_nodes(&n).unwrap();
/// # let temp = NodeField::from_submesh(&support.get(0).unwrap(),
/// #                                    vec!["T".into()]).unwrap();
/// # temp.get(0).unwrap().write().add_to_component("T", 4.0).unwrap();
/// # use pyrucast::aggregate::DebugItems;
/// // Une vue `Debug` qui **déréférence** les handles : sans elle, un
/// // agrégat s'afficherait comme une liste de pointeurs.
/// let rendu = format!("{:?}", DebugItems(Aggregate::items(&maillage)));
/// assert!(rendu.starts_with('['));
/// assert!(rendu.contains("TRI3"));
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub struct DebugItems<'a, S: Any + Send + Sync>(pub &'a [Handle<S>]);

impl<S: Any + Send + Sync + std::fmt::Debug> std::fmt::Debug for DebugItems<'_, S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut list = f.debug_list();
        for h in self.0 {
            list.entry(&DebugItem(h));
        }
        list.finish()
    }
}

/// A single dereferenced handle (see [`DebugItems`]).
struct DebugItem<'a, S: Any + Send + Sync>(&'a Handle<S>);

impl<S: Any + Send + Sync + std::fmt::Debug> std::fmt::Debug for DebugItem<'_, S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // No fallback: holding the handle guarantees the object is there.
        let s = self.0.read();
        if f.alternate() {
            write!(f, "{:#?}", *s)
        } else {
            write!(f, "{:?}", *s)
        }
    }
}

// ─── Helper: Python indexing (signed → unsigned) ────────────────────────────

/// Normalize a Python index (possibly negative) against `len`.
///
/// Returns `Some(positive_idx)` if valid, `None` otherwise. The call site
/// turns `None` into the appropriate error (`PyIndexError` on the Python
/// side, `PyrucastError::Message` on the Rust side).
///
/// ```
/// # use pyrucast::aggregate::normalize_index;
/// // L'indexation négative de Python, portée telle quelle en Rust.
/// assert_eq!(normalize_index(-1, 3), Some(2));
/// assert_eq!(normalize_index(0, 3), Some(0));
/// assert_eq!(normalize_index(3, 3), None); // hors bornes
/// ```
pub fn normalize_index(idx: isize, len: usize) -> Option<usize> {
    let n = len as isize;
    let i = if idx < 0 { n + idx } else { idx };
    if i < 0 || i >= n {
        None
    } else {
        Some(i as usize)
    }
}

// ─── Python macro: uniform __len__ / __getitem__ ────────────────────────────

/// Defines `__len__` and `__getitem__` on a `pyclass` that owns an `inner`
/// field implementing [`Aggregate`], wrapping each sub-handle in a
/// `$Sub { handle: h }` wrapper.
///
/// Python iteration (`for x in parent:`) naturally falls back to the
/// sequence protocol: if `__iter__` is not defined, CPython falls back to
/// `__getitem__` until it receives an `IndexError`.
///
/// # Struct precondition
///
/// The struct `$T` **must** have a field named `inner` that implements
/// [`Aggregate`]. The name `inner` is hardcoded by this macro.
///
/// `$Inner` is the **Rust** aggregate type stored in `$T`'s `inner` field
/// (e.g. `Mesh` behind `PyMesh`); it owns the
/// `union`/`union_sub`/`union_sub_first`/`union_subs` constructors that back
/// the `|` operator. The macro wires the aggregate-level `|` (on `$T`, both
/// senses: `__or__` and the reflected `__ror__` for `sub | agg`) **and** the
/// sub-level `|` (on `$Sub`), so a single invocation gives the whole uniform
/// union surface.
///
/// # Type stubs
///
/// `__getitem__` / `__or__` / `__ror__` are **polymorphic**: their Rust
/// signature is `&Bound<PyAny> -> Py<PyAny>`, from which `pyo3-stub-gen` can
/// only infer `typing.Any` — which costs every aggregate its IDE completion
/// (`mesh[0].` suggesting nothing). They therefore live in `#[pymethods]`
/// blocks **deliberately left undecorated**, invisible to the stub generator,
/// and their `.pyi` entries are written by hand in Python syntax: `$stub` for
/// the aggregate, `$sub_stub` for the sub-object. Both are parsed by
/// `gen_methods_from_python!`, which binds them to the Rust type named by the
/// `class` line (hence `class PyMesh:`, not `class Mesh:`), so each aggregate
/// states its own return types *and* its own docstrings.
///
/// The undecorated blocks are **closed**: a method added there would silently
/// vanish from the stub. Anything new goes in the decorated blocks.
///
/// # Usage
///
/// ```ignore
/// pyrucast::impl_aggregate_pymethods!(
///     PyMesh, PySubMesh, "Mesh", submesh, Mesh,
///     r#"
/// class PyMesh:
///     @overload
///     def __getitem__(self, key: int) -> pyo3_stub_gen.RustType["PySubMesh"]:
///         """`mesh[i]` → the `SubMesh` of zone i."""
///     "#,
///     r#"
/// class PySubMesh:
///     def __or__(self, other: pyo3_stub_gen.RustType["PySubMesh"]) -> pyo3_stub_gen.RustType["PyMesh"]:
///         """`sub | sub` → a fresh `Mesh` holding both zones."""
///     "#
/// );
/// ```
///
/// `$sub` is given once; `paste!` derives `{$sub}_count`, `$sub(i)`, and
/// `add_{$sub}` automatically.
#[cfg(feature = "python-api")]
#[macro_export]
macro_rules! impl_aggregate_pymethods {
    (
        $T:ident, $Sub:ident, $name:literal, $sub:ident, $Inner:ty,
        $stub:literal, $sub_stub:literal
        $(, $components:ident)?
    ) => {
        paste::paste! {
            #[cfg_attr(
                feature = "stub-gen",
                pyo3_stub_gen::derive::gen_stub_pymethods
            )]
            #[pyo3::pymethods]
            impl $T {
                fn __len__(&self) -> pyo3::PyResult<usize> {
                    Ok($crate::aggregate::Aggregate::len(&self.inner))
                }
            }

            // Polymorphic subscript — **closed block**, undecorated on purpose:
            // its `.pyi` entry comes from `$stub`, not from the generator.
            #[pyo3::pymethods]
            impl $T {
                /// `agg[i]` → the typed **view** of zone `i` (negative indices
                /// supported); `agg[i:j:k]` → a **fresh aggregate** of the same
                /// type holding the sliced zones (Python slicing: step, negative
                /// bounds). For field aggregates, a **string** key `agg["u_x"]`
                /// or a **list** key `agg[["u_x", "u_y"]]` returns a fresh field
                /// keeping only those components (`filter_components`). Other key
                /// types raise `TypeError`. The Python-facing wording, which
                /// differs per aggregate, lives in `$stub`.
                fn __getitem__(
                    &self,
                    py: pyo3::Python<'_>,
                    key: &pyo3::Bound<'_, pyo3::PyAny>,
                ) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>> {
                    let n = $crate::aggregate::Aggregate::len(&self.inner);

                    // Slice: agg[1:3], agg[::2], agg[-2:] ...
                    if let Ok(slice) = key.cast::<pyo3::types::PySlice>() {
                        let ind = slice.indices(n as isize)?;
                        let mut idxs = Vec::new();
                        let mut i = ind.start;
                        if ind.step > 0 {
                            while i < ind.stop {
                                idxs.push(i as usize);
                                i += ind.step;
                            }
                        } else {
                            while i > ind.stop {
                                idxs.push(i as usize);
                                i += ind.step;
                            }
                        }
                        let inner = $crate::aggregate::Aggregate::subset(&self.inner, idxs)?;
                        return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
                    }

                    $(
                        // Component key(s) — only for field aggregates (the
                        // `$components` flag). `agg["u_x"]` (a single name) or
                        // `agg[["u_x", "u_y"]]` (a list) → filter_components.
                        // Checked before the integer branch; ints never extract
                        // as `String`/`Vec<String>`, so `agg[0]` still works.
                        let _ = stringify!($components);
                        if let Ok(name) = key.extract::<String>() {
                            let inner =
                                $crate::containers::field::Field::filter_components(&self.inner, name)?;
                            return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
                        }
                        if let Ok(names) = key.extract::<Vec<String>>() {
                            let inner =
                                $crate::containers::field::Field::filter_components(&self.inner, names)?;
                            return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
                        }
                    )?

                    // Integer: agg[0], agg[-1]
                    let idx: isize = key.extract().map_err(|_| {
                        pyo3::exceptions::PyTypeError::new_err(concat!(
                            $name,
                            " indices must be integers or slices"
                        ))
                    })?;
                    let i = $crate::aggregate::normalize_index(idx, n).ok_or_else(|| {
                        pyo3::exceptions::PyIndexError::new_err(format!(
                            concat!($name, " index {} out of range (len={})"),
                            idx, n
                        ))
                    })?;
                    let h = $crate::aggregate::Aggregate::get(&self.inner, i)?;
                    Ok(pyo3::Py::new(py, $Sub { handle: h })?.into_any())
                }
            }

            #[cfg_attr(
                feature = "stub-gen",
                pyo3_stub_gen::derive::gen_stub_pymethods
            )]
            #[pyo3::pymethods]
            impl $T {
                /// The sole sub-object **view** of a unitary aggregate
                /// (exactly one sub), else a clear error. Use it where the
                /// single-zone case needs a sub method: `parent.unit().m(...)`.
                /// More honest than `parent[0]` (which silently takes the
                /// first of several) — see `CONVENTIONS.md`.
                fn unit(&self) -> pyo3::PyResult<$Sub> {
                    let h = $crate::aggregate::Aggregate::unit(&self.inner)?;
                    Ok($Sub { handle: h })
                }

                /// Append a sub-object **in place** (the handle is shared, not
                /// deep-copied). The functional counterpart is `|`, which leaves
                /// the operands untouched and returns a fresh aggregate.
                fn add_sub(&mut self, sub: pyo3::PyRef<'_, $Sub>) -> pyo3::PyResult<()> {
                    $crate::aggregate::Aggregate::add_sub(&mut self.inner, sub.handle.clone())?;
                    Ok(())
                }

                fn __repr__(&self) -> pyo3::PyResult<String> {
                    Ok(format!("{:?}", self.inner))
                }

                fn __str__(&self) -> pyo3::PyResult<String> {
                    Ok(format!("{}", self.inner))
                }

                /// Print the full content (third display level) to stdout:
                /// every sub-object's values/topology, beyond `repr`'s bounded
                /// structure. Returns nothing.
                #[pyo3(signature = (precision=3, max_rows=20, max_cols=12))]
                fn dump(
                    &self,
                    py: pyo3::Python<'_>,
                    precision: usize,
                    max_rows: usize,
                    max_cols: usize,
                ) -> pyo3::PyResult<()> {
                    let text = $crate::dump::Dump::render(
                        &self.inner,
                        &$crate::dump::DumpOptions { precision, max_rows, max_cols },
                    );
                    $crate::dump::py_print(py, &text)
                }
            }

            // Polymorphic union — **closed block**, undecorated on purpose:
            // its `.pyi` entries come from `$stub`, not from the generator.
            #[pyo3::pymethods]
            impl $T {
                /// `a | b` — **union** of this aggregate with `other`. `other`
                /// may be another aggregate of the same type or a single
                /// sub-object. Sub-objects already present (the same object)
                /// are not added twice; remaining handles are **shared**
                /// (refcount bump), not deep-copied. Same-support zones are
                /// handled **asymmetrically** by the two field types:
                /// `NodeField` *fuses* them (union of components), whereas
                /// `ElementField` keeps component-disjoint zones side by side
                /// and only rejects a component carried by two zones on one
                /// support — fuse those explicitly with `element_field::consolidate`
                /// (`element_field::consolidate`). Returns `NotImplemented` for any
                /// other type so Python can fall back to the right operand's
                /// `__ror__`.
                fn __or__(
                    &self,
                    py: pyo3::Python<'_>,
                    other: &pyo3::Bound<'_, pyo3::PyAny>,
                ) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>> {
                    use $crate::aggregate::Aggregate;
                    if let Ok(o) = other.extract::<pyo3::PyRef<'_, $T>>() {
                        let inner = self.inner.union(&o.inner)?;
                        return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
                    }
                    if let Ok(s) = other.extract::<pyo3::PyRef<'_, $Sub>>() {
                        let inner = self.inner.union_sub(&s.handle)?;
                        return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
                    }
                    Ok(py.NotImplemented())
                }

                /// Right-hand `sub | aggregate`: the **union with the
                /// sub-object first**, then this aggregate's zones — the
                /// mirror of `aggregate | sub`, with the same deduplication
                /// and finalization. Reached when the left operand's `__or__`
                /// returns `NotImplemented` (a sub-object only knows how to
                /// union another sub-object), so both senses of `|` are
                /// accepted and differ only in zone order. Returns
                /// `NotImplemented` for any other left-hand type.
                fn __ror__(
                    &self,
                    py: pyo3::Python<'_>,
                    other: &pyo3::Bound<'_, pyo3::PyAny>,
                ) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>> {
                    use $crate::aggregate::Aggregate;
                    if let Ok(s) = other.extract::<pyo3::PyRef<'_, $Sub>>() {
                        let inner = self.inner.union_sub_first(&s.handle)?;
                        return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
                    }
                    Ok(py.NotImplemented())
                }
            }

            // Sub-level `|` (uniform with the aggregate-level one above):
            // `sub | sub` → a fresh aggregate holding both sub-objects.
            // **Closed block**, undecorated on purpose: its `.pyi` entry comes
            // from `$sub_stub`, not from the generator.
            #[pyo3::pymethods]
            impl $Sub {
                /// `sub | sub` → a fresh aggregate holding both sub-objects
                /// (first-seen order, deduplicated by handle, then finalized).
                /// Sub-handles are shared (refcount bump). Returns
                /// `NotImplemented` for any other right-hand type.
                fn __or__(
                    &self,
                    py: pyo3::Python<'_>,
                    other: &pyo3::Bound<'_, pyo3::PyAny>,
                ) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>> {
                    if let Ok(o) = other.extract::<pyo3::PyRef<'_, $Sub>>() {
                        let inner = <$Inner>::union_subs(&self.handle, &o.handle)?;
                        return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
                    }
                    Ok(py.NotImplemented())
                }
            }

            // Hand-written `.pyi` entries for the two closed blocks above.
            #[cfg(feature = "stub-gen")]
            pyo3_stub_gen::inventory::submit! {
                pyo3_stub_gen::derive::gen_methods_from_python! { $stub }
            }

            #[cfg(feature = "stub-gen")]
            pyo3_stub_gen::inventory::submit! {
                pyo3_stub_gen::derive::gen_methods_from_python! { $sub_stub }
            }
        }
    };
}

// ─── Python dump method (non-aggregate wrappers) ────────────────────────────

/// Define the `dump(precision, max_rows, max_cols) -> str` pymethod on a
/// `pyclass` wrapper whose payload implements [`crate::dump::Dump`].
///
/// Two forms depending on how the wrapper holds its payload:
/// * `handle $PyT, $field` — `$field: Handle<Sub>`, read through its guard;
/// * `value  $PyT, $field` — `$field` is an owned value (e.g. a view).
///
/// Aggregate wrappers get `dump` from [`impl_aggregate_pymethods`] instead.
#[cfg(feature = "python-api")]
#[macro_export]
macro_rules! impl_dump_pymethod {
    (handle $PyT:ty, $field:ident) => {
        #[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
        #[pyo3::pymethods]
        impl $PyT {
            /// Print the full content (third display level) to stdout: values /
            /// topology, beyond `repr`'s bounded structure. Returns nothing.
            #[pyo3(signature = (precision=3, max_rows=20, max_cols=12))]
            fn dump(
                &self,
                py: pyo3::Python<'_>,
                precision: usize,
                max_rows: usize,
                max_cols: usize,
            ) -> pyo3::PyResult<()> {
                let opts = $crate::dump::DumpOptions {
                    precision,
                    max_rows,
                    max_cols,
                };
                let text = $crate::dump::Dump::render(&*self.$field.read(), &opts);
                $crate::dump::py_print(py, &text)
            }
        }
    };
    (value $PyT:ty, $field:ident) => {
        #[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
        #[pyo3::pymethods]
        impl $PyT {
            /// Print the full content (third display level) to stdout: values /
            /// topology, beyond `repr`'s bounded structure. Returns nothing.
            #[pyo3(signature = (precision=3, max_rows=20, max_cols=12))]
            fn dump(
                &self,
                py: pyo3::Python<'_>,
                precision: usize,
                max_rows: usize,
                max_cols: usize,
            ) -> pyo3::PyResult<()> {
                let opts = $crate::dump::DumpOptions {
                    precision,
                    max_rows,
                    max_cols,
                };
                let text = $crate::dump::Dump::render(&self.$field, &opts);
                $crate::dump::py_print(py, &text)
            }
        }
    };
}

// ─── Unified aggregate macro ────────────────────────────────────────────────

/// Derive a complete `Aggregate` implementation for a struct whose only
/// collection field is named `subs: Vec<Handle<Sub>>`.
///
/// # Struct precondition
///
/// The struct `$T` **must** have a field named `subs: Vec<Handle<$Sub>>`.
/// The name `subs` is hardcoded by this macro.
///
/// Access goes through the [`Aggregate`] trait (generic, no per-type
/// aliases): `len()`, `is_empty()`, `get(i)`, `add_sub(h)`, `iter()`,
/// `unit()`, `union()`/`union_sub()`, plus `Index`/`IntoIterator` and the
/// `union_subs(a, b)` constructor from [`crate::impl_aggregate_std_traits`].
/// The `$sub` snake-name is still passed (it names the sub in docs/call
/// sites) but no longer generates methods.
///
/// An optional trailing `{ … }` block is forwarded verbatim into the
/// `impl Aggregate` body to override default methods (`check_push`,
/// `display_extra`, …).
///
/// # Usage
/// ```text
/// impl_aggregate!(Mesh, SubMesh, submesh, "submesh(es)", {
///     fn check_push(&self, h: &Handle<SubMesh>) -> Result<()> { … }
///     fn display_extra(&self) -> Option<String> { … }
/// });
/// impl_aggregate!(Model, SubModel, sub_model, "sub-model(s)");
/// ```
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].id()])?;
/// // Ce que la macro donne à chaque agrégat, sans alias par type : le même
/// // vocabulaire pour les maillages, les champs, les modèles et les
/// // matrices.
/// let m = Mesh::from_submesh(sm);
/// assert_eq!(m.len(), 1);
/// assert!(!m.is_empty());
/// assert!(m.unit().is_ok());        // le raccourci du cas à une zone
/// assert_eq!(m.iter().count(), 1);
/// assert_eq!(m.union(&m)?.len(), 1); // dédupliqué par handle
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[macro_export]
macro_rules! impl_aggregate {
    // Without Aggregate overrides.
    ($T:ty, $Sub:ty, $sub:ident, $name:literal) => {
        $crate::impl_aggregate!($T, $Sub, $sub, $name, {});
    };
    // With Aggregate overrides (check_push, display_extra, …).
    ($T:ty, $Sub:ty, $sub:ident, $name:literal, { $($override:tt)* }) => {
        paste::paste! {
            impl $crate::aggregate::Aggregate for $T {
                type Sub = $Sub;
                fn items(&self) -> &[$crate::handle::Handle<$Sub>] { &self.subs }
                fn items_mut(&mut self) -> &mut Vec<$crate::handle::Handle<$Sub>> {
                    &mut self.subs
                }
                fn type_name() -> &'static str { stringify!($T) }
                fn sub_display_name() -> &'static str { $name }
                $($override)*
            }

            $crate::impl_aggregate_std_traits!($T);
        }
    };
}

// ─── Std-trait macro ────────────────────────────────────────────────────────

/// Generate `Index`, `IntoIterator`, `fmt::Debug`, `fmt::Display`, and the
/// `T::union_subs(a, b)` constructor (`sub | sub`, returning `Result<T>`)
/// for a concrete type that implements [`Aggregate`].
///
/// # Usage
/// ```ignore
/// impl_aggregate_std_traits!(Mesh);
/// impl_aggregate_std_traits!(FiniteElementSpace);
/// ```
#[macro_export]
macro_rules! impl_aggregate_std_traits {
    ($T:ty) => {
        impl std::ops::Index<usize> for $T {
            type Output = $crate::handle::Handle<<$T as $crate::aggregate::Aggregate>::Sub>;
            fn index(&self, idx: usize) -> &Self::Output {
                &$crate::aggregate::Aggregate::items(self)[idx]
            }
        }

        impl<'a> IntoIterator for &'a $T {
            type Item = &'a $crate::handle::Handle<<$T as $crate::aggregate::Aggregate>::Sub>;
            type IntoIter = std::slice::Iter<
                'a,
                $crate::handle::Handle<<$T as $crate::aggregate::Aggregate>::Sub>,
            >;
            fn into_iter(self) -> Self::IntoIter {
                $crate::aggregate::Aggregate::iter(self)
            }
        }

        impl std::fmt::Debug for $T {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_struct(<$T as $crate::aggregate::Aggregate>::type_name())
                    .field("count", &$crate::aggregate::Aggregate::len(self))
                    .field(
                        "items",
                        &$crate::aggregate::DebugItems($crate::aggregate::Aggregate::items(self)),
                    )
                    .finish()
            }
        }

        impl std::fmt::Display for $T {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(
                    f,
                    "{}: {} {}",
                    <$T as $crate::aggregate::Aggregate>::type_name(),
                    $crate::aggregate::Aggregate::len(self),
                    <$T as $crate::aggregate::Aggregate>::sub_display_name(),
                )?;
                if let Some(extra) = $crate::aggregate::Aggregate::display_extra(self) {
                    f.write_str(&extra)?;
                }
                Ok(())
            }
        }

        // `union` / `union_sub` / `union_sub_first` (aggregate | aggregate,
        // aggregate | sub, sub | aggregate) are default methods on the
        // `Aggregate` trait. Only `sub | sub`
        // needs a generated builder here: a sub-handle alone cannot name
        // its parent aggregate type, so we hang the constructor on `$T`.
        impl $T {
            /// Build the aggregate that is the union of two sub-objects
            /// (first-seen order, deduplicated by handle, then finalized).
            /// Backs Python's `sub | sub`.
            ///
            /// ```
            /// # use pyrucast::aggregate::Aggregate;
            /// # use pyrucast::atoms::{ElementType, Node};
            /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
            /// # use pyrucast::coords::Coords;
            /// # use pyrucast::handle::Handle;
            /// # let coords = Handle::new(Coords::new(2).unwrap());
            /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
            /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
            /// # let faire = |t| {
            /// #     let mut sm = SubMesh::new(coords.clone(), t);
            /// #     sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
            /// #     Handle::new(sm)
            /// # };
            /// # let (a, b) = (faire(ElementType::SEG2), faire(ElementType::SEG2));
            /// // Deux sous-objets seuls ne savent pas nommer leur agrégat :
            /// // le constructeur est porté par le type agrégat.
            /// let m = Mesh::union_subs(&a, &b)?;
            /// assert_eq!(m.len(), 2);
            ///
            /// // Le même sous-objet deux fois ne compte qu'une : la
            /// // déduplication se fait **par handle**, pas par contenu.
            /// assert_eq!(Mesh::union_subs(&a, &a)?.len(), 1);
            /// # Ok::<(), pyrucast::PyrucastError>(())
            /// ```
            pub fn union_subs(
                a: &$crate::handle::Handle<<$T as $crate::aggregate::Aggregate>::Sub>,
                b: &$crate::handle::Handle<<$T as $crate::aggregate::Aggregate>::Sub>,
            ) -> $crate::error::Result<$T> {
                use $crate::aggregate::Aggregate;
                let mut out = <$T as ::std::default::Default>::default();
                out.add_sub(a.clone())?;
                if !a.same_object(b) {
                    out.add_sub(b.clone())?;
                }
                out.finalize()?;
                Ok(out)
            }
        }
    };
}

// ─── Aggregate Dump macro ────────────────────────────────────────────────────

/// Derive [`crate::dump::Dump`] for an [`Aggregate`] whose `Sub` is itself
/// `Dump`: the one-line `Display` summary, then each sub-object's full `dump`
/// indented under a `── [i] ──` marker.
///
/// Kept separate from [`crate::impl_aggregate_std_traits`] so aggregates with a
/// non-generic content layout (e.g. `Matrix`, dumped as a single global grid)
/// can hand-write their own `Dump` instead.
///
/// # Usage
/// ```ignore
/// impl_aggregate_dump!(Mesh);
/// ```
#[macro_export]
macro_rules! impl_aggregate_dump {
    ($T:ty) => {
        impl $crate::dump::Dump for $T {
            fn render(&self, opts: &$crate::dump::DumpOptions) -> String {
                let mut out = format!("{self}\n");
                for (i, h) in $crate::aggregate::Aggregate::items(self).iter().enumerate() {
                    let body = $crate::dump::Dump::render(&*h.read(), opts);
                    out.push_str(&format!("── [{i}] ──\n"));
                    for line in body.lines() {
                        out.push_str("  ");
                        out.push_str(line);
                        out.push('\n');
                    }
                }
                out
            }
        }
    };
}

// ─── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::handle::Handle;
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize)]
    struct Item(u32);

    #[derive(Default)]
    struct Bag {
        items: Vec<Handle<Item>>,
    }
    impl Aggregate for Bag {
        type Sub = Item;
        fn items(&self) -> &[Handle<Item>] {
            &self.items
        }
        fn items_mut(&mut self) -> &mut Vec<Handle<Item>> {
            &mut self.items
        }
        fn type_name() -> &'static str {
            "Bag"
        }
    }

    #[test]
    fn empty_bag_is_empty() {
        let b = Bag::default();
        assert_eq!(b.len(), 0);
        assert!(b.is_empty());
        assert!(b.get(0).is_err());
    }

    #[test]
    fn push_then_get() {
        let mut b = Bag::default();
        b.push(Handle::new(Item(1)));
        b.push(Handle::new(Item(2)));
        b.push(Handle::new(Item(3)));
        assert_eq!(b.len(), 3);
        let h = b.get(1).unwrap();
        assert_eq!(h.read().0, 2);
    }

    #[test]
    fn iter_walks_in_order() {
        let mut b = Bag::default();
        b.push(Handle::new(Item(10)));
        b.push(Handle::new(Item(20)));
        let collected: Vec<u32> = b.iter().map(|h| h.read().0).collect();
        assert_eq!(collected, vec![10, 20]);
    }

    #[test]
    fn out_of_bounds_message_includes_len() {
        let b = Bag::default();
        let err = b.get(5).unwrap_err();
        let msg = format!("{}", err);
        assert!(msg.contains("out of bounds"));
        assert!(msg.contains("len=0"));
    }

    #[test]
    fn unit_returns_sole_handle_or_errors() {
        let mut b = Bag::default();
        assert!(b.unit().is_err()); // empty → error
        b.push(Handle::new(Item(7)));
        let h = b.unit().unwrap();
        assert_eq!(h.read().0, 7);
        b.push(Handle::new(Item(8)));
        assert!(b.unit().is_err()); // two → error
    }

    #[test]
    fn union_sub_first_mirrors_union_sub() {
        let mut b = Bag::default();
        b.push(Handle::new(Item(1)));
        b.push(Handle::new(Item(2)));
        let h = Handle::new(Item(3));

        let appended = b.union_sub(&h).unwrap();
        let prepended = b.union_sub_first(&h).unwrap();
        let values = |bag: &Bag| -> Vec<u32> { bag.iter().map(|h| h.read().0).collect() };
        assert_eq!(values(&appended), vec![1, 2, 3]);
        assert_eq!(values(&prepended), vec![3, 1, 2]);

        // A sub already held is not duplicated — it just moves to the front.
        let already = b.get(1).unwrap();
        assert_eq!(values(&b.union_sub_first(&already).unwrap()), vec![2, 1]);
    }

    #[test]
    fn normalize_negative_index() {
        assert_eq!(normalize_index(0, 3), Some(0));
        assert_eq!(normalize_index(2, 3), Some(2));
        assert_eq!(normalize_index(-1, 3), Some(2));
        assert_eq!(normalize_index(-3, 3), Some(0));
        assert_eq!(normalize_index(-4, 3), None);
        assert_eq!(normalize_index(3, 3), None);
        assert_eq!(normalize_index(0, 0), None);
    }
}