### Example: Simple Spawn and Join Source: https://docs.rs/procspawn/latest/procspawn/fn.init.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates basic usage of procspawn: initializing, spawning a process that performs a calculation, and joining to get the result. ```rust fn main() { procspawn::init(); let handle = spawn((1, 2), |(a, b)| { println!("in process: {:?} {:?}", a, b); a + b }); println!("result: {}", handle.join().unwrap()); } ``` -------------------------------- ### Example: Killing a Process Source: https://docs.rs/procspawn/latest/procspawn/fn.init.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates initializing procspawn and then killing a spawned process. ```rust fn main() { procspawn::init(); let mut handle = spawn((), |()| loop {}); handle.kill().unwrap(); } ``` -------------------------------- ### Example Usage of a Function Source: https://docs.rs/procspawn/latest/scrape-examples-help.html An example demonstrating how to call a function from another crate. ```Rust // examples/ex.rs fn main() { a_crate::a_func(); } ``` -------------------------------- ### Example Usage of procspawn::spawn Source: https://docs.rs/procspawn/latest/src/procspawn/proc.rs.html?search=std%3A%3Avec Demonstrates calling `procspawn::init()` and then spawning a process to execute a function and retrieve its result. ```rust /// call this early in your main() function. This is where all spawned /// functions will be invoked. procspawn::init(); let data = vec![1, 2, 3, 4]; let handle = procspawn::spawn(data, |data| { println!("Received data {:?}", &data); data.into_iter().sum::() }); let result = handle.join().unwrap(); ``` -------------------------------- ### Example: Using the `spawn!` Macro Source: https://docs.rs/procspawn/latest/procspawn/fn.init.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to use the `spawn!` macro for spawning processes, including variable capture and mutable variable modification. ```rust fn main() { procspawn::init(); let a = 42u32; let b = 23u32; let c = 1; let handle = spawn!((a => new_name1, b, mut c) || -> Result<_, ()> { c += 1; Ok(new_name1 + b + c) }); let value = handle.join().unwrap(); println!("{:?}", value); } ``` -------------------------------- ### Example: Timeout on Join Source: https://docs.rs/procspawn/latest/procspawn/fn.init.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates initializing procspawn and using `join_timeout` to limit the waiting time for a spawned process. ```rust fn main() { procspawn::init(); let mut handle = spawn((), |()| { thread::sleep(Duration::from_secs(10)); }); println!("result: {:?}", handle.join_timeout(Duration::from_secs(1))); } ``` -------------------------------- ### Initialize procspawn with a timeout example Source: https://docs.rs/procspawn/latest/procspawn/fn.init.html Illustrates initializing procspawn and spawning a process that sleeps for an extended period, then demonstrating the use of `join_timeout`. ```rust fn main() { procspawn::init(); let mut handle = spawn((), |()| { thread::sleep(Duration::from_secs(10)); }); println!("result: {:?}", handle.join_timeout(Duration::from_secs(1))); } ``` -------------------------------- ### Create Default ProcConfig Source: https://docs.rs/procspawn/latest/procspawn/struct.ProcConfig.html?search= Initializes a ProcConfig with default settings. This is the starting point for configuring a process. ```rust pub fn new() -> ProcConfig ``` -------------------------------- ### Join a spawned process and get its result Source: https://docs.rs/procspawn/latest/procspawn/struct.JoinHandle.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to wait for a spawned process to complete and retrieve its return value using the `join` method. This is the primary way to get results from child processes. ```rust fn main() { procspawn::init(); let handle = spawn((), |()| std::env::args().collect::>()); let args = handle.join().unwrap(); println!("args in subprocess: {:?}", args); } ``` ```rust fn main() { procspawn::init(); let handle = spawn((1, 2), |(a, b)| { println!("in process: {:?} {:?}", a, b); a + b }); println!("result: {}", handle.join().unwrap()); } ``` ```rust fn main() { procspawn::init(); let a = 42u32; let b = 23u32; let c = 1; let handle = spawn!((a => new_name1, b, mut c) || -> Result<_, ()> { c += 1; Ok(new_name1 + b + c) }); let value = handle.join().unwrap(); println!("{:?}", value); } ``` ```rust fn main() { procspawn::init(); let bytes = MyBytes::open("Cargo.toml").unwrap(); let bytes_two = procspawn::spawn!((bytes.clone() => bytes) || { println!("length: {}", bytes.bytes.len()); bytes }) .join() .unwrap(); assert_eq!(bytes, bytes_two); } ``` ```rust fn main() { procspawn::init(); let five = spawn(5, fibonacci); let ten = spawn(10, fibonacci); let thirty = spawn(30, fibonacci); assert_eq!(five.join().unwrap(), 5); assert_eq!(ten.join().unwrap(), 55); assert_eq!(thirty.join().unwrap(), 832_040); println!("Successfully calculated fibonacci values!"); } ``` ```rust fn main() { procspawn::init(); let handle = spawn((), |()| { panic!("Whatever!"); }); match handle.join() { Ok(()) => unreachable!(), Err(err) => { let panic = err.panic_info().expect("got a non panic error"); println!("process panicked with {}", panic.message()); println!("{:#?}", panic); } } } ``` -------------------------------- ### Example: Custom Serialization with `spawn!` Macro Source: https://docs.rs/procspawn/latest/procspawn/fn.init.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates using the `spawn!` macro with custom types that implement serialization, ensuring data can be passed between processes. ```rust fn main() { procspawn::init(); let bytes = MyBytes::open("Cargo.toml").unwrap(); let bytes_two = procspawn::spawn!((bytes.clone() => bytes) || { println!("length: {}", bytes.bytes.len()); bytes }) .join() .unwrap(); assert_eq!(bytes, bytes_two); } ``` -------------------------------- ### Basic Process Spawning Configuration Source: https://docs.rs/procspawn/latest/src/procspawn/proc.rs.html?search=u32+-%3E+bool Initializes a new `Builder` for spawning a process. This is the starting point for configuring process execution. ```rust impl Builder { /// Generates the base configuration for spawning a thread, from which /// configuration methods can be chained. pub fn new() -> Self { Self { stdin: None, stdout: None, stderr: None, common: ProcCommon::default(), } } pub(crate) fn common(&mut self, common: ProcCommon) -> &mut Self { self.common = common; self } define_common_methods!(); /// Captures the `stdin` of the spawned process, allowing you to manually /// send data via `JoinHandle::stdin` pub fn stdin>(&mut self, cfg: T) -> &mut Self { self.stdin = Some(cfg.into()); self } /// Captures the `stdout` of the spawned process, allowing you to manually /// receive data via `JoinHandle::stdout` pub fn stdout>(&mut self, cfg: T) -> &mut Self { self.stdout = Some(cfg.into()); self } /// Captures the `stderr` of the spawned process, allowing you to manually /// receive data via `JoinHandle::stderr` pub fn stderr>(&mut self, cfg: T) -> &mut Self { self.stderr = Some(cfg.into()); self } } ``` -------------------------------- ### Binary Search By Example Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html Demonstrates using binary_search_by with a custom comparator function to search within a sorted slice. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let seek = 13; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9)); let seek = 4; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7)); let seek = 100; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13)); let seek = 1; let r = s.binary_search_by(|probe| probe.cmp(&seek)); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### mark_initialized Source: https://docs.rs/procspawn/latest/src/procspawn/core.rs.html?search= Marks the procspawn system as initialized. This should be called to indicate that the necessary setup for spawning processes has been completed. ```APIDOC ## mark_initialized ### Description Marks the procspawn system as initialized. ### Method `fn mark_initialized()` ``` -------------------------------- ### Rust binary_search Example Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates using `binary_search` to find elements in a sorted slice. Shows successful lookups, failed lookups, and handling of multiple matches. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); assert_eq!(s.binary_search(&4), Err(7)); assert_eq!(s.binary_search(&100), Err(13)); let r = s.binary_search(&1); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Binary Search Example Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html Demonstrates basic binary search operations on a sorted slice, including finding an element, handling not found cases, and checking for multiple matches. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); assert_eq!(s.binary_search(&4), Err(7)); assert_eq!(s.binary_search(&100), Err(13)); let r = s.binary_search(&1); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Spawn Function with Tuple Arguments Source: https://docs.rs/procspawn/latest/procspawn/macro.spawn.html Example of using the spawn macro to spawn a function with tuple arguments, including mutable aliasing. ```rust let a = 42u32; let b = 23u32; let handle = procspawn::spawn!((a, mut b) || { b += 1; a + b }); ``` -------------------------------- ### Simple Spawned Function with Return Value Source: https://docs.rs/procspawn/latest/procspawn/fn.spawn.html?search=std%3A%3Avec A basic example of spawning a function that takes two arguments and returns their sum. `procspawn::init()` is required. ```rust procspawn::init(); let handle = spawn((1, 2), |(a, b)| { println!("in process: {:?} {:?}", a, b); a + b }); println!("result: {}", handle.join().unwrap()); ``` -------------------------------- ### Basic Procspawn Usage Source: https://docs.rs/procspawn/latest/src/simple/simple.rs.html?search= Initializes procspawn, spawns a process to perform a calculation, and joins the process to get the result. Ensure procspawn::init() is called before spawning any processes. ```Rust use procspawn::{self, spawn}; fn main() { procspawn::init(); let handle = spawn((1, 2), |(a, b)| { println!("in process: {:?} {:?}", a, b); a + b }); println!("result: {}", handle.join().unwrap()); } ``` -------------------------------- ### Join a Child Process with Custom Serialization Source: https://docs.rs/procspawn/latest/procspawn/struct.JoinHandle.html Demonstrates spawning a process that serializes and deserializes a custom type (`MyBytes`). This example highlights the flexibility of `procspawn` with custom data structures. ```rust 71fn main() { 72 procspawn::init(); 73 74 let bytes = MyBytes::open("Cargo.toml").unwrap(); 75 76 let bytes_two = procspawn::spawn!((bytes.clone() => bytes) || { 77 println!("length: {}", bytes.bytes.len()); 78 bytes 79 }) 80 .join() 81 .unwrap(); 82 83 assert_eq!(bytes, bytes_two); 84} ``` -------------------------------- ### Get Element Index by Pointer Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html Use `element_offset` to find the index of an element within a slice using its memory address. This method relies on pointer arithmetic and does not compare elements. It returns `None` if the pointer is not aligned to the start of an element. ```Rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```Rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Basic Builder Usage with Stdout Capture Source: https://docs.rs/procspawn/latest/procspawn/struct.Builder.html?search=u32+-%3E+bool Demonstrates initializing procspawn, creating a Builder, configuring stdout to be piped, spawning a process, and reading its output. ```rust 4fn main() { procspawn::init(); let mut builder = procspawn::Builder::new(); builder.stdout(Stdio::piped()); let mut handle = builder.spawn((1, 2), |(a, b)| { println!("{:?} {:?}", a, b); }); let mut s = String::new(); handle.stdout().unwrap().read_to_string(&mut s).unwrap(); assert_eq!(s, "1 2\n"); } ``` -------------------------------- ### Join a spawned process to get its result Source: https://docs.rs/procspawn/latest/procspawn/struct.JoinHandle.html?search=u32+-%3E+bool Demonstrates how to wait for a spawned process to complete and retrieve its return value using the `join` method. This is the primary way to get results from child processes. ```rust fn main() { procspawn::init(); let handle = spawn((), |()| std::env::args().collect::>()); let args = handle.join().unwrap(); println!("args in subprocess: {:?}", args); } ``` ```rust fn main() { procspawn::init(); let handle = spawn((1, 2), |(a, b)| { println!("in process: {:?} {:?}", a, b); a + b }); println!("result: {}", handle.join().unwrap()); } ``` ```rust fn main() { procspawn::init(); let a = 42u32; let b = 23u32; let c = 1; let handle = spawn!((a => new_name1, b, mut c) || -> Result<_, ()> { c += 1; Ok(new_name1 + b + c) }); let value = handle.join().unwrap(); println!("{:?}", value); } ``` ```rust fn main() { procspawn::init(); let bytes = MyBytes::open("Cargo.toml").unwrap(); let bytes_two = procspawn::spawn!((bytes.clone() => bytes) || { println!("length: {}", bytes.bytes.len()); bytes }) .join() .unwrap(); assert_eq!(bytes, bytes_two); } ``` ```rust fn main() { procspawn::init(); let five = spawn(5, fibonacci); let ten = spawn(10, fibonacci); let thirty = spawn(30, fibonacci); assert_eq!(five.join().unwrap(), 5); assert_eq!(ten.join().unwrap(), 55); assert_eq!(thirty.join().unwrap(), 832_040); println!("Successfully calculated fibonacci values!"); } ``` -------------------------------- ### type_id Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the `TypeId` of the Shmem value. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Returns - `TypeId`: The type identifier of the value. ``` -------------------------------- ### starts_with Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html Checks if the slice starts with a given prefix. ```APIDOC ## pub fn starts_with(&self, needle: &[T]) -> bool ### Description Returns `true` if `needle` is a prefix of the slice or equal to the slice. ### Parameters #### Path Parameters - `needle` (&[T]) - Required - The slice to check as a prefix. ### Returns - `bool` - `true` if the slice starts with `needle`, `false` otherwise. ``` -------------------------------- ### Initialize procspawn and perform a simple calculation Source: https://docs.rs/procspawn/latest/procspawn/fn.init.html Shows how to initialize procspawn and spawn a process that performs a simple addition after printing its received arguments. ```rust fn main() { procspawn::init(); let handle = spawn((1, 2), |(a, b)| { println!("in process: {:?} {:?}", a, b); a + b }); println!("result: {}", handle.join().unwrap()); } ``` -------------------------------- ### iter Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html Returns an iterator over the slice, yielding all items from start to end. ```APIDOC ## pub fn iter(&self) -> Iter<'_, T> ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ##### §Examples ``` let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` ``` -------------------------------- ### Initialize procspawn and collect arguments Source: https://docs.rs/procspawn/latest/procspawn/fn.init.html Demonstrates initializing procspawn and then spawning a process that collects and returns its command-line arguments. ```rust fn main() { procspawn::init(); let handle = spawn((), |()| std::env::args().collect::>()); let args = handle.join().unwrap(); println!("args in subprocess: {:?}", args); } ``` -------------------------------- ### ProcConfig::init Source: https://docs.rs/procspawn/latest/procspawn/struct.ProcConfig.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Consumes the configuration and initializes the process according to the settings. ```APIDOC ## ProcConfig::init ### Description Consumes the config and initializes the process. ### Method `init(&mut self)` ``` -------------------------------- ### ProcConfig::init Source: https://docs.rs/procspawn/latest/procspawn/struct.ProcConfig.html Consumes the ProcConfig and initializes the process with the configured settings. ```APIDOC ## ProcConfig::init ### Description Consumes the config and initializes the process with the specified configuration. ### Method `init(&mut self)` ### Returns This method does not return a value. ``` -------------------------------- ### Iterate Over Slice Elements Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html Provides an iterator that yields all items from the start to the end of the slice. ```Rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### Basic Spawn and Join Source: https://docs.rs/procspawn/latest/procspawn/fn.spawn.html?search=u32+-%3E+bool Demonstrates the basic usage of `procspawn::spawn` to run a function in a new process and retrieve its result using `join()`. ```rust pub fn spawn( args: A, f: fn(A) -> R, ) -> JoinHandle ``` ```rust // call this early in your main() function. This is where all spawned // functions will be invoked. procspawn::init(); let data = vec![1, 2, 3, 4]; let handle = procspawn::spawn(data, |data| { println!("Received data {:?}", &data); data.into_iter().sum::() }); let result = handle.join().unwrap(); ``` -------------------------------- ### Get Stderr Handle Source: https://docs.rs/procspawn/latest/src/procspawn/proc.rs.html?search=std%3A%3Avec Fetches the `stderr` handle if it has been captured. Returns None for pooled handles. ```rust pub fn stderr(&mut self) -> Option<&mut ChildStderr> { match self.inner { Ok(JoinHandleInner::Process(ref mut process)) => process.stderr(), Ok(JoinHandleInner::Pooled(..)) => None, Err(_) => None, } } ``` -------------------------------- ### Get Stdin Handle Source: https://docs.rs/procspawn/latest/src/procspawn/proc.rs.html?search=std%3A%3Avec Fetches the `stdin` handle if it has been captured. Returns None for pooled handles. ```rust pub fn stdin(&mut self) -> Option<&mut ChildStdin> { match self.inner { Ok(JoinHandleInner::Process(ref mut process)) => process.stdin(), Ok(JoinHandleInner::Pooled(..)) => None, Err(_) => None, } } ``` -------------------------------- ### ProcConfig::init Source: https://docs.rs/procspawn/latest/procspawn/struct.ProcConfig.html?search= Consumes the configuration and initializes the process according to the specified settings. ```APIDOC ## ProcConfig::init ### Description Consumes the config and initializes the process. ### Method ```rust pub fn init(&mut self) ``` ### Returns This method consumes the `ProcConfig` instance. ``` -------------------------------- ### Initialize procspawn Source: https://docs.rs/procspawn/latest/procspawn/fn.init.html This is the basic initialization required for procspawn. It must be called once at the start of your main function. ```rust fn main() { procspawn::init(); let mut handle = spawn((), |()| loop {}); handle.kill().unwrap(); } ``` -------------------------------- ### Basic Panic Handling with procspawn Source: https://docs.rs/procspawn/latest/procspawn/struct.PanicInfo.html?search=u32+-%3E+bool Demonstrates how to spawn a task that panics and then catch the panic information using `handle.join()` and `err.panic_info()`. ```rust use procspawn; use std::thread; use std::time::Duration; fn main() { procspawn::init(); let handle = spawn((), |()| { panic!("Whatever!"); }); match handle.join() { Ok(()) => unreachable!(), Err(err) => { let panic = err.panic_info().expect("got a non panic error"); println!("process panicked with {}", panic.message()); println!("{:#?}", panic); } } } ``` -------------------------------- ### as_array Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html Gets a reference to the underlying array. Returns `None` if `N` is not exactly equal to the length of `self`. ```APIDOC ## pub fn as_array(&self) -> Option<&[T; N]> ### Description Gets a reference to the underlying array. If `N` is not exactly equal to the length of `self`, then this method returns `None`. ``` -------------------------------- ### get Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html Returns a reference to an element or subslice depending on the type of index. Returns `None` if the index is out of bounds. ```APIDOC ## pub fn get(&self, index: I) -> Option<&>::Output> ### Description Returns a reference to an element or subslice depending on the type of index. * If given a position, returns a reference to the element at that position or `None` if out of bounds. * If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ### Examples ``` let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` ``` -------------------------------- ### Handling Panics in Spawned Processes Source: https://docs.rs/procspawn/latest/procspawn/fn.spawn.html?search=std%3A%3Avec Shows how to spawn a process that intentionally panics and how to catch and inspect the panic information. `procspawn::init()` is required. ```rust procspawn::init(); let handle = spawn((), |()| { panic!("Whatever!"); }); match handle.join() { Ok(()) => unreachable!(), Err(err) => { let panic = err.panic_info().expect("got a non panic error"); println!("process panicked with {}", panic.message()); println!("{:#?}", panic); } } ``` -------------------------------- ### Get Last Element of a Slice Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html Retrieves the last element of a slice. Returns `None` if the slice is empty. ```Rust let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` -------------------------------- ### Initialize procspawn with custom serialization using spawn! macro Source: https://docs.rs/procspawn/latest/procspawn/fn.init.html Shows how to initialize procspawn and use the `procspawn::spawn!` macro with custom types that require specific serialization handling. ```rust fn main() { procspawn::init(); let bytes = MyBytes::open("Cargo.toml").unwrap(); let bytes_two = procspawn::spawn!((bytes.clone() => bytes) || { println!("length: {}", bytes.bytes.len()); bytes }) .join() .unwrap(); assert_eq!(bytes, bytes_two); } ``` -------------------------------- ### Get Length of Shmem Slice Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html The `len` method returns the number of elements in the `Shmem` byte slice. ```rust pub fn len(&self) -> usize ``` ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### init Source: https://docs.rs/procspawn/latest/index.html Initializes the procspawn library. This function must be called before using other procspawn functionalities. ```APIDOC ## init ### Description Initializes procspawn. ### Method Not applicable (function call) ### Parameters None ### Request Example init() ### Response None ``` -------------------------------- ### strip_prefix Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html Returns a subslice with the prefix removed if the slice starts with the specified prefix. Returns None otherwise. ```APIDOC ## pub fn strip_prefix

