recoverable_spawn/thread/sync.rs
1use super::{r#trait::*, r#type::*};
2use std::{
3 any::Any,
4 thread::{JoinHandle, spawn},
5};
6
7/// Executes a recoverable function within a panic-safe context.
8///
9/// - `func`: A function implementing the `RecoverableFunction` trait.
10/// - Returns: A `SpawnResult` indicating the success or failure of the function execution.
11pub fn run_function<F: RecoverableFunction>(func: F) -> SpawnResult {
12 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
13 func();
14 }))
15}
16
17/// Executes an error-handling function with a given error message within a panic-safe context.
18///
19/// - `func`: A function implementing the `ErrorHandlerFunction` trait.
20/// - `error`: A string slice representing the error message.
21/// - Returns: A `SpawnResult` indicating the success or failure of the error-handling function execution.
22pub fn run_error_handle_function<E: ErrorHandlerFunction>(func: E, error: &str) -> SpawnResult {
23 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
24 func(error);
25 }))
26}
27
28/// Converts a panic-captured error value into a string.
29///
30/// - `err`: The captured error value, of type `Box<dyn Any + Send>`.
31/// - Returns: A string representation of the error value.
32pub fn spawn_error_to_string(err: Box<dyn Any + Send>) -> String {
33 match err.downcast_ref::<&str>() {
34 Some(str_slice) => str_slice.to_string(),
35 None => match err.downcast_ref::<String>() {
36 Some(string) => string.to_owned(),
37 None => format!("{:?}", err),
38 },
39 }
40}
41
42/// Spawns a new thread to run the provided function `function` in a recoverable manner.
43/// If the function `function` panics during execution, the panic will be caught, and the thread
44/// will terminate without crashing the entire program.
45///
46/// # Parameters
47/// - `function`: A function of type `function` to be executed in the spawned thread. It must implement `FnOnce()`, `Send`, `Sync`, and `'static` traits.
48/// - `FnOnce()`: The function is callable with no arguments and no return value.
49/// - `Send`: The function can be safely transferred across thread boundaries.
50/// - `Sync`: The function can be shared across threads safely.
51/// - `'static`: The function does not contain references to non-static data (i.e., data that lives beyond the function's scope).
52///
53/// # Returns
54/// - A `JoinHandle<()>` representing the spawned thread. The thread can be joined later to wait for its completion.
55///
56///
57/// # Panics
58/// - This function itself will not panic, but the function `function` could panic during execution.
59/// The panic will be caught, preventing the program from crashing.
60pub fn recoverable_spawn<F>(function: F) -> JoinHandle<()>
61where
62 F: RecoverableFunction,
63{
64 spawn(|| {
65 let _: SpawnResult = run_function(function);
66 })
67}
68
69/// Spawns a recoverable function with an error-handling function in a new thread.
70///
71/// - `function`: The primary function to execute, implementing the `RecoverableFunction` trait.
72/// - `error_handle_function`: A function to handle errors, implementing the `ErrorHandlerFunction` trait.
73/// - Returns: A `JoinHandle<()>` that can be used to manage the spawned thread.
74pub fn recoverable_spawn_catch<F, E>(function: F, error_handle_function: E) -> JoinHandle<()>
75where
76 F: RecoverableFunction,
77 E: ErrorHandlerFunction,
78{
79 spawn(|| {
80 let run_result: SpawnResult = run_function(function);
81 if let Err(err) = run_result {
82 let err_string: String = spawn_error_to_string(err);
83 let _: SpawnResult = run_error_handle_function(error_handle_function, &err_string);
84 }
85 })
86}
87
88pub fn recoverable_spawn_catch_finally<F, E, L>(
89 function: F,
90 error_handle_function: E,
91 finally: L,
92) -> JoinHandle<()>
93where
94 F: RecoverableFunction,
95 E: ErrorHandlerFunction,
96 L: RecoverableFunction,
97{
98 spawn(|| {
99 let run_result: SpawnResult = run_function(function);
100 if let Err(err) = run_result {
101 let err_string: String = spawn_error_to_string(err);
102 let _: SpawnResult = run_error_handle_function(error_handle_function, &err_string);
103 }
104 let _: SpawnResult = run_function(finally);
105 })
106}