ordofp_core 0.1.0

OrdoFP core provides developers with HList, Disiunctio, NominataUniversalis, Universalis, and functional type classes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! Easy Error Handling
//!
//! Simplified error handling patterns that hide the complexity
//! of effect-based error management.
//!
//! # Example
//!
//! ```rust
//! use ordofp_core::easy::*;
//!
//! let result: Result<i32, String> = run_with_error(|| {
//!     let x: i32 = "42".parse().map_err(|_| "parse error".to_string())?;
//!     Ok(x * 2)
//! });
//! assert_eq!(result, Ok(84));
//! ```

use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

// =============================================================================
// Basic Error Operations
// =============================================================================

/// Run a computation that may fail.
///
/// # Errors
///
/// Propagates whatever `Err` the `computation` closure itself returns;
/// this function adds no failure modes of its own.
///
/// # Example
///
/// ```rust
/// use ordofp_core::easy::run_with_error;
///
/// let result: Result<i32, &str> = run_with_error(|| Ok(42));
/// assert_eq!(result, Ok(42));
/// ```
pub fn run_with_error<A, E, F>(computation: F) -> Result<A, E>
where
    F: FnOnce() -> Result<A, E>,
{
    computation()
}

/// Run a computation, converting panics to errors.
///
/// Note: This requires std and `catch_unwind` support.
///
/// # Errors
///
/// Returns `Err` if the `computation` panics. The panic payload is
/// rendered as the error message when it is a `&str` or `String`;
/// any other payload becomes `"Unknown panic"`.
#[cfg(feature = "std")]
pub fn run_catching<A, F>(computation: F) -> Result<A, String>
where
    F: FnOnce() -> A + std::panic::UnwindSafe,
{
    std::panic::catch_unwind(computation).map_err(|e| {
        if let Some(s) = e.downcast_ref::<&str>() {
            String::from(*s)
        } else if let Some(s) = e.downcast_ref::<String>() {
            s.clone()
        } else {
            String::from("Unknown panic")
        }
    })
}

/// Run a fallible computation, providing a default on error.
///
/// # Example
///
/// ```rust
/// use ordofp_core::easy::run_or_default;
///
/// let result = run_or_default(|| Err("oops"), 42);
/// assert_eq!(result, 42);
/// ```
pub fn run_or_default<A, E, F>(computation: F, default: A) -> A
where
    F: FnOnce() -> Result<A, E>,
{
    computation().unwrap_or(default)
}

/// Run a fallible computation, using a fallback on error.
///
/// # Example
///
/// ```rust
/// use ordofp_core::easy::run_or_else;
///
/// let result = run_or_else(|| Err("oops"), |_| 42);
/// assert_eq!(result, 42);
/// ```
pub fn run_or_else<A, E, F, G>(computation: F, fallback: G) -> A
where
    F: FnOnce() -> Result<A, E>,
    G: FnOnce(E) -> A,
{
    computation().unwrap_or_else(fallback)
}

// =============================================================================
// Error Composition
// =============================================================================

/// Sequence multiple fallible operations.
///
/// # Errors
///
/// Returns the first `Err` produced inside the `computation` closure
/// (typically via the `?` operator); no failure modes are added here.
///
/// # Example
///
/// ```rust
/// use ordofp_core::easy::try_all;
///
/// let step1 = || -> Result<i32, &str> { Ok(1) };
/// let step2 = |a: i32| -> Result<i32, &str> { Ok(a + 1) };
///
/// let result = try_all(|| -> Result<i32, &str> {
///     let a = step1()?;
///     let b = step2(a)?;
///     Ok(b)
/// });
/// assert_eq!(result, Ok(2));
/// ```
pub fn try_all<A, E, F>(computation: F) -> Result<A, E>
where
    F: FnOnce() -> Result<A, E>,
{
    computation()
}

/// Chain two fallible operations.
///
/// # Errors
///
/// Returns the error of `first` if it fails; otherwise `second` is run
/// on the success value and its error, if any, is returned.
///
/// # Example
///
/// ```rust
/// use ordofp_core::easy::try_chain;
///
/// let result: Result<i32, &str> = try_chain(
///     || Ok(21),
///     |x| Ok(x * 2),
/// );
/// assert_eq!(result, Ok(42));
/// ```
pub fn try_chain<A, B, E, F1, F2>(first: F1, second: F2) -> Result<B, E>
where
    F1: FnOnce() -> Result<A, E>,
    F2: FnOnce(A) -> Result<B, E>,
{
    first().and_then(second)
}

