try_drop/drop_strategies/
panic.rs

1use crate::{Error, TryDropStrategy};
2use std::borrow::Cow;
3use std::string::String;
4
5/// A drop strategy that panics with a message if a drop error occurs.
6#[cfg_attr(
7    feature = "derives",
8    derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)
9)]
10pub struct PanicDropStrategy {
11    /// The message to panic with.
12    pub message: Cow<'static, str>,
13}
14
15impl PanicDropStrategy {
16    /// The default panic drop strategy.
17    pub const DEFAULT: Self = Self::with_static_message("error occurred when dropping an object");
18
19    /// Creates a new panic drop strategy with the given message.
20    pub fn with_message(message: impl Into<Cow<'static, str>>) -> Self {
21        Self {
22            message: message.into(),
23        }
24    }
25
26    /// Creates a new panic drop strategy with the given static message.
27    pub const fn with_static_message(message: &'static str) -> Self {
28        Self {
29            message: Cow::Borrowed(message),
30        }
31    }
32
33    /// Creates a new panic drop strategy with the given string message.
34    pub const fn with_dynamic_message(message: String) -> Self {
35        Self {
36            message: Cow::Owned(message),
37        }
38    }
39}
40
41impl TryDropStrategy for PanicDropStrategy {
42    fn handle_error(&self, error: Error) {
43        Err(error).expect(&self.message)
44    }
45}
46
47impl Default for PanicDropStrategy {
48    fn default() -> Self {
49        Self::DEFAULT
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56    use crate::drop_strategies::AbortDropStrategy;
57    use crate::test_utils::{ErrorsOnDrop, Fallible};
58    use crate::PureTryDrop;
59    use std::string::ToString;
60
61    #[test]
62    fn test_with_message() {
63        let strategy = PanicDropStrategy::with_message("test message");
64        assert_eq!(strategy.message, "test message");
65    }
66
67    #[test]
68    fn test_with_static_message() {
69        let strategy = PanicDropStrategy::with_static_message("test message");
70        assert_eq!(strategy.message, "test message");
71    }
72
73    #[test]
74    fn test_with_dynamic_message() {
75        let strategy = PanicDropStrategy::with_dynamic_message("test message".to_string());
76        assert_eq!(strategy.message, "test message");
77    }
78
79    #[test]
80    #[should_panic]
81    fn test_strategy() {
82        let _errors =
83            ErrorsOnDrop::<Fallible, _>::given(PanicDropStrategy::DEFAULT, AbortDropStrategy)
84                .adapt();
85    }
86}