panicmsg/
lib.rs

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
//! This crate provides reusable error messages ([PanicMsg]) for use with 
//! panics, assertions (`assert`, `assert_eq`, `assert_ne`), and `expect`.
//! It also includes debug versions of each of these methods.
//! 
//! Simply declare a [PanicMsg]:
//! ```rust, no_run
//! const EXAMPLE_PANIC: PanicMsg = PanicMsg::new("This is an example panic message.");
//! ```
//! Then use it like this:
//! ```rust, no_run
// ...
//! EXAMPLE_PANIC.panic();
//! // ...
//! EXAMPLE_PANIC.panic_if(left >= right);
//! // ...
//! EXAMPLE_PANIC.assert(left < right);
//! // ...
//! EXAMPLE_PANIC.assert_eq(left, right);
//! // ...
//! EXAMPLE_PANIC.assert_ne(left, right);
//! // ...
//! EXAMPLE_PANIC.expect(option);
//! // ...
//! EXAMPLE_PANIC.expect(result);
//! // ...
//! EXAMPLE_PANIC.debug_panic();
//! // ...
//! EXAMPLE_PANIC.debug_panic_if(left >= right);
//! // ...
//! EXAMPLE_PANIC.debug_assert(left < right);
//! // ...
//! EXAMPLE_PANIC.debug_assert_eq(left, right);
//! // ...
//! EXAMPLE_PANIC.debug_assert_ne(left, right);
//! // ...
//! EXAMPLE_PANIC.debug_expect(option);
//! // ...
//! EXAMPLE_PANIC.debug_expect(result);
//! ```

mod private {
    pub trait Sealed {}
    impl<T> Sealed for Option<T> {}
    impl<T, E> Sealed for Result<T, E> {}
}

/// Used to convert [Result] into [Option], or keep [Option] as it is.
pub trait IntoOption: private::Sealed {
    type OptionT;
    fn into_option(self) -> Option<Self::OptionT>;
}

impl<T> IntoOption for Option<T> {
    type OptionT = T;
    fn into_option(self) -> Option<Self::OptionT> {
        self
    }
}

impl<T, E> IntoOption for Result<T, E> {
    type OptionT = T;
    fn into_option(self) -> Option<Self::OptionT> {
        self.ok()
    }
}

/// A compile-time initialized panic message that can be reused with specific error messages
/// for panics, allowing for consistent and reusable error reporting.
/// 
/// # Example
/// ```rust, no_run
/// const EXAMPLE_PANIC: PanicMsg = PanicMsg::new("This is an example panic message.");
/// // ...
/// EXAMPLE_PANIC.panic();
/// // ...
/// EXAMPLE_PANIC.panic_if(left >= right);
/// // ...
/// EXAMPLE_PANIC.assert(left < right);
/// // ...
/// EXAMPLE_PANIC.assert_eq(left, right);
/// // ...
/// EXAMPLE_PANIC.assert_ne(left, right);
/// // ...
/// EXAMPLE_PANIC.expect(option);
/// // ...
/// EXAMPLE_PANIC.expect(result);
/// ```
/// There are also `debug` variants of each of these methods.
pub struct PanicMsg<M: std::fmt::Display = &'static str> {
    message: M,
}

impl<M: std::fmt::Display> PanicMsg<M> {
    pub const fn new(message: M) -> Self {
        Self { message }
    }

    /// Panic at runtime.
    /// 
    /// See [panic].
    #[cold]
    #[track_caller]
    pub fn panic(&self) -> ! {
        panic!("{}", self.message);
    }

    /// Panic if the condition is `true` at runtime.
    /// 
    /// See [panic].
    #[track_caller]
    pub fn panic_if(&self, condition: bool) {
        if condition {
            panic!("{}", self.message);
        }
    }

    /// Asserts that a boolean expression is `true` at runtime.
    /// 
    /// see [assert].
    #[track_caller]
    pub fn assert(&self, condition: bool) {
        assert!(condition, "{}", self.message);
    }

    /// Assert that two expressions are equal to each other (using [PartialEq]).
    /// 
    /// See [assert_eq].
    #[track_caller]
    pub fn assert_eq<L, R>(&self, lhs: L, rhs: R)
    where
        L: PartialEq<R>,
        L: std::fmt::Debug,
        R: std::fmt::Debug
    {
        assert_eq!(lhs, rhs, "{}", self.message);
    }

    /// Assert that two expressions are not equal to each other (using [PartialEq]).
    /// 
    /// See [assert_ne].
    #[track_caller]
    pub fn assert_ne<L, R>(&self, lhs: L, rhs: R)
    where
        L: PartialEq<R>,
        L: std::fmt::Debug,
        R: std::fmt::Debug
    {
        assert_ne!(lhs, rhs, "{}", self.message);
    }

    /// Panic at runtime with `debug_assertions`.
    /// 
    /// See [panic].
    #[cold]
    #[track_caller]
    pub fn debug_panic(&self) {
        if cfg!(debug_assertions) {
            panic!("{}", self.message);
        }
    }