/// Chain three fallible operations.
///
/// # Errors
///
/// Short-circuits on the first failing step: the error of `first`,
/// else of `second`, else of `third`. Later steps are not run once
/// an earlier one has failed.
pub fn try_chain3<A, B, C, E, F1, F2, F3>(first: F1, second: F2, third: F3) -> Result<C, E>
where
    F1: FnOnce() -> Result<A, E>,
    F2: FnOnce(A) -> Result<B, E>,
    F3: FnOnce(B) -> Result<C, E>,
{
    first().and_then(second).and_then(third)
}

/// Run multiple fallible operations, collecting all results.
///
/// # Errors
///
/// Returns the first `Err` encountered while running `operations` in
/// order; operations after the failing one are not run. Use
/// [`partition_results`] to keep going and gather every error instead.
///
/// # Example
///
/// ```rust
/// use ordofp_core::easy::try_collect;
///
/// let ops: [fn() -> Result<i32, &'static str>; 3] = [|| Ok(1), || Ok(2), || Ok(3)];
/// let results = try_collect(&ops);
/// assert_eq!(results, Ok(vec![1, 2, 3]));
/// ```
pub fn try_collect<A, E, F>(operations: &[F]) -> Result<Vec<A>, E>
where
    F: Fn() -> Result<A, E>,
{
    operations.iter().map(|f| f()).collect()
}

/// Run two fallible operations and combine results.
///
/// # Errors
///
/// Returns the error of `first` if it fails (in which case `second`
/// is never run), otherwise the error of `second` if that fails.
///
/// # Example
///
/// ```rust
/// use ordofp_core::easy::try_both;
///
/// let result: Result<(i32, i32), &str> = try_both(|| Ok(1), || Ok(2));
/// assert_eq!(result, Ok((1, 2)));
/// ```
pub fn try_both<A, B, E, F1, F2>(first: F1, second: F2) -> Result<(A, B), E>
where
    F1: FnOnce() -> Result<A, E>,
    F2: FnOnce() -> Result<B, E>,
{
    Ok((first()?, second()?))
}

// =============================================================================
// Error Recovery
// =============================================================================

/// Retry a fallible operation up to N times.
///
/// # Errors
///
/// Returns the error from the final attempt when all `max_attempts`
/// invocations of `operation` fail; earlier errors are discarded.
///
/// # Panics
///
/// Panics if `max_attempts` is `0` — there is then no error to return.
///
/// # Example
///
/// ```rust
/// use ordofp_core::easy::retry;
///
/// let mut attempts = 0;
/// let result = retry(3, || {
///     attempts += 1;
///     if attempts < 3 { Err("not yet") } else { Ok(42) }
/// });
/// assert_eq!(result, Ok(42));
/// ```
pub fn retry<A, E, F>(max_attempts: usize, mut operation: F) -> Result<A, E>
where
    F: FnMut() -> Result<A, E>,
{
    let mut last_error = None;
    for _ in 0..max_attempts {
        match operation() {
            Ok(a) => return Ok(a),
            Err(e) => last_error = Some(e),
        }
    }
    Err(last_error.expect("retry: max_attempts must be > 0"))
}

/// Retry with a condition for retrying.
///
/// # Errors
///
/// Returns an error immediately if `should_retry` rejects it (no
/// further attempts are made), or the final attempt's error once all
/// `max_attempts` invocations of `operation` have failed.
///
/// # Panics
///
/// Panics if `max_attempts` is `0` — there is then no error to return.
pub fn retry_if<A, E, F, P>(max_attempts: usize, mut operation: F, should_retry: P) -> Result<A, E>
where
    F: FnMut() -> Result<A, E>,
    P: Fn(&E) -> bool,
{
    let mut last_error = None;
    for _ in 0..max_attempts {
        match operation() {
            Ok(a) => return Ok(a),
            Err(e) => {
                if !should_retry(&e) {
                    return Err(e);
                }
                last_error = Some(e);
            }
        }
    }
    Err(last_error.expect("retry_if: max_attempts must be > 0"))
}

