grid1d 0.7.0

A mathematically rigorous, type-safe Rust library for 1D grid operations and interval partitions, supporting both native and arbitrary-precision numerics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
#![deny(rustdoc::broken_intra_doc_links)]

//! `From` and `TryFrom` conversions between concrete interval types and enum wrappers.
//!
//! This module provides lossless type conversions between all concrete interval types
//! and the enum wrappers [`Interval`],
//! [`IntervalFinitePositiveLength`], [`IntervalFiniteLength`], and
//! [`IntervalInfiniteLength`].
//!
//! Conversion paths to [`Interval`] are:
//! - Compile-time dispatch via a sealed private internal dispatcher trait
//!   and a single blanket `From<T> for Interval<_>` implementation.
//! - Runtime-bound reconstruction via
//!   [`crate::intervals::IntervalTrait::to_interval_runtime`] for fully generic
//!   contexts where static bound markers are not available.
//!
//! Fallible conversions (`TryFrom`) return an error when the source enum variant
//! does not match the requested concrete type.
//!
//! This module primarily adds `impl` blocks for conversion coverage.
//!
//! ## Example
//!
//! ```rust
//! use grid1d::intervals::*;
//!
//! let closed = IntervalClosed::new(0.0_f64, 1.0);
//! let general: Interval<f64> = closed.into();
//! let back: IntervalClosed<f64> = general.try_into().unwrap();
//! assert_eq!(back.lower_bound_value(), &0.0);
//! ```

use crate::{
    grids::traits::Grid1DIntervalBuilder,
    intervals::{unbounded::*, *},
};
use duplicate::duplicate_item;
use num_valid::core::errors::capture_backtrace;

//------------------------------------------------------------------------------------------------
mod sealed {

    use super::*;

    pub trait SealedToIntervalFinitePositiveLength {}

    #[duplicate_item(
        T;
        [IntervalClosed];
        [IntervalOpen];
        [IntervalLowerClosedUpperOpen];
        [IntervalLowerOpenUpperClosed];
    )]
    impl<RealType: RealScalar> SealedToIntervalFinitePositiveLength for T<RealType> {}

    pub trait SealedToIntervalInfiniteLength {}

    #[duplicate_item(
        T;
        [IntervalLowerClosedUpperUnbounded];
        [IntervalLowerOpenUpperUnbounded];
        [IntervalLowerUnboundedUpperClosed];
        [IntervalLowerUnboundedUpperOpen];
        [IntervalLowerUnboundedUpperUnbounded];
    )]
    impl<RealType: RealScalar> SealedToIntervalInfiniteLength for T<RealType> {}

    pub trait SealedToInterval {}

    #[duplicate_item(
        T;
        [IntervalClosed];
        [IntervalOpen];
        [IntervalLowerClosedUpperOpen];
        [IntervalLowerOpenUpperClosed];
        [IntervalLowerClosedUpperUnbounded];
        [IntervalLowerOpenUpperUnbounded];
        [IntervalLowerUnboundedUpperClosed];
        [IntervalLowerUnboundedUpperOpen];
        [IntervalLowerUnboundedUpperUnbounded];
        [IntervalFinitePositiveLength];
        [IntervalFiniteLength];
        [IntervalInfiniteLength];
        [IntervalSingleton];
    )]
    impl<RealType: RealScalar> SealedToInterval for T<RealType> {}
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
/// Internal dispatcher for converting finite positive-length concrete intervals
/// into [`IntervalFinitePositiveLength`].
///
/// This trait is intentionally private and sealed to keep conversion coverage
/// centralized in this module. Implementations are provided only for the bounded
/// alias families:
/// - [`IntervalClosed`]
/// - [`IntervalOpen`]
/// - [`IntervalLowerClosedUpperOpen`]
/// - [`IntervalLowerOpenUpperClosed`]
///
/// It supports the blanket conversion:
/// `From<T> for IntervalFinitePositiveLength<T::CoordType>`.
trait ToIntervalFinitePositiveLength:
    HasCoordType + sealed::SealedToIntervalFinitePositiveLength
{
    /// Converts `self` to the corresponding finite positive-length enum variant.
    fn to_interval_finite_positive_length(self) -> IntervalFinitePositiveLength<Self::CoordType>;
}

