qubit-argument 0.4.2

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

use std::ops::{
    Bound,
    RangeBounds,
};

use crate::argument::{
    ArgumentBound,
    ArgumentError,
    ArgumentErrorKind,
    ArgumentResult,
    ArgumentValue,
    ComparisonConstraint,
    RangeConstraint,
    sealed::Sealed,
};

/// Restricts numeric validation to supported primitive numeric values.
///
/// Implementations provide the type's zero value, an exact structured error
/// representation, and NaN detection. The trait is private so arbitrary
/// partially ordered caller types cannot opt into numeric validation.
trait NumericValue: Sealed + Copy + PartialOrd {
    /// Returns the zero value for this primitive numeric type.
    fn zero() -> Self;

    /// Captures this value without losing integer magnitude or floating bits.
    fn to_argument_value(self) -> ArgumentValue;

    /// Returns whether this value is a floating-point NaN.
    ///
    /// Integer implementations always return `false`.
    fn is_nan(self) -> bool;
}

/// Implements primitive numeric conversion and non-NaN behavior for integers.
macro_rules! impl_numeric_value_for_integer {
    ($($numeric_type:ty),+ $(,)?) => {
        $(
            impl NumericValue for $numeric_type {
                /// Returns integer zero.
                #[inline]
                fn zero() -> Self {
                    0
                }

                /// Captures the integer without losing its value.
                #[inline]
                fn to_argument_value(self) -> ArgumentValue {
                    ArgumentValue::from(self)
                }

                /// Reports that an integer can never be NaN.
                #[inline]
                fn is_nan(self) -> bool {
                    false
                }
            }
        )+
    };
}

impl_numeric_value_for_integer!(i8, i16, i32, i64, i128, isize);
impl_numeric_value_for_integer!(u8, u16, u32, u64, u128, usize);

impl NumericValue for f32 {
    /// Returns positive floating-point zero.
    #[inline]
    fn zero() -> Self {
        0.0
    }

    /// Captures the exact IEEE 754 bit pattern of this value.
    #[inline]
    fn to_argument_value(self) -> ArgumentValue {
        ArgumentValue::from(self)
    }

    /// Returns whether this value is NaN.
    #[inline]
    fn is_nan(self) -> bool {
        self.is_nan()
    }
}

impl NumericValue for f64 {
    /// Returns positive floating-point zero.
    #[inline]
    fn zero() -> Self {
        0.0
    }

    /// Captures the exact IEEE 754 bit pattern of this value.
    #[inline]
    fn to_argument_value(self) -> ArgumentValue {
        ArgumentValue::from(self)
    }

    /// Returns whether this value is NaN.
    #[inline]
    fn is_nan(self) -> bool {
        self.is_nan()
    }
}

/// Validates primitive numeric arguments while preserving their values.
///
/// Every successful method returns the original value without conversion or
/// normalization. Failures contain structured comparison or range data, and
/// every method rejects floating-point NaN values with
/// [`ArgumentErrorKind::NotANumber`].
///
/// The trait is sealed and implemented only for primitive numeric types.
pub trait NumericArgument: Sealed + Sized {
    /// Requires this value to equal zero.
    ///
    /// Success returns the original value without cloning. A nonzero value
    /// returns [`ArgumentErrorKind::Comparison`] with an `EqualTo(0)`
    /// constraint at `path`; NaN returns [`ArgumentErrorKind::NotANumber`].
    fn require_zero(self, path: &str) -> ArgumentResult<Self>;

    /// Requires this value not to equal zero.
    ///
    /// Success returns the original value without cloning. Zero returns
    /// [`ArgumentErrorKind::Comparison`] with a `NotEqualTo(0)` constraint at
    /// `path`; NaN returns [`ArgumentErrorKind::NotANumber`].
    fn require_non_zero(self, path: &str) -> ArgumentResult<Self>;

    /// Requires this value to be strictly greater than zero.
    ///
    /// Success returns the original value without cloning. A value that is not
    /// positive returns [`ArgumentErrorKind::Comparison`] with a
    /// `GreaterThan(0)` constraint at `path`; NaN returns
    /// [`ArgumentErrorKind::NotANumber`].
    fn require_positive(self, path: &str) -> ArgumentResult<Self>;

    /// Requires this value to be greater than or equal to zero.
    ///
    /// Success returns the original value without cloning. A negative value
    /// returns [`ArgumentErrorKind::Comparison`] with an `AtLeast(0)`
    /// constraint at `path`; NaN returns [`ArgumentErrorKind::NotANumber`].
    fn require_non_negative(self, path: &str) -> ArgumentResult<Self>;

