use decrust::*;
pub fn risky_operation() -> Result<String> {
Ok("Risky operation completed successfully!".to_string())
}
pub fn failing_operation() -> Result<String> {
Err(validation_error!(
"test_field",
"This operation always fails for testing"
))
}
pub fn network_simulation() -> Result<String> {
Err(oops!(
"Network connection timeout",
std::io::Error::new(std::io::ErrorKind::TimedOut, "Connection timed out")
))
}
pub fn any_operation(operation_type: &str) -> Result<String> {
match operation_type {
"file_read" => {
match std::fs::read_to_string("config.toml") {
Ok(content) => Ok(format!("File content loaded: {} bytes", content.len())),
Err(_) => Ok("File not found, using default config".to_string()),
}
}
"file_write" => {
let temp_content = "# Generated config\nversion = \"1.0\"\n";
match std::fs::write("temp_config.toml", temp_content) {
Ok(_) => Ok("Configuration file written successfully".to_string()),
Err(e) => Err(oops!("Failed to write config file", e)),
}
}
"network_get" => {
use std::time::Duration;
std::thread::sleep(Duration::from_millis(10)); Ok("HTTP 200 OK: {\"status\": \"success\", \"data\": \"API response\"}".to_string())
}
"network_timeout" => {
let source = std::io::Error::new(std::io::ErrorKind::TimedOut, "Request timeout");
Err(oops!("Network request timed out after 30 seconds", source))
}
"parse_json" => {
let json_data = r#"{"name": "Decrust", "version": "1.0", "features": ["error_handling", "autocorrection"]}"#;
if json_data.starts_with('{') && json_data.ends_with('}') {
Ok("JSON parsed successfully: Decrust v1.0 with 2 features".to_string())
} else {
Err(validation_error!("json_data", "Invalid JSON format"))
}
}
"parse_invalid" => {
Err(validation_error!(
"data_format",
"Expected JSON but received malformed XML"
))
}
"math_compute" => {
let result = (1..1000).map(|x| x * x).sum::<i32>();
Ok(format!("Mathematical computation result: {}", result))
}
"math_divide_zero" => {
let numerator = 42;
let denominator = 0;
if denominator == 0 {
Err(validation_error!(
"denominator",
"Division by zero is not allowed"
))
} else {
Ok(format!("Division result: {}", numerator / denominator))
}
}
"memory_allocate" => {
let large_vec: Vec<u8> = vec![0; 1024 * 1024]; Ok(format!("Memory allocated: {} bytes", large_vec.len()))
}
"memory_limit" => {
Err(oops!(
"Memory allocation failed: insufficient memory",
std::io::Error::new(std::io::ErrorKind::OutOfMemory, "Out of memory")
))
}
"config_load" => {
let config_sources = ["config.toml", "config.yaml", "config.json"];
for source in &config_sources {
if source.ends_with(".toml") {
return Ok(format!("Configuration loaded from {}", source));
}
}
Ok("Using default configuration".to_string())
}
"config_invalid" => {
Err(validation_error!(
"config.database.url",
"Database URL is required but not provided"
))
}
"db_connect" => {
use std::time::Duration;
std::thread::sleep(Duration::from_millis(5)); Ok("Database connection established: postgresql://localhost:5432/app".to_string())
}
"db_query" => {
let query = "SELECT * FROM users WHERE active = true";
Ok(format!("Query executed: {} (returned 42 rows)", query))
}
"db_connection_failed" => {
let source =
std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "Connection refused");
Err(oops!("Failed to connect to database server", source))
}
"validate_email" => {
let email = "user@example.com";
if email.contains('@') && email.contains('.') {
Ok(format!("Email validation passed: {}", email))
} else {
Err(validation_error!("email", "Invalid email format"))
}
}
"validate_password" => {
let password = "weak";
if password.len() < 8 {
Err(validation_error!(
"password",
"Password must be at least 8 characters long"
))
} else {
Ok("Password validation passed".to_string())
}
}
"system_info" => {
let os = std::env::consts::OS;
let arch = std::env::consts::ARCH;
Ok(format!("System: {} on {}", os, arch))
}
"system_permission" => {
let source = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "Access denied");
Err(oops!(
"Permission denied: cannot access system resource",
source
))
}
"async_task" => {
use std::time::Duration;
std::thread::sleep(Duration::from_millis(20)); Ok("Async task completed successfully".to_string())
}
"async_timeout" => {
let source = std::io::Error::new(std::io::ErrorKind::TimedOut, "Operation timeout");
Err(oops!("Async operation timed out after 5 seconds", source))
}
"business_process" => {
let steps = [
"validate_input",
"process_data",
"update_records",
"send_notification",
];
let completed_steps = steps.len();
Ok(format!(
"Business process completed: {} steps executed",
completed_steps
))
}
"business_rule_violation" => {
Err(validation_error!(
"business_rule",
"Cannot process order: customer credit limit exceeded"
))
}
"env_var" => {
match std::env::var("DECRUST_TEST_ENV") {
Ok(val) => Ok(format!("Environment variable DECRUST_TEST_ENV: {}", val)),
Err(_) => Err(validation_error!("env_var", "Environment variable not set")),
}
}
"recovery_success" => {
Ok("Operation recovered successfully from previous failure".to_string())
}
"recovery_fallback" => {
Ok("Primary operation failed, fallback mechanism activated".to_string())
}
"autocorrect_unused_import" => {
Err(validation_error!(
"unused_import",
"unused import: `std::collections::HashMap`"
))
}
"autocorrect_missing_file" => {
Err(oops!(
"File not found: config.json",
std::io::Error::new(std::io::ErrorKind::NotFound, "No such file or directory")
))
}
"autocorrect_permission_denied" => {
Err(oops!(
"Permission denied: /etc/hosts",
std::io::Error::new(std::io::ErrorKind::PermissionDenied, "Access denied")
))
}
"autocorrect_syntax_error" => {
Err(validation_error!(
"json_syntax",
"Invalid JSON syntax at line 5: unexpected token"
))
}
"autocorrect_missing_dependency" => {
Err(validation_error!(
"missing_dependency",
"failed to resolve: use of undeclared crate or module `serde`"
))
}
_ => {
Err(validation_error!(
"operation_type",
&format!("Unknown operation type: '{}'. Supported types: file_read, file_write, network_get, parse_json, math_compute, db_connect, validate_email, system_info, async_task, business_process, recovery_success, etc.", operation_type)
))
}
}
}
#[cfg(not(test))]
fn main() -> Result<()> {
println!("🚀 === The Ultimate Decrust M.A.R.S. Auto-Correction Example === 🚀");
println!(" One import: use decrust::*;");
println!(" One macro: decrust!(any_operation())");
println!(" Handles ANY operation automatically!\n");
println!("1. 🎯 Testing successful operation:");
let result = decrust!(risky_operation());
match result {
Ok(value) => println!(" ✅ Success: {}", value),
Err(e) => println!(" ❌ Error: {}", e),
}
println!("\n2. 🔍 Testing validation error:");
let result = decrust!(failing_operation());
match result {
Ok(value) => println!(" ✅ Success: {}", value),
Err(e) => println!(" 🤖 M.A.R.S. Analysis: {}", e),
}
println!("\n3. 🌐 Testing network error:");
let result = decrust!(network_simulation());
match result {
Ok(value) => println!(" ✅ Success: {}", value),
Err(e) => println!(" 🤖 M.A.R.S. Analysis: {}", e),
}
println!("\n4. 📁 Testing file operations:");
let operations = ["file_read", "file_write"];
for op in &operations {
let result = decrust!(any_operation(op));
match result {
Ok(value) => println!(" ✅ {}: {}", op, value),
Err(e) => println!(" 🤖 M.A.R.S. Analysis: {}", e),
}
}
println!("\n5. 🤖 Testing M.A.R.S. Auto-Correction:");
let autocorrect_operations = [
"autocorrect_unused_import",
"autocorrect_missing_file",
"autocorrect_syntax_error",
];
for op in &autocorrect_operations {
println!(" 🔧 Testing M.A.R.S. auto-correction for: {}", op);
let result = decrust!(any_operation(op));
match result {
Ok(value) => println!(" ✅ {}: {}", op, value),
Err(e) => {
println!(" 🤖 M.A.R.S. Analysis: {}", e);
println!(" 💡 Auto-correction suggestions should appear above");
}
}
println!();
}
println!("\n🎉 === ULTIMATE Decrust Error-Handling Example Complete! === 🎉");
println!("✅ The vision works! One import, one macro, handles EVERYTHING!");
println!("🚀 any_operation() demonstrates true universality with M.A.R.S. auto-correction!");
Ok(())
}