#[duplicate_item(
    src                            tgt;
    [IntervalClosed]               [Closed];
    [IntervalOpen]                 [Open];
    [IntervalLowerClosedUpperOpen] [LowerClosedUpperOpen];
    [IntervalLowerOpenUpperClosed] [LowerOpenUpperClosed];
)]
impl<RealType: RealScalar> ToIntervalFinitePositiveLength for src<RealType> {
    fn to_interval_finite_positive_length(self) -> IntervalFinitePositiveLength<RealType> {
        IntervalFinitePositiveLength::tgt(self)
    }
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
/// Internal dispatcher for converting concrete infinite-length intervals into
/// [`IntervalInfiniteLength`].
///
/// This trait is private and sealed. It is implemented only for the unbounded
/// alias families:
/// - [`IntervalLowerClosedUpperUnbounded`]
/// - [`IntervalLowerOpenUpperUnbounded`]
/// - [`IntervalLowerUnboundedUpperClosed`]
/// - [`IntervalLowerUnboundedUpperOpen`]
/// - [`IntervalLowerUnboundedUpperUnbounded`]
///
/// It supports the blanket conversion:
/// `From<T> for IntervalInfiniteLength<T::CoordType>`.
trait ToIntervalInfiniteLength: HasCoordType + sealed::SealedToIntervalInfiniteLength {
    /// Converts `self` to the corresponding infinite-length enum variant.
    fn to_interval_infinite_length(self) -> IntervalInfiniteLength<Self::CoordType>;
}

#[duplicate_item(
    src                                    tgt;
    [IntervalLowerClosedUpperUnbounded]    [LowerClosedUpperUnbounded];
    [IntervalLowerOpenUpperUnbounded]      [LowerOpenUpperUnbounded];
    [IntervalLowerUnboundedUpperClosed]    [LowerUnboundedUpperClosed];
    [IntervalLowerUnboundedUpperOpen]      [LowerUnboundedUpperOpen];
    [IntervalLowerUnboundedUpperUnbounded] [LowerUnboundedUpperUnbounded];
)]
impl<RealType: RealScalar> ToIntervalInfiniteLength for src<RealType> {
    #[inline(always)]
    fn to_interval_infinite_length(self) -> IntervalInfiniteLength<RealType> {
        IntervalInfiniteLength::tgt(self)
    }
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
/// Internal unified dispatcher for converting supported interval representations
/// into the top-level [`Interval`] enum.
///
/// This trait merges finite and infinite conversion paths into a single
/// compile-time dispatch point, avoiding overlapping blanket `From`
/// implementations for `Interval<_>`.
///
/// The trait is private and sealed. Implementations are provided for:
/// - all bounded and unbounded concrete alias families
/// - wrapper enums: [`IntervalFinitePositiveLength`], [`IntervalFiniteLength`],
///   [`IntervalInfiniteLength`]
/// - [`IntervalSingleton`]
///
/// It powers the blanket conversion:
/// `From<T> for Interval<T::CoordType>`.
trait ToInterval: HasCoordType + sealed::SealedToInterval {
    /// Converts `self` to the corresponding [`Interval`] variant.
    fn to_interval(self) -> Interval<Self::CoordType>;
}

// Finite interval types conversion to Interval
#[duplicate_item(
    src                            tgt;
    [IntervalClosed]               [Closed];
    [IntervalOpen]                 [Open];
    [IntervalLowerClosedUpperOpen] [LowerClosedUpperOpen];
    [IntervalLowerOpenUpperClosed] [LowerOpenUpperClosed];
)]
impl<RealType: RealScalar> ToInterval for src<RealType> {
    #[inline(always)]
    fn to_interval(self) -> Interval<RealType> {
        Interval::FiniteLength(IntervalFinitePositiveLength::tgt(self).into())
    }
}

// Special singleton type
impl<RealType: RealScalar> ToInterval for IntervalSingleton<RealType> {
    #[inline(always)]
    fn to_interval(self) -> Interval<RealType> {
        Interval::FiniteLength(IntervalFiniteLength::ZeroLength(self))
    }
}