    /// Requires this value to be strictly less than zero.
    ///
    /// Success returns the original value without cloning. A value that is not
    /// negative returns [`ArgumentErrorKind::Comparison`] with a `LessThan(0)`
    /// constraint at `path`; NaN returns [`ArgumentErrorKind::NotANumber`].
    fn require_negative(self, path: &str) -> ArgumentResult<Self>;

    /// Requires this value to be less than or equal to zero.
    ///
    /// Success returns the original value without cloning. A positive value
    /// returns [`ArgumentErrorKind::Comparison`] with an `AtMost(0)`
    /// constraint at `path`; NaN returns [`ArgumentErrorKind::NotANumber`].
    fn require_non_positive(self, path: &str) -> ArgumentResult<Self>;

    /// Requires this value to be strictly less than `bound`.
    ///
    /// Success returns the original value without cloning. An unsatisfied
    /// comparison returns [`ArgumentErrorKind::Comparison`] with a `LessThan`
    /// constraint at `path`; a NaN value or bound returns
    /// [`ArgumentErrorKind::NotANumber`].
    fn require_less_than(self, path: &str, bound: Self)
    -> ArgumentResult<Self>;

    /// Requires this value to be less than or equal to `bound`.
    ///
    /// Success returns the original value without cloning. An unsatisfied
    /// comparison returns [`ArgumentErrorKind::Comparison`] with an `AtMost`
    /// constraint at `path`; a NaN value or bound returns
    /// [`ArgumentErrorKind::NotANumber`].
    fn require_at_most(self, path: &str, bound: Self) -> ArgumentResult<Self>;

    /// Requires this value to be strictly greater than `bound`.
    ///
    /// Success returns the original value without cloning. An unsatisfied
    /// comparison returns [`ArgumentErrorKind::Comparison`] with a
    /// `GreaterThan` constraint at `path`; a NaN value or bound returns
    /// [`ArgumentErrorKind::NotANumber`].
    fn require_greater_than(
        self,
        path: &str,
        bound: Self,
    ) -> ArgumentResult<Self>;

    /// Requires this value to be greater than or equal to `bound`.
    ///
    /// Success returns the original value without cloning. An unsatisfied
    /// comparison returns [`ArgumentErrorKind::Comparison`] with an `AtLeast`
    /// constraint at `path`; a NaN value or bound returns
    /// [`ArgumentErrorKind::NotANumber`].
    fn require_at_least(self, path: &str, bound: Self) -> ArgumentResult<Self>;

    /// Requires this value to lie within `range`.
    ///
    /// Standard inclusive, exclusive, and unbounded [`RangeBounds`] are
    /// supported. The range structure is validated before this value: reversed
    /// endpoints and equal endpoints with either endpoint excluded return
    /// [`ArgumentErrorKind::InvalidRangeConstraint`]. NaN endpoints or values
    /// return [`ArgumentErrorKind::NotANumber`].
    /// An otherwise out-of-range value returns [`ArgumentErrorKind::Range`].
    /// The range's start and end accessors are each called exactly once, and
    /// all checks use that owned endpoint snapshot.
    /// Successful validation returns the original value without cloning.
    fn require_in_range<R>(self, path: &str, range: R) -> ArgumentResult<Self>
    where
        R: RangeBounds<Self>;
}

