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
/*******************************************************************************
*
* Copyright (c) 2025 - 2026 Haixing Hu.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0.
*
******************************************************************************/
//! # Boxed Error Conversion
//!
//! Provides an extension trait for explicitly boxing concrete error values.
//!
//! Many `BoxResult<T>` functions can rely on the `?` operator to convert
//! concrete errors into [`BoxError`]. `IntoBoxError` covers the cases where the
//! conversion must be written as an expression, such as `map_err` closures or
//! manually constructed `Err` values.
//!
use Error;
use BoxError;
/// Extension trait for converting concrete errors into [`BoxError`].
///
/// In many `BoxResult<T>` functions, the `?` operator can perform this
/// conversion automatically. This trait is useful when a call site needs an
/// explicit conversion, for example inside `map_err`.
///
/// # Design Rationale
///
/// The standard conversion from a concrete error to `Box<dyn Error + ...>` is
/// available through `From`, but writing it explicitly often requires a verbose
/// cast. This trait gives the conversion a project-specific name and keeps call
/// sites readable:
///
/// ```rust
/// # use qubit_error::error::IntoBoxError;
/// # fn demo() -> qubit_error::error::BoxResult<u16> {
/// let port = "8080"
/// .parse::<u16>()
/// .map_err(|error| error.into_box_error())?;
/// # Ok(port)
/// # }
/// ```
///
/// # When to Use
///
/// Use `IntoBoxError` when a concrete error must be converted explicitly. If a
/// function already returns [`BoxResult`](super::BoxResult), prefer plain `?`
/// when inference is clear.
///
/// # Examples
///
/// Explicit conversion in `map_err`:
///
/// ```rust
/// use qubit_error::error::{BoxResult, IntoBoxError};
///
/// fn parse_port(text: &str) -> BoxResult<u16> {
/// text.parse::<u16>()
/// .map_err(|error| error.into_box_error())
/// }
///
/// assert_eq!(parse_port("8080").expect("valid port"), 8080);
/// assert!(parse_port("not-a-port").is_err());
/// ```
///
/// Manual `Err` construction:
///
/// ```rust
/// use std::io;
///
/// use qubit_error::error::{BoxResult, IntoBoxError};
///
/// fn require_enabled(enabled: bool) -> BoxResult<()> {
/// if enabled {
/// Ok(())
/// } else {
/// Err(io::Error::other("feature disabled").into_box_error())
/// }
/// }
///
/// assert!(require_enabled(true).is_ok());
/// assert_eq!(
/// require_enabled(false)
/// .expect_err("disabled feature should fail")
/// .to_string(),
/// "feature disabled"
/// );
/// ```