/// Try the first operation, falling back to the second on error.
///
/// # Errors
///
/// Returns the error of `second` when both operations fail; the error
/// from `first` is discarded once the fallback is attempted.
///
/// # Example
///
/// ```rust
/// use ordofp_core::easy::fallback;
///
/// let result: Result<i32, &str> = fallback(
///     || Err("first failed"),
///     || Ok(42),
/// );
/// assert_eq!(result, Ok(42));
/// ```
pub fn fallback<A, E, F1, F2>(first: F1, second: F2) -> Result<A, E>
where
    F1: FnOnce() -> Result<A, E>,
    F2: FnOnce() -> Result<A, E>,
{
    first().or_else(|_| second())
}

/// Try multiple fallback options in order.
///
/// # Errors
///
/// Returns the error of the last option when every option in the
/// slice fails; errors from earlier options are discarded.
///
/// # Panics
///
/// Panics if `options` is empty — there is then no error to return.
pub fn fallback_chain<A, E, F>(options: &[F]) -> Result<A, E>
where
    F: Fn() -> Result<A, E>,
{
    let mut last_error = None;
    for option in options {
        match option() {
            Ok(a) => return Ok(a),
            Err(e) => last_error = Some(e),
        }
    }
    Err(last_error.expect("fallback_chain: options must not be empty"))
}

// =============================================================================
// Error Accumulation
// =============================================================================

/// Accumulate errors from multiple validations.
///
/// # Errors
///
/// Every predicate is run against `value`; if any fail, returns a
/// `Vec` containing the error of each failed validation, in slice
/// order. This accumulates rather than short-circuiting.
///
/// # Example
///
/// ```rust
/// use ordofp_core::easy::validate_all_errors;
///
/// let result = validate_all_errors(42, &[
///     (|x| *x > 0, "must be positive"),
///     (|x: &i32| *x < 100, "must be < 100"),
/// ]);
/// assert_eq!(result, Ok(42));
/// ```
pub fn validate_all_errors<T, E: Clone>(
    value: T,
    validations: &[crate::easy::Validation<T, E>],
) -> Result<T, Vec<E>> {
    let errors: Vec<E> = validations
        .iter()
        .filter(|(pred, _)| !pred(&value))
        .map(|(_, err)| err.clone())
        .collect();

    if errors.is_empty() {
        Ok(value)
    } else {
        Err(errors)
    }
}

/// Collect all errors from multiple operations.
///
/// Returns all successes and all errors.
pub fn partition_results<A, E, F>(operations: &[F]) -> (Vec<A>, Vec<E>)
where
    F: Fn() -> Result<A, E>,
{
    let mut successes = Vec::new();
    let mut errors = Vec::new();

    for op in operations {
        match op() {
            Ok(a) => successes.push(a),
            Err(e) => errors.push(e),
        }
    }

    (successes, errors)
}

// =============================================================================
// Error Types
// =============================================================================

/// A simple error with a message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SimpleError {
    message: String,
}

impl SimpleError {
    /// Create a new simple error.
    pub fn new(message: impl Into<String>) -> Self {
        SimpleError {
            message: message.into(),
        }
    }

    /// Get the error message.
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for SimpleError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

/// Create a simple error.
pub fn error(message: impl Into<String>) -> SimpleError {
    SimpleError::new(message)
}

/// A multi-error that collects multiple errors.
#[derive(Debug, Clone)]
pub struct MultiError<E> {
    errors: Vec<E>,
}

impl<E> MultiError<E> {
    /// Create an empty multi-error.
    pub fn new() -> Self {
        MultiError { errors: Vec::new() }
    }

    /// Create from a single error.
    pub fn single(error: E) -> Self {
        MultiError {
            errors: alloc::vec![error],
        }
    }

    /// Create from multiple errors.
    pub fn many(errors: Vec<E>) -> Self {
        MultiError { errors }
    }

    /// Add an error.
    pub fn push(&mut self, error: E) {
        self.errors.push(error);
    }

    /// Check if there are any errors.
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// Get the number of errors.
    pub fn len(&self) -> usize {
        self.errors.len()
    }

    /// Get all errors.
    pub fn errors(&self) -> &[E] {
        &self.errors
    }

    /// Convert to Result (Ok if empty, Err otherwise).
    ///
    /// # Errors
    ///
    /// Returns `Err(self)` — the accumulated errors — when at least
    /// one error has been collected; `value` is discarded in that case.
    pub fn into_result<A>(self, value: A) -> Result<A, Self> {
        if self.is_empty() {
            Ok(value)
        } else {
            Err(self)
        }
    }
}

impl<E> Default for MultiError<E> {
    fn default() -> Self {
        Self::new()
    }
}

impl<E: fmt::Display> fmt::Display for MultiError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Multiple errors ({}):", self.errors.len())?;
        for (i, e) in self.errors.iter().enumerate() {
            write!(f, "\n  {}: {}", i + 1, e)?;
        }
        Ok(())
    }
}