impl<T> NumericArgument for T
where
    T: NumericValue,
{
    /// Requires equality with zero and preserves the original value.
    #[inline]
    fn require_zero(self, path: &str) -> ArgumentResult<Self> {
        let zero = T::zero();
        validate_comparison(
            self,
            path,
            zero,
            ComparisonConstraint::EqualTo(zero.to_argument_value()),
            |actual, bound| actual == bound,
        )
    }

    /// Requires inequality with zero and preserves the original value.
    #[inline]
    fn require_non_zero(self, path: &str) -> ArgumentResult<Self> {
        let zero = T::zero();
        validate_comparison(
            self,
            path,
            zero,
            ComparisonConstraint::NotEqualTo(zero.to_argument_value()),
            |actual, bound| actual != bound,
        )
    }

    /// Requires a value strictly greater than zero.
    #[inline]
    fn require_positive(self, path: &str) -> ArgumentResult<Self> {
        let zero = T::zero();
        validate_comparison(
            self,
            path,
            zero,
            ComparisonConstraint::GreaterThan(zero.to_argument_value()),
            |actual, bound| actual > bound,
        )
    }

    /// Requires a value greater than or equal to zero.
    #[inline]
    fn require_non_negative(self, path: &str) -> ArgumentResult<Self> {
        let zero = T::zero();
        validate_comparison(
            self,
            path,
            zero,
            ComparisonConstraint::AtLeast(zero.to_argument_value()),
            |actual, bound| actual >= bound,
        )
    }

    /// Requires a value strictly less than zero.
    #[inline]
    fn require_negative(self, path: &str) -> ArgumentResult<Self> {
        let zero = T::zero();
        validate_comparison(
            self,
            path,
            zero,
            ComparisonConstraint::LessThan(zero.to_argument_value()),
            |actual, bound| actual < bound,
        )
    }

    /// Requires a value less than or equal to zero.
    #[inline]
    fn require_non_positive(self, path: &str) -> ArgumentResult<Self> {
        let zero = T::zero();
        validate_comparison(
            self,
            path,
            zero,
            ComparisonConstraint::AtMost(zero.to_argument_value()),
            |actual, bound| actual <= bound,
        )
    }

    /// Requires a value strictly less than the supplied bound.
    #[inline]
    fn require_less_than(
        self,
        path: &str,
        bound: Self,
    ) -> ArgumentResult<Self> {
        validate_comparison(
            self,
            path,
            bound,
            ComparisonConstraint::LessThan(bound.to_argument_value()),
            |actual, bound| actual < bound,
        )
    }

    /// Requires a value less than or equal to the supplied bound.
    #[inline]
    fn require_at_most(self, path: &str, bound: Self) -> ArgumentResult<Self> {
        validate_comparison(
            self,
            path,
            bound,
            ComparisonConstraint::AtMost(bound.to_argument_value()),
            |actual, bound| actual <= bound,
        )
    }

    /// Requires a value strictly greater than the supplied bound.
    #[inline]
    fn require_greater_than(
        self,
        path: &str,
        bound: Self,
    ) -> ArgumentResult<Self> {
        validate_comparison(
            self,
            path,
            bound,
            ComparisonConstraint::GreaterThan(bound.to_argument_value()),
            |actual, bound| actual > bound,
        )
    }

    /// Requires a value greater than or equal to the supplied bound.
    #[inline]
    fn require_at_least(self, path: &str, bound: Self) -> ArgumentResult<Self> {
        validate_comparison(
            self,
            path,
            bound,
            ComparisonConstraint::AtLeast(bound.to_argument_value()),
            |actual, bound| actual >= bound,
        )
    }

    /// Validates the range structure before checking and returning this value.
    #[inline]
    fn require_in_range<R>(self, path: &str, range: R) -> ArgumentResult<Self>
    where
        R: RangeBounds<Self>,
    {
        let (lower_bound, upper_bound) = snapshot_range_bounds(&range);
        let constraint = capture_range_constraint(lower_bound, upper_bound);
        validate_range_structure(path, lower_bound, upper_bound, &constraint)?;
        validate_not_nan(path, self)?;
        if range_contains(lower_bound, upper_bound, self) {
            Ok(self)
        } else {
            Err(ArgumentError::new(
                path,
                ArgumentErrorKind::Range {
                    actual: self.to_argument_value(),
                    constraint,
                },
            ))
        }
    }
}

/// Rejects a NaN numeric value or constraint at the supplied argument path.
///
/// `value` is inspected without normalization. Integer values always succeed;
/// floating-point NaN values return `ArgumentErrorKind::NotANumber` at `path`.
fn validate_not_nan<T>(path: &str, value: T) -> ArgumentResult<()>
where
    T: NumericValue,
{
    if value.is_nan() {
        Err(ArgumentError::new(path, ArgumentErrorKind::NotANumber))
    } else {
        Ok(())
    }
}

/// Applies one comparison and returns the unchanged numeric value on success.
///
/// `actual` and `bound` are checked for NaN before `predicate` is evaluated.
/// If the predicate returns `false`, the error records `actual` and the exact
/// supplied `constraint` at `path`.
fn validate_comparison<T, F>(
    actual: T,
    path: &str,
    bound: T,
    constraint: ComparisonConstraint,
    predicate: F,
) -> ArgumentResult<T>
where
    T: NumericValue,
    F: FnOnce(T, T) -> bool,
{
    validate_not_nan(path, actual)?;
    validate_not_nan(path, bound)?;
    if predicate(actual, bound) {
        Ok(actual)
    } else {
        Err(ArgumentError::new(
            path,
            ArgumentErrorKind::Comparison {
                actual: actual.to_argument_value(),
                constraint,
            },
        ))
    }
}

