| Crates.io | isolator |
| lib.rs | isolator |
| version | 0.1.2 |
| created_at | 2025-01-26 07:59:54.865144+00 |
| updated_at | 2025-01-26 08:12:15.578133+00 |
| description | A lightweight library for isolating Rust functions |
| homepage | |
| repository | |
| max_upload_size | |
| id | 1531152 |
| size | 42,779 |
A Rust library for running functions in isolation using separate threads, with panic catching and error handling.
Add this to your Cargo.toml:
[dependencies]
isolator = "0.1.2"
use isolator::{isolate, IsolationResult};
fn main() -> IsolationResult<()> {
// Run a function in a separate thread
let result = isolate(|| {
println!("Running in a separate thread!");
42
})?;
println!("Result: {}", result); // prints: Result: 42
Ok(())
}
use isolator::{isolate_async, IsolationResult};
#[tokio::main]
async fn main() -> IsolationResult<()> {
let result = isolate_async(|| async {
// This async code runs in Tokio's thread pool
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
42
}).await?;
println!("Async result: {}", result);
Ok(())
}
The library provides the IsolationError enum for handling both panics and regular errors:
#[derive(Error, Debug)]
pub enum IsolationError {
#[error("Function panicked: {0}")]
Panic(String),
#[error("Function failed: {0}")]
Error(Box<dyn std::error::Error + Send + Sync>),
}
Example with error handling:
use isolator::{isolate, IsolationError};
fn main() {
match isolate(|| {
if true {
panic!("Something went wrong!");
}
42
}) {
Ok(value) => println!("Success: {}", value),
Err(IsolationError::Panic(msg)) => println!("Panic caught: {}", msg),
Err(IsolationError::Error(e)) => println!("Error caught: {}", e),
}
}
You can use your own error types as long as they implement std::error::Error:
use thiserror::Error;
use isolator::isolate;
#[derive(Error, Debug)]
enum MyError {
#[error("Custom error: {0}")]
Custom(String),
}
fn fallible_function() -> Result<(), MyError> {
Err(MyError::Custom("oops".to_string()))
}
fn main() {
let result = isolate(|| fallible_function());
// Handle the result...
}
The library uses Tokio's thread pools for isolation:
isolate() uses spawn_blocking for CPU-intensive tasksisolate_async() uses Tokio's async runtime for concurrent tasksuse isolator::isolate_async;
use tokio;
#[tokio::main]
async fn main() {
let result = isolate_async(|| async {
// Runs in Tokio's thread pool
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
"Done!"
}).await;
println!("Result: {:?}", result);
}
For detailed API documentation, visit docs.rs/isolator.
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
This project is licensed under the GPL-3.0 License - see the LICENSE file for details.
Made by Voltaged.