// Infinite interval types conversion to Interval
#[duplicate_item(
    src                                    tgt;
    [IntervalLowerClosedUpperUnbounded]    [LowerClosedUpperUnbounded];
    [IntervalLowerOpenUpperUnbounded]      [LowerOpenUpperUnbounded];
    [IntervalLowerUnboundedUpperClosed]    [LowerUnboundedUpperClosed];
    [IntervalLowerUnboundedUpperOpen]      [LowerUnboundedUpperOpen];
    [IntervalLowerUnboundedUpperUnbounded] [LowerUnboundedUpperUnbounded];
)]
impl<RealType: RealScalar> ToInterval for src<RealType> {
    #[inline(always)]
    fn to_interval(self) -> Interval<RealType> {
        Interval::InfiniteLength(IntervalInfiniteLength::tgt(self))
    }
}
/*
impl<T> ToInterval for T
where
    T: ToIntervalInfiniteLength + sealed::SealedToInterval,
{
    #[inline(always)]
    fn to_interval(self) -> Interval<T::CoordType> {
        Interval::InfiniteLength(self.to_interval_infinite_length())
    }
}
    */

// Wrapper enum implementations for ToInterval
impl<RealType: RealScalar> ToInterval for IntervalFinitePositiveLength<RealType> {
    #[inline(always)]
    fn to_interval(self) -> Interval<RealType> {
        Interval::FiniteLength(IntervalFiniteLength::PositiveLength(self))
    }
}

impl<RealType: RealScalar> ToInterval for IntervalFiniteLength<RealType> {
    #[inline(always)]
    fn to_interval(self) -> Interval<RealType> {
        Interval::FiniteLength(self)
    }
}

impl<RealType: RealScalar> ToInterval for IntervalInfiniteLength<RealType> {
    #[inline(always)]
    fn to_interval(self) -> Interval<RealType> {
        Interval::InfiniteLength(self)
    }
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
#[duplicate_item(
    T;
    [Interval];
    [IntervalFinitePositiveLength];
)]
impl<PartitionDomain1D: Grid1DIntervalBuilder> From<SubIntervalInPartition<PartitionDomain1D>>
    for T<PartitionDomain1D::CoordType>