/// Copies a borrowed standard-library bound into an owned bound.
///
/// Included and excluded endpoints are copied exactly; an unbounded endpoint
/// remains unbounded.
fn copy_range_bound<T>(bound: Bound<&T>) -> Bound<T>
where
    T: NumericValue,
{
    match bound {
        Bound::Unbounded => Bound::Unbounded,
        Bound::Included(value) => Bound::Included(*value),
        Bound::Excluded(value) => Bound::Excluded(*value),
    }
}

/// Reads each endpoint from `range` once and returns an owned snapshot.
///
/// The lower and upper endpoint accessors are each invoked exactly once. The
/// returned values are reused for constraint construction, validation, and
/// membership checks.
fn snapshot_range_bounds<T, R>(range: &R) -> (Bound<T>, Bound<T>)
where
    T: NumericValue,
    R: RangeBounds<T>,
{
    let lower_bound = copy_range_bound(range.start_bound());
    let upper_bound = copy_range_bound(range.end_bound());
    (lower_bound, upper_bound)
}

/// Captures an owned standard-library bound as a structured argument bound.
///
/// Included and excluded endpoints are converted without losing numeric bits;
/// an unbounded endpoint remains unbounded.
fn capture_argument_bound<T>(bound: Bound<T>) -> ArgumentBound
where
    T: NumericValue,
{
    match bound {
        Bound::Unbounded => ArgumentBound::Unbounded,
        Bound::Included(value) => {
            ArgumentBound::Included(value.to_argument_value())
        }
        Bound::Excluded(value) => {
            ArgumentBound::Excluded(value.to_argument_value())
        }
    }
}

/// Captures both owned endpoints without validating their relationship.
///
/// The returned constraint preserves inclusive, exclusive, unbounded, and
/// floating-point bit-pattern details exactly.
fn capture_range_constraint<T>(
    lower_bound: Bound<T>,
    upper_bound: Bound<T>,
) -> RangeConstraint
where
    T: NumericValue,
{
    RangeConstraint::new(
        capture_argument_bound(lower_bound),
        capture_argument_bound(upper_bound),
    )
}

/// Validates that two snapshotted bounds form a non-empty numeric interval.
///
/// Endpoint NaNs return `NotANumber`. Reversed endpoints, or equal endpoints
/// where either bound is excluded, return `InvalidRangeConstraint` containing
/// a clone of `constraint`. Unbounded sides require no ordering comparison.
fn validate_range_structure<T>(
    path: &str,
    lower_bound: Bound<T>,
    upper_bound: Bound<T>,
    constraint: &RangeConstraint,
) -> ArgumentResult<()>
where
    T: NumericValue,
{
    validate_range_bound_not_nan(path, lower_bound)?;
    validate_range_bound_not_nan(path, upper_bound)?;

    let is_valid = match (lower_bound, upper_bound) {
        (Bound::Unbounded, _) | (_, Bound::Unbounded) => return Ok(()),
        (Bound::Included(lower), Bound::Included(upper)) => lower <= upper,
        (Bound::Included(lower), Bound::Excluded(upper))
        | (Bound::Excluded(lower), Bound::Included(upper))
        | (Bound::Excluded(lower), Bound::Excluded(upper)) => lower < upper,
    };
    if is_valid {
        Ok(())
    } else {
        Err(ArgumentError::new(
            path,
            ArgumentErrorKind::InvalidRangeConstraint {
                constraint: constraint.clone(),
            },
        ))
    }
}

/// Rejects a NaN endpoint while accepting unbounded and ordinary endpoints.
///
/// A NaN included or excluded endpoint returns `NotANumber` at `path`.
fn validate_range_bound_not_nan<T>(
    path: &str,
    bound: Bound<T>,
) -> ArgumentResult<()>
where
    T: NumericValue,
{
    match bound {
        Bound::Included(value) | Bound::Excluded(value) => {
            validate_not_nan(path, value)
        }
        Bound::Unbounded => Ok(()),
    }
}

/// Returns whether `actual` satisfies two snapshotted bounds.
///
/// This helper assumes the bounds and all values were already checked for NaN.
/// It uses comparisons only and performs no endpoint arithmetic.
fn range_contains<T>(
    lower_bound: Bound<T>,
    upper_bound: Bound<T>,
    actual: T,
) -> bool
where
    T: NumericValue,
{
    let satisfies_lower = match lower_bound {
        Bound::Unbounded => true,
        Bound::Included(lower) => actual >= lower,
        Bound::Excluded(lower) => actual > lower,
    };
    let satisfies_upper = match upper_bound {
        Bound::Unbounded => true,
        Bound::Included(upper) => actual <= upper,
        Bound::Excluded(upper) => actual < upper,
    };
    satisfies_lower && satisfies_upper
}