    /// Panic if the condition is `true` at runtime with `debug_assertions`.
    /// 
    /// See [panic].
    #[track_caller]
    pub fn debug_panic_if(&self, condition: bool) {
        #[cfg(debug_assertions)]
        if condition {
            panic!("{}", self.message);
        }
    }

    /// Asserts that a boolean expression is `true` at runtime with `debug_assertions`.
    /// 
    /// see [assert].
    #[track_caller]
    pub fn debug_assert(&self, condition: bool) {
        debug_assert!(condition, "{}", self.message);
    }

    /// Assert that two expressions are equal to each other (using [PartialEq])
    /// with `debug_assertions`.
    /// 
    /// See [assert_eq].
    #[track_caller]
    pub fn debug_assert_eq<L, R>(&self, lhs: L, rhs: R)
    where
        L: PartialEq<R>,
        L: std::fmt::Debug,
        R: std::fmt::Debug
    {
        debug_assert_eq!(lhs, rhs, "{}", self.message);
    }

    /// Assert that two expressions are not equal to each other (using [PartialEq])
    /// with `debug_assertions`.
    /// 
    /// See [assert_ne].
    #[track_caller]
    pub fn debug_assert_ne<L, R>(&self, lhs: L, rhs: R)
    where
        L: PartialEq<R>,
        L: std::fmt::Debug,
        R: std::fmt::Debug,
    {
        debug_assert_ne!(lhs, rhs, "{}", self.message);
    }

    #[track_caller]
    pub fn expect<T: IntoOption>(&self, value: T) -> T::OptionT {
        let Some(value) = value.into_option() else {
            panic!("{}", self.message);
        };
        value
    }

    /// Resturn a reference to the contained message.
    pub fn msg(&self) -> &M {
        &self.message
    }

}

// Trait implementations.

impl<M: std::fmt::Display + Clone> Clone for PanicMsg<M> {
    fn clone(&self) -> Self {
        Self {
            message: self.message.clone()
        }
    }

    fn clone_from(&mut self, source: &Self) {
        self.message = source.message.clone();
    }
}

impl<M: std::fmt::Display + Copy> Copy for PanicMsg<M> {}

impl<M: std::fmt::Display + PartialEq> PartialEq<M> for PanicMsg<M> {
    fn eq(&self, other: &M) -> bool {
        self.message == *other
    }

    fn ne(&self, other: &M) -> bool {
        self.message != *other
    }
}

impl<M: std::fmt::Display + PartialEq> PartialEq<PanicMsg<M>> for PanicMsg<M> {
    fn eq(&self, other: &PanicMsg<M>) -> bool {
        self.message == other.message
    }

    fn ne(&self, other: &PanicMsg<M>) -> bool {
        self.message != other.message
    }
}

impl<M: std::fmt::Display + Eq> Eq for PanicMsg<M> {}

impl<M: std::fmt::Display + PartialOrd> PartialOrd<M> for PanicMsg<M> {
    fn partial_cmp(&self, other: &M) -> Option<std::cmp::Ordering> {
        self.message.partial_cmp(other)
    }
}

impl<M: std::fmt::Display + PartialOrd> PartialOrd<PanicMsg<M>> for PanicMsg<M> {
    fn partial_cmp(&self, other: &PanicMsg<M>) -> Option<std::cmp::Ordering> {
        self.message.partial_cmp(&other.message)
    }
}

impl<M: std::fmt::Display + Ord> Ord for PanicMsg<M> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.message.cmp(&other.message)
    }
}

impl<M: std::fmt::Display + std::hash::Hash> std::hash::Hash for PanicMsg<M> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.message.hash(state);
    }

    fn hash_slice<H: std::hash::Hasher>(data: &[Self], state: &mut H)
        where
            Self: Sized, {
        unsafe {
            let trans_data: &[M] = std::mem::transmute(data);
            M::hash_slice(trans_data, state);
        }
    }
}

/// Declare a const [PanicMsg] with an `&'static str` message.
/// 
/// # Example
/// ```rust, no_run
/// const_panic_msg!(PRIVATE_ERROR = "This is declared with private visibility.");
/// const_panic_msg!(pub PUBLIC_ERROR = "This is declared with public visiblity.");
/// // ...
/// PRIVATE_ERROR.panic();
/// // ...
/// PUBLIC_ERROR.debug_assert(left < right);
/// ```
#[macro_export]
macro_rules! const_panic_msg {
    ($visibility:vis $name:ident = $msg:literal) => {
        $visibility const $name: PanicMsg<&'static str> = PanicMsg::new($msg);
    };
}

#[cfg(test)]
mod tests {
    #![allow(unused)]
    use super::PanicMsg;
    const_panic_msg!(TEST_PANIC = "Test panic.");

    #[should_panic]
    #[test]
    fn panic_test() {
        TEST_PANIC.panic();
    }

    #[should_panic]
    #[test]
    fn expect_test() {
        let some: Option<()> = None;
        let result: Result<(), ()> = Err(());
        // let num = TEST_PANIC.expect(some);
        let string = TEST_PANIC.expect(result);
    }
}