where
    T<PartitionDomain1D::CoordType>: From<PartitionDomain1D>,
{
    #[inline(always)]
    fn from(src: SubIntervalInPartition<PartitionDomain1D>) -> Self {
        match src {
            SubIntervalInPartition::Single(interval) => interval.into(),
            SubIntervalInPartition::First(interval) => interval.into(),
            SubIntervalInPartition::Middle(interval) => interval.into(),
            SubIntervalInPartition::Last(interval) => interval.into(),
        }
    }
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
// Unified blanket From<T> for Interval<_> based on ToInterval dispatcher
impl<T> From<T> for Interval<T::CoordType>
where
    T: ToInterval,
{
    #[inline(always)]
    fn from(interval: T) -> Self {
        interval.to_interval()
    }
}

//------------------------------------------------------------------------------------------------
// NOTE: `Into<Interval>` is available through a sealed compile-time dispatcher.
//
// The implementations above for type aliases (IntervalClosed, IntervalOpen, etc.) provide
// compile-time conversion coverage for these SPECIFIC combinations of bound types:
//   - IntervalBounded<T, Closed, Closed> (via IntervalClosed)
//   - IntervalBounded<T, Open, Open> (via IntervalOpen)
//   - IntervalBounded<T, Closed, Open> (via IntervalLowerClosedUpperOpen)
//   - IntervalBounded<T, Open, Closed> (via IntervalLowerOpenUpperClosed)
//
// IMPORTANT: There is NO blanket implementation:
//   impl<T, L, U> From<IntervalBounded<T, L, U>> for Interval<T>
//   where L: BoundType, U: BoundType { ... }  // ❌ Does NOT exist
//
// This means:
// ✅ Works: let bounded: IntervalBounded<f64, Closed, Open> = ...;
//           bounded.into() // OK - concrete types match an existing impl
//
// ✅ Works: fn convert<L, U>(i: IntervalBounded<f64, L, U>) -> Interval<f64>
//           where IntervalBounded<f64, L, U>: Into<Interval<f64>> { i.into() }
//           // OK when called with concrete L,U due to monomorphization
//
// ❌ Fails: fn convert<L, U>(i: IntervalBounded<f64, L, U>) -> Interval<f64>
//           where L: BoundType, U: BoundType { i.into() }
//           // ERROR: compiler can't prove Into exists for arbitrary L,U
//
// The reason: Implementing From for arbitrary L,U would require type-level inspection
// of the bound types at compile time, which Rust doesn't support without specialization.
//
// For fully generic code where static bound types are unavailable, use
// `IntervalTrait::to_interval_runtime()` to reconstruct `Interval` from runtime bounds.
//------------------------------------------------------------------------------------------------

impl<T> From<T> for IntervalFinitePositiveLength<T::CoordType>
where
    T: ToIntervalFinitePositiveLength,
{
    #[inline(always)]
    fn from(interval: T) -> Self {
        interval.to_interval_finite_positive_length()
    }
}

impl<T> From<T> for IntervalFiniteLength<T::CoordType>
where
    T: ToIntervalFinitePositiveLength,
{
    #[inline(always)]
    fn from(interval: T) -> Self {
        IntervalFiniteLength::PositiveLength(IntervalFinitePositiveLength::from(interval))
    }
}

impl<RealType: RealScalar> From<IntervalFinitePositiveLength<RealType>>
    for IntervalFiniteLength<RealType>
{
    #[inline(always)]
    fn from(interval: IntervalFinitePositiveLength<RealType>) -> Self {
        IntervalFiniteLength::PositiveLength(interval)
    }
}

impl<RealType: RealScalar> From<IntervalSingleton<RealType>> for IntervalFiniteLength<RealType> {
    #[inline(always)]
    fn from(interval: IntervalSingleton<RealType>) -> Self {
        IntervalFiniteLength::ZeroLength(interval)
    }
}

impl<T> From<T> for IntervalInfiniteLength<T::CoordType>
where
    T: ToIntervalInfiniteLength,
{
    #[inline(always)]
    fn from(interval: T) -> Self {
        interval.to_interval_infinite_length()
    }
}

//------------------------------------------------------------------------------------------------

impl<RealType: RealScalar> TryFrom<Interval<RealType>> for IntervalFiniteLength<RealType> {
    type Error = ErrorsIntervalConversion<RealType>;

    fn try_from(interval: Interval<RealType>) -> Result<Self, Self::Error> {
        match interval {
            Interval::FiniteLength(interval_finite_length) => Ok(interval_finite_length),
            Interval::InfiniteLength(_) => Err(ErrorsIntervalConversion::NotIntervalFiniteLength {
                interval,
                backtrace: capture_backtrace(),
            }),
        }
    }
}

#[inline(always)]
fn err_not_positive<RealType: RealScalar>(
    interval: Interval<RealType>,
) -> ErrorsIntervalConversion<RealType> {
    ErrorsIntervalConversion::NotIntervalPositiveLength {
        interval,
        backtrace: capture_backtrace(),
    }
}

impl<RealType: RealScalar> TryFrom<Interval<RealType>> for IntervalFinitePositiveLength<RealType> {
    type Error = ErrorsIntervalConversion<RealType>;

    fn try_from(interval: Interval<RealType>) -> Result<Self, Self::Error> {
        match interval {
            Interval::FiniteLength(interval_finite_length) => match interval_finite_length {
                IntervalFiniteLength::PositiveLength(interval_positive_length) => {
                    Ok(interval_positive_length)
                }
                IntervalFiniteLength::ZeroLength(interval_zero_length) => {
                    Err(err_not_positive(interval_zero_length.into()))
                }
            },
            Interval::InfiniteLength(_) => Err(err_not_positive(interval)),
        }
    }
}

impl<RealType: RealScalar> TryFrom<Interval<RealType>> for IntervalInfiniteLength<RealType> {
    type Error = ErrorsIntervalConversion<RealType>;

    fn try_from(interval: Interval<RealType>) -> Result<Self, Self::Error> {
        match interval {
            Interval::InfiniteLength(interval_infinite_length) => Ok(interval_infinite_length),
            _ => Err(ErrorsIntervalConversion::NotIntervalInfiniteLength {
                interval,
                backtrace: capture_backtrace(),
            }),
        }
    }
}

//------------------------------------------------------------------------------------------------

#[duplicate_item(
    src                            ok_enum                err ;
    [IntervalClosed]               [Closed]               [NotIntervalClosed];
    [IntervalOpen]                 [Open]                 [NotIntervalOpen];
    [IntervalLowerOpenUpperClosed] [LowerOpenUpperClosed] [NotIntervalLowerOpenUpperClosed];
    [IntervalLowerClosedUpperOpen] [LowerClosedUpperOpen] [NotIntervalLowerClosedUpperOpen];
)]
impl<RealType: RealScalar> TryFrom<Interval<RealType>> for src<RealType> {
    type Error = ErrorsIntervalConversion<RealType>;