(&self, prefix: &P) -> Option<&[T]> ### Description Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ### Parameters #### Path Parameters - `prefix`: The pattern to strip from the beginning of the slice. ### Response - `Some(&[T])`: If the slice starts with the prefix, returns the remaining subslice. - `None`: If the slice does not start with the prefix. ### Examples ```rust let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` ``` -------------------------------- ### ProcConfig::new Source: https://docs.rs/procspawn/latest/procspawn/struct.ProcConfig.html Creates a default ProcConfig instance. ```APIDOC ## ProcConfig::new ### Description Creates a default proc config. ### Method `new()` ### Returns - `ProcConfig`: A new ProcConfig instance with default settings. ``` -------------------------------- ### ProcConfig::new Source: https://docs.rs/procspawn/latest/procspawn/struct.ProcConfig.html?search= Creates a new ProcConfig with default settings. ```APIDOC ## ProcConfig::new ### Description Creates a default proc config. ### Method ``` pub fn new() -> ProcConfig ``` ### Returns A new `ProcConfig` instance with default values. ``` -------------------------------- ### ProcConfig::new Source: https://docs.rs/procspawn/latest/procspawn/struct.ProcConfig.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new ProcConfig with default settings. ```APIDOC ## ProcConfig::new ### Description Creates a default proc config. ### Method `new()` ### Returns A new `ProcConfig` instance. ``` -------------------------------- ### Get Process ID Source: https://docs.rs/procspawn/latest/src/procspawn/proc.rs.html?search=std%3A%3Avec Returns the process ID if available. The PID is unavailable for pooled calls that are not yet scheduled. ```rust pub fn pid(&self) -> Option { self.process_handle_state().and_then(|x| x.pid()) } ``` -------------------------------- ### Initialize and Spawn Process with Piped Stdout Source: https://docs.rs/procspawn/latest/procspawn/struct.Builder.html?search= Initializes procspawn and creates a Builder to configure a spawned process. It sets stdout to be piped, spawns a closure, and then reads the output from the spawned process. ```rust 4fn main() { 5 procspawn::init(); 6 7 let mut builder = procspawn::Builder::new(); 8 builder.stdout(Stdio::piped()); 9 10 let mut handle = builder.spawn((1, 2), |(a, b)| { 11 println!("{:?} {:?}", a, b); 12 }); 13 14 let mut s = String::new(); 15 handle.stdout().unwrap().read_to_string(&mut s).unwrap(); 16 assert_eq!(s, "1 2\n"); 17} ``` -------------------------------- ### Getting Process ID Source: https://docs.rs/procspawn/latest/src/procspawn/proc.rs.html Returns the process ID if available. The PID is unavailable for pooled calls that are not yet scheduled. ```rust /// Returns the process ID if available. /// /// The process ID is unavailable when pooled calls are not scheduled to /// processes. pub fn pid(&self) -> Option { self.process_handle_state().and_then(|x| x.pid()) } ``` -------------------------------- ### Basic Panic Handling Source: https://docs.rs/procspawn/latest/procspawn/struct.PanicInfo.html Demonstrates how to catch a panic from a spawned process using `procspawn::spawn` and access its `PanicInfo` to print the panic message and details. ```rust use procspawn; use std::thread; fn main() { procspawn::init(); let handle = spawn((), |()| { panic!("Whatever!"); }); match handle.join() { Ok(()) => unreachable!(), Err(err) => { let panic = err.panic_info().expect("got a non panic error"); println!("process panicked with {}", panic.message()); println!("{:#?}", panic); } } } ``` -------------------------------- ### Configure Panic Handling Source: https://docs.rs/procspawn/latest/procspawn/struct.ProcConfig.html?search= Enables or disables the automatic catching of panics and installation of a panic handler. Defaults to enabled. ```rust pub fn panic_handling(&mut self, enabled: bool) -> &mut Self ``` -------------------------------- ### Handling Panics in Spawned Processes Source: https://docs.rs/procspawn/latest/procspawn/fn.spawn.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates how to spawn a process that intentionally panics and how to catch and inspect the panic information from the `JoinHandle`. `procspawn::init()` is required. ```rust fn main() { procspawn::init(); let handle = spawn((), |()| { panic!("Whatever!"); }); match handle.join() { Ok(()) => unreachable!(), Err(err) => { let panic = err.panic_info().expect("got a non panic error"); println!("process panicked with {}", panic.message()); println!("{:#?}", panic); } } } ``` -------------------------------- ### ProcConfig: Initialize Process Source: https://docs.rs/procspawn/latest/src/procspawn/core.rs.html?search=u32+-%3E+bool Consumes the configuration and initializes the process. This should be called once. ```rust pub fn init(&mut self) { mark_initialized(); PASS_ARGS.store(self.pass_args, Ordering::SeqCst); if let Ok(token) = env::var(ENV_NAME) { // permit nested invocations std::env::remove_var(ENV_NAME); if let Some(callback) = self.callback.take() { callback(); } bootstrap_ipc(token, self); } } ``` -------------------------------- ### Access Shmem Buffer as Bytes Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html Use `as_bytes` to get a read-only slice of the bytes contained within the `Shmem` buffer. ```rust pub fn as_bytes(&self) -> &[u8] ``` -------------------------------- ### procspawn::spawn Source: https://docs.rs/procspawn/latest/src/procspawn/proc.rs.html?search=u32+-%3E+bool Spawns a new process to run a function with a given payload. This is the primary function for starting new processes. ```APIDOC ## procspawn::spawn ### Description Spawns a new process to run a function with some payload. This function should be called early in `main()` as it initializes the system for handling spawned functions. ### Method Public ### Endpoint N/A ### Parameters - **args** (`A: Serialize + DeserializeOwned`): The payload to be sent to the spawned function. - **f** (`fn(A) -> R`): The function to be executed in the new process. ### Response - `JoinHandle`: A handle to the spawned process, which can be used to wait for its result or manage its lifecycle. ``` -------------------------------- ### procspawn::init Source: https://docs.rs/procspawn/latest/procspawn/fn.init.html?search=u32+-%3E+bool Initializes procspawn. This function must be called at the beginning of `main`. Whatever comes before it is also executed for all processes spawned through the `spawn` function. ```APIDOC ## Function init ### Description Initializes procspawn. This function must be called at the beginning of `main`. Whatever comes before it is also executed for all processes spawned through the `spawn` function. For more complex initializations see `ProcConfig`. ### Signature ```rust pub fn init() ``` ### Examples #### Basic Initialization ```rust fn main() { procspawn::init(); // ... rest of your code that spawns processes } ``` #### Initialization with a simple spawn ```rust fn main() { procspawn::init(); let handle = procspawn::spawn((), |()| { println!("In subprocess"); 42 }); let result = handle.join().unwrap(); println!("Result: {}", result); } ``` ``` -------------------------------- ### procspawn::init Source: https://docs.rs/procspawn/latest/procspawn/fn.init.html Initializes procspawn. This function must be called at the beginning of `main`. Whatever comes before it is also executed for all processes spawned through the `spawn` function. For more complex initializations see `ProcConfig`. ```APIDOC ## init ### Description Initializes procspawn. This function must be called at the beginning of `main`. Whatever comes before it is also executed for all processes spawned through the `spawn` function. For more complex initializations see `ProcConfig`. ### Signature ```rust pub fn init() ``` ### Examples #### Basic Usage ```rust fn main() { procspawn::init(); // ... rest of your code } ``` #### Example with `spawn` ```rust fn main() { procspawn::init(); let mut handle = procspawn::spawn((), |()| loop {}); handle.kill().unwrap(); } ``` #### Example with arguments and return value ```rust fn main() { procspawn::init(); let handle = procspawn::spawn((1, 2), |(a, b)| { a + b }); let result = handle.join().unwrap(); println!("result: {}", result); } ``` ``` -------------------------------- ### ProcConfig: Panic Handling Source: https://docs.rs/procspawn/latest/src/procspawn/core.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Configures the automatic panic handling mechanism. The default behavior is to catch panics and install a handler. ```rust pub fn panic_handling(&mut self, enabled: bool) -> &mut Self { self.panic_handling = enabled; self } ``` -------------------------------- ### Handling Potential Overflow with `repeat` Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html?search=std%3A%3Avec Provides an example of a panic that occurs when `repeat` is called with a value that would cause capacity overflow. ```rust // this will panic at runtime b"0123456789abcdef".repeat(usize::MAX); ``` -------------------------------- ### Spawn Process with Arguments and Function Source: https://docs.rs/procspawn/latest/src/procspawn/proc.rs.html?search=std%3A%3Avec Spawns a new process with the configured settings, passing arguments and a function to be executed within the new process. Returns a `JoinHandle` for the spawned process. ```rust pub fn spawn( &mut self, args: A, func: fn(A) -> R, ) -> JoinHandle { assert_spawn_okay(); JoinHandle { inner: mem::take(self) .spawn_helper(args, func) .map(JoinHandleInner::Process), } } ``` -------------------------------- ### Spawn Function in a Pool Source: https://docs.rs/procspawn/latest/procspawn/macro.spawn.html Example of using the spawn macro to spawn a function within a specified pool, handling tuple arguments. ```rust let a = 42u32; let b = 23u32; let handle = procspawn::spawn!(in pool, (a, mut b) || { b += 1; a + b }); ``` -------------------------------- ### ProcConfig Methods Source: https://docs.rs/procspawn/latest/procspawn/struct.ProcConfig.html?search=u32+-%3E+bool This section details the methods available on the ProcConfig struct for configuring process spawning. These methods allow for customization of arguments, panic handling, backtrace capturing, and initialization callbacks. ```APIDOC ## ProcConfig ### Description Can be used to configure the process. ### Methods #### `new()` Creates a default proc config. #### `config_callback(&mut self, f: F) -> &mut Self` Attaches a callback that is used to initializes all processes. #### `pass_args(&mut self, enabled: bool) -> &mut Self` Enables or disables argument passing. By default all arguments are forwarded to the spawned process. #### `panic_handling(&mut self, enabled: bool) -> &mut Self` Configure the automatic panic handling. The default behavior is that panics are caught and that a panic handler is installed. #### `capture_backtraces(&mut self, enabled: bool) -> &mut Self` Configures if backtraces should be captured. The default behavior is that if panic handling is enabled backtraces will be captured. This requires the `backtrace` feature. #### `resolve_backtraces(&mut self, enabled: bool) -> &mut Self` Controls whether backtraces should be resolved. #### `init(&mut self)` Consumes the config and initializes the process. ``` -------------------------------- ### Capture stdout from spawned process Source: https://docs.rs/procspawn/latest/src/stdout/stdout.rs.html This snippet shows how to initialize procspawn, set up a builder to capture stdout, spawn a closure, and read the captured output. Ensure procspawn is initialized before spawning. ```rust use std::io::Read; use std::process::Stdio; fn main() { procspawn::init(); let mut builder = procspawn::Builder::new(); builder.stdout(Stdio::piped()); let mut handle = builder.spawn((1, 2), |(a, b)| { println!("{:?} {:?}", a, b); }); let mut s = String::new(); handle.stdout().unwrap().read_to_string(&mut s).unwrap(); assert_eq!(s, "1 2\n"); } ``` -------------------------------- ### Helper Function for Spawning Process Source: https://docs.rs/procspawn/latest/src/procspawn/proc.rs.html?search= Internal helper to manage the process spawning logic, including IPC setup and command configuration. ```rust fn spawn_helper( self, args: A, func: fn(A) -> R, ) -> Result, SpawnError> { let (server, token) = IpcOneShotServer::>::new()?; let me = if cfg!(target_os = "linux") { // will work even if exe is moved let path: PathBuf = "/proc/self/exe".into(); if path.is_file() { path } else { // might not exist, e.g. on chroot env::current_exe()? } } else { env::current_exe()? }; let mut child = process::Command::new(me); child.envs(self.common.vars); child.env(ENV_NAME, token); #[cfg(unix)] { use std::os::unix::process::CommandExt; if let Some(id) = self.common.uid { child.uid(id); } if let Some(id) = self.common.gid { child.gid(id); } if let Some(ref func) = self.common.pre_exec { let func = func.clone(); unsafe { #[allow(clippy::needless_borrow)] child.pre_exec(move || (&mut *func.lock().unwrap())()); } } } let (can_pass_args, should_silence_stdout) = { #[cfg(feature = "test-support")] { match crate::testsupport::update_command_for_tests(&mut child) { None => (true, false), Some(crate::testsupport::TestMode { can_pass_args, should_silence_stdout, }) => (can_pass_args, should_silence_stdout), } } #[cfg(not(feature = "test-support"))] { (true, false) } }; if can_pass_args && should_pass_args() { child.args(env::args_os().skip(1)); } if let Some(stdin) = self.stdin { child.stdin(stdin); } if let Some(stdout) = self.stdout { child.stdout(stdout); } else if should_silence_stdout { child.stdout(Stdio::null()); } if let Some(stderr) = self.stderr { child.stderr(stderr); } let process = child.spawn()?; let (_rx, tx) = server.accept()?; let (args_tx, args_rx) = ipc::channel()?; // ... rest of the function unimplemented!() } ``` -------------------------------- ### assert_spawn_okay Source: https://docs.rs/procspawn/latest/src/procspawn/core.rs.html?search=std%3A%3Avec Asserts that the procspawn library has been initialized. If not initialized, it panics. It also checks for safety conditions related to shared libraries. ```APIDOC ## assert_spawn_okay ### Description Asserts that the procspawn library has been initialized. If not initialized, it panics. It also checks for safety conditions related to shared libraries. ### Method `assert_spawn_okay()` ### Returns * `()` - This function does not return a value, but may panic if conditions are not met. ``` -------------------------------- ### Get Last Chunk of a Slice Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html Returns an array reference to the last `N` items in the slice. Returns `None` if the slice is shorter than `N`. ```Rust let u = [10, 40, 30]; assert_eq!(Some(&[40, 30]), u.last_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.last_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.last_chunk::<0>()); ``` -------------------------------- ### ProcConfig: Initialize Process Source: https://docs.rs/procspawn/latest/src/procspawn/core.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Consumes the configuration and initializes the process. This function should be called to set up procspawn's internal state and handle any necessary IPC bootstrapping. ```rust pub fn init(&mut self) { mark_initialized(); PASS_ARGS.store(self.pass_args, Ordering::SeqCst); if let Ok(token) = env::var(ENV_NAME) { // permit nested invocations std::env::remove_var(ENV_NAME); if let Some(callback) = self.callback.take() { callback(); } bootstrap_ipc(token, self); } } ``` -------------------------------- ### Spawn and Kill a Process Source: https://docs.rs/procspawn/latest/src/kill/kill.rs.html?search= This snippet shows how to initialize procspawn, spawn a new process that runs an infinite loop, and then terminate it using the `kill()` method. Ensure `procspawn::init()` is called before spawning any processes. ```rust use procspawn::{self, spawn}; #[allow(clippy::empty_loop)] fn main() { procspawn::init(); let mut handle = spawn((), |()| loop {}); handle.kill().unwrap(); } ``` -------------------------------- ### Get First Chunk of a Slice Source: https://docs.rs/procspawn/latest/procspawn/serde/struct.Shmem.html Returns an array reference to the first `N` items in the slice. Returns `None` if the slice is shorter than `N`. ```Rust let u = [10, 40, 30]; assert_eq!(Some(&[10, 40]), u.first_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.first_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.first_chunk::<0>()); ``` -------------------------------- ### Create and use a process pool Source: https://docs.rs/procspawn/latest/procspawn/struct.Pool.html Demonstrates creating a new process pool, spawning multiple tasks within it, and handling their results or panics. The pool is shut down after all tasks are joined. ```rust fn main() { procspawn::init(); let pool = Pool::new(4).unwrap(); let mut handles = vec![[]]; for counter in 0..8 { handles.push(procspawn::spawn!(in pool, (counter) || { thread::sleep(Duration::from_millis(500)); counter })); } for handle in handles { match handle.join() { Ok(val) => println!("got result: {}", val), Err(err) => { let panic = err.panic_info().expect("got a non panic error"); println!("process panicked with {}", panic.message()); println!("{:#?}", panic); } } } pool.shutdown(); } ``` -------------------------------- ### Join a Process to Get its Result Source: https://docs.rs/procspawn/latest/procspawn/struct.JoinHandle.html?search= Waits for a spawned process to complete and retrieves its return value. This is useful for processes that compute a value and return it. ```rust fn main() { procspawn::init(); let handle = spawn((), |()| std::env::args().collect::>()); let args = handle.join().unwrap(); println!("args in subprocess: {:?}", args); } ``` ```rust fn main() { procspawn::init(); let handle = spawn((1, 2), |(a, b)| { println!("in process: {:?} {:?}", a, b); a + b }); println!("result: {}", handle.join().unwrap()); } ``` ```rust fn main() { procspawn::init(); let five = spawn(5, fibonacci); let ten = spawn(10, fibonacci); let thirty = spawn(30, fibonacci); assert_eq!(five.join().unwrap(), 5); assert_eq!(ten.join().unwrap(), 55); assert_eq!(thirty.join().unwrap(), 832_040); println!("Successfully calculated fibonacci values!"); } ```