Skip to main content

grid1d/bounds/
runtime.rs

1#![deny(rustdoc::broken_intra_doc_links)]
2
3//! Runtime-dispatched bound representation for dynamic or serialization-driven contexts.
4//!
5//! This module provides [`IntervalBoundRuntime<RealType, Side>`] — an enum whose
6//! `Open`/`Closed` variant is chosen at runtime rather than encoded in the type.
7//! It complements the compile-time bound types when the boundary inclusion semantics
8//! are not known until runtime (e.g. user input, deserialization, configuration files).
9//!
10//! ## Types
11//!
12//! | Type | Description |
13//! |------|-------------|
14//! | [`IntervalBoundRuntime<T, Side>`] | Enum with `Open(IntervalBound<T, Side, Open>)` and `Closed(IntervalBound<T, Side, Closed>)` variants |
15//! | [`LowerBoundRuntime<T>`] | Type alias for `IntervalBoundRuntime<T, Lower>` |
16//! | [`UpperBoundRuntime<T>`] | Type alias for `IntervalBoundRuntime<T, Upper>` |
17//!
18//! ## When to Use
19//!
20//! Prefer the compile-time typed bounds ([`LowerBoundClosed`](crate::bounds::LowerBoundClosed),
21//! [`UpperBoundOpen`](crate::bounds::UpperBoundOpen), etc.) whenever the open/closed nature is
22//! known at compile time — they are zero-cost abstractions with stronger type guarantees.
23//! Use the runtime enum when:
24//!
25//! - Constructing bounds from user input or configuration
26//! - Deserializing bounds from JSON / other formats
27//! - Writing algorithms that must handle both open and closed bounds generically
28//!
29//! ## Example
30//!
31//! ```rust
32//! use grid1d::bounds::*;
33//! use try_create::New;
34//!
35//! fn make_lower(value: f64, closed: bool) -> LowerBoundRuntime<f64> {
36//!     if closed {
37//!         IntervalBoundRuntime::Closed(LowerBoundClosed::new(value))
38//!     } else {
39//!         IntervalBoundRuntime::Open(LowerBoundOpen::new(value))
40//!     }
41//! }
42//!
43//! let b = make_lower(0.0, true);
44//! assert!(b.is_closed());
45//! assert!(b.value_within_bound(&0.0));
46//! ```
47
48use crate::{
49    HasCoordType,
50    bounds::{
51        IntervalBound,
52        markers::{Closed, Lower, Open, Upper},
53        traits::{
54            BoundSide, BoundSideRuntimeChecks, BoundType, BoundTypeRuntimeChecks, ValueWithinBound,
55        },
56    },
57};
58use num_valid::RealScalar;
59use serde::{Deserialize, Serialize};
60use std::{cmp::Ordering, fmt::Debug, marker::PhantomData};
61use try_create::{IntoInner, New};
62
63//------------------------------------------------------------------------------------------------
64/// Runtime-determined bound type that can be either open or closed.
65///
66/// [`IntervalBoundRuntime<RealType, Side>`] provides a unified enum for representing bounds
67/// where the open/closed nature needs to be determined at runtime rather than
68/// compile time. This is essential for dynamic interval construction, serialization,
69/// configuration-driven applications, and algorithms that need to work with varying
70/// boundary semantics.
71///
72/// ## Design Philosophy
73///
74/// ### Compile-Time vs Runtime Trade-offs
75///
76/// Unlike the compile-time typed bounds ([`LowerBoundOpen`](crate::bounds::LowerBoundOpen), [`LowerBoundClosed`](crate::bounds::LowerBoundClosed), etc.),
77/// this enum moves the open/closed distinction from compile time to runtime:
78///
79/// | Aspect | Compile-Time Bounds | Runtime Bounds |
80/// |--------|-------------------|----------------|
81/// | **Type Safety** | ✅ Cannot mix open/closed at compile time | ❌ Open/closed confusion possible |
82/// | **Performance** | ✅ Zero-cost abstractions, inlined | ⚡ Small pattern matching overhead |
83/// | **Flexibility** | ❌ Fixed at compile time | ✅ Can change dynamically |
84/// | **Serialization** | ❌ Complex (type information lost) | ✅ Natural enum serialization |
85/// | **User Input** | ❌ Requires compile-time knowledge | ✅ Can handle dynamic input |
86///
87/// ### When to Use Runtime Bounds
88///
89/// ```rust
90/// use grid1d::bounds::*;
91/// use try_create::New;
92///
93/// // ✅ GOOD: Dynamic interval construction from user input
94/// fn create_bound_from_config(value: f64, is_closed: bool) -> LowerBoundRuntime<f64> {
95///     if is_closed {
96///         IntervalBoundRuntime::Closed(LowerBoundClosed::new(value))
97///     } else {
98///         IntervalBoundRuntime::Open(LowerBoundOpen::new(value))
99///     }
100/// }
101///
102/// // ✅ GOOD: Serialization scenarios
103/// let bound = create_bound_from_config(0.0, true);
104/// let serialized = serde_json::to_string(&bound).unwrap();
105/// let deserialized: LowerBoundRuntime<f64> = serde_json::from_str(&serialized).unwrap();
106///
107/// // ❌ AVOID: When bound type is known at compile time
108/// fn bad_usage() -> LowerBoundRuntime<f64> {
109///     // This should just be LowerBoundClosed::new(0.0)
110///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0))
111/// }
112/// ```
113///
114/// ## Type Parameters
115///
116/// - **`RealType`**: Any scalar type implementing [`num_valid::RealScalar`]
117/// - **`Side`**: Either [`Lower`] or [`Upper`] boundary side marker
118///
119/// ## Variants
120///
121/// ### [`IntervalBoundRuntime::Open`]
122///
123/// Contains an open bound that excludes the boundary value:
124///
125/// ```rust
126/// use grid1d::bounds::*;
127/// use try_create::New;
128///
129/// let open_lower = IntervalBoundRuntime::Open(LowerBoundOpen::new(5.0));
130/// let open_upper = IntervalBoundRuntime::Open(UpperBoundOpen::new(10.0));
131///
132/// // Open bounds exclude their boundary values
133/// assert!(!open_lower.value_within_bound(&5.0));   // 5 > 5 → false
134/// assert!(!open_upper.value_within_bound(&10.0));  // 10 < 10 → false
135///
136/// // But include nearby values
137/// assert!(open_lower.value_within_bound(&5.1));    // 5.1 > 5 → true
138/// assert!(open_upper.value_within_bound(&9.9));    // 9.9 < 10 → true
139/// ```
140///
141/// ### [`IntervalBoundRuntime::Closed`]
142///
143/// Contains a closed bound that includes the boundary value:
144///
145/// ```rust
146/// use grid1d::bounds::*;
147/// use try_create::New;
148///
149/// let closed_lower = IntervalBoundRuntime::Closed(LowerBoundClosed::new(5.0));
150/// let closed_upper = IntervalBoundRuntime::Closed(UpperBoundClosed::new(10.0));
151///
152/// // Closed bounds include their boundary values
153/// assert!(closed_lower.value_within_bound(&5.0));   // 5 ≥ 5 → true
154/// assert!(closed_upper.value_within_bound(&10.0));  // 10 ≤ 10 → true
155///
156/// // And also include nearby values
157/// assert!(closed_lower.value_within_bound(&5.1));   // 5.1 ≥ 5 → true
158/// assert!(closed_upper.value_within_bound(&9.9));   // 9.9 ≤ 10 → true
159/// ```
160///
161/// ## Type Aliases for Convenience
162///
163/// ```rust
164/// use grid1d::bounds::*;
165/// use try_create::New;
166///
167/// // Specific side aliases for cleaner code
168/// type LowerBoundRuntime<T> = IntervalBoundRuntime<T, Lower>;
169/// type UpperBoundRuntime<T> = IntervalBoundRuntime<T, Upper>;
170///
171/// // Usage examples
172/// let lower: LowerBoundRuntime<f64> = IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0));
173/// let upper: UpperBoundRuntime<f64> = IntervalBoundRuntime::Open(UpperBoundOpen::new(1.0));
174/// ```
175///
176/// ## Core Operations
177///
178/// ### Boundary Constraint Testing
179///
180/// All runtime bounds implement [`BoundTypeRuntimeChecks`] and provide constraint validation:
181///
182/// ```rust
183/// use grid1d::bounds::*;
184/// use num_valid::RealScalar;
185/// use try_create::New;
186///
187/// fn test_constraint<T: RealScalar>(
188///     bound: &IntervalBoundRuntime<T, Lower>,
189///     test_value: &T
190/// ) -> bool {
191///     match bound {
192///         IntervalBoundRuntime::Open(open_bound) => {
193///             open_bound.value_within_bound(test_value)  // x > bound_value
194///         }
195///         IntervalBoundRuntime::Closed(closed_bound) => {
196///             closed_bound.value_within_bound(test_value)  // x ≥ bound_value
197///         }
198///     }
199/// }
200///
201/// let open_bound = IntervalBoundRuntime::Open(LowerBoundOpen::new(5.0));
202/// let closed_bound = IntervalBoundRuntime::Closed(LowerBoundClosed::new(5.0));
203///
204/// assert!(!test_constraint(&open_bound, &5.0));    // 5 > 5 → false
205/// assert!(test_constraint(&closed_bound, &5.0));   // 5 ≥ 5 → true
206/// ```
207///
208/// ### Value Access and Manipulation
209///
210/// ```rust
211/// use grid1d::bounds::*;
212/// use try_create::{New, IntoInner};
213///
214/// let bound = IntervalBoundRuntime::Closed(LowerBoundClosed::new(3.14));
215///
216/// // Access the underlying value
217/// let value_ref: &f64 = bound.as_ref();
218/// assert_eq!(*value_ref, 3.14);
219///
220/// // Extract the value (consuming the bound)
221/// let value: f64 = bound.into_inner();
222/// assert_eq!(value, 3.14);
223/// ```
224///
225/// ### Type Information Queries
226///
227/// ```rust
228/// use grid1d::bounds::*;
229/// use try_create::New;
230///
231/// let open_bound = IntervalBoundRuntime::Open(LowerBoundOpen::new(1.0));
232/// let closed_bound = IntervalBoundRuntime::Closed(UpperBoundClosed::new(2.0));
233///
234/// // Query boundary inclusion behavior
235/// assert!(open_bound.is_open());
236/// assert!(!open_bound.is_closed());
237/// assert!(!open_bound.includes_boundary());
238///
239/// assert!(!closed_bound.is_open());
240/// assert!(closed_bound.is_closed());
241/// assert!(closed_bound.includes_boundary());
242/// ```
243///
244/// ## Conversion Patterns
245///
246/// ### From Compile-Time to Runtime Bounds
247///
248/// ```rust
249/// use grid1d::bounds::*;
250/// use try_create::New;
251///
252/// // Automatic conversion via From trait
253/// let compile_time_bound = LowerBoundClosed::new(5.0);
254/// let runtime_bound: LowerBoundRuntime<f64> = compile_time_bound.into();
255///
256/// match runtime_bound {
257///     IntervalBoundRuntime::Closed(bound) => {
258///         println!("Converted to runtime closed bound: {}", bound.as_ref());
259///     }
260///     IntervalBoundRuntime::Open(_) => unreachable!(),
261/// }
262/// ```
263///
264/// ### Collection of Mixed Bound Types
265///
266/// ```rust
267/// use grid1d::bounds::*;
268/// use try_create::New;
269///
270/// // Store different bound types in the same collection
271/// let bounds: Vec<LowerBoundRuntime<f64>> = vec![
272///     LowerBoundClosed::new(0.0).into(),
273///     LowerBoundOpen::new(1.0).into(),
274///     LowerBoundClosed::new(2.0).into(),
275///     LowerBoundOpen::new(3.0).into(),
276/// ];
277///
278/// // Process them uniformly
279/// for (i, bound) in bounds.iter().enumerate() {
280///     let inclusion = if bound.is_closed() { "includes" } else { "excludes" };
281///     println!("Bound {}: {} (value {})", i, inclusion, bound.as_ref());
282/// }
283/// ```
284///
285/// ## Mathematical Ordering
286///
287/// Runtime bounds maintain the same mathematical ordering as their compile-time counterparts:
288///
289/// ```rust
290/// use grid1d::bounds::*;
291/// use try_create::New;
292///
293/// let closed_lower = LowerBoundRuntime::Closed(LowerBoundClosed::new(5.0));
294/// let open_lower = LowerBoundRuntime::Open(LowerBoundOpen::new(5.0));
295///
296/// // For lower bounds: closed is "tighter" than open
297/// assert!(closed_lower < open_lower);  // [5 < (5
298///
299/// let open_upper = UpperBoundRuntime::Open(UpperBoundOpen::new(5.0));
300/// let closed_upper = UpperBoundRuntime::Closed(UpperBoundClosed::new(5.0));
301///
302/// // For upper bounds: open is "tighter" than closed
303/// assert!(open_upper < closed_upper);  // 5) < 5]
304/// ```
305///
306/// ## Serialization Support
307///
308/// Runtime bounds have natural serialization support via `serde`:
309///
310/// ```rust
311/// use grid1d::bounds::*;
312/// use try_create::New;
313/// use serde_json;
314///
315/// let bounds = vec![
316///     LowerBoundRuntime::Closed(LowerBoundClosed::new(0.0)),
317///     LowerBoundRuntime::Open(LowerBoundOpen::new(1.0)),
318/// ];
319///
320/// // Serialize to JSON
321/// let json = serde_json::to_string_pretty(&bounds).unwrap();
322/// println!("Serialized bounds:\n{}", json);
323///
324/// // Deserialize back
325/// let deserialized: Vec<LowerBoundRuntime<f64>> =
326///     serde_json::from_str(&json).unwrap();
327///
328/// assert_eq!(bounds.len(), deserialized.len());
329/// for (original, restored) in bounds.iter().zip(deserialized.iter()) {
330///     assert_eq!(original.as_ref(), restored.as_ref());
331///     assert_eq!(original.is_closed(), restored.is_closed());
332/// }
333/// ```
334///
335/// ## Advanced Usage Patterns
336///
337/// ### Dynamic Interval Construction
338///
339/// ```rust
340/// use grid1d::bounds::*;
341/// use try_create::New;
342///
343/// struct IntervalConfig {
344///     lower_value: f64,
345///     lower_closed: bool,
346///     upper_value: f64,
347///     upper_closed: bool,
348/// }
349///
350/// fn create_dynamic_interval(config: IntervalConfig) -> (LowerBoundRuntime<f64>, UpperBoundRuntime<f64>) {
351///     let lower = if config.lower_closed {
352///         IntervalBoundRuntime::Closed(LowerBoundClosed::new(config.lower_value))
353///     } else {
354///         IntervalBoundRuntime::Open(LowerBoundOpen::new(config.lower_value))
355///     };
356///     
357///     let upper = if config.upper_closed {
358///         IntervalBoundRuntime::Closed(UpperBoundClosed::new(config.upper_value))
359///     } else {
360///         IntervalBoundRuntime::Open(UpperBoundOpen::new(config.upper_value))
361///     };
362///     
363///     (lower, upper)
364/// }
365///
366/// // Create different interval types from configuration
367/// let closed_interval = create_dynamic_interval(IntervalConfig {
368///     lower_value: 0.0, lower_closed: true,
369///     upper_value: 1.0, upper_closed: true,
370/// }); // Represents [0, 1]
371///
372/// let half_open_interval = create_dynamic_interval(IntervalConfig {
373///     lower_value: 0.0, lower_closed: true,
374///     upper_value: 1.0, upper_closed: false,
375/// }); // Represents [0, 1)
376/// ```
377///
378/// ### Generic Algorithm Implementation
379///
380/// ```rust
381/// use grid1d::bounds::*;
382/// use num_valid::RealScalar;
383/// use try_create::New;
384///
385/// fn find_overlapping_bounds<T: RealScalar + std::fmt::Display>(
386///     bounds: &[IntervalBoundRuntime<T, Lower>],
387///     test_value: &T
388/// ) -> Vec<usize> {
389///     bounds.iter()
390///         .enumerate()
391///         .filter_map(|(i, bound)| {
392///             let satisfies = match bound {
393///                 IntervalBoundRuntime::Open(open_bound) => {
394///                     open_bound.value_within_bound(test_value)
395///                 }
396///                 IntervalBoundRuntime::Closed(closed_bound) => {
397///                     closed_bound.value_within_bound(test_value)
398///                 }
399///             };
400///             if satisfies { Some(i) } else { None }
401///         })
402///         .collect()
403/// }
404///
405/// let bounds = vec![
406///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0)),  // [0 - includes 0.0
407///     IntervalBoundRuntime::Open(LowerBoundOpen::new(0.0)),      // (0 - excludes 0.0
408///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(1.0)),  // [1 - excludes 0.0
409/// ];
410///
411/// let overlapping = find_overlapping_bounds(&bounds, &0.0);
412/// assert_eq!(overlapping, vec![0]); // Only the closed bound includes 0.0
413/// ```
414///
415/// ## Performance Characteristics
416///
417/// ### Memory Layout
418/// - **Size**: Same as underlying [`IntervalBound`] plus enum discriminant
419/// - **Alignment**: Natural alignment of the largest variant
420/// - **Overhead**: One byte discriminant plus potential padding
421///
422/// ### Operation Complexity
423/// | Operation | Time | Notes |
424/// |-----------|------|-------|
425/// | Construction | O(1) | Simple enum wrapping |
426/// | Pattern matching | O(1) | Compile-time branch prediction |
427/// | Value access | O(1) | Direct field access |
428/// | Constraint testing | O(1) | Inlined comparison operations |
429/// | Serialization | O(1) | Direct enum serialization |
430///
431/// ### Performance vs Compile-Time Bounds
432///
433/// ```rust
434/// use grid1d::bounds::*;
435///
436/// // Runtime bounds: small pattern matching overhead
437/// fn check_runtime_bound(bound: &LowerBoundRuntime<f64>, value: f64) -> bool {
438///     match bound {  // Small branching cost
439///         IntervalBoundRuntime::Open(b) => value > *b.as_ref(),
440///         IntervalBoundRuntime::Closed(b) => value >= *b.as_ref(),
441///     }
442/// }
443///
444/// // Compile-time bounds: zero overhead
445/// fn check_compile_time_bound<T: BoundType>(bound: &LowerBound<f64, T>, value: f64) -> bool {
446///     if T::is_open() {
447///         value > *bound.as_ref()  // Optimized to direct comparison
448///     } else {
449///         value >= *bound.as_ref() // Optimized to direct comparison
450///     }
451/// }
452/// ```
453///
454/// ## Best Practices
455///
456/// ### When to Use Runtime Bounds
457/// - ✅ **User input**: Boundary types determined by configuration
458/// - ✅ **Serialization**: Saving/loading interval data
459/// - ✅ **Dynamic algorithms**: Boundary types vary during execution
460/// - ✅ **Heterogeneous collections**: Storing different bound types together
461///
462/// ### When to Use Compile-Time Bounds
463/// - ✅ **Known constraints**: Boundary types fixed at compile time
464/// - ✅ **Performance critical**: Zero-overhead abstractions required
465/// - ✅ **Type safety**: Prevent mixing incompatible boundary types
466/// - ✅ **Generic algorithms**: Type-parameterized over boundary semantics
467///
468/// ### Conversion Strategy
469/// ```rust
470/// use grid1d::bounds::*;
471/// use try_create::New;
472///
473/// // Pattern: Convert from runtime to compile-time when possible
474/// fn extract_closed_bound(bound: LowerBoundRuntime<f64>) -> Option<LowerBoundClosed<f64>> {
475///     match bound {
476///         IntervalBoundRuntime::Closed(closed_bound) => Some(closed_bound),
477///         IntervalBoundRuntime::Open(_) => None,
478///     }
479/// }
480///
481/// // Pattern: Use runtime bounds at API boundaries, compile-time internally
482/// fn process_user_interval(
483///     lower: LowerBoundRuntime<f64>,
484///     upper: UpperBoundRuntime<f64>
485/// ) -> String {
486///     match (lower, upper) {
487///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Closed(u)) => {
488///             process_closed_interval(l, u)  // Delegate to compile-time version
489///         }
490///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Open(u)) => {
491///             process_open_interval(l, u)    // Delegate to compile-time version
492///         }
493///         // Handle mixed cases...
494///         _ => "Mixed interval types".to_string(),
495///     }
496/// }
497///
498/// fn process_closed_interval(
499///     lower: LowerBoundClosed<f64>,
500///     upper: UpperBoundClosed<f64>
501/// ) -> String {
502///     format!("Closed interval: [{}, {}]", lower.as_ref(), upper.as_ref())
503/// }
504///
505/// fn process_open_interval(
506///     lower: LowerBoundOpen<f64>,
507///     upper: UpperBoundOpen<f64>
508/// ) -> String {
509///     format!("Open interval: ({}, {})", lower.as_ref(), upper.as_ref())
510/// }
511/// ```
512///
513/// ## Integration with Grid1D
514///
515/// Runtime bounds integrate seamlessly with the broader grid1d ecosystem:
516///
517/// ```rust
518/// use grid1d::{bounds::*, intervals::*};
519/// use try_create::{IntoInner, New};
520///
521/// // Convert runtime bounds to actual intervals when needed
522/// fn runtime_bounds_to_interval(
523///     lower: LowerBoundRuntime<f64>,
524///     upper: UpperBoundRuntime<f64>
525/// ) -> Box<dyn std::fmt::Debug> {
526///     match (lower, upper) {
527///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Closed(u)) => {
528///             Box::new(IntervalClosed::new(l.into_inner(), u.into_inner()))
529///         }
530///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Open(u)) => {
531///             Box::new(IntervalOpen::new(l.into_inner(), u.into_inner()))
532///         }
533///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Open(u)) => {
534///             Box::new(IntervalLowerClosedUpperOpen::new(l.into_inner(), u.into_inner()))
535///         }
536///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Closed(u)) => {
537///             Box::new(IntervalLowerOpenUpperClosed::new(l.into_inner(), u.into_inner()))
538///         }
539///     }
540/// }
541/// ```
542///
543/// The [`IntervalBoundRuntime`] enum provides essential flexibility for dynamic interval
544/// construction while maintaining mathematical correctness and integration with the
545/// grid1d type system. Use it when runtime flexibility is needed, but prefer
546/// compile-time bounds when the boundary semantics are known statically.
547#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
548#[serde(bound(deserialize = "RealType: for<'a> Deserialize<'a>"))]
549pub enum IntervalBoundRuntime<RealType: RealScalar, Side: BoundSide> {
550    /// An open (exclusive) interval bound.
551    Open(IntervalBound<RealType, Side, Open>),
552    /// A closed (inclusive) interval bound.
553    Closed(IntervalBound<RealType, Side, Closed>),
554}
555
556/// A bound scalar that is either borrowed or retained as an owned fallback.
557#[derive(Debug)]
558pub enum BoundValue<'a, RealType> {
559    /// A scalar borrowed from its interval.
560    Borrowed(&'a RealType),
561    /// A scalar moved from an owned runtime bound.
562    Owned(RealType),
563}
564
565impl<RealType> AsRef<RealType> for BoundValue<'_, RealType> {
566    #[inline(always)]
567    fn as_ref(&self) -> &RealType {
568        match self {
569            Self::Borrowed(value) => value,
570            Self::Owned(value) => value,
571        }
572    }
573}
574
575/// Open/closed runtime bound view.
576///
577/// Built-in intervals return borrowed scalar references. The owned variant is used by the
578/// default [`IntervalBoundsRuntime`](crate::intervals::IntervalBoundsRuntime) implementation
579/// to preserve source compatibility for external trait implementors.
580#[derive(Debug)]
581pub struct IntervalBoundView<'a, RealType: RealScalar, Side: BoundSide> {
582    value: BoundValue<'a, RealType>,
583    is_closed: bool,
584    _side: PhantomData<Side>,
585}
586
587impl<'a, RealType: RealScalar, Side: BoundSide> IntervalBoundView<'a, RealType, Side> {
588    /// Creates a view over a borrowed bound value.
589    #[inline(always)]
590    pub fn new_borrowed(value: &'a RealType, is_closed: bool) -> Self {
591        Self {
592            value: BoundValue::Borrowed(value),
593            is_closed,
594            _side: PhantomData,
595        }
596    }
597
598    /// Creates a view from an owned runtime bound without cloning its scalar.
599    #[inline(always)]
600    pub(crate) fn from_runtime(bound: IntervalBoundRuntime<RealType, Side>) -> Self {
601        match bound {
602            IntervalBoundRuntime::Open(bound) => Self {
603                value: BoundValue::Owned(bound.into_inner()),
604                is_closed: false,
605                _side: PhantomData,
606            },
607            IntervalBoundRuntime::Closed(bound) => Self {
608                value: BoundValue::Owned(bound.into_inner()),
609                is_closed: true,
610                _side: PhantomData,
611            },
612        }
613    }
614
615    /// Returns the bound value.
616    #[inline(always)]
617    pub fn value(&self) -> &RealType {
618        self.value.as_ref()
619    }
620
621    /// Returns whether the bound includes its endpoint.
622    #[inline(always)]
623    pub fn is_closed(&self) -> bool {
624        self.is_closed
625    }
626
627    /// Returns whether the scalar is borrowed rather than stored in the owned fallback.
628    #[inline(always)]
629    pub fn is_borrowed(&self) -> bool {
630        matches!(&self.value, BoundValue::Borrowed(_))
631    }
632}
633
634/// Borrowed-or-owned lower runtime bound view.
635pub type LowerBoundView<'a, RealType> = IntervalBoundView<'a, RealType, Lower>;
636
637/// Borrowed-or-owned upper runtime bound view.
638pub type UpperBoundView<'a, RealType> = IntervalBoundView<'a, RealType, Upper>;
639
640/// Compares lower-bound views according to set containment semantics.
641pub(crate) fn lower_bound_view_contains<RealType: RealScalar>(
642    container: &Option<LowerBoundView<'_, RealType>>,
643    target: &Option<LowerBoundView<'_, RealType>>,
644) -> bool {
645    bound_view_contains(container, target, false)
646}
647
648/// Compares upper-bound views according to set containment semantics.
649pub(crate) fn upper_bound_view_contains<RealType: RealScalar>(
650    container: &Option<UpperBoundView<'_, RealType>>,
651    target: &Option<UpperBoundView<'_, RealType>>,
652) -> bool {
653    bound_view_contains(container, target, true)
654}
655
656fn bound_view_contains<RealType: RealScalar, Side: BoundSide>(
657    container: &Option<IntervalBoundView<'_, RealType, Side>>,
658    target: &Option<IntervalBoundView<'_, RealType, Side>>,
659    upper: bool,
660) -> bool {
661    match (container, target) {
662        (None, _) => true,
663        (_, None) => false,
664        (Some(container), Some(target)) => match container.value().partial_cmp(target.value()) {
665            Some(Ordering::Equal) => container.is_closed() || !target.is_closed(),
666            Some(Ordering::Less) => !upper,
667            Some(Ordering::Greater) => upper,
668            None => false,
669        },
670    }
671}
672
673impl<RealType: RealScalar, Side: BoundSide> IntervalBoundRuntime<RealType, Side> {
674    /// Create a new open (exclusive) runtime bound.
675    ///
676    /// This is a convenience constructor that creates an open bound variant without
677    /// requiring explicit construction of the underlying [`IntervalBound`].
678    ///
679    /// # Mathematical Meaning
680    ///
681    /// - For **lower bounds**: Creates `x > value` constraint (excludes the boundary)
682    /// - For **upper bounds**: Creates `x < value` constraint (excludes the boundary)
683    ///
684    /// # Examples
685    ///
686    /// ## Lower Bound
687    ///
688    /// ```rust
689    /// use grid1d::bounds::*;
690    ///
691    /// let lower_open: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
692    ///
693    /// // Excludes the boundary value
694    /// assert!(!lower_open.value_within_bound(&5.0));  // 5 > 5 → false
695    /// assert!(lower_open.value_within_bound(&5.1));   // 5.1 > 5 → true
696    /// assert!(!lower_open.value_within_bound(&4.9));  // 4.9 > 5 → false
697    ///
698    /// assert!(lower_open.is_open());
699    /// assert!(lower_open.is_open_variant());
700    /// ```
701    ///
702    /// ## Upper Bound
703    ///
704    /// ```rust
705    /// use grid1d::bounds::*;
706    ///
707    /// let upper_open: UpperBoundRuntime<f64> = IntervalBoundRuntime::new_open(10.0);
708    ///
709    /// // Excludes the boundary value
710    /// assert!(!upper_open.value_within_bound(&10.0));  // 10 < 10 → false
711    /// assert!(upper_open.value_within_bound(&9.9));    // 9.9 < 10 → true
712    /// assert!(!upper_open.value_within_bound(&10.1));  // 10.1 < 10 → false
713    ///
714    /// assert!(upper_open.is_open());
715    /// assert!(upper_open.is_open_variant());
716    /// ```
717    ///
718    /// ## Comparison with Manual Construction
719    ///
720    /// ```rust
721    /// use grid1d::bounds::*;
722    /// use try_create::New;
723    ///
724    /// // Using convenience constructor (cleaner)
725    /// let bound1: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
726    ///
727    /// // Manual construction (more verbose)
728    /// let bound2: LowerBoundRuntime<f64> =
729    ///     IntervalBoundRuntime::Open(LowerBoundOpen::new(5.0));
730    ///
731    /// assert_eq!(bound1, bound2);
732    /// ```
733    ///
734    /// # See Also
735    ///
736    /// - [`new_closed`](Self::new_closed) - Create a closed (inclusive) bound
737    /// - [`is_open_variant`](Self::is_open_variant) - Check if bound is open
738    #[must_use]
739    pub fn new_open(value: RealType) -> Self {
740        Self::Open(IntervalBound::<RealType, Side, Open>::new(value))
741    }
742
743    /// Create a new closed (inclusive) runtime bound.
744    ///
745    /// This is a convenience constructor that creates a closed bound variant without
746    /// requiring explicit construction of the underlying [`IntervalBound`].
747    ///
748    /// # Mathematical Meaning
749    ///
750    /// - For **lower bounds**: Creates `x ≥ value` constraint (includes the boundary)
751    /// - For **upper bounds**: Creates `x ≤ value` constraint (includes the boundary)
752    ///
753    /// # Examples
754    ///
755    /// ## Lower Bound
756    ///
757    /// ```rust
758    /// use grid1d::bounds::*;
759    ///
760    /// let lower_closed: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(5.0);
761    ///
762    /// // Includes the boundary value
763    /// assert!(lower_closed.value_within_bound(&5.0));  // 5 ≥ 5 → true
764    /// assert!(lower_closed.value_within_bound(&5.1));  // 5.1 ≥ 5 → true
765    /// assert!(!lower_closed.value_within_bound(&4.9)); // 4.9 ≥ 5 → false
766    ///
767    /// assert!(lower_closed.is_closed());
768    /// assert!(lower_closed.is_closed_variant());
769    /// ```
770    ///
771    /// ## Upper Bound
772    ///
773    /// ```rust
774    /// use grid1d::bounds::*;
775    ///
776    /// let upper_closed: UpperBoundRuntime<f64> = IntervalBoundRuntime::new_closed(10.0);
777    ///
778    /// // Includes the boundary value
779    /// assert!(upper_closed.value_within_bound(&10.0));  // 10 ≤ 10 → true
780    /// assert!(upper_closed.value_within_bound(&9.9));   // 9.9 ≤ 10 → true
781    /// assert!(!upper_closed.value_within_bound(&10.1)); // 10.1 ≤ 10 → false
782    ///
783    /// assert!(upper_closed.is_closed());
784    /// assert!(upper_closed.is_closed_variant());
785    /// ```
786    ///
787    /// ## Comparison with Manual Construction
788    ///
789    /// ```rust
790    /// use grid1d::bounds::*;
791    /// use try_create::New;
792    ///
793    /// // Using convenience constructor (cleaner)
794    /// let bound1: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(5.0);
795    ///
796    /// // Manual construction (more verbose)
797    /// let bound2: LowerBoundRuntime<f64> =
798    ///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(5.0));
799    ///
800    /// assert_eq!(bound1, bound2);
801    /// ```
802    ///
803    /// # See Also
804    ///
805    /// - [`new_open`](Self::new_open) - Create an open (exclusive) bound
806    /// - [`is_closed_variant`](Self::is_closed_variant) - Check if bound is closed
807    #[must_use]
808    pub fn new_closed(value: RealType) -> Self {
809        Self::Closed(IntervalBound::<RealType, Side, Closed>::new(value))
810    }
811
812    /// Check if this runtime bound is a closed variant without consuming it.
813    ///
814    /// This method provides a non-consuming way to check the bound type, which is useful
815    /// when you need to inspect the bound type without pattern matching or when you want
816    /// to check the type multiple times.
817    ///
818    /// # Returns
819    ///
820    /// - `true` if the bound is [`IntervalBoundRuntime::Closed`]
821    /// - `false` if the bound is [`IntervalBoundRuntime::Open`]
822    ///
823    /// # Performance
824    ///
825    /// This is a zero-cost check that compiles to a simple discriminant comparison.
826    ///
827    /// # Examples
828    ///
829    /// ## Basic Usage
830    ///
831    /// ```rust
832    /// use grid1d::bounds::*;
833    ///
834    /// let closed_bound: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(5.0);
835    /// let open_bound: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
836    ///
837    /// assert!(closed_bound.is_closed_variant());
838    /// assert!(!open_bound.is_closed_variant());
839    /// ```
840    ///
841    /// ## Conditional Logic
842    ///
843    /// ```rust
844    /// use grid1d::bounds::*;
845    ///
846    /// fn describe_bound(bound: &LowerBoundRuntime<f64>) -> String {
847    ///     let inclusion = if bound.is_closed_variant() {
848    ///         "inclusive"
849    ///     } else {
850    ///         "exclusive"
851    ///     };
852    ///     format!("Lower bound at {} ({})", bound.as_ref(), inclusion)
853    /// }
854    ///
855    /// let bound = IntervalBoundRuntime::new_closed(10.0);
856    /// assert_eq!(describe_bound(&bound), "Lower bound at 10 (inclusive)");
857    /// ```
858    ///
859    /// ## Difference from `is_closed()` Trait Method
860    ///
861    /// ```rust
862    /// use grid1d::bounds::*;
863    ///
864    /// let bound: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(5.0);
865    ///
866    /// // Both return the same result
867    /// assert_eq!(bound.is_closed_variant(), bound.is_closed());
868    ///
869    /// // is_closed_variant() is more explicit about checking the enum variant
870    /// // is_closed() comes from the BoundTypeRuntimeChecks trait
871    /// ```
872    ///
873    /// # See Also
874    ///
875    /// - [`is_open_variant`](Self::is_open_variant) - Check if bound is open
876    /// - [`is_closed`](BoundTypeRuntimeChecks::is_closed) - Trait method for same check
877    /// - [`new_closed`](Self::new_closed) - Create a closed bound
878    #[inline(always)]
879    pub fn is_closed_variant(&self) -> bool {
880        matches!(self, Self::Closed(_))
881    }
882
883    /// Check if this runtime bound is an open variant without consuming it.
884    ///
885    /// This method provides a non-consuming way to check the bound type, which is useful
886    /// when you need to inspect the bound type without pattern matching or when you want
887    /// to check the type multiple times.
888    ///
889    /// # Returns
890    ///
891    /// - `true` if the bound is [`IntervalBoundRuntime::Open`]
892    /// - `false` if the bound is [`IntervalBoundRuntime::Closed`]
893    ///
894    /// # Performance
895    ///
896    /// This is a zero-cost check that compiles to a simple discriminant comparison.
897    ///
898    /// # Examples
899    ///
900    /// ## Basic Usage
901    ///
902    /// ```rust
903    /// use grid1d::bounds::*;
904    ///
905    /// let open_bound: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
906    /// let closed_bound: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(5.0);
907    ///
908    /// assert!(open_bound.is_open_variant());
909    /// assert!(!closed_bound.is_open_variant());
910    /// ```
911    ///
912    /// ## Conditional Logic
913    ///
914    /// ```rust
915    /// use grid1d::bounds::*;
916    ///
917    /// fn describe_constraint(bound: &UpperBoundRuntime<f64>) -> String {
918    ///     let symbol = if bound.is_open_variant() { "<" } else { "≤" };
919    ///     format!("x {} {}", symbol, bound.as_ref())
920    /// }
921    ///
922    /// let bound = IntervalBoundRuntime::new_open(100.0);
923    /// assert_eq!(describe_constraint(&bound), "x < 100");
924    /// ```
925    ///
926    /// ## Collecting by Type
927    ///
928    /// ```rust
929    /// use grid1d::bounds::*;
930    ///
931    /// let bounds = vec![
932    ///     LowerBoundRuntime::new_open(1.0),
933    ///     LowerBoundRuntime::new_closed(2.0),
934    ///     LowerBoundRuntime::new_open(3.0),
935    ///     LowerBoundRuntime::new_closed(4.0),
936    /// ];
937    ///
938    /// let open_count = bounds.iter().filter(|b| b.is_open_variant()).count();
939    /// let closed_count = bounds.iter().filter(|b| b.is_closed_variant()).count();
940    ///
941    /// assert_eq!(open_count, 2);
942    /// assert_eq!(closed_count, 2);
943    /// ```
944    ///
945    /// ## Difference from `is_open()` Trait Method
946    ///
947    /// ```rust
948    /// use grid1d::bounds::*;
949    ///
950    /// let bound: UpperBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
951    ///
952    /// // Both return the same result
953    /// assert_eq!(bound.is_open_variant(), bound.is_open());
954    ///
955    /// // is_open_variant() is more explicit about checking the enum variant
956    /// // is_open() comes from the BoundTypeRuntimeChecks trait
957    /// ```
958    ///
959    /// # See Also
960    ///
961    /// - [`is_closed_variant`](Self::is_closed_variant) - Check if bound is closed
962    /// - [`is_open`](BoundTypeRuntimeChecks::is_open) - Trait method for same check
963    /// - [`new_open`](Self::new_open) - Create an open bound
964    #[inline(always)]
965    pub fn is_open_variant(&self) -> bool {
966        matches!(self, Self::Open(_))
967    }
968
969    /// Convert this bound to the opposite bound type, preserving the value.
970    ///
971    /// This method transforms an open bound to a closed bound with the same value, or vice versa.
972    /// The side (lower/upper) is preserved - only the inclusion/exclusion semantics change.
973    ///
974    /// # Mathematical Meaning
975    ///
976    /// ## For Lower Bounds
977    /// - **Open → Closed**: `(a` becomes `[a` — changes `x > a` to `x ≥ a`
978    /// - **Closed → Open**: `[a` becomes `(a` — changes `x ≥ a` to `x > a`
979    ///
980    /// ## For Upper Bounds
981    /// - **Open → Closed**: `b)` becomes `b]` — changes `x < b` to `x ≤ b`
982    /// - **Closed → Open**: `b]` becomes `b)` — changes `x ≤ b` to `x < b`
983    ///
984    /// # Use Cases
985    ///
986    /// This method is particularly useful when:
987    /// - Adjusting interval boundaries in set difference operations
988    /// - Converting between interval types (e.g., `[a, b)` ↔ `(a, b]`)
989    /// - Implementing boundary adjustments in computational geometry
990    /// - Handling boundary conditions in numerical algorithms
991    ///
992    /// # Examples
993    ///
994    /// ## Lower Bound Conversion
995    ///
996    /// ```rust
997    /// use grid1d::bounds::*;
998    ///
999    /// let open_lower: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
1000    ///
1001    /// // Check properties before conversion
1002    /// assert!(open_lower.is_open_variant());
1003    /// assert!(!open_lower.value_within_bound(&5.0));   // 5 > 5 → false
1004    ///
1005    /// // Convert (consumes original)
1006    /// let closed_lower = open_lower.flip_bound_type();
1007    ///
1008    /// // Value is preserved
1009    /// assert_eq!(*closed_lower.as_ref(), 5.0);
1010    ///
1011    /// // But semantics change
1012    /// assert!(closed_lower.is_closed_variant());
1013    /// assert!(closed_lower.value_within_bound(&5.0));  // 5 ≥ 5 → true
1014    /// ```
1015    ///
1016    /// ## Upper Bound Conversion
1017    ///
1018    /// ```rust
1019    /// use grid1d::bounds::*;
1020    ///
1021    /// let closed_upper: UpperBoundRuntime<f64> = IntervalBoundRuntime::new_closed(10.0);
1022    ///
1023    /// // Check properties before conversion
1024    /// assert!(closed_upper.is_closed_variant());
1025    /// assert!(closed_upper.value_within_bound(&10.0));  // 10 ≤ 10 → true
1026    ///
1027    /// // Convert (consumes original)
1028    /// let open_upper = closed_upper.flip_bound_type();
1029    ///
1030    /// // Value is preserved
1031    /// assert_eq!(*open_upper.as_ref(), 10.0);
1032    ///
1033    /// // But semantics change
1034    /// assert!(open_upper.is_open_variant());
1035    /// assert!(!open_upper.value_within_bound(&10.0));   // 10 < 10 → false
1036    /// ```
1037    ///
1038    /// ## Interval Boundary Adjustment
1039    ///
1040    /// ```rust
1041    /// use grid1d::bounds::*;
1042    ///
1043    /// // When computing interval difference A \ B, we often need to flip boundaries
1044    /// // If B has lower bound [b, we need to create upper bound b) for the left remainder
1045    /// let b_lower: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(3.0);  // [3
1046    /// let left_upper = b_lower.flip_bound_type();            // 3) — exclude what B includes
1047    ///
1048    /// // Similarly for upper bounds
1049    /// let b_upper: UpperBoundRuntime<f64> = IntervalBoundRuntime::new_open(7.0);    // 7)
1050    /// let right_lower = b_upper.flip_bound_type();          // [7 — include what B excludes
1051    ///
1052    /// assert!(left_upper.is_open_variant());
1053    /// assert!(right_lower.is_closed_variant());
1054    /// ```
1055    ///
1056    /// ## Round-Trip Consistency
1057    ///
1058    /// ```rust
1059    /// use grid1d::bounds::*;
1060    ///
1061    /// let original: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(2.5);
1062    ///
1063    /// // Save properties for comparison
1064    /// let original_value = *original.as_ref();
1065    /// let was_closed = original.is_closed_variant();
1066    ///
1067    /// // Double flip restores the type
1068    /// let flipped = original.flip_bound_type();
1069    /// let restored = flipped.flip_bound_type();
1070    ///
1071    /// // Value preserved through transformations
1072    /// assert_eq!(*restored.as_ref(), original_value);
1073    ///
1074    /// // Type restored
1075    /// assert_eq!(was_closed, restored.is_closed_variant());
1076    /// ```
1077    ///
1078    /// ## Dynamic Interval Adjustment
1079    ///
1080    /// ```rust
1081    /// use grid1d::bounds::*;
1082    ///
1083    /// fn adjust_boundary_for_exclusion(bound: LowerBoundRuntime<f64>) -> LowerBoundRuntime<f64> {
1084    ///     // Convert any lower bound to open (exclusive) form
1085    ///     if bound.is_closed_variant() {
1086    ///         bound.flip_bound_type()
1087    ///     } else {
1088    ///         bound
1089    ///     }
1090    /// }
1091    ///
1092    /// let closed = IntervalBoundRuntime::new_closed(1.0);
1093    /// let open = adjust_boundary_for_exclusion(closed);
1094    ///
1095    /// assert!(!open.value_within_bound(&1.0));  // Now excludes the boundary
1096    /// assert!(open.value_within_bound(&1.1));   // But includes values above
1097    /// ```
1098    ///
1099    /// # Performance
1100    ///
1101    /// This is an O(1) operation that:
1102    /// - Extracts the underlying scalar value (moving it)
1103    /// - Constructs a new enum variant
1104    /// - Has no allocations or clones
1105    ///
1106    /// For `Copy` types like `f64`, this is a single register move. For non-`Copy` types,
1107    /// it moves the value without cloning.
1108    ///
1109    /// If you need to preserve the original bound, clone it before calling this method:
1110    /// ```rust
1111    /// use grid1d::bounds::*;
1112    ///
1113    /// let original: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
1114    /// let flipped = original.clone().flip_bound_type();  // Keep original
1115    ///
1116    /// assert!(original.is_open_variant());
1117    /// assert!(flipped.is_closed_variant());
1118    /// ```
1119    ///
1120    /// # See Also
1121    ///
1122    /// - [`new_open`](Self::new_open) - Create an open bound
1123    /// - [`new_closed`](Self::new_closed) - Create a closed bound
1124    /// - [`is_open_variant`](Self::is_open_variant) - Check if bound is open
1125    /// - [`is_closed_variant`](Self::is_closed_variant) - Check if bound is closed
1126    #[inline(always)]
1127    pub fn flip_bound_type(self) -> Self {
1128        match self {
1129            Self::Open(bound) => Self::Closed(IntervalBound::new(bound.into_inner())),
1130            Self::Closed(bound) => Self::Open(IntervalBound::new(bound.into_inner())),
1131        }
1132    }
1133
1134    /// Converts a bound to the opposite side while preserving the open/closed type.
1135    ///
1136    /// This function transforms an `IntervalBoundRuntime<RealType, Side>` to
1137    /// `IntervalBoundRuntime<RealType, Side::Opposite>`, changing `Lower` ↔ `Upper`
1138    /// while keeping `Open` ↔ `Open` and `Closed` ↔ `Closed`.
1139    ///
1140    /// The return type is determined by the [`BoundSide::Opposite`] associated type,
1141    /// so no turbofish syntax is needed - the type system automatically infers the
1142    /// correct opposite side based on the input.
1143    ///
1144    /// # Type Transformations
1145    ///
1146    /// | Input Type | Output Type |
1147    /// |------------|-------------|
1148    /// | `LowerBoundRuntime::Open(a)` | `UpperBoundRuntime::Open(a)` |
1149    /// | `LowerBoundRuntime::Closed(a)` | `UpperBoundRuntime::Closed(a)` |
1150    /// | `UpperBoundRuntime::Open(b)` | `LowerBoundRuntime::Open(b)` |
1151    /// | `UpperBoundRuntime::Closed(b)` | `LowerBoundRuntime::Closed(b)` |
1152    ///
1153    /// # Use Cases
1154    ///
1155    /// This function is primarily useful in interval set operations (like difference)
1156    /// where you need to take a bound from one interval and use it as the opposite
1157    /// side for another interval, while flipping the inclusion/exclusion semantics.
1158    ///
1159    /// # Examples
1160    ///
1161    /// ## Converting Lower to Upper Bounds
1162    ///
1163    /// ```rust
1164    /// use grid1d::bounds::*;
1165    ///
1166    /// // Convert lower bound to upper bound (both open)
1167    /// let lower_open = LowerBoundRuntime::new_open(5.0);
1168    /// let upper_open: UpperBoundRuntime<f64> = lower_open.flip_bound_side();
1169    /// assert!(upper_open.is_open_variant());
1170    /// assert_eq!(*upper_open.as_ref(), 5.0);
1171    ///
1172    /// // Convert lower bound to upper bound (both closed)
1173    /// let lower_closed = LowerBoundRuntime::new_closed(10.0);
1174    /// let upper_closed: UpperBoundRuntime<f64> = lower_closed.flip_bound_side();
1175    /// assert!(upper_closed.is_closed_variant());
1176    /// assert_eq!(*upper_closed.as_ref(), 10.0);
1177    /// ```
1178    ///
1179    /// ## Converting Upper to Lower Bounds
1180    ///
1181    /// ```rust
1182    /// use grid1d::bounds::*;
1183    ///
1184    /// // Convert upper bound to lower bound (both open)
1185    /// let upper_open = UpperBoundRuntime::new_open(20.0);
1186    /// let lower_open: LowerBoundRuntime<f64> = upper_open.flip_bound_side();
1187    /// assert!(lower_open.is_open_variant());
1188    /// assert_eq!(*lower_open.as_ref(), 20.0);
1189    ///
1190    /// // Convert upper bound to lower bound (both closed)
1191    /// let upper_closed = UpperBoundRuntime::new_closed(15.0);
1192    /// let lower_closed: LowerBoundRuntime<f64> = upper_closed.flip_bound_side();
1193    /// assert!(lower_closed.is_closed_variant());
1194    /// assert_eq!(*lower_closed.as_ref(), 15.0);
1195    /// ```
1196    ///
1197    /// ## Combining with Bound Type Flipping
1198    ///
1199    /// You can combine `flip_bound_side()` with `flip_bound_type()` to perform
1200    /// both transformations:
1201    ///
1202    /// ```rust
1203    /// use grid1d::bounds::*;
1204    ///
1205    /// // Start with a closed lower bound
1206    /// let lower_closed = LowerBoundRuntime::new_closed(3.0);
1207    ///
1208    /// // Convert to open upper bound (both transformations)
1209    /// let upper_open: UpperBoundRuntime<f64> = lower_closed
1210    ///     .flip_bound_side()  // Lower Closed -> Upper Closed
1211    ///     .flip_bound_type();  // Upper Closed -> Upper Open
1212    ///
1213    /// assert!(upper_open.is_open_variant());
1214    /// assert_eq!(*upper_open.as_ref(), 3.0);
1215    /// ```
1216    ///
1217    /// ## Use in Interval Difference Operations
1218    ///
1219    /// ```rust
1220    /// use grid1d::bounds::*;
1221    ///
1222    /// // When computing A \ B, if B has lower bound [5, we need upper bound )5
1223    /// let b_lower = LowerBoundRuntime::new_closed(5.0);
1224    ///
1225    /// // Convert and flip for the difference result
1226    /// let result_upper: UpperBoundRuntime<f64> = b_lower
1227    ///     .flip_bound_side()   // Lower -> Upper
1228    ///     .flip_bound_type();   // Closed -> Open
1229    ///
1230    /// assert!(result_upper.is_open_variant());
1231    /// assert_eq!(*result_upper.as_ref(), 5.0);
1232    /// // This creates the upper bound )5 from the lower bound [5
1233    /// ```
1234    ///
1235    /// # Performance
1236    ///
1237    /// - **Time Complexity**: O(1) - just moves the underlying value
1238    /// - **Memory**: Consumes `self`, no allocation or cloning required
1239    /// - **Inlining**: Marked `#[inline(always)]` for zero-cost abstraction
1240    ///
1241    /// # See Also
1242    ///
1243    /// - [`flip_bound_type`](Self::flip_bound_type) - Change Open ↔ Closed
1244    /// - [`new_open`](Self::new_open) - Create an open bound
1245    /// - [`new_closed`](Self::new_closed) - Create a closed bound
1246    #[inline(always)]
1247    pub fn flip_bound_side(self) -> IntervalBoundRuntime<RealType, Side::Opposite> {
1248        match self {
1249            Self::Open(bound) => IntervalBoundRuntime::Open(IntervalBound::new(bound.into_inner())),
1250            Self::Closed(bound) => {
1251                IntervalBoundRuntime::Closed(IntervalBound::new(bound.into_inner()))
1252            }
1253        }
1254    }
1255
1256    /// Converts a bound to the opposite side AND flips the open/closed type.
1257    ///
1258    /// This is a convenience function that combines [`flip_bound_side`](Self::flip_bound_side)
1259    /// and [`flip_bound_type`](Self::flip_bound_type) in a single operation, performing
1260    /// both transformations atomically:
1261    /// - Changes `Lower` ↔ `Upper` (side transformation)
1262    /// - Changes `Open` ↔ `Closed` (type transformation)
1263    ///
1264    /// This is equivalent to calling `self.flip_bound_side().flip_bound_type()` but
1265    /// more concise and expresses the intent clearly.
1266    ///
1267    /// # Type Transformations
1268    ///
1269    /// | Input Type | Output Type |
1270    /// |------------|-------------|
1271    /// | `LowerBoundRuntime::Open(a)` | `UpperBoundRuntime::Closed(a)` |
1272    /// | `LowerBoundRuntime::Closed(a)` | `UpperBoundRuntime::Open(a)` |
1273    /// | `UpperBoundRuntime::Open(b)` | `LowerBoundRuntime::Closed(b)` |
1274    /// | `UpperBoundRuntime::Closed(b)` | `LowerBoundRuntime::Open(b)` |
1275    ///
1276    /// # Mathematical Motivation
1277    ///
1278    /// In interval arithmetic, particularly in set difference operations, when you
1279    /// exclude a portion of an interval, the complementary bound needs both transformations:
1280    ///
1281    /// - If the excluded interval has a **closed** lower bound `[a`, the remaining part
1282    ///   needs an **open** upper bound `)a` to avoid including the boundary
1283    /// - If the excluded interval has an **open** lower bound `(a`, the remaining part
1284    ///   needs a **closed** upper bound `]a` to include what was excluded
1285    ///
1286    /// This is precisely the transformation this function performs.
1287    ///
1288    /// # Use Cases
1289    ///
1290    /// This function is essential for interval difference operations (`A \ B`) where
1291    /// bounds from the subtracted interval need to become complementary bounds in the result.
1292    ///
1293    /// # Examples
1294    ///
1295    /// ## Basic Transformations
1296    ///
1297    /// ```rust
1298    /// use grid1d::bounds::*;
1299    ///
1300    /// // Lower Closed -> Upper Open
1301    /// let lower_closed = LowerBoundRuntime::new_closed(5.0);
1302    /// let upper_open: UpperBoundRuntime<f64> = lower_closed.flip_bound_side_and_type();
1303    /// assert!(upper_open.is_open_variant());
1304    /// assert_eq!(*upper_open.as_ref(), 5.0);
1305    ///
1306    /// // Lower Open -> Upper Closed
1307    /// let lower_open = LowerBoundRuntime::new_open(10.0);
1308    /// let upper_closed: UpperBoundRuntime<f64> = lower_open.flip_bound_side_and_type();
1309    /// assert!(upper_closed.is_closed_variant());
1310    /// assert_eq!(*upper_closed.as_ref(), 10.0);
1311    ///
1312    /// // Upper Closed -> Lower Open
1313    /// let upper_closed = UpperBoundRuntime::new_closed(15.0);
1314    /// let lower_open: LowerBoundRuntime<f64> = upper_closed.flip_bound_side_and_type();
1315    /// assert!(lower_open.is_open_variant());
1316    /// assert_eq!(*lower_open.as_ref(), 15.0);
1317    ///
1318    /// // Upper Open -> Lower Closed
1319    /// let upper_open = UpperBoundRuntime::new_open(20.0);
1320    /// let lower_closed: LowerBoundRuntime<f64> = upper_open.flip_bound_side_and_type();
1321    /// assert!(lower_closed.is_closed_variant());
1322    /// assert_eq!(*lower_closed.as_ref(), 20.0);
1323    /// ```
1324    ///
1325    /// ## Interval Difference: Why This Matters
1326    ///
1327    /// ```rust
1328    /// use grid1d::bounds::*;
1329    ///
1330    /// // Computing A \ B where:
1331    /// // A = [0, 10]
1332    /// // B = [5, 7]
1333    /// // Result should be [0, 5) ∪ (7, 10]
1334    ///
1335    /// // B's lower bound is [5 (closed), so left remainder needs )5 (open upper)
1336    /// let b_lower = LowerBoundRuntime::new_closed(5.0);
1337    /// let left_upper: UpperBoundRuntime<f64> = b_lower.flip_bound_side_and_type();
1338    /// assert!(left_upper.is_open_variant());
1339    /// assert_eq!(*left_upper.as_ref(), 5.0);
1340    /// // This creates [0, 5) - the left part of A \ B
1341    ///
1342    /// // B's upper bound is ]7 (closed), so right remainder needs (7 (open lower)
1343    /// let b_upper = UpperBoundRuntime::new_closed(7.0);
1344    /// let right_lower: LowerBoundRuntime<f64> = b_upper.flip_bound_side_and_type();
1345    /// assert!(right_lower.is_open_variant());
1346    /// assert_eq!(*right_lower.as_ref(), 7.0);
1347    /// // This creates (7, 10] - the right part of A \ B
1348    /// ```
1349    ///
1350    /// ## Comparison with Sequential Operations
1351    ///
1352    /// ```rust
1353    /// use grid1d::bounds::*;
1354    ///
1355    /// let bound = LowerBoundRuntime::new_closed(3.0);
1356    ///
1357    /// // These are equivalent:
1358    /// let result1: UpperBoundRuntime<f64> = bound.clone().flip_bound_side_and_type();
1359    /// let result2: UpperBoundRuntime<f64> = bound.flip_bound_side().flip_bound_type();
1360    ///
1361    /// assert_eq!(result1.is_open_variant(), result2.is_open_variant());
1362    /// assert_eq!(*result1.as_ref(), *result2.as_ref());
1363    /// ```
1364    ///
1365    /// ## Involutive Property
1366    ///
1367    /// Applying this transformation twice returns to the original state (modulo the value):
1368    ///
1369    /// ```rust
1370    /// use grid1d::bounds::*;
1371    ///
1372    /// let original = LowerBoundRuntime::new_closed(7.5);
1373    /// let was_closed = original.is_closed_variant();
1374    /// let original_value = *original.as_ref();
1375    ///
1376    /// // Apply transformation twice
1377    /// let transformed: UpperBoundRuntime<f64> = original.flip_bound_side_and_type();
1378    /// let back: LowerBoundRuntime<f64> = transformed.flip_bound_side_and_type();
1379    ///
1380    /// // Returns to original type and value
1381    /// assert_eq!(back.is_closed_variant(), was_closed);
1382    /// assert_eq!(*back.as_ref(), original_value);
1383    /// ```
1384    ///
1385    /// # Performance
1386    ///
1387    /// - **Time Complexity**: O(1) - single pattern match and value move
1388    /// - **Memory**: Consumes `self`, no allocation or cloning required
1389    /// - **Inlining**: Marked `#[inline(always)]` for zero-cost abstraction
1390    /// - **Optimization**: Compiler can optimize to a simple field swap
1391    ///
1392    /// # See Also
1393    ///
1394    /// - [`flip_bound_side`](Self::flip_bound_side) - Change only the side (Lower ↔ Upper)
1395    /// - [`flip_bound_type`](Self::flip_bound_type) - Change only the type (Open ↔ Closed)
1396    /// - [`new_open`](Self::new_open) - Create an open bound
1397    /// - [`new_closed`](Self::new_closed) - Create a closed bound
1398    #[inline(always)]
1399    pub fn flip_bound_side_and_type(self) -> IntervalBoundRuntime<RealType, Side::Opposite> {
1400        match self {
1401            Self::Open(bound) => {
1402                IntervalBoundRuntime::Closed(IntervalBound::new(bound.into_inner()))
1403            }
1404            Self::Closed(bound) => {
1405                IntervalBoundRuntime::Open(IntervalBound::new(bound.into_inner()))
1406            }
1407        }
1408    }
1409}
1410
1411/// Runtime-determined lower bound that can be either open or closed.
1412///
1413/// [`LowerBoundRuntime<RealType>`] is a convenient type alias for [`IntervalBoundRuntime<RealType, Lower>`]
1414/// that specifically represents lower boundaries where the open/closed nature is determined at runtime.
1415/// This type is essential for dynamic interval construction, user configuration, serialization,
1416/// and algorithms that work with varying lower boundary semantics.
1417///
1418/// ## Type Definition
1419///
1420/// ```rust
1421/// use grid1d::bounds::*;
1422///
1423/// // These are equivalent:
1424/// type LowerBoundRuntime<T> = IntervalBoundRuntime<T, Lower>;
1425/// type ExplicitForm<T> = IntervalBoundRuntime<T, Lower>;
1426/// ```
1427///
1428/// ## Mathematical Properties
1429///
1430/// Lower bounds define minimum constraints for intervals and domains with runtime-determined inclusion:
1431///
1432/// | Variant | Mathematical Constraint | Notation | Value at Boundary |
1433/// |---------|------------------------|----------|-------------------|
1434/// | `Open(LowerBoundOpen)`   | `x > lower_value` | `(a` | **Excluded** |
1435/// | `Closed(LowerBoundClosed)` | `x ≥ lower_value` | `[a` | **Included** |
1436///
1437/// ## When to Use Lower Bound Runtime
1438///
1439/// ### ✅ **Recommended Use Cases**
1440///
1441/// ```rust
1442/// use grid1d::bounds::*;
1443/// use try_create::New;
1444///
1445/// // ✅ GOOD: User input with configuration
1446/// fn create_constraint_from_user_input(min_value: f64, inclusive: bool) -> LowerBoundRuntime<f64> {
1447///     if inclusive {
1448///         IntervalBoundRuntime::Closed(LowerBoundClosed::new(min_value))
1449///     } else {
1450///         IntervalBoundRuntime::Open(LowerBoundOpen::new(min_value))
1451///     }
1452/// }
1453///
1454/// // ✅ GOOD: Configuration-driven interval construction
1455/// struct DomainConfig {
1456///     start: f64,
1457///     include_start: bool,
1458///     end: f64,
1459///     include_end: bool,
1460/// }
1461///
1462/// fn build_dynamic_domain(config: DomainConfig) -> (LowerBoundRuntime<f64>, UpperBoundRuntime<f64>) {
1463///     let lower = create_constraint_from_user_input(config.start, config.include_start);
1464///     let upper = if config.include_end {
1465///         IntervalBoundRuntime::Closed(UpperBoundClosed::new(config.end))
1466///     } else {
1467///         IntervalBoundRuntime::Open(UpperBoundOpen::new(config.end))
1468///     };
1469///     (lower, upper)
1470/// }
1471/// ```
1472///
1473/// ### ❌ **Avoid When**
1474///
1475/// ```rust
1476/// use grid1d::bounds::*;
1477/// use try_create::New;
1478///
1479/// // ❌ AVOID: When boundary type is known at compile time
1480/// fn bad_usage() -> LowerBoundRuntime<f64> {
1481///     // This should just be LowerBoundClosed::new(0.0)
1482///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0))
1483/// }
1484///
1485/// // ✅ BETTER: Use compile-time types when semantics are fixed
1486/// fn good_usage() -> LowerBoundClosed<f64> {
1487///     LowerBoundClosed::new(0.0)
1488/// }
1489/// ```
1490///
1491/// ## Core Operations
1492///
1493/// ### Constraint Testing
1494///
1495/// ```rust
1496/// use grid1d::bounds::*;
1497/// use try_create::New;
1498///
1499/// let closed_lower = IntervalBoundRuntime::Closed(LowerBoundClosed::new(5.0));
1500/// let open_lower = IntervalBoundRuntime::Open(LowerBoundOpen::new(5.0));
1501///
1502/// // Test the boundary value itself
1503/// assert!(closed_lower.value_within_bound(&5.0));  // 5 ≥ 5 → true
1504/// assert!(!open_lower.value_within_bound(&5.0));   // 5 > 5 → false
1505///
1506/// // Test values above the boundary
1507/// assert!(closed_lower.value_within_bound(&5.1));  // 5.1 ≥ 5 → true
1508/// assert!(open_lower.value_within_bound(&5.1));    // 5.1 > 5 → true
1509///
1510/// // Test values below the boundary
1511/// assert!(!closed_lower.value_within_bound(&4.9)); // 4.9 ≥ 5 → false
1512/// assert!(!open_lower.value_within_bound(&4.9));   // 4.9 > 5 → false
1513/// ```
1514///
1515/// ### Type Information Queries
1516///
1517/// ```rust
1518/// use grid1d::bounds::*;
1519/// use try_create::New;
1520///
1521/// let closed_bound = IntervalBoundRuntime::Closed(LowerBoundClosed::new(1.0));
1522/// let open_bound = IntervalBoundRuntime::Open(LowerBoundOpen::new(1.0));
1523///
1524/// // Query boundary inclusion behavior
1525/// assert!(closed_bound.is_closed());
1526/// assert!(!closed_bound.is_open());
1527/// assert!(closed_bound.includes_boundary());
1528///
1529/// assert!(!open_bound.is_closed());
1530/// assert!(open_bound.is_open());
1531/// assert!(!open_bound.includes_boundary());
1532///
1533/// // All lower bounds share this property
1534/// assert!(closed_bound.is_lower_bound());
1535/// assert!(open_bound.is_lower_bound());
1536/// assert!(!closed_bound.is_upper_bound());
1537/// assert!(!open_bound.is_upper_bound());
1538/// ```
1539///
1540/// ### Value Access
1541///
1542/// ```rust
1543/// use grid1d::bounds::*;
1544/// use try_create::{New, IntoInner};
1545///
1546/// let bound = IntervalBoundRuntime::Closed(LowerBoundClosed::new(3.14));
1547///
1548/// // Access the underlying value by reference
1549/// let value_ref: &f64 = bound.as_ref();
1550/// assert_eq!(*value_ref, 3.14);
1551///
1552/// // Extract the value (consuming the bound)
1553/// let value: f64 = bound.into_inner();
1554/// assert_eq!(value, 3.14);
1555/// ```
1556///
1557/// ## Mathematical Ordering
1558///
1559/// Lower bounds maintain mathematically correct ordering where "tighter" constraints are considered smaller:
1560///
1561/// ```rust
1562/// use grid1d::bounds::*;
1563/// use try_create::New;
1564///
1565/// let closed_lower = IntervalBoundRuntime::Closed(LowerBoundClosed::new(5.0));  // [5
1566/// let open_lower = IntervalBoundRuntime::Open(LowerBoundOpen::new(5.0));        // (5
1567///
1568/// // Closed bound is "tighter" (more restrictive) than open bound
1569/// assert!(closed_lower < open_lower);  // [5 < (5
1570///
1571/// // This ordering ensures correct interval operations:
1572/// // intersection([5, 10]) ∩ (5, 10]) = (5, 10] (the looser constraint wins)
1573/// ```
1574///
1575/// ## Practical Usage Patterns
1576///
1577/// ### Dynamic Interval Construction
1578///
1579/// ```rust
1580/// use grid1d::bounds::*;
1581/// use try_create::New;
1582///
1583/// struct IntervalBuilder {
1584///     lower_value: f64,
1585///     lower_inclusive: bool,
1586/// }
1587///
1588/// impl IntervalBuilder {
1589///     fn build_lower_bound(&self) -> LowerBoundRuntime<f64> {
1590///         if self.lower_inclusive {
1591///             IntervalBoundRuntime::Closed(LowerBoundClosed::new(self.lower_value))
1592///         } else {
1593///             IntervalBoundRuntime::Open(LowerBoundOpen::new(self.lower_value))
1594///         }
1595///     }
1596///     
1597///     fn set_constraint(&mut self, value: f64, inclusive: bool) {
1598///         self.lower_value = value;
1599///         self.lower_inclusive = inclusive;
1600///     }
1601/// }
1602///
1603/// let mut builder = IntervalBuilder { lower_value: 0.0, lower_inclusive: true };
1604/// let bound1 = builder.build_lower_bound(); // [0
1605///
1606/// builder.set_constraint(1.0, false);
1607/// let bound2 = builder.build_lower_bound(); // (1
1608///
1609/// assert!(bound1.is_closed());
1610/// assert!(bound2.is_open());
1611/// ```
1612///
1613/// ### Configuration-Driven Systems
1614///
1615/// ```rust
1616/// use grid1d::bounds::*;
1617/// use try_create::New;
1618/// use serde::{Deserialize, Serialize};
1619///
1620/// #[derive(Serialize, Deserialize)]
1621/// struct ConstraintConfig {
1622///     minimum_value: f64,
1623///     include_minimum: bool,
1624/// }
1625///
1626/// impl ConstraintConfig {
1627///     fn to_lower_bound(&self) -> LowerBoundRuntime<f64> {
1628///         if self.include_minimum {
1629///             IntervalBoundRuntime::Closed(LowerBoundClosed::new(self.minimum_value))
1630///         } else {
1631///             IntervalBoundRuntime::Open(LowerBoundOpen::new(self.minimum_value))
1632///         }
1633///     }
1634/// }
1635///
1636/// // Load from configuration file or user input
1637/// let config = ConstraintConfig {
1638///     minimum_value: 0.0,
1639///     include_minimum: true,
1640/// };
1641///
1642/// let lower_bound = config.to_lower_bound();
1643/// assert!(lower_bound.value_within_bound(&0.0)); // Includes minimum
1644/// ```
1645///
1646/// ### Collection Processing
1647///
1648/// ```rust
1649/// use grid1d::bounds::*;
1650/// use try_create::New;
1651///
1652/// // Store different lower bound types in the same collection
1653/// let constraints: Vec<LowerBoundRuntime<f64>> = vec![
1654///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0)),   // [0
1655///     IntervalBoundRuntime::Open(LowerBoundOpen::new(1.0)),       // (1
1656///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(2.0)),   // [2
1657///     IntervalBoundRuntime::Open(LowerBoundOpen::new(3.0)),       // (3
1658/// ];
1659///
1660/// // Process them uniformly
1661/// for (i, constraint) in constraints.iter().enumerate() {
1662///     let inclusion = if constraint.is_closed() { "≥" } else { ">" };
1663///     println!("Constraint {}: x {} {}", i, inclusion, constraint.as_ref());
1664/// }
1665/// // Output:
1666/// // Constraint 0: x ≥ 0
1667/// // Constraint 1: x > 1
1668/// // Constraint 2: x ≥ 2
1669/// // Constraint 3: x > 3
1670///
1671/// // Find all constraints satisfied by a test value
1672/// let test_value = 2.0;
1673/// let satisfied: Vec<usize> = constraints.iter()
1674///     .enumerate()
1675///     .filter(|(_, constraint)| constraint.value_within_bound(&test_value))
1676///     .map(|(i, _)| i)
1677///     .collect();
1678///
1679/// assert_eq!(satisfied, vec![0, 1, 2]); // Only [0, (1 and [2 include 2.0
1680/// ```
1681///
1682/// ## Serialization Support
1683///
1684/// Runtime bounds have natural serialization support, making them ideal for persistent configuration:
1685///
1686/// ```rust
1687/// use grid1d::bounds::*;
1688/// use try_create::New;
1689/// use serde_json;
1690///
1691/// let bounds = vec![
1692///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0)),
1693///     IntervalBoundRuntime::Open(LowerBoundOpen::new(1.5)),
1694/// ];
1695///
1696/// // Serialize to JSON
1697/// let json = serde_json::to_string_pretty(&bounds).unwrap();
1698/// println!("Serialized lower bounds:\n{}", json);
1699///
1700/// // Deserialize back
1701/// let deserialized: Vec<LowerBoundRuntime<f64>> =
1702///     serde_json::from_str(&json).unwrap();
1703///
1704/// // Verify round-trip correctness
1705/// for (original, restored) in bounds.iter().zip(deserialized.iter()) {
1706///     assert_eq!(original.as_ref(), restored.as_ref());
1707///     assert_eq!(original.is_closed(), restored.is_closed());
1708///     assert_eq!(original.value_within_bound(&0.0), restored.value_within_bound(&0.0));
1709/// }
1710/// ```
1711///
1712/// ## Generic Algorithm Support
1713///
1714/// ```rust
1715/// use grid1d::bounds::*;
1716/// use num_valid::RealScalar;
1717/// use try_create::New;
1718///
1719/// fn find_minimum_satisfying_constraint<T: RealScalar + Copy>(
1720///     candidates: &[T],
1721///     constraint: &LowerBoundRuntime<T>
1722/// ) -> Option<T>
1723/// where
1724///     T: PartialOrd,
1725/// {
1726///     candidates.iter()
1727///         .filter(|&&value| constraint.value_within_bound(&value))
1728///         .min_by(|a, b| a.partial_cmp(b).unwrap())
1729///         .copied()
1730/// }
1731///
1732/// let values = vec![0.0, 0.5, 1.0, 1.5, 2.0];
1733///
1734/// let closed_constraint = IntervalBoundRuntime::Closed(LowerBoundClosed::new(1.0));
1735/// let open_constraint = IntervalBoundRuntime::Open(LowerBoundOpen::new(1.0));
1736///
1737/// assert_eq!(find_minimum_satisfying_constraint(&values, &closed_constraint), Some(1.0)); // x ≥ 1
1738/// assert_eq!(find_minimum_satisfying_constraint(&values, &open_constraint), Some(1.5));   // x > 1
1739/// ```
1740///
1741/// ## Performance vs Compile-Time Bounds
1742///
1743/// ### Runtime Performance
1744/// - **Memory**: Same as underlying bound plus small enum discriminant (~9 bytes for f64)
1745/// - **Operations**: Small pattern matching overhead (~1-2 CPU cycles)
1746/// - **Constraint Testing**: O(1) with inlined comparisons
1747///
1748/// ### Comparison with Compile-Time Bounds
1749///
1750/// ```rust
1751/// use grid1d::bounds::*;
1752/// use try_create::New;
1753///
1754/// // Runtime bound: small branching cost
1755/// fn check_runtime_constraint(bound: &LowerBoundRuntime<f64>, value: f64) -> bool {
1756///     match bound {  // Runtime dispatch (small cost)
1757///         IntervalBoundRuntime::Open(b) => value > *b.as_ref(),
1758///         IntervalBoundRuntime::Closed(b) => value >= *b.as_ref(),
1759///     }
1760/// }
1761///
1762/// // Compile-time bound: zero overhead
1763/// fn check_compile_time_constraint<T: BoundType>(bound: &LowerBound<f64, T>, value: f64) -> bool {
1764///     if T::is_open() {
1765///         value > *bound.as_ref()  // Direct comparison, no branching
1766///     } else {
1767///         value >= *bound.as_ref() // Direct comparison, no branching
1768///     }
1769/// }
1770/// ```
1771///
1772/// ## Integration with Grid1D
1773///
1774/// Runtime bounds integrate seamlessly with interval construction:
1775///
1776/// ```rust
1777/// use grid1d::{bounds::*, intervals::*};
1778/// use try_create::{IntoInner, New};
1779///
1780/// fn create_interval_from_runtime_bounds(
1781///     lower: LowerBoundRuntime<f64>,
1782///     upper: UpperBoundRuntime<f64>
1783/// ) -> Box<dyn std::fmt::Debug> {
1784///     match (lower, upper) {
1785///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Closed(u)) => {
1786///             Box::new(IntervalClosed::new(l.into_inner(), u.into_inner()))
1787///         }
1788///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Open(u)) => {
1789///             Box::new(IntervalOpen::new(l.into_inner(), u.into_inner()))
1790///         }
1791///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Open(u)) => {
1792///             Box::new(IntervalLowerClosedUpperOpen::new(l.into_inner(), u.into_inner()))
1793///         }
1794///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Closed(u)) => {
1795///             Box::new(IntervalLowerOpenUpperClosed::new(l.into_inner(), u.into_inner()))
1796///         }
1797///     }
1798/// }
1799///
1800/// // Example usage
1801/// let lower = IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0));
1802/// let upper = IntervalBoundRuntime::Open(UpperBoundOpen::new(1.0));
1803/// let interval = create_interval_from_runtime_bounds(lower, upper); // Creates [0, 1)
1804/// ```
1805///
1806/// ## Conversion Patterns
1807///
1808/// ### Extract Specific Bound Types
1809///
1810/// ```rust
1811/// use grid1d::bounds::*;
1812/// use try_create::New;
1813///
1814/// fn extract_closed_lower_bound(bound: LowerBoundRuntime<f64>) -> Option<LowerBoundClosed<f64>> {
1815///     match bound {
1816///         IntervalBoundRuntime::Closed(closed_bound) => Some(closed_bound),
1817///         IntervalBoundRuntime::Open(_) => None,
1818///     }
1819/// }
1820///
1821/// let runtime_bound = IntervalBoundRuntime::Closed(LowerBoundClosed::new(5.0));
1822/// let compile_time_bound = extract_closed_lower_bound(runtime_bound);
1823/// assert!(compile_time_bound.is_some());
1824/// ```
1825///
1826/// ### Convert to Compile-Time When Possible
1827///
1828/// ```rust
1829/// use grid1d::bounds::*;
1830/// use try_create::New;
1831///
1832/// // Pattern: Use runtime bounds at API boundaries, compile-time internally
1833/// fn process_constraint(constraint: LowerBoundRuntime<f64>) -> String {
1834///     match constraint {
1835///         IntervalBoundRuntime::Closed(closed_bound) => {
1836///             // Delegate to compile-time optimized function
1837///             process_closed_constraint(closed_bound)
1838///         }
1839///         IntervalBoundRuntime::Open(open_bound) => {
1840///             // Delegate to compile-time optimized function
1841///             process_open_constraint(open_bound)
1842///         }
1843///     }
1844/// }
1845///
1846/// fn process_closed_constraint(bound: LowerBoundClosed<f64>) -> String {
1847///     format!("Inclusive lower bound: x ≥ {}", bound.as_ref())
1848/// }
1849///
1850/// fn process_open_constraint(bound: LowerBoundOpen<f64>) -> String {
1851///     format!("Exclusive lower bound: x > {}", bound.as_ref())
1852/// }
1853/// ```
1854///
1855/// ## Best Practices
1856///
1857/// ### 1. **Use at API Boundaries**
1858/// ```rust
1859/// use grid1d::bounds::*;
1860///
1861/// // ✅ GOOD: Runtime bounds for user-facing APIs
1862/// pub fn create_domain_from_config(
1863///     lower: LowerBoundRuntime<f64>,
1864///     upper: UpperBoundRuntime<f64>
1865/// ) -> Result<Box<dyn std::fmt::Debug>, String> {
1866///     // Implementation...
1867///     Ok(Box::new(format!("Domain created")))
1868/// }
1869///
1870/// // ✅ GOOD: Compile-time bounds for internal algorithms
1871/// fn optimize_grid_spacing<T: BoundType>(
1872///     lower: &LowerBound<f64, T>
1873/// ) -> f64 {
1874///     // High-performance internal computation
1875///     *lower.as_ref() * 1.1
1876/// }
1877/// ```
1878///
1879/// ### 2. **Pattern Match Early**
1880/// ```rust
1881/// use grid1d::bounds::*;
1882/// use try_create::New;
1883///
1884/// // ✅ GOOD: Extract compile-time types early
1885/// fn efficient_processing(constraint: LowerBoundRuntime<f64>) -> f64 {
1886///     match constraint {
1887///         IntervalBoundRuntime::Closed(bound) => {
1888///             // Use compile-time optimized path
1889///             bound.as_ref() * 1.0  // Zero overhead
1890///         }
1891///         IntervalBoundRuntime::Open(bound) => {
1892///             // Use compile-time optimized path
1893///             bound.as_ref() + f64::EPSILON  // Zero overhead
1894///         }
1895///     }
1896/// }
1897/// ```
1898///
1899/// ### 3. **Validate Early**
1900/// ```rust
1901/// use grid1d::bounds::*;
1902/// use try_create::New;
1903///
1904/// fn create_constraint_with_validation(
1905///     value: f64,
1906///     inclusive: bool
1907/// ) -> Result<LowerBoundRuntime<f64>, String> {
1908///     if !value.is_finite() {
1909///         return Err(format!("Constraint value must be finite, got: {}", value));
1910///     }
1911///     
1912///     let bound = if inclusive {
1913///         IntervalBoundRuntime::Closed(LowerBoundClosed::new(value))
1914///     } else {
1915///         IntervalBoundRuntime::Open(LowerBoundOpen::new(value))
1916///     };
1917///     
1918///     Ok(bound)
1919/// }
1920/// ```
1921///
1922/// ## Mathematical Guarantees
1923///
1924/// The [`LowerBoundRuntime`] type maintains mathematical correctness by:
1925///
1926/// - **Constraint Semantics**: Properly implements `x ≥ a` (closed) vs `x > a` (open)
1927/// - **Ordering Consistency**: Maintains mathematical ordering where `[a < (a`
1928/// - **Type Safety**: Prevents mixing with upper bounds at compile time
1929/// - **Value Preservation**: Maintains exact scalar values without precision loss
1930/// - **Conversion Safety**: Provides safe extraction of compile-time types
1931///
1932/// Use [`LowerBoundRuntime`] when you need the flexibility of runtime boundary semantics
1933/// while maintaining mathematical correctness and integration with the grid1d ecosystem.
1934/// For maximum performance when boundary types are known at compile time, prefer the
1935/// direct types [`LowerBoundClosed`](crate::bounds::LowerBoundClosed) and [`LowerBoundOpen`](crate::bounds::LowerBoundOpen).
1936pub type LowerBoundRuntime<RealType> = IntervalBoundRuntime<RealType, Lower>;
1937
1938/// Runtime-determined upper bound that can be either open or closed.
1939///
1940/// [`UpperBoundRuntime<RealType>`] is a convenient type alias for [`IntervalBoundRuntime<RealType, Upper>`]
1941/// that specifically represents upper boundaries where the open/closed nature is determined at runtime.
1942/// This type is essential for dynamic interval construction, user configuration, serialization,
1943/// and algorithms that work with varying upper boundary semantics.
1944///
1945/// ## Type Definition
1946///
1947/// ```rust
1948/// use grid1d::bounds::*;
1949///
1950/// // These are equivalent:
1951/// type UpperBoundRuntime<T> = IntervalBoundRuntime<T, Upper>;
1952/// type ExplicitForm<T> = IntervalBoundRuntime<T, Upper>;
1953/// ```
1954///
1955/// ## Mathematical Properties
1956///
1957/// Upper bounds define maximum constraints for intervals and domains with runtime-determined inclusion:
1958///
1959/// | Variant | Mathematical Constraint | Notation | Value at Boundary |
1960/// |---------|------------------------|----------|-------------------|
1961/// | `Open(UpperBoundOpen)`   | `x < upper_value` | `b)` | **Excluded** |
1962/// | `Closed(UpperBoundClosed)` | `x ≤ upper_value` | `b]` | **Included** |
1963///
1964/// ## When to Use Upper Bound Runtime
1965///
1966/// ### ✅ **Recommended Use Cases**
1967///
1968/// ```rust
1969/// use grid1d::bounds::*;
1970/// use try_create::New;
1971///
1972/// // ✅ GOOD: User input with configuration
1973/// fn create_upper_constraint_from_user_input(max_value: f64, inclusive: bool) -> UpperBoundRuntime<f64> {
1974///     if inclusive {
1975///         IntervalBoundRuntime::Closed(UpperBoundClosed::new(max_value))
1976///     } else {
1977///         IntervalBoundRuntime::Open(UpperBoundOpen::new(max_value))
1978///     }
1979/// }
1980///
1981/// // ✅ GOOD: Configuration-driven interval construction
1982/// struct RangeConfig {
1983///     start: f64,
1984///     include_start: bool,
1985///     end: f64,
1986///     include_end: bool,
1987/// }
1988///
1989/// fn build_dynamic_range(config: RangeConfig) -> (LowerBoundRuntime<f64>, UpperBoundRuntime<f64>) {
1990///     let lower = if config.include_start {
1991///         IntervalBoundRuntime::Closed(LowerBoundClosed::new(config.start))
1992///     } else {
1993///         IntervalBoundRuntime::Open(LowerBoundOpen::new(config.start))
1994///     };
1995///     
1996///     let upper = create_upper_constraint_from_user_input(config.end, config.include_end);
1997///     (lower, upper)
1998/// }
1999/// ```
2000///
2001/// ### ❌ **Avoid When**
2002///
2003/// ```rust
2004/// use grid1d::bounds::*;
2005/// use try_create::New;
2006///
2007/// // ❌ AVOID: When boundary type is known at compile time
2008/// fn bad_usage() -> UpperBoundRuntime<f64> {
2009///     // This should just be UpperBoundOpen::new(10.0)
2010///     IntervalBoundRuntime::Open(UpperBoundOpen::new(10.0))
2011/// }
2012///
2013/// // ✅ BETTER: Use compile-time types when semantics are fixed
2014/// fn good_usage() -> UpperBoundOpen<f64> {
2015///     UpperBoundOpen::new(10.0)
2016/// }
2017/// ```
2018///
2019/// ## Core Operations
2020///
2021/// ### Constraint Testing
2022///
2023/// ```rust
2024/// use grid1d::bounds::*;
2025/// use try_create::New;
2026///
2027/// let closed_upper = IntervalBoundRuntime::Closed(UpperBoundClosed::new(10.0));
2028/// let open_upper = IntervalBoundRuntime::Open(UpperBoundOpen::new(10.0));
2029///
2030/// // Test the boundary value itself
2031/// assert!(closed_upper.value_within_bound(&10.0));  // 10 ≤ 10 → true
2032/// assert!(!open_upper.value_within_bound(&10.0));   // 10 < 10 → false
2033///
2034/// // Test values below the boundary
2035/// assert!(closed_upper.value_within_bound(&9.5));   // 9.5 ≤ 10 → true
2036/// assert!(open_upper.value_within_bound(&9.5));     // 9.5 < 10 → true
2037///
2038/// // Test values above the boundary
2039/// assert!(!closed_upper.value_within_bound(&10.5)); // 10.5 ≤ 10 → false
2040/// assert!(!open_upper.value_within_bound(&10.5));   // 10.5 < 10 → false
2041/// ```
2042///
2043/// ### Type Information Queries
2044///
2045/// ```rust
2046/// use grid1d::bounds::*;
2047/// use try_create::New;
2048///
2049/// let closed_bound = IntervalBoundRuntime::Closed(UpperBoundClosed::new(5.0));
2050/// let open_bound = IntervalBoundRuntime::Open(UpperBoundOpen::new(5.0));
2051///
2052/// // Query boundary inclusion behavior
2053/// assert!(closed_bound.is_closed());
2054/// assert!(!closed_bound.is_open());
2055/// assert!(closed_bound.includes_boundary());
2056///
2057/// assert!(!open_bound.is_closed());
2058/// assert!(open_bound.is_open());
2059/// assert!(!open_bound.includes_boundary());
2060///
2061/// // All upper bounds share this property
2062/// assert!(closed_bound.is_upper_bound());
2063/// assert!(open_bound.is_upper_bound());
2064/// assert!(!closed_bound.is_lower_bound());
2065/// assert!(!open_bound.is_lower_bound());
2066/// ```
2067///
2068/// ### Value Access
2069///
2070/// ```rust
2071/// use grid1d::bounds::*;
2072/// use try_create::{New, IntoInner};
2073///
2074/// let bound = IntervalBoundRuntime::Closed(UpperBoundClosed::new(2.718));
2075///
2076/// // Access the underlying value by reference
2077/// let value_ref: &f64 = bound.as_ref();
2078/// assert_eq!(*value_ref, 2.718);
2079///
2080/// // Extract the value (consuming the bound)
2081/// let value: f64 = bound.into_inner();
2082/// assert_eq!(value, 2.718);
2083/// ```
2084///
2085/// ## Mathematical Ordering
2086///
2087/// Upper bounds maintain mathematically correct ordering where "tighter" constraints are considered smaller:
2088///
2089/// ```rust
2090/// use grid1d::bounds::*;
2091/// use try_create::New;
2092///
2093/// let open_upper = IntervalBoundRuntime::Open(UpperBoundOpen::new(10.0));        // 10)
2094/// let closed_upper = IntervalBoundRuntime::Closed(UpperBoundClosed::new(10.0));  // 10]
2095///
2096/// // Open bound is "tighter" (more restrictive) than closed bound
2097/// assert!(open_upper < closed_upper);  // 10) < 10]
2098///
2099/// // This ordering ensures correct interval operations:
2100/// // intersection([0, 10)) ∩ [0, 10]) = [0, 10) (the tighter constraint wins)
2101/// ```
2102///
2103/// ## Practical Usage Patterns
2104///
2105/// ### Dynamic Range Construction
2106///
2107/// ```rust
2108/// use grid1d::bounds::*;
2109/// use try_create::New;
2110///
2111/// struct RangeBuilder {
2112///     upper_value: f64,
2113///     upper_inclusive: bool,
2114/// }
2115///
2116/// impl RangeBuilder {
2117///     fn build_upper_bound(&self) -> UpperBoundRuntime<f64> {
2118///         if self.upper_inclusive {
2119///             IntervalBoundRuntime::Closed(UpperBoundClosed::new(self.upper_value))
2120///         } else {
2121///             IntervalBoundRuntime::Open(UpperBoundOpen::new(self.upper_value))
2122///         }
2123///     }
2124///     
2125///     fn set_maximum(&mut self, value: f64, inclusive: bool) {
2126///         self.upper_value = value;
2127///         self.upper_inclusive = inclusive;
2128///     }
2129/// }
2130///
2131/// let mut builder = RangeBuilder { upper_value: 100.0, upper_inclusive: true };
2132/// let bound1 = builder.build_upper_bound(); // 100]
2133///
2134/// builder.set_maximum(50.0, false);
2135/// let bound2 = builder.build_upper_bound(); // 50)
2136///
2137/// assert!(bound1.is_closed());
2138/// assert!(bound2.is_open());
2139/// ```
2140///
2141/// ### Configuration-Driven Systems
2142///
2143/// ```rust
2144/// use grid1d::bounds::*;
2145/// use try_create::New;
2146/// use serde::{Deserialize, Serialize};
2147///
2148/// #[derive(Serialize, Deserialize)]
2149/// struct MaximumConfig {
2150///     maximum_value: f64,
2151///     include_maximum: bool,
2152/// }
2153///
2154/// impl MaximumConfig {
2155///     fn to_upper_bound(&self) -> UpperBoundRuntime<f64> {
2156///         if self.include_maximum {
2157///             IntervalBoundRuntime::Closed(UpperBoundClosed::new(self.maximum_value))
2158///         } else {
2159///             IntervalBoundRuntime::Open(UpperBoundOpen::new(self.maximum_value))
2160///         }
2161///     }
2162/// }
2163///
2164/// // Load from configuration file or user input
2165/// let config = MaximumConfig {
2166///     maximum_value: 100.0,
2167///     include_maximum: false,
2168/// };
2169///
2170/// let upper_bound = config.to_upper_bound();
2171/// assert!(!upper_bound.value_within_bound(&100.0)); // Excludes maximum
2172/// assert!(upper_bound.value_within_bound(&99.9));   // Includes values below
2173/// ```
2174///
2175/// ### Collection Processing
2176///
2177/// ```rust
2178/// use grid1d::bounds::*;
2179/// use try_create::New;
2180///
2181/// // Store different upper bound types in the same collection
2182/// let constraints: Vec<UpperBoundRuntime<f64>> = vec![
2183///     IntervalBoundRuntime::Closed(UpperBoundClosed::new(10.0)),  // 10]
2184///     IntervalBoundRuntime::Open(UpperBoundOpen::new(20.0)),      // 20)
2185///     IntervalBoundRuntime::Closed(UpperBoundClosed::new(30.0)),  // 30]
2186///     IntervalBoundRuntime::Open(UpperBoundOpen::new(40.0)),      // 40)
2187/// ];
2188///
2189/// // Process them uniformly
2190/// for (i, constraint) in constraints.iter().enumerate() {
2191///     let inclusion = if constraint.is_closed() { "≤" } else { "<" };
2192///     println!("Constraint {}: x {} {}", i, inclusion, constraint.as_ref());
2193/// }
2194/// // Output:
2195/// // Constraint 0: x ≤ 10
2196/// // Constraint 1: x < 20
2197/// // Constraint 2: x ≤ 30
2198/// // Constraint 3: x < 40
2199///
2200/// // Find all constraints satisfied by a test value
2201/// let test_value = 20.0;
2202/// let satisfied: Vec<usize> = constraints.iter()
2203///     .enumerate()
2204///     .filter(|(_, constraint)| constraint.value_within_bound(&test_value))
2205///     .map(|(i, _)| i)
2206///     .collect();
2207///
2208/// assert_eq!(satisfied, vec![2, 3]); // Only 30] and 40) include 20.0
2209/// ```
2210///
2211/// ## Serialization Support
2212///
2213/// Runtime bounds have natural serialization support, making them ideal for persistent configuration:
2214///
2215/// ```rust
2216/// use grid1d::bounds::*;
2217/// use try_create::New;
2218/// use serde_json;
2219///
2220/// let bounds = vec![
2221///     IntervalBoundRuntime::Closed(UpperBoundClosed::new(100.0)),
2222///     IntervalBoundRuntime::Open(UpperBoundOpen::new(50.0)),
2223/// ];
2224///
2225/// // Serialize to JSON
2226/// let json = serde_json::to_string_pretty(&bounds).unwrap();
2227/// println!("Serialized upper bounds:\n{}", json);
2228///
2229/// // Deserialize back
2230/// let deserialized: Vec<UpperBoundRuntime<f64>> =
2231///     serde_json::from_str(&json).unwrap();
2232///
2233/// // Verify round-trip correctness
2234/// for (original, restored) in bounds.iter().zip(deserialized.iter()) {
2235///     assert_eq!(original.as_ref(), restored.as_ref());
2236///     assert_eq!(original.is_closed(), restored.is_closed());
2237///     assert_eq!(original.value_within_bound(&50.0), restored.value_within_bound(&50.0));
2238/// }
2239/// ```
2240///
2241/// ## Generic Algorithm Support
2242///
2243/// ```rust
2244/// use grid1d::bounds::*;
2245/// use num_valid::RealScalar;
2246/// use try_create::New;
2247///
2248/// fn find_maximum_satisfying_constraint<T: RealScalar + Copy>(
2249///     candidates: &[T],
2250///     constraint: &UpperBoundRuntime<T>
2251/// ) -> Option<T>
2252/// where
2253///     T: PartialOrd,
2254/// {
2255///     candidates.iter()
2256///         .filter(|&&value| constraint.value_within_bound(&value))
2257///         .max_by(|a, b| a.partial_cmp(b).unwrap())
2258///         .copied()
2259/// }
2260///
2261/// let values = vec![8.0, 9.0, 10.0, 11.0, 12.0];
2262///
2263/// let closed_constraint = IntervalBoundRuntime::Closed(UpperBoundClosed::new(10.0));
2264/// let open_constraint = IntervalBoundRuntime::Open(UpperBoundOpen::new(10.0));
2265///
2266/// assert_eq!(find_maximum_satisfying_constraint(&values, &closed_constraint), Some(10.0)); // x ≤ 10
2267/// assert_eq!(find_maximum_satisfying_constraint(&values, &open_constraint), Some(9.0));    // x < 10
2268/// ```
2269///
2270/// ## Performance vs Compile-Time Bounds
2271///
2272/// ### Runtime Performance
2273/// - **Memory**: Same as underlying bound plus small enum discriminant (~9 bytes for f64)
2274/// - **Operations**: Small pattern matching overhead (~1-2 CPU cycles)
2275/// - **Constraint Testing**: O(1) with inlined comparisons
2276///
2277/// ### Comparison with Compile-Time Bounds
2278///
2279/// ```rust
2280/// use grid1d::bounds::*;
2281/// use try_create::New;
2282///
2283/// // Runtime bound: small branching cost
2284/// fn check_runtime_constraint(bound: &UpperBoundRuntime<f64>, value: f64) -> bool {
2285///     match bound {  // Runtime dispatch (small cost)
2286///         IntervalBoundRuntime::Open(b) => value < *b.as_ref(),
2287///         IntervalBoundRuntime::Closed(b) => value <= *b.as_ref(),
2288///     }
2289/// }
2290///
2291/// // Compile-time bound: zero overhead
2292/// fn check_compile_time_constraint<T: BoundType>(bound: &UpperBound<f64, T>, value: f64) -> bool {
2293///     if T::is_open() {
2294///         value < *bound.as_ref()  // Direct comparison, no branching
2295///     } else {
2296///         value <= *bound.as_ref() // Direct comparison, no branching
2297///     }
2298/// }
2299/// ```
2300///
2301/// ## Integration with Grid1D
2302///
2303/// Runtime bounds integrate seamlessly with interval construction:
2304///
2305/// ```rust
2306/// use grid1d::{bounds::*, intervals::*};
2307/// use try_create::{IntoInner, New};
2308///
2309/// fn create_interval_from_runtime_bounds(
2310///     lower: LowerBoundRuntime<f64>,
2311///     upper: UpperBoundRuntime<f64>
2312/// ) -> Box<dyn std::fmt::Debug> {
2313///     match (lower, upper) {
2314///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Closed(u)) => {
2315///             Box::new(IntervalClosed::new(l.into_inner(), u.into_inner()))
2316///         }
2317///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Open(u)) => {
2318///             Box::new(IntervalOpen::new(l.into_inner(), u.into_inner()))
2319///         }
2320///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Open(u)) => {
2321///             Box::new(IntervalLowerClosedUpperOpen::new(l.into_inner(), u.into_inner()))
2322///         }
2323///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Closed(u)) => {
2324///             Box::new(IntervalLowerOpenUpperClosed::new(l.into_inner(), u.into_inner()))
2325///         }
2326///     }
2327/// }
2328///
2329/// // Example usage
2330/// let lower = IntervalBoundRuntime::Open(LowerBoundOpen::new(0.0));
2331/// let upper = IntervalBoundRuntime::Closed(UpperBoundClosed::new(1.0));
2332/// let interval = create_interval_from_runtime_bounds(lower, upper); // Creates (0, 1]
2333/// ```
2334///
2335/// ## Conversion Patterns
2336///
2337/// ### Extract Specific Bound Types
2338///
2339/// ```rust
2340/// use grid1d::bounds::*;
2341/// use try_create::New;
2342///
2343/// fn extract_open_upper_bound(bound: UpperBoundRuntime<f64>) -> Option<UpperBoundOpen<f64>> {
2344///     match bound {
2345///         IntervalBoundRuntime::Open(open_bound) => Some(open_bound),
2346///         IntervalBoundRuntime::Closed(_) => None,
2347///     }
2348/// }
2349///
2350/// let runtime_bound = IntervalBoundRuntime::Open(UpperBoundOpen::new(10.0));
2351/// let compile_time_bound = extract_open_upper_bound(runtime_bound);
2352/// assert!(compile_time_bound.is_some());
2353/// ```
2354///
2355/// ### Convert to Compile-Time When Possible
2356///
2357/// ```rust
2358/// use grid1d::bounds::*;
2359/// use try_create::New;
2360///
2361/// // Pattern: Use runtime bounds at API boundaries, compile-time internally
2362/// fn process_upper_constraint(constraint: UpperBoundRuntime<f64>) -> String {
2363///     match constraint {
2364///         IntervalBoundRuntime::Closed(closed_bound) => {
2365///             // Delegate to compile-time optimized function
2366///             process_closed_upper_constraint(closed_bound)
2367///         }
2368///         IntervalBoundRuntime::Open(open_bound) => {
2369///             // Delegate to compile-time optimized function
2370///             process_open_upper_constraint(open_bound)
2371///         }
2372///     }
2373/// }
2374///
2375/// fn process_closed_upper_constraint(bound: UpperBoundClosed<f64>) -> String {
2376///     format!("Inclusive upper bound: x ≤ {}", bound.as_ref())
2377/// }
2378///
2379/// fn process_open_upper_constraint(bound: UpperBoundOpen<f64>) -> String {
2380///     format!("Exclusive upper bound: x < {}", bound.as_ref())
2381/// }
2382/// ```
2383///
2384/// ## Best Practices
2385///
2386/// ### 1. **Use at API Boundaries**
2387/// ```rust
2388/// use grid1d::bounds::*;
2389///
2390/// // ✅ GOOD: Runtime bounds for user-facing APIs
2391/// pub fn create_range_from_config(
2392///     lower: LowerBoundRuntime<f64>,
2393///     upper: UpperBoundRuntime<f64>
2394/// ) -> Result<Box<dyn std::fmt::Debug>, String> {
2395///     // Implementation...
2396///     Ok(Box::new(format!("Range created")))
2397/// }
2398///
2399/// // ✅ GOOD: Compile-time bounds for internal algorithms
2400/// fn optimize_upper_limit<T: BoundType>(
2401///     upper: &UpperBound<f64, T>
2402/// ) -> f64 {
2403///     // High-performance internal computation
2404///     *upper.as_ref() * 0.9
2405/// }
2406/// ```
2407///
2408/// ### 2. **Pattern Match Early**
2409/// ```rust
2410/// use grid1d::bounds::*;
2411/// use try_create::New;
2412///
2413/// // ✅ GOOD: Extract compile-time types early
2414/// fn efficient_upper_processing(constraint: UpperBoundRuntime<f64>) -> f64 {
2415///     match constraint {
2416///         IntervalBoundRuntime::Closed(bound) => {
2417///             // Use compile-time optimized path
2418///             *bound.as_ref()  // Zero overhead
2419///         }
2420///         IntervalBoundRuntime::Open(bound) => {
2421///             // Use compile-time optimized path
2422///             *bound.as_ref() - f64::EPSILON  // Zero overhead
2423///         }
2424///     }
2425/// }
2426/// ```
2427///
2428/// ### 3. **Validate Early**
2429/// ```rust
2430/// use grid1d::bounds::*;
2431/// use try_create::New;
2432///
2433/// fn create_upper_constraint_with_validation(
2434///     value: f64,
2435///     inclusive: bool
2436/// ) -> Result<UpperBoundRuntime<f64>, String> {
2437///     if !value.is_finite() {
2438///         return Err(format!("Upper bound value must be finite, got: {}", value));
2439///     }
2440///     
2441///     let bound = if inclusive {
2442///         IntervalBoundRuntime::Closed(UpperBoundClosed::new(value))
2443///     } else {
2444///         IntervalBoundRuntime::Open(UpperBoundOpen::new(value))
2445///     };
2446///     
2447///     Ok(bound)
2448/// }
2449/// ```
2450///
2451/// ## Array-Like Range Construction
2452///
2453/// Upper bounds work naturally with Rust-style range construction:
2454///
2455/// ```rust
2456/// use grid1d::bounds::*;
2457/// use try_create::New;
2458///
2459/// // Pattern: Rust-style ranges with runtime bounds
2460/// fn create_rust_like_range(start: f64, end: f64, end_inclusive: bool) -> (LowerBoundClosed<f64>, UpperBoundRuntime<f64>) {
2461///     let lower = LowerBoundClosed::new(start);  // Always include start like [start, ...)
2462///     let upper = if end_inclusive {
2463///         IntervalBoundRuntime::Closed(UpperBoundClosed::new(end))  // [start, end]
2464///     } else {
2465///         IntervalBoundRuntime::Open(UpperBoundOpen::new(end))      // [start, end)
2466///     };
2467///     (lower, upper)
2468/// }
2469///
2470/// let (lower, upper_inclusive) = create_rust_like_range(0.0, 10.0, true);   // [0, 10]
2471/// let (_, upper_exclusive) = create_rust_like_range(0.0, 10.0, false);      // [0, 10)
2472///
2473/// assert!(upper_inclusive.value_within_bound(&10.0));  // 10 ≤ 10 → true
2474/// assert!(!upper_exclusive.value_within_bound(&10.0)); // 10 < 10 → false
2475/// ```
2476///
2477/// ## Mathematical Guarantees
2478///
2479/// The [`UpperBoundRuntime`] type maintains mathematical correctness by:
2480///
2481/// - **Constraint Semantics**: Properly implements `x ≤ b` (closed) vs `x < b` (open)
2482/// - **Ordering Consistency**: Maintains mathematical ordering where `b) < b]`
2483/// - **Type Safety**: Prevents mixing with lower bounds at compile time
2484/// - **Value Preservation**: Maintains exact scalar values without precision loss
2485/// - **Conversion Safety**: Provides safe extraction of compile-time types
2486///
2487/// Use [`UpperBoundRuntime`] when you need the flexibility of runtime boundary semantics
2488/// while maintaining mathematical correctness and integration with the grid1d ecosystem.
2489/// For maximum performance when boundary types are known at compile time, prefer the
2490/// direct types [`UpperBoundClosed`](crate::bounds::UpperBoundClosed) and [`UpperBoundOpen`](crate::bounds::UpperBoundOpen).
2491pub type UpperBoundRuntime<RealType> = IntervalBoundRuntime<RealType, Upper>;
2492
2493impl<RealType: RealScalar, Side: BoundSide> BoundTypeRuntimeChecks
2494    for IntervalBoundRuntime<RealType, Side>
2495{
2496    #[inline(always)]
2497    fn includes_boundary(&self) -> bool {
2498        matches!(self, IntervalBoundRuntime::Closed(_))
2499    }
2500}
2501
2502impl<RealType: RealScalar> BoundSideRuntimeChecks for LowerBoundRuntime<RealType> {
2503    #[inline(always)]
2504    fn is_upper_bound(&self) -> bool {
2505        false
2506    }
2507}
2508
2509impl<RealType: RealScalar> BoundSideRuntimeChecks for UpperBoundRuntime<RealType> {
2510    #[inline(always)]
2511    fn is_upper_bound(&self) -> bool {
2512        true
2513    }
2514}
2515
2516impl<RealType: RealScalar, Side: BoundSide> HasCoordType for IntervalBoundRuntime<RealType, Side> {
2517    type CoordType = RealType;
2518}
2519
2520impl<RealType: RealScalar, Side: BoundSide> ValueWithinBound
2521    for IntervalBoundRuntime<RealType, Side>
2522{
2523    #[inline(always)]
2524    fn value_within_bound(&self, value: &RealType) -> bool {
2525        match self {
2526            IntervalBoundRuntime::Open(bound) => bound.value_within_bound(value),
2527            IntervalBoundRuntime::Closed(bound) => bound.value_within_bound(value),
2528        }
2529    }
2530}
2531
2532impl<RealType: RealScalar, Side: BoundSide> AsRef<RealType>
2533    for IntervalBoundRuntime<RealType, Side>
2534{
2535    #[inline(always)]
2536    fn as_ref(&self) -> &RealType {
2537        match self {
2538            IntervalBoundRuntime::Open(bound) => bound.as_ref(),
2539            IntervalBoundRuntime::Closed(bound) => bound.as_ref(),
2540        }
2541    }
2542}
2543
2544impl<RealType: RealScalar, Side: BoundSide> IntoInner for IntervalBoundRuntime<RealType, Side> {
2545    type InnerType = RealType;
2546
2547    #[inline(always)]
2548    fn into_inner(self) -> RealType {
2549        match self {
2550            IntervalBoundRuntime::Open(bound) => bound.into_inner(),
2551            IntervalBoundRuntime::Closed(bound) => bound.into_inner(),
2552        }
2553    }
2554}
2555
2556impl<RealType: RealScalar, Side: BoundSide, Type: BoundType>
2557    From<IntervalBound<RealType, Side, Type>> for IntervalBoundRuntime<RealType, Side>
2558{
2559    #[inline(always)]
2560    fn from(bound: IntervalBound<RealType, Side, Type>) -> Self {
2561        if Type::is_open() {
2562            IntervalBoundRuntime::Open(bound.with_bound_type::<Open>())
2563        } else {
2564            IntervalBoundRuntime::Closed(bound.with_bound_type::<Closed>())
2565        }
2566    }
2567}
2568
2569impl<RealType: RealScalar> PartialOrd for LowerBoundRuntime<RealType> {
2570    #[inline]
2571    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2572        if self.as_ref() == other.as_ref() {
2573            // Same value, closed is "less than" open
2574            Some(match (self, other) {
2575                (LowerBoundRuntime::Closed(_), LowerBoundRuntime::Open(_)) => Ordering::Less,
2576                (LowerBoundRuntime::Open(_), LowerBoundRuntime::Closed(_)) => Ordering::Greater,
2577                _ => Ordering::Equal,
2578            })
2579        } else {
2580            // different values, compare normally
2581            self.as_ref().partial_cmp(other.as_ref())
2582        }
2583    }
2584}
2585
2586impl<RealType: RealScalar> PartialOrd for UpperBoundRuntime<RealType> {
2587    #[inline]
2588    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2589        if self.as_ref() == other.as_ref() {
2590            // Same value, closed is "less than" open
2591            Some(match (self, other) {
2592                (UpperBoundRuntime::Closed(_), UpperBoundRuntime::Open(_)) => Ordering::Greater,
2593                (UpperBoundRuntime::Open(_), UpperBoundRuntime::Closed(_)) => Ordering::Less,
2594                _ => Ordering::Equal,
2595            })
2596        } else {
2597            // different values, compare normally
2598            self.as_ref().partial_cmp(other.as_ref())
2599        }
2600    }
2601}
2602//------------------------------------------------------------------------------------------------
2603
2604#[cfg(test)]
2605mod test {
2606    use super::*;
2607    use crate::bounds::*;
2608
2609    mod lower_bound {
2610        use super::*;
2611        use crate::bounds::{LowerBoundClosed, LowerBoundOpen};
2612        use std::cmp::Ordering;
2613
2614        #[test]
2615        fn test_interval_lower_bound_equality() {
2616            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
2617            let closed_2 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
2618            let closed_3 = LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0));
2619
2620            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
2621            let open_2 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
2622
2623            // Test equality for same variant and value
2624            assert_eq!(closed_1, closed_2);
2625            assert_eq!(open_1, open_2);
2626
2627            // Test inequality for different values
2628            assert_ne!(closed_1, closed_3);
2629
2630            // Test inequality for different variants, same value
2631            assert_ne!(closed_1, open_1);
2632        }
2633
2634        mod interval_upper_bound {
2635            use super::*;
2636            use crate::bounds::{UpperBoundClosed, UpperBoundOpen};
2637            use std::cmp::Ordering;
2638
2639            #[test]
2640            fn test_interval_upper_bound_equality() {
2641                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
2642                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
2643                let closed_3 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));
2644
2645                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
2646                let open_2 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
2647
2648                // Test equality for same variant and value
2649                assert_eq!(closed_1, closed_2);
2650                assert_eq!(open_1, open_2);
2651
2652                // Test inequality for different values
2653                assert_ne!(closed_1, closed_3);
2654
2655                // Test inequality for different variants, same value
2656                assert_ne!(closed_1, open_1);
2657            }
2658
2659            #[test]
2660            fn test_interval_upper_bound_partial_ord() {
2661                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
2662                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));
2663                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
2664                let open_2 = UpperBoundRuntime::Open(UpperBoundOpen::new(2.0));
2665
2666                // Test closed vs closed
2667                assert_eq!(closed_1.partial_cmp(&closed_1), Some(Ordering::Equal));
2668                assert_eq!(closed_1.partial_cmp(&closed_2), Some(Ordering::Less));
2669                assert_eq!(closed_2.partial_cmp(&closed_1), Some(Ordering::Greater));
2670
2671                // Test open vs open
2672                assert_eq!(open_1.partial_cmp(&open_1), Some(Ordering::Equal));
2673                assert_eq!(open_1.partial_cmp(&open_2), Some(Ordering::Less));
2674                assert_eq!(open_2.partial_cmp(&open_1), Some(Ordering::Greater));
2675
2676                // Test open vs closed with same value (open < closed for upper bounds)
2677                assert_eq!(open_1.partial_cmp(&closed_1), Some(Ordering::Less));
2678                assert_eq!(closed_1.partial_cmp(&open_1), Some(Ordering::Greater));
2679
2680                // Test open vs closed with different values
2681                assert_eq!(open_1.partial_cmp(&closed_2), Some(Ordering::Less));
2682                assert_eq!(closed_1.partial_cmp(&open_2), Some(Ordering::Less));
2683            }
2684
2685            #[test]
2686            fn test_interval_upper_bound_ordering_consistency() {
2687                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
2688                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
2689                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));
2690                let open_2 = UpperBoundRuntime::Open(UpperBoundOpen::new(2.0));
2691
2692                // Create sorted list based on expected ordering
2693                // For upper bounds: smaller values < larger values, and open < closed for same value
2694                let bounds = vec![
2695                    open_1.clone(),
2696                    closed_1.clone(),
2697                    open_2.clone(),
2698                    closed_2.clone(),
2699                ];
2700
2701                // Test that the ordering is consistent
2702                for i in 0..bounds.len() {
2703                    for j in i + 1..bounds.len() {
2704                        assert!(bounds[i] < bounds[j],);
2705                        assert!(bounds[j] > bounds[i],);
2706                    }
2707                }
2708
2709                // Test sorting
2710                let mut shuffled = bounds.clone();
2711                shuffled.reverse();
2712                shuffled.sort_by(|a, b| a.partial_cmp(b).unwrap());
2713                assert_eq!(shuffled, bounds);
2714            }
2715
2716            #[test]
2717            fn test_interval_upper_bound_edge_cases() {
2718                // Test with special floating point values
2719                let closed_zero = UpperBoundRuntime::Closed(UpperBoundClosed::new(0.0));
2720                let closed_neg_zero = UpperBoundRuntime::Closed(UpperBoundClosed::new(-0.0));
2721                let open_zero = UpperBoundRuntime::Open(UpperBoundOpen::new(0.0));
2722
2723                // 0.0 and -0.0 should be equal
2724                assert_eq!(closed_zero, closed_neg_zero);
2725
2726                // But closed and open should be different even with same value
2727                assert_ne!(closed_zero, open_zero);
2728                assert!(open_zero < closed_zero); // open < closed for upper bounds
2729
2730                // Test with very small differences
2731                let closed_small = UpperBoundRuntime::Closed(UpperBoundClosed::new(1e-15));
2732                let open_small = UpperBoundRuntime::Open(UpperBoundOpen::new(1e-15));
2733                assert!(open_small < closed_small);
2734            }
2735
2736            #[test]
2737            fn test_interval_upper_bound_transitivity() {
2738                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
2739                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
2740                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));
2741
2742                // Test transitivity: if a < b and b < c, then a < c
2743                assert!(open_1 < closed_1);
2744                assert!(closed_1 < closed_2);
2745                assert!(open_1 < closed_2); // transitivity
2746            }
2747
2748            #[test]
2749            fn test_interval_upper_bound_reflexivity() {
2750                let closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
2751                let open = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
2752
2753                // Test reflexivity: a == a
2754                assert_eq!(closed.partial_cmp(&closed), Some(Ordering::Equal));
2755                assert_eq!(open.partial_cmp(&open), Some(Ordering::Equal));
2756            }
2757
2758            #[test]
2759            fn test_interval_upper_bound_antisymmetry() {
2760                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
2761                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));
2762                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
2763
2764                // Test antisymmetry: if a <= b and b <= a, then a == b
2765                // (This should only happen when a == b)
2766                assert_eq!(closed_1.partial_cmp(&closed_1), Some(Ordering::Equal));
2767
2768                // When a < b, then b > a (not equal)
2769                assert_eq!(closed_1.partial_cmp(&closed_2), Some(Ordering::Less));
2770                assert_eq!(closed_2.partial_cmp(&closed_1), Some(Ordering::Greater));
2771
2772                assert_eq!(open_1.partial_cmp(&closed_1), Some(Ordering::Less));
2773                assert_eq!(closed_1.partial_cmp(&open_1), Some(Ordering::Greater));
2774            }
2775
2776            #[test]
2777            fn test_min_upper_bound() {
2778                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
2779                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
2780                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));
2781
2782                // min with same value, different types should be open (smaller for upper bounds)
2783                assert_eq!(min_upper_bound(closed_1.clone(), open_1.clone()), open_1);
2784                assert_eq!(min_upper_bound(open_1.clone(), closed_1.clone()), open_1);
2785
2786                // min with different values
2787                assert_eq!(
2788                    min_upper_bound(closed_1.clone(), closed_2.clone()),
2789                    closed_1
2790                );
2791                assert_eq!(
2792                    min_upper_bound(closed_2.clone(), closed_1.clone()),
2793                    closed_1
2794                );
2795
2796                // min with same bound should return that bound
2797                assert_eq!(
2798                    min_upper_bound(closed_1.clone(), closed_1.clone()),
2799                    closed_1
2800                );
2801            }
2802
2803            #[test]
2804            fn test_max_upper_bound() {
2805                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
2806                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
2807                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));
2808
2809                // max with same value, different types should be closed (larger for upper bounds)
2810                assert_eq!(max_upper_bound(closed_1.clone(), open_1.clone()), closed_1);
2811                assert_eq!(max_upper_bound(open_1.clone(), closed_1.clone()), closed_1);
2812
2813                // max with different values
2814                assert_eq!(
2815                    max_upper_bound(closed_1.clone(), closed_2.clone()),
2816                    closed_2
2817                );
2818                assert_eq!(
2819                    max_upper_bound(closed_2.clone(), closed_1.clone()),
2820                    closed_2
2821                );
2822
2823                // max with same bound should return that bound
2824                assert_eq!(
2825                    max_upper_bound(closed_1.clone(), closed_1.clone()),
2826                    closed_1
2827                );
2828            }
2829
2830            #[test]
2831            fn test_interval_upper_bound_with_negative_values() {
2832                let closed_neg = UpperBoundRuntime::Closed(UpperBoundClosed::new(-5.0));
2833                let open_neg = UpperBoundRuntime::Open(UpperBoundOpen::new(-5.0));
2834                let closed_pos = UpperBoundRuntime::Closed(UpperBoundClosed::new(5.0));
2835
2836                // Negative values should still follow the ordering rules
2837                assert!(open_neg < closed_neg);
2838                assert!(closed_neg < closed_pos);
2839
2840                // More negative values should be smaller
2841                let closed_more_neg = UpperBoundRuntime::Closed(UpperBoundClosed::new(-10.0));
2842                assert!(closed_more_neg < closed_neg);
2843            }
2844
2845            #[test]
2846            fn test_interval_upper_bound_with_large_values() {
2847                let closed_large = UpperBoundRuntime::Closed(UpperBoundClosed::new(1e6));
2848                let open_large = UpperBoundRuntime::Open(UpperBoundOpen::new(1e6));
2849                let closed_larger = UpperBoundRuntime::Closed(UpperBoundClosed::new(1e9));
2850
2851                // Large values should still follow ordering
2852                assert!(open_large < closed_large);
2853                assert!(closed_large < closed_larger);
2854
2855                // Should be consistent with regular values
2856                let closed_small = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
2857                assert!(closed_small < closed_large);
2858            }
2859
2860            #[test]
2861            fn test_interval_upper_bound_boundary_semantics() {
2862                // Test the key difference between upper and lower bounds:
2863                // For upper bounds, open < closed (opposite of lower bounds)
2864
2865                let open_5 = UpperBoundRuntime::Open(UpperBoundOpen::new(5.0));
2866                let closed_5 = UpperBoundRuntime::Closed(UpperBoundClosed::new(5.0));
2867
2868                // For upper bounds: open is more restrictive (smaller) than closed
2869                assert!(open_5 < closed_5);
2870                assert!(closed_5 > open_5);
2871
2872                // This reflects the fact that (-∞, 5) ⊂ (-∞, 5]
2873                // The open upper bound excludes the endpoint, making it "smaller"
2874            }
2875        }
2876
2877        #[test]
2878        fn test_interval_lower_bound_partial_ord() {
2879            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
2880            let closed_2 = LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0));
2881            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
2882            let open_2 = LowerBoundRuntime::Open(LowerBoundOpen::new(2.0));
2883
2884            // Test closed vs closed
2885            assert_eq!(closed_1.partial_cmp(&closed_1), Some(Ordering::Equal));
2886            assert_eq!(closed_1.partial_cmp(&closed_2), Some(Ordering::Less));
2887            assert_eq!(closed_2.partial_cmp(&closed_1), Some(Ordering::Greater));
2888
2889            // Test open vs open
2890            assert_eq!(open_1.partial_cmp(&open_1), Some(Ordering::Equal));
2891            assert_eq!(open_1.partial_cmp(&open_2), Some(Ordering::Less));
2892            assert_eq!(open_2.partial_cmp(&open_1), Some(Ordering::Greater));
2893
2894            // Test closed vs open with same value (closed < open)
2895            assert_eq!(closed_1.partial_cmp(&open_1), Some(Ordering::Less));
2896            assert_eq!(open_1.partial_cmp(&closed_1), Some(Ordering::Greater));
2897
2898            // Test closed vs open with different values
2899            assert_eq!(closed_1.partial_cmp(&open_2), Some(Ordering::Less));
2900            assert_eq!(open_1.partial_cmp(&closed_2), Some(Ordering::Less));
2901        }
2902
2903        #[test]
2904        fn test_interval_lower_bound_ordering_consistency() {
2905            let closed_0 = LowerBoundRuntime::Closed(LowerBoundClosed::new(0.0));
2906            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
2907            let open_0 = LowerBoundRuntime::Open(LowerBoundOpen::new(0.0));
2908            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
2909
2910            // Create sorted list based on expected ordering
2911            let bounds = vec![
2912                closed_0.clone(),
2913                open_0.clone(),
2914                closed_1.clone(),
2915                open_1.clone(),
2916            ];
2917
2918            // Test that the ordering is consistent
2919            for i in 0..bounds.len() {
2920                for j in i + 1..bounds.len() {
2921                    assert!(bounds[i] < bounds[j],);
2922                    assert!(bounds[j] > bounds[i],);
2923                }
2924            }
2925
2926            // Test sorting
2927            let mut shuffled = bounds.clone();
2928            shuffled.reverse();
2929            shuffled.sort_by(|a, b| a.partial_cmp(b).unwrap());
2930            assert_eq!(shuffled, bounds);
2931        }
2932
2933        #[test]
2934        fn test_interval_lower_bound_edge_cases() {
2935            // Test with special floating point values
2936            let closed_zero = LowerBoundRuntime::Closed(LowerBoundClosed::new(0.0));
2937            let closed_neg_zero = LowerBoundRuntime::Closed(LowerBoundClosed::new(-0.0));
2938            let open_zero = LowerBoundRuntime::Open(LowerBoundOpen::new(0.0));
2939
2940            // 0.0 and -0.0 should be equal
2941            assert_eq!(closed_zero, closed_neg_zero);
2942
2943            // But closed and open should be different even with same value
2944            assert_ne!(closed_zero, open_zero);
2945            assert!(closed_zero < open_zero);
2946
2947            // Test with very small differences
2948            let closed_small = LowerBoundRuntime::Closed(LowerBoundClosed::new(1e-15));
2949            let open_small = LowerBoundRuntime::Open(LowerBoundOpen::new(1e-15));
2950            assert!(closed_small < open_small);
2951        }
2952
2953        #[test]
2954        fn test_interval_lower_bound_transitivity() {
2955            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
2956            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
2957            let closed_2 = LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0));
2958
2959            // Test transitivity: if a < b and b < c, then a < c
2960            assert!(closed_1 < open_1);
2961
2962            assert!(open_1 < closed_2);
2963            assert!(closed_1 < closed_2); // transitivity
2964        }
2965
2966        #[test]
2967        fn test_interval_lower_bound_reflexivity() {
2968            let closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
2969            let open = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
2970
2971            // Test reflexivity: a == a
2972            assert_eq!(closed.partial_cmp(&closed), Some(Ordering::Equal));
2973            assert_eq!(open.partial_cmp(&open), Some(Ordering::Equal));
2974        }
2975
2976        #[test]
2977        fn test_interval_lower_bound_antisymmetry() {
2978            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
2979            let closed_2 = LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0));
2980            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
2981
2982            // Test antisymmetry: if a <= b and b <= a, then a == b
2983            // (This should only happen when a == b)
2984            assert_eq!(closed_1.partial_cmp(&closed_1), Some(Ordering::Equal));
2985
2986            // When a < b, then b > a (not equal)
2987            assert_eq!(closed_1.partial_cmp(&closed_2), Some(Ordering::Less));
2988            assert_eq!(closed_2.partial_cmp(&closed_1), Some(Ordering::Greater));
2989
2990            assert_eq!(closed_1.partial_cmp(&open_1), Some(Ordering::Less));
2991            assert_eq!(open_1.partial_cmp(&closed_1), Some(Ordering::Greater));
2992        }
2993
2994        #[test]
2995        fn test_min_lower_bound() {
2996            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
2997            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
2998            let closed_2 = LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0));
2999
3000            // min with same value, different types should be closed (smaller)
3001            assert_eq!(min_lower_bound(closed_1.clone(), open_1.clone()), closed_1);
3002            assert_eq!(min_lower_bound(open_1.clone(), closed_1.clone()), closed_1);
3003
3004            // min with different values
3005            assert_eq!(
3006                min_lower_bound(closed_1.clone(), closed_2.clone()),
3007                closed_1
3008            );
3009            assert_eq!(
3010                min_lower_bound(closed_2.clone(), closed_1.clone()),
3011                closed_1
3012            );
3013
3014            // min with same bound should return that bound
3015            assert_eq!(
3016                min_lower_bound(closed_1.clone(), closed_1.clone()),
3017                closed_1
3018            );
3019        }
3020
3021        #[test]
3022        fn test_max_lower_bound() {
3023            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
3024            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
3025            let closed_2 = LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0));
3026
3027            // max with same value, different types should be open (larger)
3028            assert_eq!(max_lower_bound(closed_1.clone(), open_1.clone()), open_1);
3029            assert_eq!(max_lower_bound(open_1.clone(), closed_1.clone()), open_1);
3030
3031            // max with different values
3032            assert_eq!(
3033                max_lower_bound(closed_1.clone(), closed_2.clone()),
3034                closed_2
3035            );
3036            assert_eq!(
3037                max_lower_bound(closed_2.clone(), closed_1.clone()),
3038                closed_2
3039            );
3040
3041            // max with same bound should return that bound
3042            assert_eq!(
3043                max_lower_bound(closed_1.clone(), closed_1.clone()),
3044                closed_1
3045            );
3046        }
3047
3048        #[test]
3049        fn test_interval_lower_bound_with_negative_values() {
3050            let closed_neg = LowerBoundRuntime::Closed(LowerBoundClosed::new(-5.0));
3051            let open_neg = LowerBoundRuntime::Open(LowerBoundOpen::new(-5.0));
3052            let closed_pos = LowerBoundRuntime::Closed(LowerBoundClosed::new(5.0));
3053
3054            // Negative values should still follow the ordering rules
3055            assert!(closed_neg < open_neg);
3056            assert!(open_neg < closed_pos);
3057
3058            // More negative values should be smaller
3059            let closed_more_neg = LowerBoundRuntime::Closed(LowerBoundClosed::new(-10.0));
3060            assert!(closed_more_neg < closed_neg);
3061        }
3062
3063        #[test]
3064        fn test_interval_lower_bound_with_large_values() {
3065            let closed_large = LowerBoundRuntime::Closed(LowerBoundClosed::new(1e6));
3066            let open_large = LowerBoundRuntime::Open(LowerBoundOpen::new(1e6));
3067            let closed_larger = LowerBoundRuntime::Closed(LowerBoundClosed::new(1e9));
3068
3069            // Large values should still follow ordering
3070            assert!(closed_large < open_large);
3071            assert!(open_large < closed_larger);
3072
3073            // Should be consistent with regular values
3074            let closed_small = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
3075            assert!(closed_small < closed_large);
3076        }
3077    }
3078
3079    mod interval_bounds_runtime {
3080        use super::*;
3081        use crate::intervals::*;
3082
3083        #[test]
3084        fn get_interval_bound_closed() {
3085            let interval = IntervalClosed::new(1.0, 2.0);
3086
3087            let lower = interval.lower_bound_runtime().unwrap();
3088            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)));
3089
3090            let upper = interval.upper_bound_runtime().unwrap();
3091            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0)));
3092        }
3093
3094        #[test]
3095        fn get_interval_bound_open() {
3096            let interval = IntervalOpen::new(1.0, 2.0);
3097
3098            let lower = interval.lower_bound_runtime().unwrap();
3099            assert_eq!(lower, LowerBoundRuntime::Open(LowerBoundOpen::new(1.0)));
3100
3101            let upper = interval.upper_bound_runtime().unwrap();
3102            assert_eq!(upper, UpperBoundRuntime::Open(UpperBoundOpen::new(2.0)));
3103        }
3104
3105        #[test]
3106        fn get_interval_bound_left_open_upper_closed() {
3107            let interval = IntervalLowerOpenUpperClosed::new(1.0, 2.0);
3108
3109            let lower = interval.lower_bound_runtime().unwrap();
3110            assert_eq!(lower, LowerBoundRuntime::Open(LowerBoundOpen::new(1.0)));
3111
3112            let upper = interval.upper_bound_runtime().unwrap();
3113            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0)));
3114        }
3115
3116        #[test]
3117        fn get_interval_bound_left_closed_upper_open() {
3118            let interval = IntervalLowerClosedUpperOpen::new(1.0, 2.0);
3119
3120            let lower = interval.lower_bound_runtime().unwrap();
3121            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)));
3122
3123            let upper = interval.upper_bound_runtime().unwrap();
3124            assert_eq!(upper, UpperBoundRuntime::Open(UpperBoundOpen::new(2.0)));
3125        }
3126
3127        #[test]
3128        fn get_interval_bound_lower_closed_upper_unbounded() {
3129            let interval = IntervalLowerClosedUpperUnbounded::new(1.0);
3130
3131            let lower = interval.lower_bound_runtime().unwrap();
3132            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)));
3133
3134            let upper = interval.upper_bound_runtime();
3135            assert_eq!(upper, None);
3136        }
3137
3138        #[test]
3139        fn get_interval_bound_lower_open_upper_unbounded() {
3140            let interval = IntervalLowerOpenUpperUnbounded::new(1.0);
3141
3142            let lower = interval.lower_bound_runtime().unwrap();
3143            assert_eq!(lower, LowerBoundRuntime::Open(LowerBoundOpen::new(1.0)));
3144
3145            let upper = interval.upper_bound_runtime();
3146            assert_eq!(upper, None);
3147        }
3148
3149        #[test]
3150        fn get_interval_bound_lower_unbounded_upper_closed() {
3151            let interval = IntervalLowerUnboundedUpperClosed::new(2.0);
3152
3153            let lower = interval.lower_bound_runtime();
3154            assert_eq!(lower, None);
3155
3156            let upper = interval.upper_bound_runtime().unwrap();
3157            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0)));
3158        }
3159
3160        #[test]
3161        fn get_interval_bound_lower_unbounded_upper_open() {
3162            let interval = IntervalLowerUnboundedUpperOpen::new(2.0);
3163
3164            let lower = interval.lower_bound_runtime();
3165            assert_eq!(lower, None);
3166
3167            let upper = interval.upper_bound_runtime().unwrap();
3168            assert_eq!(upper, UpperBoundRuntime::Open(UpperBoundOpen::new(2.0)));
3169        }
3170
3171        #[test]
3172        fn get_interval_bound_singleton() {
3173            let interval = IntervalSingleton::new(1.5);
3174
3175            let lower = interval.lower_bound_runtime().unwrap();
3176            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.5)));
3177
3178            let upper = interval.upper_bound_runtime().unwrap();
3179            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(1.5)));
3180        }
3181
3182        #[test]
3183        fn get_interval_bound_finite_length() {
3184            let closed = IntervalClosed::new(1.0, 2.0);
3185            let singleton = IntervalSingleton::new(1.5);
3186            let finite =
3187                IntervalFiniteLength::PositiveLength(IntervalFinitePositiveLength::Closed(closed));
3188            let zero = IntervalFiniteLength::ZeroLength(singleton);
3189
3190            let lower = finite.lower_bound_runtime().unwrap();
3191            let upper = finite.upper_bound_runtime().unwrap();
3192            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)));
3193            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0)));
3194
3195            let lower = zero.lower_bound_runtime().unwrap();
3196            let upper = zero.upper_bound_runtime().unwrap();
3197            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.5)));
3198            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(1.5)));
3199        }
3200
3201        #[test]
3202        fn get_interval_bound_finite_positive_length() {
3203            use crate::intervals::IntervalFinitePositiveLengthTrait;
3204
3205            let closed = IntervalClosed::new(1.0, 2.0);
3206            let open = IntervalOpen::new(1.0, 2.0);
3207            let left = IntervalLowerOpenUpperClosed::new(1.0, 2.0);
3208            let right = IntervalLowerClosedUpperOpen::new(1.0, 2.0);
3209
3210            let c = IntervalFinitePositiveLength::Closed(closed);
3211            let o = IntervalFinitePositiveLength::Open(open);
3212            let l = IntervalFinitePositiveLength::LowerOpenUpperClosed(left);
3213            let r = IntervalFinitePositiveLength::LowerClosedUpperOpen(right);
3214
3215            let (lower, upper) = (
3216                c.lower_bound_runtime().unwrap(),
3217                c.upper_bound_runtime().unwrap(),
3218            );
3219            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)));
3220            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0)));
3221            assert_eq!(c.clone().into_bounds_pair(), (1., 2.));
3222
3223            let (lower, upper) = (
3224                o.lower_bound_runtime().unwrap(),
3225                o.upper_bound_runtime().unwrap(),
3226            );
3227            assert_eq!(lower, LowerBoundRuntime::Open(LowerBoundOpen::new(1.0)));
3228            assert_eq!(upper, UpperBoundRuntime::Open(UpperBoundOpen::new(2.0)));
3229            assert_eq!(o.clone().into_bounds_pair(), (1., 2.));
3230
3231            let (lower, upper) = (
3232                l.lower_bound_runtime().unwrap(),
3233                l.upper_bound_runtime().unwrap(),
3234            );
3235            assert_eq!(lower, LowerBoundRuntime::Open(LowerBoundOpen::new(1.0)));
3236            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0)));
3237            assert_eq!(l.clone().into_bounds_pair(), (1., 2.));
3238
3239            let (lower, upper) = (
3240                r.lower_bound_runtime().unwrap(),
3241                r.upper_bound_runtime().unwrap(),
3242            );
3243            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)));
3244            assert_eq!(upper, UpperBoundRuntime::Open(UpperBoundOpen::new(2.0)));
3245            assert_eq!(r.clone().into_bounds_pair(), (1., 2.));
3246        }
3247
3248        #[test]
3249        fn get_interval_bound_infinite_length() {
3250            let closed = IntervalLowerClosedUpperUnbounded::new(1.0);
3251            let open = IntervalLowerOpenUpperUnbounded::new(2.0);
3252            let right_closed = IntervalLowerUnboundedUpperClosed::new(3.0);
3253            let right_open = IntervalLowerUnboundedUpperOpen::new(4.0);
3254            let unbounded = IntervalLowerUnboundedUpperUnbounded::<f64>::new();
3255
3256            let c = IntervalInfiniteLength::LowerClosedUpperUnbounded(closed);
3257            let o = IntervalInfiniteLength::LowerOpenUpperUnbounded(open);
3258            let rc = IntervalInfiniteLength::LowerUnboundedUpperClosed(right_closed);
3259            let ro = IntervalInfiniteLength::LowerUnboundedUpperOpen(right_open);
3260            let u = IntervalInfiniteLength::LowerUnboundedUpperUnbounded(unbounded);
3261
3262            let (lower, upper) = (c.lower_bound_runtime(), c.upper_bound_runtime());
3263            assert_eq!(
3264                lower.unwrap(),
3265                LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0))
3266            );
3267            assert_eq!(upper, None);
3268
3269            let (lower, upper) = (o.lower_bound_runtime(), o.upper_bound_runtime());
3270            assert_eq!(
3271                lower.unwrap(),
3272                LowerBoundRuntime::Open(LowerBoundOpen::new(2.0))
3273            );
3274            assert_eq!(upper, None);
3275
3276            let (lower, upper) = (rc.lower_bound_runtime(), rc.upper_bound_runtime());
3277            assert_eq!(lower, None);
3278            assert_eq!(
3279                upper.unwrap(),
3280                UpperBoundRuntime::Closed(UpperBoundClosed::new(3.0))
3281            );
3282
3283            let (lower, upper) = (ro.lower_bound_runtime(), ro.upper_bound_runtime());
3284            assert_eq!(lower, None);
3285            assert_eq!(
3286                upper.unwrap(),
3287                UpperBoundRuntime::Open(UpperBoundOpen::new(4.0))
3288            );
3289
3290            let (lower, upper) = (u.lower_bound_runtime(), u.upper_bound_runtime());
3291            assert_eq!(lower, None);
3292            assert_eq!(upper, None);
3293        }
3294
3295        #[test]
3296        fn get_interval_bound_enum_wrappers() {
3297            let closed = IntervalClosed::new(1.0, 2.0);
3298            let finite =
3299                IntervalFiniteLength::PositiveLength(IntervalFinitePositiveLength::Closed(closed));
3300            let inf = IntervalInfiniteLength::LowerUnboundedUpperUnbounded(
3301                IntervalLowerUnboundedUpperUnbounded::<f64>::new(),
3302            );
3303            let interval = Interval::FiniteLength(finite.clone());
3304            let interval_inf = Interval::InfiniteLength(inf.clone());
3305
3306            let (lower, upper) = (
3307                interval.lower_bound_runtime(),
3308                interval.upper_bound_runtime(),
3309            );
3310            assert_eq!(
3311                lower.unwrap(),
3312                LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0))
3313            );
3314            assert_eq!(
3315                upper.unwrap(),
3316                UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0))
3317            );
3318
3319            let (lower, upper) = (
3320                interval_inf.lower_bound_runtime(),
3321                interval_inf.upper_bound_runtime(),
3322            );
3323            assert_eq!(lower, None);
3324            assert_eq!(upper, None);
3325        }
3326
3327        #[test]
3328        fn get_interval_bound_subinterval_in_partition() {
3329            type S = SubIntervalInPartition<IntervalClosed<f64>>;
3330            let first = IntervalLowerClosedUpperOpen::new(1.0, 2.0);
3331            let last = IntervalClosed::new(2.0, 3.0);
3332            let s1 = S::First(first);
3333            let s2 = S::Last(last);
3334
3335            let (lower, upper) = (s1.lower_bound_runtime(), s1.upper_bound_runtime());
3336            assert_eq!(
3337                lower,
3338                Some(LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)))
3339            );
3340            assert_eq!(
3341                upper,
3342                Some(UpperBoundRuntime::Open(UpperBoundOpen::new(2.0)))
3343            );
3344
3345            let (lower, upper) = (s2.lower_bound_runtime(), s2.upper_bound_runtime());
3346            assert_eq!(
3347                lower,
3348                Some(LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0)))
3349            );
3350            assert_eq!(
3351                upper,
3352                Some(UpperBoundRuntime::Closed(UpperBoundClosed::new(3.0)))
3353            );
3354        }
3355    }
3356
3357    mod partial_ord {
3358        use super::*;
3359
3360        #[test]
3361        fn partial_ord_lower_bound_structs() {
3362            let closed1 = LowerBoundClosed::new(1.0);
3363            let closed2 = LowerBoundClosed::new(2.0);
3364            let open1 = LowerBoundOpen::new(1.0);
3365            let open2 = LowerBoundOpen::new(2.0);
3366
3367            assert!(closed1 < closed2);
3368            assert!(open1 < open2);
3369            assert!(closed1 < open2);
3370            assert!(open1 < closed2);
3371            assert!(closed1 < open1); // closed < open if same value
3372            assert!(open2 > closed1);
3373            assert!(closed1 <= closed1);
3374            assert!(open2 >= open2);
3375            assert!(!(closed1 == open1));
3376        }
3377
3378        #[test]
3379        fn partial_ord_upper_bound_structs() {
3380            let closed1 = UpperBoundClosed::new(1.0);
3381            let closed2 = UpperBoundClosed::new(2.0);
3382            let open1 = UpperBoundOpen::new(1.0);
3383            let open2 = UpperBoundOpen::new(2.0);
3384
3385            assert!(closed1 < closed2);
3386            assert!(open1 < open2);
3387            assert!(closed1 < open2);
3388            assert!(open1 < closed2);
3389            assert!(open1 < closed1); // open < closed if same value
3390            assert!(closed2 > open1);
3391            assert!(closed1 <= closed1);
3392            assert!(open2 >= open2);
3393            assert!(!(closed1 == open1));
3394        }
3395
3396        #[test]
3397        fn partial_ord_interval_lower_bound_enum() {
3398            let closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
3399            let open = LowerBoundRuntime::Open(LowerBoundOpen::new(2.0));
3400
3401            assert_eq!(closed.partial_cmp(&open), Some(std::cmp::Ordering::Less));
3402            assert_eq!(open.partial_cmp(&closed), Some(std::cmp::Ordering::Greater));
3403            assert_eq!(closed.partial_cmp(&closed), Some(std::cmp::Ordering::Equal));
3404            assert_eq!(open.partial_cmp(&open), Some(std::cmp::Ordering::Equal));
3405        }
3406
3407        #[test]
3408        fn partial_ord_interval_upper_bound_enum() {
3409            let closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
3410            let open = UpperBoundRuntime::Open(UpperBoundOpen::new(2.0));
3411
3412            assert_eq!(closed.partial_cmp(&open), Some(std::cmp::Ordering::Less));
3413            assert_eq!(open.partial_cmp(&closed), Some(std::cmp::Ordering::Greater));
3414            assert_eq!(closed.partial_cmp(&closed), Some(std::cmp::Ordering::Equal));
3415            assert_eq!(open.partial_cmp(&open), Some(std::cmp::Ordering::Equal));
3416        }
3417
3418        #[test]
3419        fn partial_ord_interval_lower_bound_enum_same_value() {
3420            let closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
3421            let open = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
3422            assert_eq!(closed.partial_cmp(&open), Some(std::cmp::Ordering::Less));
3423            assert_eq!(open.partial_cmp(&closed), Some(std::cmp::Ordering::Greater));
3424        }
3425
3426        #[test]
3427        fn partial_ord_interval_upper_bound_enum_same_value() {
3428            let closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
3429            let open = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
3430            assert_eq!(open.partial_cmp(&closed), Some(std::cmp::Ordering::Less));
3431            assert_eq!(closed.partial_cmp(&open), Some(std::cmp::Ordering::Greater));
3432        }
3433    }
3434
3435    mod bounds_comparisons {
3436        use super::*;
3437        use try_create::TryNew;
3438
3439        type Real = f64;
3440
3441        /// Test PartialOrd implementation for LowerBoundRuntime
3442        #[test]
3443        fn test_interval_lower_bound_comparison() {
3444            // Create test bounds
3445            let lower_bound_closed_5 =
3446                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
3447            let lower_bound_open_5 =
3448                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));
3449            let lower_bound_closed_3 =
3450                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(3.0).unwrap()));
3451            let lower_bound_open_3 =
3452                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(3.0).unwrap()));
3453            let lower_bound_closed_7 =
3454                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(7.0).unwrap()));
3455
3456            // Test basic ordering by value
3457            assert_eq!(
3458                lower_bound_closed_3.partial_cmp(&lower_bound_closed_5),
3459                Some(Ordering::Less)
3460            );
3461            assert_eq!(
3462                lower_bound_closed_5.partial_cmp(&lower_bound_closed_3),
3463                Some(Ordering::Greater)
3464            );
3465            assert_eq!(
3466                lower_bound_closed_5.partial_cmp(&lower_bound_closed_5),
3467                Some(Ordering::Equal)
3468            );
3469
3470            // Test ordering between closed and open bounds with same value
3471            // For lower bounds: closed < open at same value (closed is more restrictive for lower)
3472            assert_eq!(
3473                lower_bound_closed_5.partial_cmp(&lower_bound_open_5),
3474                Some(Ordering::Less)
3475            );
3476            assert_eq!(
3477                lower_bound_open_5.partial_cmp(&lower_bound_closed_5),
3478                Some(Ordering::Greater)
3479            );
3480
3481            // Test mixed value and boundary type comparisons
3482            assert_eq!(
3483                lower_bound_closed_3.partial_cmp(&lower_bound_open_5),
3484                Some(Ordering::Less)
3485            );
3486            assert_eq!(
3487                lower_bound_open_3.partial_cmp(&lower_bound_closed_5),
3488                Some(Ordering::Less)
3489            );
3490            assert_eq!(
3491                lower_bound_closed_5.partial_cmp(&lower_bound_open_3),
3492                Some(Ordering::Greater)
3493            );
3494
3495            // Test transitivity
3496            assert_eq!(
3497                lower_bound_closed_3.partial_cmp(&lower_bound_closed_7),
3498                Some(Ordering::Less)
3499            );
3500            assert_eq!(
3501                lower_bound_open_3.partial_cmp(&lower_bound_closed_7),
3502                Some(Ordering::Less)
3503            );
3504        }
3505
3506        /// Test PartialOrd implementation for UpperBoundRuntime
3507        #[test]
3508        fn test_interval_upper_bound_comparison() {
3509            // Create test bounds
3510            let upper_bound_closed_5 =
3511                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
3512            let upper_bound_open_5 =
3513                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(5.0).unwrap()));
3514            let upper_bound_closed_3 =
3515                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(3.0).unwrap()));
3516            let upper_bound_open_3 =
3517                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(3.0).unwrap()));
3518            let upper_bound_closed_7 =
3519                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(7.0).unwrap()));
3520
3521            // Test basic ordering by value
3522            assert_eq!(
3523                upper_bound_closed_3.partial_cmp(&upper_bound_closed_5),
3524                Some(Ordering::Less)
3525            );
3526            assert_eq!(
3527                upper_bound_closed_5.partial_cmp(&upper_bound_closed_3),
3528                Some(Ordering::Greater)
3529            );
3530            assert_eq!(
3531                upper_bound_closed_5.partial_cmp(&upper_bound_closed_5),
3532                Some(Ordering::Equal)
3533            );
3534
3535            // Test ordering between closed and open bounds with same value
3536            // For upper bounds: open < closed at same value (open is more restrictive for upper)
3537            assert_eq!(
3538                upper_bound_open_5.partial_cmp(&upper_bound_closed_5),
3539                Some(Ordering::Less)
3540            );
3541            assert_eq!(
3542                upper_bound_closed_5.partial_cmp(&upper_bound_open_5),
3543                Some(Ordering::Greater)
3544            );
3545
3546            // Test mixed value and boundary type comparisons
3547            assert_eq!(
3548                upper_bound_closed_3.partial_cmp(&upper_bound_open_5),
3549                Some(Ordering::Less)
3550            );
3551            assert_eq!(
3552                upper_bound_open_3.partial_cmp(&upper_bound_closed_5),
3553                Some(Ordering::Less)
3554            );
3555            assert_eq!(
3556                upper_bound_closed_5.partial_cmp(&upper_bound_open_3),
3557                Some(Ordering::Greater)
3558            );
3559
3560            // Test transitivity
3561            assert_eq!(
3562                upper_bound_closed_3.partial_cmp(&upper_bound_closed_7),
3563                Some(Ordering::Less)
3564            );
3565            assert_eq!(
3566                upper_bound_open_3.partial_cmp(&upper_bound_closed_7),
3567                Some(Ordering::Less)
3568            );
3569        }
3570
3571        /// Test boundary type semantics for lower bounds
3572        #[test]
3573        fn test_lower_bound_semantics() {
3574            let closed_5 =
3575                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
3576            let open_5 = LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));
3577
3578            // For lower bounds, closed is more restrictive (smaller) than open at same value
3579            // This is because [5,b) contains 5, while (5,b) does not
3580            more_asserts::assert_lt!(closed_5, open_5);
3581            more_asserts::assert_ge!(open_5, closed_5);
3582            assert_ne!(closed_5, open_5);
3583        }
3584
3585        /// Test boundary type semantics for upper bounds
3586        #[test]
3587        fn test_upper_bound_semantics() {
3588            let closed_5 =
3589                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
3590            let open_5 = UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(5.0).unwrap()));
3591
3592            // For upper bounds, open is more restrictive (smaller) than closed at same value
3593            // This is because [a,5) excludes 5, while [a,5] includes 5
3594            more_asserts::assert_lt!(open_5, closed_5);
3595            more_asserts::assert_ge!(closed_5, open_5);
3596            assert_ne!(open_5, closed_5);
3597        }
3598
3599        /// Test consistency with mathematical interval ordering
3600        #[test]
3601        fn test_mathematical_consistency() {
3602            // Create bounds that would represent valid intervals
3603            let lower_closed_1 =
3604                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(1.0).unwrap()));
3605            let lower_open_1 =
3606                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(1.0).unwrap()));
3607            let upper_open_2 =
3608                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(2.0).unwrap()));
3609            let upper_closed_2 =
3610                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(2.0).unwrap()));
3611
3612            // Mathematical consistency checks:
3613            // [1,2) should have closed lower bound and open upper bound
3614            // (1,2] should have open lower bound and closed upper bound
3615            // [1,2] should have closed bounds
3616            // (1,2) should have open bounds
3617
3618            // Verify ordering is consistent with interval containment
3619            // [1,x] contains more points than (1,x] at the same x
3620            assert!(lower_closed_1 < lower_open_1);
3621
3622            // [x,2) contains fewer points than [x,2] at the same x
3623            assert!(upper_open_2 < upper_closed_2);
3624        }
3625
3626        /// Test reflexivity property
3627        #[test]
3628        fn test_reflexivity() {
3629            let lower_closed =
3630                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
3631            let lower_open =
3632                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));
3633            let upper_closed =
3634                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
3635            let upper_open =
3636                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(5.0).unwrap()));
3637
3638            // Reflexivity: x.partial_cmp(&x) == Some(Ordering::Equal)
3639            assert_eq!(
3640                lower_closed.partial_cmp(&lower_closed),
3641                Some(Ordering::Equal)
3642            );
3643            assert_eq!(lower_open.partial_cmp(&lower_open), Some(Ordering::Equal));
3644            assert_eq!(
3645                upper_closed.partial_cmp(&upper_closed),
3646                Some(Ordering::Equal)
3647            );
3648            assert_eq!(upper_open.partial_cmp(&upper_open), Some(Ordering::Equal));
3649        }
3650
3651        /// Test antisymmetry property
3652        #[test]
3653        fn test_antisymmetry() {
3654            let lower_closed_3 =
3655                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(3.0).unwrap()));
3656            let lower_closed_5 =
3657                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
3658
3659            // Antisymmetry: if x <= y and y <= x, then x == y
3660            if lower_closed_3.partial_cmp(&lower_closed_5) == Some(Ordering::Less) {
3661                assert_eq!(
3662                    lower_closed_5.partial_cmp(&lower_closed_3),
3663                    Some(Ordering::Greater)
3664                );
3665            }
3666        }
3667
3668        /// Test transitivity property
3669        #[test]
3670        fn test_transitivity() {
3671            let lower_closed_1 =
3672                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(1.0).unwrap()));
3673            let lower_open_3 =
3674                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(3.0).unwrap()));
3675            let lower_closed_5 =
3676                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
3677
3678            // Transitivity: if x <= y and y <= z, then x <= z
3679            let ord_1_3 = lower_closed_1.partial_cmp(&lower_open_3);
3680            let ord_3_5 = lower_open_3.partial_cmp(&lower_closed_5);
3681            let ord_1_5 = lower_closed_1.partial_cmp(&lower_closed_5);
3682
3683            if ord_1_3 == Some(Ordering::Less) && ord_3_5 == Some(Ordering::Less) {
3684                assert_eq!(ord_1_5, Some(Ordering::Less));
3685            }
3686        }
3687
3688        /// Test edge cases with same values but different boundary types
3689        #[test]
3690        fn test_edge_cases_same_values() {
3691            let value = Real::try_new(42.0).unwrap();
3692
3693            let lower_closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(value));
3694            let lower_open = LowerBoundRuntime::Open(LowerBoundOpen::new(value));
3695            let upper_closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(value));
3696            let upper_open = UpperBoundRuntime::Open(UpperBoundOpen::new(value));
3697
3698            // Test that boundary type matters even with same value
3699            assert_ne!(lower_closed.partial_cmp(&lower_open), Some(Ordering::Equal));
3700            assert_ne!(upper_closed.partial_cmp(&upper_open), Some(Ordering::Equal));
3701
3702            // Verify specific ordering relationships
3703            assert_eq!(lower_closed.partial_cmp(&lower_open), Some(Ordering::Less));
3704            assert_eq!(upper_open.partial_cmp(&upper_closed), Some(Ordering::Less));
3705        }
3706
3707        /// Test with extreme values
3708        #[test]
3709        fn test_extreme_values() {
3710            let min_val = Real::try_new(f64::MIN).unwrap();
3711            let max_val = Real::try_new(f64::MAX).unwrap();
3712
3713            let lower_min_closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(min_val));
3714            let lower_max_open = LowerBoundRuntime::Open(LowerBoundOpen::new(max_val));
3715            let upper_min_open = UpperBoundRuntime::Open(UpperBoundOpen::new(min_val));
3716            let upper_max_closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(max_val));
3717
3718            // Test that extreme values still follow ordering rules
3719            assert_eq!(
3720                lower_min_closed.partial_cmp(&lower_max_open),
3721                Some(Ordering::Less)
3722            );
3723            assert_eq!(
3724                upper_min_open.partial_cmp(&upper_max_closed),
3725                Some(Ordering::Less)
3726            );
3727        }
3728
3729        /// Test helper functions min_lower_bound and max_lower_bound
3730        #[test]
3731        fn test_min_max_lower_bound() {
3732            let lower_closed_3 =
3733                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(3.0).unwrap()));
3734            let lower_open_5 =
3735                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));
3736
3737            // Test min_lower_bound
3738            let min_result = min_lower_bound(lower_closed_3.clone(), lower_open_5.clone());
3739            assert_eq!(min_result, lower_closed_3);
3740
3741            // Test max_lower_bound
3742            let max_result = max_lower_bound(lower_closed_3.clone(), lower_open_5.clone());
3743            assert_eq!(max_result, lower_open_5);
3744        }
3745
3746        /// Test helper functions min_upper_bound and max_upper_bound
3747        #[test]
3748        fn test_min_max_upper_bound() {
3749            let upper_open_3 =
3750                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(3.0).unwrap()));
3751            let upper_closed_5 =
3752                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
3753
3754            // Test min_upper_bound
3755            let min_result = min_upper_bound(upper_open_3.clone(), upper_closed_5.clone());
3756            assert_eq!(min_result, upper_open_3);
3757
3758            // Test max_upper_bound
3759            let max_result = max_upper_bound(upper_open_3.clone(), upper_closed_5.clone());
3760            assert_eq!(max_result, upper_closed_5);
3761        }
3762
3763        /// Test new_open and new_closed constructors for LowerBoundRuntime
3764        #[test]
3765        fn test_lower_bound_runtime_constructors() {
3766            let value = Real::try_new(5.0).unwrap();
3767
3768            // Test new_open
3769            let open_bound = LowerBoundRuntime::new_open(value);
3770            assert!(open_bound.is_open());
3771            assert!(open_bound.is_open_variant());
3772            assert!(!open_bound.is_closed());
3773            assert!(!open_bound.is_closed_variant());
3774            assert_eq!(open_bound.as_ref(), &value);
3775
3776            // Test new_closed
3777            let closed_bound = LowerBoundRuntime::new_closed(value);
3778            assert!(closed_bound.is_closed());
3779            assert!(closed_bound.is_closed_variant());
3780            assert!(!closed_bound.is_open());
3781            assert!(!closed_bound.is_open_variant());
3782            assert_eq!(closed_bound.as_ref(), &value);
3783
3784            // Test constraint semantics for open bound
3785            assert!(!open_bound.value_within_bound(&value)); // 5 > 5 → false
3786            assert!(open_bound.value_within_bound(&Real::try_new(5.1).unwrap())); // 5.1 > 5 → true
3787            assert!(!open_bound.value_within_bound(&Real::try_new(4.9).unwrap())); // 4.9 > 5 → false
3788
3789            // Test constraint semantics for closed bound
3790            assert!(closed_bound.value_within_bound(&value)); // 5 ≥ 5 → true
3791            assert!(closed_bound.value_within_bound(&Real::try_new(5.1).unwrap())); // 5.1 ≥ 5 → true
3792            assert!(!closed_bound.value_within_bound(&Real::try_new(4.9).unwrap())); // 4.9 ≥ 5 → false
3793        }
3794
3795        /// Test new_open and new_closed constructors for UpperBoundRuntime
3796        #[test]
3797        fn test_upper_bound_runtime_constructors() {
3798            let value = Real::try_new(10.0).unwrap();
3799
3800            // Test new_open
3801            let open_bound = UpperBoundRuntime::new_open(value);
3802            assert!(open_bound.is_open());
3803            assert!(open_bound.is_open_variant());
3804            assert!(!open_bound.is_closed());
3805            assert!(!open_bound.is_closed_variant());
3806            assert_eq!(open_bound.as_ref(), &value);
3807
3808            // Test new_closed
3809            let closed_bound = UpperBoundRuntime::new_closed(value);
3810            assert!(closed_bound.is_closed());
3811            assert!(closed_bound.is_closed_variant());
3812            assert!(!closed_bound.is_open());
3813            assert!(!closed_bound.is_open_variant());
3814            assert_eq!(closed_bound.as_ref(), &value);
3815
3816            // Test constraint semantics for open bound
3817            assert!(!open_bound.value_within_bound(&value)); // 10 < 10 → false
3818            assert!(open_bound.value_within_bound(&Real::try_new(9.9).unwrap())); // 9.9 < 10 → true
3819            assert!(!open_bound.value_within_bound(&Real::try_new(10.1).unwrap())); // 10.1 < 10 → false
3820
3821            // Test constraint semantics for closed bound
3822            assert!(closed_bound.value_within_bound(&value)); // 10 ≤ 10 → true
3823            assert!(closed_bound.value_within_bound(&Real::try_new(9.9).unwrap())); // 9.9 ≤ 10 → true
3824            assert!(!closed_bound.value_within_bound(&Real::try_new(10.1).unwrap())); // 10.1 ≤ 10 → false
3825        }
3826
3827        /// Test equivalence between convenience constructors and manual construction
3828        #[test]
3829        fn test_constructor_equivalence() {
3830            let value = Real::try_new(7.5).unwrap();
3831
3832            // Lower bounds
3833            let lower_open_convenience = LowerBoundRuntime::new_open(value);
3834            let lower_open_manual = LowerBoundRuntime::Open(LowerBoundOpen::new(value));
3835            assert_eq!(lower_open_convenience, lower_open_manual);
3836
3837            let lower_closed_convenience = LowerBoundRuntime::new_closed(value);
3838            let lower_closed_manual = LowerBoundRuntime::Closed(LowerBoundClosed::new(value));
3839            assert_eq!(lower_closed_convenience, lower_closed_manual);
3840
3841            // Upper bounds
3842            let upper_open_convenience = UpperBoundRuntime::new_open(value);
3843            let upper_open_manual = UpperBoundRuntime::Open(UpperBoundOpen::new(value));
3844            assert_eq!(upper_open_convenience, upper_open_manual);
3845
3846            let upper_closed_convenience = UpperBoundRuntime::new_closed(value);
3847            let upper_closed_manual = UpperBoundRuntime::Closed(UpperBoundClosed::new(value));
3848            assert_eq!(upper_closed_convenience, upper_closed_manual);
3849        }
3850
3851        /// Test is_open_variant and is_closed_variant consistency
3852        #[test]
3853        fn test_variant_check_consistency() {
3854            let value = Real::try_new(3.5).unwrap();
3855
3856            // Lower bounds
3857            let lower_open = LowerBoundRuntime::new_open(value);
3858            let lower_closed = LowerBoundRuntime::new_closed(value);
3859
3860            // Verify is_open_variant matches is_open() from trait
3861            assert_eq!(lower_open.is_open_variant(), lower_open.is_open());
3862            assert_eq!(lower_closed.is_open_variant(), lower_closed.is_open());
3863
3864            // Verify is_closed_variant matches is_closed() from trait
3865            assert_eq!(lower_open.is_closed_variant(), lower_open.is_closed());
3866            assert_eq!(lower_closed.is_closed_variant(), lower_closed.is_closed());
3867
3868            // Verify complementary relationship
3869            assert_eq!(
3870                lower_open.is_open_variant(),
3871                !lower_open.is_closed_variant()
3872            );
3873            assert_eq!(
3874                lower_closed.is_open_variant(),
3875                !lower_closed.is_closed_variant()
3876            );
3877
3878            // Upper bounds
3879            let upper_open = UpperBoundRuntime::new_open(value);
3880            let upper_closed = UpperBoundRuntime::new_closed(value);
3881
3882            assert_eq!(upper_open.is_open_variant(), upper_open.is_open());
3883            assert_eq!(upper_closed.is_open_variant(), upper_closed.is_open());
3884            assert_eq!(upper_open.is_closed_variant(), upper_open.is_closed());
3885            assert_eq!(upper_closed.is_closed_variant(), upper_closed.is_closed());
3886            assert_eq!(
3887                upper_open.is_open_variant(),
3888                !upper_open.is_closed_variant()
3889            );
3890            assert_eq!(
3891                upper_closed.is_open_variant(),
3892                !upper_closed.is_closed_variant()
3893            );
3894        }
3895
3896        /// Test variant checks for filtering and categorization
3897        #[test]
3898        fn test_variant_checks_for_filtering() {
3899            let bounds = [
3900                LowerBoundRuntime::new_open(Real::try_new(1.0).unwrap()),
3901                LowerBoundRuntime::new_closed(Real::try_new(2.0).unwrap()),
3902                LowerBoundRuntime::new_open(Real::try_new(3.0).unwrap()),
3903                LowerBoundRuntime::new_closed(Real::try_new(4.0).unwrap()),
3904                LowerBoundRuntime::new_open(Real::try_new(5.0).unwrap()),
3905            ];
3906
3907            // Filter by variant type
3908            let open_bounds: Vec<_> = bounds.iter().filter(|b| b.is_open_variant()).collect();
3909            let closed_bounds: Vec<_> = bounds.iter().filter(|b| b.is_closed_variant()).collect();
3910
3911            assert_eq!(open_bounds.len(), 3);
3912            assert_eq!(closed_bounds.len(), 2);
3913
3914            // Verify all categorized correctly
3915            for bound in &open_bounds {
3916                assert!(bound.is_open_variant());
3917                assert!(!bound.is_closed_variant());
3918            }
3919            for bound in &closed_bounds {
3920                assert!(bound.is_closed_variant());
3921                assert!(!bound.is_open_variant());
3922            }
3923        }
3924
3925        /// Test variant checks are non-consuming
3926        #[test]
3927        fn test_variant_checks_non_consuming() {
3928            let bound = LowerBoundRuntime::new_open(Real::try_new(42.0).unwrap());
3929
3930            // Can check multiple times without consuming
3931            assert!(bound.is_open_variant());
3932            assert!(bound.is_open_variant());
3933            assert!(!bound.is_closed_variant());
3934            assert!(!bound.is_closed_variant());
3935
3936            // Can still use the bound after checks
3937            assert!(bound.value_within_bound(&Real::try_new(50.0).unwrap()));
3938            assert_eq!(bound.as_ref(), &Real::try_new(42.0).unwrap());
3939        }
3940
3941        /// Test constructors with different scalar types
3942        #[test]
3943        fn test_constructors_with_different_scalars() {
3944            // Test with f64
3945            let f64_open = LowerBoundRuntime::new_open(5.0_f64);
3946            let f64_closed = LowerBoundRuntime::new_closed(5.0_f64);
3947            assert!(f64_open.is_open_variant());
3948            assert!(f64_closed.is_closed_variant());
3949
3950            // Test with validated scalar
3951            let validated_value = Real::try_new(10.0).unwrap();
3952            let validated_open = UpperBoundRuntime::new_open(validated_value);
3953            let validated_closed = UpperBoundRuntime::new_closed(validated_value);
3954            assert!(validated_open.is_open_variant());
3955            assert!(validated_closed.is_closed_variant());
3956        }
3957
3958        /// Test constructors in dynamic interval creation scenarios
3959        #[test]
3960        fn test_constructors_dynamic_interval_creation() {
3961            let create_bound_from_config =
3962                |value: f64, inclusive: bool| -> LowerBoundRuntime<Real> {
3963                    let real_value = Real::try_new(value).unwrap();
3964                    if inclusive {
3965                        LowerBoundRuntime::new_closed(real_value)
3966                    } else {
3967                        LowerBoundRuntime::new_open(real_value)
3968                    }
3969                };
3970
3971            // Test inclusive bound
3972            let inclusive_bound = create_bound_from_config(0.0, true);
3973            assert!(inclusive_bound.is_closed_variant());
3974            assert!(inclusive_bound.value_within_bound(&Real::try_new(0.0).unwrap()));
3975
3976            // Test exclusive bound
3977            let exclusive_bound = create_bound_from_config(0.0, false);
3978            assert!(exclusive_bound.is_open_variant());
3979            assert!(!exclusive_bound.value_within_bound(&Real::try_new(0.0).unwrap()));
3980        }
3981
3982        /// Test that constructors maintain proper ordering relationships
3983        #[test]
3984        fn test_constructor_ordering() {
3985            let value = Real::try_new(5.0).unwrap();
3986
3987            // For lower bounds: closed < open at same value
3988            let lower_closed = LowerBoundRuntime::new_closed(value);
3989            let lower_open = LowerBoundRuntime::new_open(value);
3990            assert!(lower_closed < lower_open);
3991
3992            // For upper bounds: open < closed at same value
3993            let upper_open = UpperBoundRuntime::new_open(value);
3994            let upper_closed = UpperBoundRuntime::new_closed(value);
3995            assert!(upper_open < upper_closed);
3996        }
3997    }
3998
3999    /// Tests for new helper functions for hull computation with optional bounds
4000    mod maybe_unbounded_helpers {
4001        use super::*;
4002        use num_valid::RealNative64StrictFiniteInDebug;
4003        use try_create::TryNew;
4004
4005        type Real = RealNative64StrictFiniteInDebug;
4006
4007        /// Test min_lower_bound_maybe_unbounded with both bounds present (closed wins)
4008        #[test]
4009        fn test_min_lower_bound_both_present_closed_wins() {
4010            let value = Real::try_new(5.0).unwrap();
4011            let closed = LowerBoundRuntime::new_closed(value);
4012            let open = LowerBoundRuntime::new_open(value);
4013
4014            let result = min_lower_bound_maybe_unbounded(Some(closed), Some(open));
4015
4016            assert!(result.is_some());
4017            assert!(
4018                result.unwrap().is_closed_variant(),
4019                "Closed should win over open at same value"
4020            );
4021        }
4022
4023        /// Test min_lower_bound_maybe_unbounded with different values
4024        #[test]
4025        fn test_min_lower_bound_different_values() {
4026            let value1 = Real::try_new(3.0).unwrap();
4027            let value2 = Real::try_new(7.0).unwrap();
4028            let bound1 = LowerBoundRuntime::new_closed(value1);
4029            let bound2 = LowerBoundRuntime::new_open(value2);
4030
4031            let result = min_lower_bound_maybe_unbounded(Some(bound1.clone()), Some(bound2));
4032
4033            assert!(result.is_some());
4034            let result_bound = result.unwrap();
4035            assert_eq!(
4036                result_bound.as_ref().as_ref(),
4037                &3.0,
4038                "Should select minimum value"
4039            );
4040            assert!(result_bound.is_closed_variant());
4041        }
4042
4043        /// Test min_lower_bound_maybe_unbounded with first None (unbounded wins)
4044        #[test]
4045        fn test_min_lower_bound_first_none() {
4046            let value = Real::try_new(5.0).unwrap();
4047            let bound = LowerBoundRuntime::new_closed(value);
4048
4049            let result = min_lower_bound_maybe_unbounded(None, Some(bound));
4050
4051            assert!(result.is_none(), "None (unbounded) should win");
4052        }
4053
4054        /// Test min_lower_bound_maybe_unbounded with second None (unbounded wins)
4055        #[test]
4056        fn test_min_lower_bound_second_none() {
4057            let value = Real::try_new(5.0).unwrap();
4058            let bound = LowerBoundRuntime::new_closed(value);
4059
4060            let result = min_lower_bound_maybe_unbounded(Some(bound), None);
4061
4062            assert!(result.is_none(), "None (unbounded) should win");
4063        }
4064
4065        /// Test min_lower_bound_maybe_unbounded with both None
4066        #[test]
4067        fn test_min_lower_bound_both_none() {
4068            let result = min_lower_bound_maybe_unbounded::<Real>(None, None);
4069
4070            assert!(result.is_none());
4071        }
4072
4073        /// Test max_upper_bound_maybe_unbounded with both bounds present (closed wins)
4074        #[test]
4075        fn test_max_upper_bound_both_present_closed_wins() {
4076            let value = Real::try_new(5.0).unwrap();
4077            let closed = UpperBoundRuntime::new_closed(value);
4078            let open = UpperBoundRuntime::new_open(value);
4079
4080            let result = max_upper_bound_maybe_unbounded(Some(closed.clone()), Some(open.clone()));
4081
4082            assert!(result.is_some());
4083            assert!(
4084                result.unwrap().is_closed_variant(),
4085                "Closed should win over open at same value"
4086            );
4087        }
4088
4089        /// Test max_upper_bound_maybe_unbounded with different values
4090        #[test]
4091        fn test_max_upper_bound_different_values() {
4092            let value1 = Real::try_new(3.0).unwrap();
4093            let value2 = Real::try_new(7.0).unwrap();
4094            let bound1 = UpperBoundRuntime::new_open(value1);
4095            let bound2 = UpperBoundRuntime::new_closed(value2);
4096
4097            let result = max_upper_bound_maybe_unbounded(Some(bound1), Some(bound2.clone()));
4098
4099            assert!(result.is_some());
4100            let result_bound = result.unwrap();
4101            assert_eq!(
4102                result_bound.as_ref().as_ref(),
4103                &7.0,
4104                "Should select maximum value"
4105            );
4106            assert!(result_bound.is_closed_variant());
4107        }
4108
4109        /// Test max_upper_bound_maybe_unbounded with first None (unbounded wins)
4110        #[test]
4111        fn test_max_upper_bound_first_none() {
4112            let value = Real::try_new(5.0).unwrap();
4113            let bound = UpperBoundRuntime::new_closed(value);
4114
4115            let result = max_upper_bound_maybe_unbounded(None, Some(bound));
4116
4117            assert!(result.is_none(), "None (unbounded) should win");
4118        }
4119
4120        /// Test max_upper_bound_maybe_unbounded with second None (unbounded wins)
4121        #[test]
4122        fn test_max_upper_bound_second_none() {
4123            let value = Real::try_new(5.0).unwrap();
4124            let bound = UpperBoundRuntime::new_closed(value);
4125
4126            let result = max_upper_bound_maybe_unbounded(Some(bound), None);
4127
4128            assert!(result.is_none(), "None (unbounded) should win");
4129        }
4130
4131        /// Test max_upper_bound_maybe_unbounded with both None
4132        #[test]
4133        fn test_max_upper_bound_both_none() {
4134            let result = max_upper_bound_maybe_unbounded::<Real>(None, None);
4135
4136            assert!(result.is_none());
4137        }
4138
4139        /// Test symmetry: swapping arguments doesn't change result
4140        #[test]
4141        fn test_min_lower_bound_symmetry() {
4142            let value1 = Real::try_new(3.0).unwrap();
4143            let value2 = Real::try_new(7.0).unwrap();
4144            let bound1 = LowerBoundRuntime::new_closed(value1);
4145            let bound2 = LowerBoundRuntime::new_open(value2);
4146
4147            let result1 =
4148                min_lower_bound_maybe_unbounded(Some(bound1.clone()), Some(bound2.clone()));
4149            let result2 = min_lower_bound_maybe_unbounded(Some(bound2), Some(bound1));
4150
4151            assert_eq!(result1, result2, "Operation should be commutative");
4152        }
4153
4154        /// Test symmetry for upper bounds
4155        #[test]
4156        fn test_max_upper_bound_symmetry() {
4157            let value1 = Real::try_new(3.0).unwrap();
4158            let value2 = Real::try_new(7.0).unwrap();
4159            let bound1 = UpperBoundRuntime::new_closed(value1);
4160            let bound2 = UpperBoundRuntime::new_open(value2);
4161
4162            let result1 =
4163                max_upper_bound_maybe_unbounded(Some(bound1.clone()), Some(bound2.clone()));
4164            let result2 = max_upper_bound_maybe_unbounded(Some(bound2), Some(bound1));
4165
4166            assert_eq!(result1, result2, "Operation should be commutative");
4167        }
4168
4169        /// Test interaction with min_lower_bound (existing function)
4170        #[test]
4171        fn test_consistency_with_existing_min_lower_bound() {
4172            let value1 = Real::try_new(3.0).unwrap();
4173            let value2 = Real::try_new(7.0).unwrap();
4174            let bound1 = LowerBoundRuntime::new_closed(value1);
4175            let bound2 = LowerBoundRuntime::new_open(value2);
4176
4177            // Using the new maybe_unbounded function with Some
4178            let result_maybe =
4179                min_lower_bound_maybe_unbounded(Some(bound1.clone()), Some(bound2.clone()))
4180                    .unwrap();
4181
4182            // Using the existing function
4183            let result_direct = min_lower_bound(bound1, bound2);
4184
4185            assert_eq!(
4186                result_maybe, result_direct,
4187                "Should be consistent with existing function"
4188            );
4189        }
4190
4191        /// Test interaction with max_upper_bound (existing function)
4192        #[test]
4193        fn test_consistency_with_existing_max_upper_bound() {
4194            let value1 = Real::try_new(3.0).unwrap();
4195            let value2 = Real::try_new(7.0).unwrap();
4196            let bound1 = UpperBoundRuntime::new_closed(value1);
4197            let bound2 = UpperBoundRuntime::new_open(value2);
4198
4199            // Using the new maybe_unbounded function with Some
4200            let result_maybe =
4201                max_upper_bound_maybe_unbounded(Some(bound1.clone()), Some(bound2.clone()))
4202                    .unwrap();
4203
4204            // Using the existing function
4205            let result_direct = max_upper_bound(bound1, bound2);
4206
4207            assert_eq!(
4208                result_maybe, result_direct,
4209                "Should be consistent with existing function"
4210            );
4211        }
4212
4213        /// Test with multiple calls (associativity)
4214        #[test]
4215        fn test_min_lower_bound_associativity() {
4216            let v1 = Real::try_new(1.0).unwrap();
4217            let v2 = Real::try_new(2.0).unwrap();
4218            let v3 = Real::try_new(3.0).unwrap();
4219            let b1 = LowerBoundRuntime::new_closed(v1);
4220            let b2 = LowerBoundRuntime::new_open(v2);
4221            let b3 = LowerBoundRuntime::new_closed(v3);
4222
4223            // (b1 min b2) min b3
4224            let temp = min_lower_bound_maybe_unbounded(Some(b1.clone()), Some(b2.clone()));
4225            let result1 = min_lower_bound_maybe_unbounded(temp, Some(b3.clone()));
4226
4227            // b1 min (b2 min b3)
4228            let temp = min_lower_bound_maybe_unbounded(Some(b2), Some(b3));
4229            let result2 = min_lower_bound_maybe_unbounded(Some(b1), temp);
4230
4231            assert_eq!(result1, result2, "Operation should be associative");
4232        }
4233    }
4234
4235    // Tests for IntervalBoundRuntime::flip_bound_type() and flip_bound_side()
4236    mod transformations {
4237        use super::*;
4238
4239        /// Test flip_bound_type() on LowerBoundRuntime variants
4240        #[test]
4241        fn flip_bound_type_lower_open_to_closed() {
4242            let lower_open = LowerBoundRuntime::new_open(5.0);
4243            let lower_closed = lower_open.flip_bound_type();
4244
4245            assert!(lower_closed.is_closed_variant());
4246            assert!(!lower_closed.is_open_variant());
4247            assert_eq!(*lower_closed.as_ref(), 5.0);
4248        }
4249
4250        #[test]
4251        fn flip_bound_type_lower_closed_to_open() {
4252            let lower_closed = LowerBoundRuntime::new_closed(10.0);
4253            let lower_open = lower_closed.flip_bound_type();
4254
4255            assert!(lower_open.is_open_variant());
4256            assert!(!lower_open.is_closed_variant());
4257            assert_eq!(*lower_open.as_ref(), 10.0);
4258        }
4259
4260        /// Test flip_bound_type() on UpperBoundRuntime variants
4261        #[test]
4262        fn flip_bound_type_upper_open_to_closed() {
4263            let upper_open = UpperBoundRuntime::new_open(20.0);
4264            let upper_closed = upper_open.flip_bound_type();
4265
4266            assert!(upper_closed.is_closed_variant());
4267            assert!(!upper_closed.is_open_variant());
4268            assert_eq!(*upper_closed.as_ref(), 20.0);
4269        }
4270
4271        #[test]
4272        fn flip_bound_type_upper_closed_to_open() {
4273            let upper_closed = UpperBoundRuntime::new_closed(15.0);
4274            let upper_open = upper_closed.flip_bound_type();
4275
4276            assert!(upper_open.is_open_variant());
4277            assert!(!upper_open.is_closed_variant());
4278            assert_eq!(*upper_open.as_ref(), 15.0);
4279        }
4280
4281        /// Test that flipping bound type twice returns to original
4282        #[test]
4283        fn flip_bound_type_idempotent() {
4284            // Lower bounds
4285            let lower_open_original = LowerBoundRuntime::new_open(3.0);
4286            let lower_open_roundtrip = lower_open_original
4287                .clone()
4288                .flip_bound_type()
4289                .flip_bound_type();
4290            assert_eq!(lower_open_original, lower_open_roundtrip);
4291
4292            let lower_closed_original = LowerBoundRuntime::new_closed(7.0);
4293            let lower_closed_roundtrip = lower_closed_original
4294                .clone()
4295                .flip_bound_type()
4296                .flip_bound_type();
4297            assert_eq!(lower_closed_original, lower_closed_roundtrip);
4298
4299            // Upper bounds
4300            let upper_open_original = UpperBoundRuntime::new_open(12.0);
4301            let upper_open_roundtrip = upper_open_original
4302                .clone()
4303                .flip_bound_type()
4304                .flip_bound_type();
4305            assert_eq!(upper_open_original, upper_open_roundtrip);
4306
4307            let upper_closed_original = UpperBoundRuntime::new_closed(18.0);
4308            let upper_closed_roundtrip = upper_closed_original
4309                .clone()
4310                .flip_bound_type()
4311                .flip_bound_type();
4312            assert_eq!(upper_closed_original, upper_closed_roundtrip);
4313        }
4314
4315        /// Test flip_bound_side() from lower to upper bounds
4316        #[test]
4317        fn flip_bound_side_lower_open_to_upper_open() {
4318            let lower_open = LowerBoundRuntime::new_open(5.0);
4319            let upper_open: UpperBoundRuntime<f64> = lower_open.flip_bound_side();
4320
4321            assert!(upper_open.is_open_variant());
4322            assert_eq!(*upper_open.as_ref(), 5.0);
4323        }
4324
4325        #[test]
4326        fn flip_bound_side_lower_closed_to_upper_closed() {
4327            let lower_closed = LowerBoundRuntime::new_closed(10.0);
4328            let upper_closed: UpperBoundRuntime<f64> = lower_closed.flip_bound_side();
4329
4330            assert!(upper_closed.is_closed_variant());
4331            assert_eq!(*upper_closed.as_ref(), 10.0);
4332        }
4333
4334        /// Test flip_bound_side() from upper to lower bounds
4335        #[test]
4336        fn flip_bound_side_upper_open_to_lower_open() {
4337            let upper_open = UpperBoundRuntime::new_open(20.0);
4338            let lower_open: LowerBoundRuntime<f64> = upper_open.flip_bound_side();
4339
4340            assert!(lower_open.is_open_variant());
4341            assert_eq!(*lower_open.as_ref(), 20.0);
4342        }
4343
4344        #[test]
4345        fn flip_bound_side_upper_closed_to_lower_closed() {
4346            let upper_closed = UpperBoundRuntime::new_closed(15.0);
4347            let lower_closed: LowerBoundRuntime<f64> = upper_closed.flip_bound_side();
4348
4349            assert!(lower_closed.is_closed_variant());
4350            assert_eq!(*lower_closed.as_ref(), 15.0);
4351        }
4352
4353        /// Test that flipping bound side twice returns to original side
4354        #[test]
4355        fn flip_bound_side_roundtrip() {
4356            // Lower to upper to lower
4357            let lower_open_original = LowerBoundRuntime::new_open(3.0);
4358            let upper_open: UpperBoundRuntime<f64> = lower_open_original.clone().flip_bound_side();
4359            let lower_open_back: LowerBoundRuntime<f64> = upper_open.flip_bound_side();
4360            assert_eq!(lower_open_original, lower_open_back);
4361
4362            let lower_closed_original = LowerBoundRuntime::new_closed(7.0);
4363            let upper_closed: UpperBoundRuntime<f64> =
4364                lower_closed_original.clone().flip_bound_side();
4365            let lower_closed_back: LowerBoundRuntime<f64> = upper_closed.flip_bound_side();
4366            assert_eq!(lower_closed_original, lower_closed_back);
4367
4368            // Upper to lower to upper
4369            let upper_open_original = UpperBoundRuntime::new_open(12.0);
4370            let lower_open_temp: LowerBoundRuntime<f64> =
4371                upper_open_original.clone().flip_bound_side();
4372            let upper_open_back: UpperBoundRuntime<f64> = lower_open_temp.flip_bound_side();
4373            assert_eq!(upper_open_original, upper_open_back);
4374
4375            let upper_closed_original = UpperBoundRuntime::new_closed(18.0);
4376            let lower_closed_temp: LowerBoundRuntime<f64> =
4377                upper_closed_original.clone().flip_bound_side();
4378            let upper_closed_back: UpperBoundRuntime<f64> = lower_closed_temp.flip_bound_side();
4379            assert_eq!(upper_closed_original, upper_closed_back);
4380        }
4381
4382        /// Test combining flip_bound_side() and flip_bound_type()
4383        #[test]
4384        fn combined_flip_lower_closed_to_upper_open() {
4385            let lower_closed = LowerBoundRuntime::new_closed(3.0);
4386            let upper_open: UpperBoundRuntime<f64> = lower_closed
4387                .flip_bound_side() // Lower Closed -> Upper Closed
4388                .flip_bound_type(); // Upper Closed -> Upper Open
4389
4390            assert!(upper_open.is_open_variant());
4391            assert_eq!(*upper_open.as_ref(), 3.0);
4392        }
4393
4394        #[test]
4395        fn combined_flip_lower_open_to_upper_closed() {
4396            let lower_open = LowerBoundRuntime::new_open(8.0);
4397            let upper_closed: UpperBoundRuntime<f64> = lower_open
4398                .flip_bound_side() // Lower Open -> Upper Open
4399                .flip_bound_type(); // Upper Open -> Upper Closed
4400
4401            assert!(upper_closed.is_closed_variant());
4402            assert_eq!(*upper_closed.as_ref(), 8.0);
4403        }
4404
4405        #[test]
4406        fn combined_flip_upper_closed_to_lower_open() {
4407            let upper_closed = UpperBoundRuntime::new_closed(15.0);
4408            let lower_open: LowerBoundRuntime<f64> = upper_closed
4409                .flip_bound_side() // Upper Closed -> Lower Closed
4410                .flip_bound_type(); // Lower Closed -> Lower Open
4411
4412            assert!(lower_open.is_open_variant());
4413            assert_eq!(*lower_open.as_ref(), 15.0);
4414        }
4415
4416        #[test]
4417        fn combined_flip_upper_open_to_lower_closed() {
4418            let upper_open = UpperBoundRuntime::new_open(22.0);
4419            let lower_closed: LowerBoundRuntime<f64> = upper_open
4420                .flip_bound_side() // Upper Open -> Lower Open
4421                .flip_bound_type(); // Lower Open -> Lower Closed
4422
4423            assert!(lower_closed.is_closed_variant());
4424            assert_eq!(*lower_closed.as_ref(), 22.0);
4425        }
4426
4427        /// Test flip_bound_type() preserves value with negative numbers
4428        #[test]
4429        fn flip_bound_type_negative_values() {
4430            let lower_open = LowerBoundRuntime::new_open(-5.0);
4431            let lower_closed = lower_open.flip_bound_type();
4432            assert_eq!(*lower_closed.as_ref(), -5.0);
4433            assert!(lower_closed.is_closed_variant());
4434
4435            let upper_closed = UpperBoundRuntime::new_closed(-10.0);
4436            let upper_open = upper_closed.flip_bound_type();
4437            assert_eq!(*upper_open.as_ref(), -10.0);
4438            assert!(upper_open.is_open_variant());
4439        }
4440
4441        /// Test flip_bound_side() preserves value with negative numbers
4442        #[test]
4443        fn flip_bound_side_negative_values() {
4444            let lower_open = LowerBoundRuntime::new_open(-3.0);
4445            let upper_open: UpperBoundRuntime<f64> = lower_open.flip_bound_side();
4446            assert_eq!(*upper_open.as_ref(), -3.0);
4447            assert!(upper_open.is_open_variant());
4448
4449            let upper_closed = UpperBoundRuntime::new_closed(-7.0);
4450            let lower_closed: LowerBoundRuntime<f64> = upper_closed.flip_bound_side();
4451            assert_eq!(*lower_closed.as_ref(), -7.0);
4452            assert!(lower_closed.is_closed_variant());
4453        }
4454
4455        /// Test with zero values
4456        #[test]
4457        fn transformations_with_zero() {
4458            let lower_zero_open = LowerBoundRuntime::new_open(0.0);
4459            let lower_zero_closed = lower_zero_open.flip_bound_type();
4460            assert_eq!(*lower_zero_closed.as_ref(), 0.0);
4461            assert!(lower_zero_closed.is_closed_variant());
4462
4463            let upper_zero_closed = UpperBoundRuntime::new_closed(0.0);
4464            let lower_zero_from_upper: LowerBoundRuntime<f64> = upper_zero_closed.flip_bound_side();
4465            assert_eq!(*lower_zero_from_upper.as_ref(), 0.0);
4466            assert!(lower_zero_from_upper.is_closed_variant());
4467        }
4468
4469        /// Test with very small positive values (edge case)
4470        #[test]
4471        fn transformations_with_small_values() {
4472            let tiny_value = 1e-100;
4473
4474            let lower_open = LowerBoundRuntime::new_open(tiny_value);
4475            let lower_closed = lower_open.flip_bound_type();
4476            assert_eq!(*lower_closed.as_ref(), tiny_value);
4477
4478            let upper_open = UpperBoundRuntime::new_open(tiny_value);
4479            let lower_open_from_upper: LowerBoundRuntime<f64> = upper_open.flip_bound_side();
4480            assert_eq!(*lower_open_from_upper.as_ref(), tiny_value);
4481        }
4482
4483        /// Test with very large values
4484        #[test]
4485        fn transformations_with_large_values() {
4486            let large_value = 1e100;
4487
4488            let upper_closed = UpperBoundRuntime::new_closed(large_value);
4489            let upper_open = upper_closed.flip_bound_type();
4490            assert_eq!(*upper_open.as_ref(), large_value);
4491            assert!(upper_open.is_open_variant());
4492
4493            let lower_closed = LowerBoundRuntime::new_closed(large_value);
4494            let upper_closed_from_lower: UpperBoundRuntime<f64> = lower_closed.flip_bound_side();
4495            assert_eq!(*upper_closed_from_lower.as_ref(), large_value);
4496            assert!(upper_closed_from_lower.is_closed_variant());
4497        }
4498
4499        /// Test commutativity: order of flip_bound_side and flip_bound_type shouldn't matter
4500        #[test]
4501        fn flip_operations_commute() {
4502            let original = LowerBoundRuntime::new_closed(5.0);
4503
4504            // Side first, then type
4505            let result1: UpperBoundRuntime<f64> = original
4506                .clone()
4507                .flip_bound_side() // Lower Closed -> Upper Closed
4508                .flip_bound_type(); // Upper Closed -> Upper Open
4509
4510            // Type first, then side
4511            let result2: UpperBoundRuntime<f64> = original
4512                .flip_bound_type() // Lower Closed -> Lower Open
4513                .flip_bound_side(); // Lower Open -> Upper Open
4514
4515            assert_eq!(result1, result2);
4516            assert!(result1.is_open_variant());
4517            assert_eq!(*result1.as_ref(), 5.0);
4518        }
4519
4520        /// Test that flip_bound_side preserves the type (open/closed)
4521        #[test]
4522        fn flip_bound_side_preserves_type() {
4523            // Open bounds stay open
4524            let lower_open = LowerBoundRuntime::new_open(5.0);
4525            let upper_open: UpperBoundRuntime<f64> = lower_open.flip_bound_side();
4526            assert!(upper_open.is_open_variant());
4527
4528            let upper_open2 = UpperBoundRuntime::new_open(10.0);
4529            let lower_open2: LowerBoundRuntime<f64> = upper_open2.flip_bound_side();
4530            assert!(lower_open2.is_open_variant());
4531
4532            // Closed bounds stay closed
4533            let lower_closed = LowerBoundRuntime::new_closed(15.0);
4534            let upper_closed: UpperBoundRuntime<f64> = lower_closed.flip_bound_side();
4535            assert!(upper_closed.is_closed_variant());
4536
4537            let upper_closed2 = UpperBoundRuntime::new_closed(20.0);
4538            let lower_closed2: LowerBoundRuntime<f64> = upper_closed2.flip_bound_side();
4539            assert!(lower_closed2.is_closed_variant());
4540        }
4541
4542        /// Test that flip_bound_type preserves the side (lower/upper)
4543        #[test]
4544        fn flip_bound_type_preserves_side() {
4545            // Lower bounds stay lower (test by trying to use as lower bounds)
4546            let lower_open = LowerBoundRuntime::new_open(5.0);
4547            let lower_closed = lower_open.flip_bound_type();
4548            // If this compiles and runs, the type is still LowerBoundRuntime
4549            assert_eq!(*lower_closed.as_ref(), 5.0);
4550
4551            // Upper bounds stay upper
4552            let upper_closed = UpperBoundRuntime::new_closed(10.0);
4553            let upper_open = upper_closed.flip_bound_type();
4554            // If this compiles and runs, the type is still UpperBoundRuntime
4555            assert_eq!(*upper_open.as_ref(), 10.0);
4556        }
4557
4558        /// Test use case: interval difference computation
4559        /// When computing A \ B, we need to flip bounds appropriately
4560        #[test]
4561        fn interval_difference_use_case() {
4562            // A = [0, 10], B = [5, 7]
4563            // Result should be [0, 5) ∪ (7, 10]
4564
4565            // B's lower bound [5 needs to become upper bound )5 for left part
4566            let b_lower = LowerBoundRuntime::new_closed(5.0);
4567            let left_upper: UpperBoundRuntime<f64> = b_lower
4568                .flip_bound_side() // Lower Closed -> Upper Closed
4569                .flip_bound_type(); // Upper Closed -> Upper Open
4570
4571            assert!(left_upper.is_open_variant());
4572            assert_eq!(*left_upper.as_ref(), 5.0);
4573            // This creates the upper bound )5 for interval [0, 5)
4574
4575            // B's upper bound ]7 needs to become lower bound (7 for right part
4576            let b_upper = UpperBoundRuntime::new_closed(7.0);
4577            let right_lower: LowerBoundRuntime<f64> = b_upper
4578                .flip_bound_side() // Upper Closed -> Lower Closed
4579                .flip_bound_type(); // Lower Closed -> Lower Open
4580
4581            assert!(right_lower.is_open_variant());
4582            assert_eq!(*right_lower.as_ref(), 7.0);
4583            // This creates the lower bound (7 for interval (7, 10]
4584        }
4585
4586        /// Test with validated scalar types
4587        #[test]
4588        fn transformations_with_validated_types() {
4589            use num_valid::RealNative64StrictFiniteInDebug;
4590            use try_create::TryNew;
4591
4592            let value = RealNative64StrictFiniteInDebug::try_new(5.0).unwrap();
4593
4594            let lower_open = LowerBoundRuntime::new_open(value);
4595            let lower_closed = lower_open.flip_bound_type();
4596            assert!(lower_closed.is_closed_variant());
4597            assert_eq!(*lower_closed.as_ref(), value);
4598
4599            let upper_closed = UpperBoundRuntime::new_closed(value);
4600            let lower_closed_from_upper: LowerBoundRuntime<_> = upper_closed.flip_bound_side();
4601            assert!(lower_closed_from_upper.is_closed_variant());
4602            assert_eq!(*lower_closed_from_upper.as_ref(), value);
4603        }
4604
4605        /// Test multiple sequential transformations
4606        #[test]
4607        fn multiple_sequential_transformations() {
4608            let original = LowerBoundRuntime::new_open(10.0);
4609
4610            // Apply transformations in sequence
4611            let step1 = original.flip_bound_type(); // Lower Open -> Lower Closed
4612            let step2: UpperBoundRuntime<f64> = step1.flip_bound_side(); // Lower Closed -> Upper Closed
4613            let step3 = step2.flip_bound_type(); // Upper Closed -> Upper Open
4614            let step4: LowerBoundRuntime<f64> = step3.flip_bound_side(); // Upper Open -> Lower Open
4615
4616            // Should return to same type as original
4617            assert!(step4.is_open_variant());
4618            assert_eq!(*step4.as_ref(), 10.0);
4619        }
4620
4621        /// Test flip_bound_side_and_type method on IntervalBound
4622        #[test]
4623        fn test_flip_bound_side_and_type() {
4624            let lower_closed = IntervalBound::<f64, Lower, Closed>::new(5.0);
4625            let upper_open: IntervalBound<f64, Upper, Open> =
4626                lower_closed.flip_bound_side_and_type();
4627            assert_eq!(*upper_open.as_ref(), 5.0);
4628
4629            let upper_open2 = IntervalBound::<f64, Upper, Open>::new(10.0);
4630            let lower_closed2: IntervalBound<f64, Lower, Closed> =
4631                upper_open2.flip_bound_side_and_type();
4632            assert_eq!(*lower_closed2.as_ref(), 10.0);
4633
4634            let lower_open = IntervalBound::<f64, Lower, Open>::new(3.0);
4635            let upper_closed: IntervalBound<f64, Upper, Closed> =
4636                lower_open.flip_bound_side_and_type();
4637            assert_eq!(*upper_closed.as_ref(), 3.0);
4638
4639            let upper_closed2 = IntervalBound::<f64, Upper, Closed>::new(7.0);
4640            let lower_open2: IntervalBound<f64, Lower, Open> =
4641                upper_closed2.flip_bound_side_and_type();
4642            assert_eq!(*lower_open2.as_ref(), 7.0);
4643        }
4644
4645        /// Test BoundSide::is_lower() method
4646        #[test]
4647        fn test_bound_side() {
4648            assert!(Upper::is_upper());
4649            assert!(!Upper::is_lower());
4650            assert!(!Lower::is_upper());
4651            assert!(Lower::is_lower());
4652        }
4653
4654        /// Test BoundSideRuntimeChecks trait methods
4655        #[test]
4656        fn test_bound_side_checks() {
4657            let lower = LowerBoundRuntime::new_closed(5.0);
4658            assert!(!lower.is_upper_bound());
4659
4660            let upper = UpperBoundRuntime::new_open(10.0);
4661            assert!(upper.is_upper_bound());
4662        }
4663
4664        /// Test IntoInner trait on IntervalBoundRuntime
4665        #[test]
4666        fn test_interval_bound_runtime_into_inner() {
4667            let lower_open = LowerBoundRuntime::new_open(5.0);
4668            let value = lower_open.into_inner();
4669            assert_eq!(value, 5.0);
4670
4671            let lower_closed = LowerBoundRuntime::new_closed(7.0);
4672            let value2 = lower_closed.into_inner();
4673            assert_eq!(value2, 7.0);
4674
4675            let upper_open = UpperBoundRuntime::new_open(3.0);
4676            let value3 = upper_open.into_inner();
4677            assert_eq!(value3, 3.0);
4678
4679            let upper_closed = UpperBoundRuntime::new_closed(9.0);
4680            let value4 = upper_closed.into_inner();
4681            assert_eq!(value4, 9.0);
4682        }
4683
4684        /// Test BoundType::is_open() method
4685        #[test]
4686        fn test_bound_type_is_open() {
4687            // is_open() is defined as !includes_boundary()
4688            // Ensure it compiles and works
4689            assert!(Closed::includes_boundary() != Closed::is_open());
4690            assert!(Open::is_open());
4691            assert!(!Closed::is_open());
4692        }
4693    }
4694
4695    mod comparisons {
4696        use super::*;
4697        use try_create::TryNew;
4698
4699        type Real = f64;
4700
4701        /// Test PartialOrd implementation for LowerBoundRuntime
4702        #[test]
4703        fn test_interval_lower_bound_comparison() {
4704            // Create test bounds
4705            let lower_bound_closed_5 =
4706                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
4707            let lower_bound_open_5 =
4708                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));
4709            let lower_bound_closed_3 =
4710                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(3.0).unwrap()));
4711            let lower_bound_open_3 =
4712                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(3.0).unwrap()));
4713            let lower_bound_closed_7 =
4714                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(7.0).unwrap()));
4715
4716            // Test basic ordering by value
4717            assert_eq!(
4718                lower_bound_closed_3.partial_cmp(&lower_bound_closed_5),
4719                Some(Ordering::Less)
4720            );
4721            assert_eq!(
4722                lower_bound_closed_5.partial_cmp(&lower_bound_closed_3),
4723                Some(Ordering::Greater)
4724            );
4725            assert_eq!(
4726                lower_bound_closed_5.partial_cmp(&lower_bound_closed_5),
4727                Some(Ordering::Equal)
4728            );
4729
4730            // Test ordering between closed and open bounds with same value
4731            // For lower bounds: closed < open at same value (closed is more restrictive for lower)
4732            assert_eq!(
4733                lower_bound_closed_5.partial_cmp(&lower_bound_open_5),
4734                Some(Ordering::Less)
4735            );
4736            assert_eq!(
4737                lower_bound_open_5.partial_cmp(&lower_bound_closed_5),
4738                Some(Ordering::Greater)
4739            );
4740
4741            // Test mixed value and boundary type comparisons
4742            assert_eq!(
4743                lower_bound_closed_3.partial_cmp(&lower_bound_open_5),
4744                Some(Ordering::Less)
4745            );
4746            assert_eq!(
4747                lower_bound_open_3.partial_cmp(&lower_bound_closed_5),
4748                Some(Ordering::Less)
4749            );
4750            assert_eq!(
4751                lower_bound_closed_5.partial_cmp(&lower_bound_open_3),
4752                Some(Ordering::Greater)
4753            );
4754
4755            // Test transitivity
4756            assert_eq!(
4757                lower_bound_closed_3.partial_cmp(&lower_bound_closed_7),
4758                Some(Ordering::Less)
4759            );
4760            assert_eq!(
4761                lower_bound_open_3.partial_cmp(&lower_bound_closed_7),
4762                Some(Ordering::Less)
4763            );
4764        }
4765
4766        /// Test PartialOrd implementation for UpperBoundRuntime
4767        #[test]
4768        fn test_interval_upper_bound_comparison() {
4769            // Create test bounds
4770            let upper_bound_closed_5 =
4771                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
4772            let upper_bound_open_5 =
4773                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(5.0).unwrap()));
4774            let upper_bound_closed_3 =
4775                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(3.0).unwrap()));
4776            let upper_bound_open_3 =
4777                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(3.0).unwrap()));
4778            let upper_bound_closed_7 =
4779                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(7.0).unwrap()));
4780
4781            // Test basic ordering by value
4782            assert_eq!(
4783                upper_bound_closed_3.partial_cmp(&upper_bound_closed_5),
4784                Some(Ordering::Less)
4785            );
4786            assert_eq!(
4787                upper_bound_closed_5.partial_cmp(&upper_bound_closed_3),
4788                Some(Ordering::Greater)
4789            );
4790            assert_eq!(
4791                upper_bound_closed_5.partial_cmp(&upper_bound_closed_5),
4792                Some(Ordering::Equal)
4793            );
4794
4795            // Test ordering between closed and open bounds with same value
4796            // For upper bounds: open < closed at same value (open is more restrictive for upper)
4797            assert_eq!(
4798                upper_bound_open_5.partial_cmp(&upper_bound_closed_5),
4799                Some(Ordering::Less)
4800            );
4801            assert_eq!(
4802                upper_bound_closed_5.partial_cmp(&upper_bound_open_5),
4803                Some(Ordering::Greater)
4804            );
4805
4806            // Test mixed value and boundary type comparisons
4807            assert_eq!(
4808                upper_bound_closed_3.partial_cmp(&upper_bound_open_5),
4809                Some(Ordering::Less)
4810            );
4811            assert_eq!(
4812                upper_bound_open_3.partial_cmp(&upper_bound_closed_5),
4813                Some(Ordering::Less)
4814            );
4815            assert_eq!(
4816                upper_bound_closed_5.partial_cmp(&upper_bound_open_3),
4817                Some(Ordering::Greater)
4818            );
4819
4820            // Test transitivity
4821            assert_eq!(
4822                upper_bound_closed_3.partial_cmp(&upper_bound_closed_7),
4823                Some(Ordering::Less)
4824            );
4825            assert_eq!(
4826                upper_bound_open_3.partial_cmp(&upper_bound_closed_7),
4827                Some(Ordering::Less)
4828            );
4829        }
4830
4831        /// Test boundary type semantics for lower bounds
4832        #[test]
4833        fn test_lower_bound_semantics() {
4834            let closed_5 =
4835                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
4836            let open_5 = LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));
4837
4838            // For lower bounds, closed is more restrictive (smaller) than open at same value
4839            // This is because [5,b) contains 5, while (5,b) does not
4840            more_asserts::assert_lt!(closed_5, open_5);
4841            more_asserts::assert_ge!(open_5, closed_5);
4842            assert_ne!(closed_5, open_5);
4843        }
4844
4845        /// Test boundary type semantics for upper bounds
4846        #[test]
4847        fn test_upper_bound_semantics() {
4848            let closed_5 =
4849                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
4850            let open_5 = UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(5.0).unwrap()));
4851
4852            // For upper bounds, open is more restrictive (smaller) than closed at same value
4853            // This is because [a,5) excludes 5, while [a,5] includes 5
4854            more_asserts::assert_lt!(open_5, closed_5);
4855            more_asserts::assert_ge!(closed_5, open_5);
4856            assert_ne!(open_5, closed_5);
4857        }
4858
4859        /// Test consistency with mathematical interval ordering
4860        #[test]
4861        fn test_mathematical_consistency() {
4862            // Create bounds that would represent valid intervals
4863            let lower_closed_1 =
4864                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(1.0).unwrap()));
4865            let lower_open_1 =
4866                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(1.0).unwrap()));
4867            let upper_open_2 =
4868                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(2.0).unwrap()));
4869            let upper_closed_2 =
4870                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(2.0).unwrap()));
4871
4872            // Mathematical consistency checks:
4873            // [1,2) should have closed lower bound and open upper bound
4874            // (1,2] should have open lower bound and closed upper bound
4875            // [1,2] should have closed bounds
4876            // (1,2) should have open bounds
4877
4878            // Verify ordering is consistent with interval containment
4879            // [1,x] contains more points than (1,x] at the same x
4880            assert!(lower_closed_1 < lower_open_1);
4881
4882            // [x,2) contains fewer points than [x,2] at the same x
4883            assert!(upper_open_2 < upper_closed_2);
4884        }
4885
4886        /// Test reflexivity property
4887        #[test]
4888        fn test_reflexivity() {
4889            let lower_closed =
4890                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
4891            let lower_open =
4892                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));
4893            let upper_closed =
4894                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
4895            let upper_open =
4896                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(5.0).unwrap()));
4897
4898            // Reflexivity: x.partial_cmp(&x) == Some(Ordering::Equal)
4899            assert_eq!(
4900                lower_closed.partial_cmp(&lower_closed),
4901                Some(Ordering::Equal)
4902            );
4903            assert_eq!(lower_open.partial_cmp(&lower_open), Some(Ordering::Equal));
4904            assert_eq!(
4905                upper_closed.partial_cmp(&upper_closed),
4906                Some(Ordering::Equal)
4907            );
4908            assert_eq!(upper_open.partial_cmp(&upper_open), Some(Ordering::Equal));
4909        }
4910
4911        /// Test antisymmetry property
4912        #[test]
4913        fn test_antisymmetry() {
4914            let lower_closed_3 =
4915                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(3.0).unwrap()));
4916            let lower_closed_5 =
4917                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
4918
4919            // Antisymmetry: if x <= y and y <= x, then x == y
4920            if lower_closed_3.partial_cmp(&lower_closed_5) == Some(Ordering::Less) {
4921                assert_eq!(
4922                    lower_closed_5.partial_cmp(&lower_closed_3),
4923                    Some(Ordering::Greater)
4924                );
4925            }
4926        }
4927
4928        /// Test transitivity property
4929        #[test]
4930        fn test_transitivity() {
4931            let lower_closed_1 =
4932                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(1.0).unwrap()));
4933            let lower_open_3 =
4934                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(3.0).unwrap()));
4935            let lower_closed_5 =
4936                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
4937
4938            // Transitivity: if x <= y and y <= z, then x <= z
4939            let ord_1_3 = lower_closed_1.partial_cmp(&lower_open_3);
4940            let ord_3_5 = lower_open_3.partial_cmp(&lower_closed_5);
4941            let ord_1_5 = lower_closed_1.partial_cmp(&lower_closed_5);
4942
4943            if ord_1_3 == Some(Ordering::Less) && ord_3_5 == Some(Ordering::Less) {
4944                assert_eq!(ord_1_5, Some(Ordering::Less));
4945            }
4946        }
4947
4948        /// Test edge cases with same values but different boundary types
4949        #[test]
4950        fn test_edge_cases_same_values() {
4951            let value = Real::try_new(42.0).unwrap();
4952
4953            let lower_closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(value));
4954            let lower_open = LowerBoundRuntime::Open(LowerBoundOpen::new(value));
4955            let upper_closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(value));
4956            let upper_open = UpperBoundRuntime::Open(UpperBoundOpen::new(value));
4957
4958            // Test that boundary type matters even with same value
4959            assert_ne!(lower_closed.partial_cmp(&lower_open), Some(Ordering::Equal));
4960            assert_ne!(upper_closed.partial_cmp(&upper_open), Some(Ordering::Equal));
4961
4962            // Verify specific ordering relationships
4963            assert_eq!(lower_closed.partial_cmp(&lower_open), Some(Ordering::Less));
4964            assert_eq!(upper_open.partial_cmp(&upper_closed), Some(Ordering::Less));
4965        }
4966
4967        /// Test with extreme values
4968        #[test]
4969        fn test_extreme_values() {
4970            let min_val = Real::try_new(f64::MIN).unwrap();
4971            let max_val = Real::try_new(f64::MAX).unwrap();
4972
4973            let lower_min_closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(min_val));
4974            let lower_max_open = LowerBoundRuntime::Open(LowerBoundOpen::new(max_val));
4975            let upper_min_open = UpperBoundRuntime::Open(UpperBoundOpen::new(min_val));
4976            let upper_max_closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(max_val));
4977
4978            // Test that extreme values still follow ordering rules
4979            assert_eq!(
4980                lower_min_closed.partial_cmp(&lower_max_open),
4981                Some(Ordering::Less)
4982            );
4983            assert_eq!(
4984                upper_min_open.partial_cmp(&upper_max_closed),
4985                Some(Ordering::Less)
4986            );
4987        }
4988
4989        /// Test helper functions min_lower_bound and max_lower_bound
4990        #[test]
4991        fn test_min_max_lower_bound() {
4992            let lower_closed_3 =
4993                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(3.0).unwrap()));
4994            let lower_open_5 =
4995                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));
4996
4997            // Test min_lower_bound
4998            let min_result = min_lower_bound(lower_closed_3.clone(), lower_open_5.clone());
4999            assert_eq!(min_result, lower_closed_3);
5000
5001            // Test max_lower_bound
5002            let max_result = max_lower_bound(lower_closed_3.clone(), lower_open_5.clone());
5003            assert_eq!(max_result, lower_open_5);
5004        }
5005
5006        /// Test helper functions min_upper_bound and max_upper_bound
5007        #[test]
5008        fn test_min_max_upper_bound() {
5009            let upper_open_3 =
5010                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(3.0).unwrap()));
5011            let upper_closed_5 =
5012                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
5013
5014            // Test min_upper_bound
5015            let min_result = min_upper_bound(upper_open_3.clone(), upper_closed_5.clone());
5016            assert_eq!(min_result, upper_open_3);
5017
5018            // Test max_upper_bound
5019            let max_result = max_upper_bound(upper_open_3.clone(), upper_closed_5.clone());
5020            assert_eq!(max_result, upper_closed_5);
5021        }
5022    }
5023}