// =============================================================================
// Result Extension Helpers
// =============================================================================

/// Convert Option to Result with an error message.
///
/// # Errors
///
/// Returns a [`SimpleError`] carrying `error` when `option` is `None`.
pub fn require<T>(option: Option<T>, error: impl Into<String>) -> Result<T, SimpleError> {
    option.ok_or_else(|| SimpleError::new(error))
}

/// Convert bool to Result.
///
/// # Errors
///
/// Returns a [`SimpleError`] carrying `error` when `condition` is `false`.
pub fn require_true(condition: bool, error: impl Into<String>) -> Result<(), SimpleError> {
    if condition {
        Ok(())
    } else {
        Err(SimpleError::new(error))
    }
}

/// Ensure a condition holds, returning the value if true.
///
/// # Errors
///
/// Returns a [`SimpleError`] carrying `error` when `condition(&value)`
/// is `false`; the value is dropped in that case.
pub fn ensure<T>(
    value: T,
    condition: impl FnOnce(&T) -> bool,
    error: impl Into<String>,
) -> Result<T, SimpleError> {
    if condition(&value) {
        Ok(value)
    } else {
        Err(SimpleError::new(error))
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_run_with_error() {
        let result: Result<i32, &str> = run_with_error(|| Ok(42));
        assert_eq!(result, Ok(42));

        let result: Result<i32, &str> = run_with_error(|| Err("oops"));
        assert!(result.is_err());
    }

    #[test]
    fn test_run_or_default() {
        let result = run_or_default(|| Err::<i32, _>("oops"), 42);
        assert_eq!(result, 42);

        let result = run_or_default(|| Ok::<_, &str>(10), 42);
        assert_eq!(result, 10);
    }

    #[test]
    fn test_try_chain() {
        let result = try_chain(|| Ok::<_, &str>(21), |x| Ok(x * 2));
        assert_eq!(result, Ok(42));
    }

    #[test]
    fn test_try_both() {
        let result = try_both(|| Ok::<_, &str>(1), || Ok(2));
        assert_eq!(result, Ok((1, 2)));
    }

    #[test]
    fn test_retry() {
        let mut attempts = 0;
        let result = retry(3, || {
            attempts += 1;
            if attempts < 3 { Err("not yet") } else { Ok(42) }
        });
        assert_eq!(result, Ok(42));
        assert_eq!(attempts, 3);
    }

    #[test]
    fn test_fallback() {
        let result: Result<i32, &str> = fallback(|| Err("first failed"), || Ok(42));
        assert_eq!(result, Ok(42));
    }

    #[test]
    fn test_validate_all_errors() {
        let result = validate_all_errors(
            42,
            &[
                (|x| *x > 0, "must be positive"),
                (|x: &i32| *x < 100, "must be < 100"),
            ],
        );
        assert_eq!(result, Ok(42));

        let result = validate_all_errors(
            -5,
            &[
                (|x| *x > 0, "must be positive"),
                (|x: &i32| *x < 100, "must be < 100"),
            ],
        );
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().len(), 1);
    }

    #[test]
    fn test_partition_results() {
        let ops: Vec<fn() -> Result<i32, &'static str>> =
            alloc::vec![|| Ok(1), || Err("error"), || Ok(2),];
        let (successes, errors) = partition_results(&ops);
        assert_eq!(successes, alloc::vec![1, 2]);
        assert_eq!(errors, alloc::vec!["error"]);
    }

    #[test]
    fn test_simple_error() {
        let err = error("something went wrong");
        assert_eq!(err.message(), "something went wrong");
    }

    #[test]
    fn test_multi_error() {
        let mut multi = MultiError::new();
        multi.push("error 1");
        multi.push("error 2");

        assert_eq!(multi.len(), 2);
        assert!(!multi.is_empty());
    }

    #[test]
    fn test_require() {
        let result = require(Some(42), "value required");
        assert_eq!(result, Ok(42));

        let result = require::<i32>(None, "value required");
        assert!(result.is_err());
    }

    #[test]
    fn test_ensure() {
        let result = ensure(42, |x| *x > 0, "must be positive");
        assert_eq!(result, Ok(42));

        let result = ensure(-1, |x| *x > 0, "must be positive");
        assert!(result.is_err());
    }
}