/* src */
use log::{Record, Level, Metadata, LevelFilter, SetLoggerError};
use gag::BufferRedirect;
use std::fmt::{Debug};
use std::io::{self, Read, Write};
use std::fs::OpenOptions;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::thread;
use std::fmt::Display;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio; // Asynchronous runtime
use tokio::time::sleep;
use std::error::Error;
use std::str::FromStr;
use anyhow::{Context as AnyhowContext, Result};
/// An asynchronous function that may fail
async fn might_fail(success: bool) -> Result> {
if success {
Ok("Everything went well!".to_string())
} else {
Err("Something went wrong.".into())
}
}
// =============================================================================
// 1. Diverging Functions (Never Type) - Functions that never return
// =============================================================================
/// Diverging function example 1: panic function with where clause
/// This function accepts any displayable type but never returns normally
fn panic_with_message(message: T) -> !
where
T: Display + Send + Sync + 'static,
{
panic!("Critical error: {}", message);
}
/// Diverging function example 2: infinite server loop function
/// This function simulates a server that runs forever
fn run_infinite_server(handler: H) -> !
where
H: Fn(&str) -> String + Send + Sync + 'static,
{
let mut counter = 0;
loop {
counter += 1;
let request = format!("request_{}", counter);
let response = handler(&request);
println!("Processed: {} -> {}", request, response);
// Simulate processing delay
std::thread::sleep(Duration::from_millis(100));
// In real applications, this would be an actual network service loop
if counter >= 5 {
// For demo purposes, we exit after 5 iterations, but the type system considers this unreachable
std::process::exit(0);
}
}
}
/// Diverging function example 3: error handling function
/// Called when encountering unrecoverable errors
fn handle_fatal_error(error: E) -> !
where
E: std::error::Error + Display + Send + Sync + 'static,
{
eprintln!("Fatal error occurred: {}", error);
eprintln!("Stack trace: {:?}", std::backtrace::Backtrace::capture());
std::process::exit(1);
}
// =============================================================================
// 2. Async Functions - Automatically wrapped in Future
// =============================================================================
/// Async function example 1: simple async computation
/// Return type automatically becomes impl Future