    fn try_from(interval: Interval<RealType>) -> Result<Self, Self::Error> {
        let interval_finite_positive_length: IntervalFinitePositiveLength<RealType> =
            interval.try_into()?;
        match interval_finite_positive_length {
            IntervalFinitePositiveLength::ok_enum(interval) => Ok(interval),
            _ => Err(ErrorsIntervalConversion::err {
                interval: interval_finite_positive_length.into(),
                backtrace: capture_backtrace(),
            }),
        }
    }
}

#[duplicate_item(
    src                            ok_enum                err ;
    [IntervalClosed]               [Closed]               [NotIntervalClosed];
    [IntervalOpen]                 [Open]                 [NotIntervalOpen];
    [IntervalLowerOpenUpperClosed] [LowerOpenUpperClosed] [NotIntervalLowerOpenUpperClosed];
    [IntervalLowerClosedUpperOpen] [LowerClosedUpperOpen] [NotIntervalLowerClosedUpperOpen];
)]
impl<RealType: RealScalar> TryFrom<IntervalFinitePositiveLength<RealType>> for src<RealType> {
    type Error = ErrorsIntervalConversion<RealType>;

    fn try_from(
        interval_finite_positive_length: IntervalFinitePositiveLength<RealType>,
    ) -> Result<Self, Self::Error> {
        match interval_finite_positive_length {
            IntervalFinitePositiveLength::ok_enum(interval) => Ok(interval),
            _ => Err(ErrorsIntervalConversion::err {
                interval: interval_finite_positive_length.into(),
                backtrace: capture_backtrace(),
            }),
        }
    }
}

impl<RealType: RealScalar> TryFrom<Interval<RealType>> for IntervalSingleton<RealType> {
    type Error = ErrorsIntervalConversion<RealType>;

    fn try_from(interval: Interval<RealType>) -> Result<Self, Self::Error> {
        let interval_finite_length: IntervalFiniteLength<RealType> = interval.try_into()?;
        match interval_finite_length {
            IntervalFiniteLength::ZeroLength(singleton) => Ok(singleton),
            _ => Err(ErrorsIntervalConversion::NotIntervalSingleton {
                interval: interval_finite_length.into(),
                backtrace: capture_backtrace(),
            }),
        }
    }
}

#[duplicate_item(
    src                                 variant                     error_variant;
    [IntervalLowerUnboundedUpperClosed] [LowerUnboundedUpperClosed] [NotIntervalLowerUnboundedUpperClosed];
    [IntervalLowerUnboundedUpperOpen]   [LowerUnboundedUpperOpen]   [NotIntervalLowerUnboundedUpperOpen];
    [IntervalLowerClosedUpperUnbounded] [LowerClosedUpperUnbounded] [NotIntervalLowerClosedUpperUnbounded];
    [IntervalLowerOpenUpperUnbounded]   [LowerOpenUpperUnbounded]   [NotIntervalLowerOpenUpperUnbounded];
)]
impl<RealType: RealScalar> TryFrom<Interval<RealType>> for src<RealType> {
    type Error = ErrorsIntervalConversion<RealType>;

    fn try_from(interval: Interval<RealType>) -> Result<Self, Self::Error> {
        let interval_infinite_length: IntervalInfiniteLength<RealType> = interval.try_into()?;
        match interval_infinite_length {
            IntervalInfiniteLength::variant(interval) => Ok(interval),
            _ => Err(ErrorsIntervalConversion::error_variant {
                interval: interval_infinite_length.into(),
                backtrace: capture_backtrace(),
            }),
        }
    }
}