### expect example: panic on Err Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Demonstrates expect, which returns the Ok value or panics with a message. The first example shows a panic on Err, and the second shows a recommended message style for environment variables. ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### inspect example: parse and inspect Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Demonstrates inspect, which calls a closure with a reference to the Ok value and returns the original result. The example chains parse, inspect, map, and expect. ```rust let x: u8 = "4" .parse::() .inspect(|x| println!("original: {x}")) .map(|x| x.pow(3)) .expect("literal `4` should parse as a `u8`"); ``` -------------------------------- ### downgrade example: break reference cycle with weak handle Source: https://docs.rs/calloop/latest/calloop/struct.LoopHandle.html Example for the `downgrade` method. It creates a weak handle to the loop data and upgrades it inside a timer callback to break a reference cycle. Requires the `calloop` crate with the `timer` module. ```rust use calloop::timer::{TimeoutAction, Timer}; use calloop::EventLoop; let event_loop: EventLoop<()> = EventLoop::try_new().unwrap(); let weak_handle = event_loop.handle().downgrade(); event_loop .handle() .insert_source(Timer::immediate(), move |_, _, _| { // Hold its weak handle in the event loop's callback to break the reference cycle. let handle = weak_handle.upgrade().unwrap(); // Use the upgraded handle later... TimeoutAction::Drop }) .unwrap(); ``` -------------------------------- ### Example for Result::is_ok Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Demonstrates checking if a `Result` is `Ok`. ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` -------------------------------- ### Example for Result::is_ok_and Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Demonstrates checking if a `Result` is `Ok` and the value matches a predicate. ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### iter example: iterate over Ok value Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Demonstrates iter, which returns an iterator over the possibly contained value. The example shows that it yields one value for Ok and none for Err. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Example for Result::transpose Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Demonstrates transposing a `Result` of an `Option` into an `Option` of a `Result`. ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result, SomeErr> = Ok(Some(5)); let y: Option> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### batch_register usage example Source: https://docs.rs/calloop/latest/calloop/macro.batch_register.html Usage example of the batch_register macro. It registers four event sources with the given poll and token factory. Note that there is no scope for customization; if you need special handling for a source, leave it off the list. Error handling is try-or-early-return in the order sources are listed. ```rust calloop::batch_register!( poll, token_factory, self.source_one, self.source_two, self.source_three, self.source_four, ) ``` -------------------------------- ### Example for Result::copied on &mut T Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Demonstrates using `copied` on a `Result<&mut T, E>` to copy the `Ok` value. ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` -------------------------------- ### Example for Result::cloned on &mut T Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Demonstrates using `cloned` on a `Result<&mut T, E>` to clone the `Ok` value. ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### as_deref example: deref Ok value Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Demonstrates as_deref, which converts Result to Result<&T::Target, &E> by dereferencing the Ok value. The example shows both Ok and Err cases. ```rust let x: Result = Ok("hello".to_string()); let y: Result<&str, &u32> = Ok("hello"); assert_eq!(x.as_deref(), y); let x: Result = Err(42); let y: Result<&str, &u32> = Err(&42); assert_eq!(x.as_deref(), y); ``` -------------------------------- ### Example for Result::cloned on &T Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Demonstrates using `cloned` to map a `Result<&T, E>` to `Result` by cloning the `Ok` value. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### Example for Result::flatten Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Demonstrates flattening a `Result, E>` into a `Result`, including multiple levels of nesting. ```rust let x: Result, u32> = Ok(Ok("hello")); assert_eq!(Ok("hello"), x.flatten()); let x: Result, u32> = Ok(Err(6)); assert_eq!(Err(6), x.flatten()); let x: Result, u32> = Err(6); assert_eq!(Err(6), x.flatten()); ``` ```rust let x: Result, u32>, u32> = Ok(Ok(Ok("hello"))); assert_eq!(Ok(Ok("hello")), x.flatten()); assert_eq!(Ok("hello"), x.flatten().flatten()); ``` -------------------------------- ### Result::map example Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Maps the Ok value of a Result using a closure, leaving errors untouched. In this example, it parses each line of a string and prints the doubled value. ```rust let line = "1\n2\n3\n4\n"; for num in line.lines() { match num.parse::().map(|i| i * 2) { Ok(n) => println!("{n}"), Err(..) => {} } } ``` -------------------------------- ### Example for Result::copied on &T Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Demonstrates using `copied` to map a `Result<&T, E>` to `Result` by copying the `Ok` value. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` -------------------------------- ### Result::as_ref example Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Converts a Result to a Result of references, allowing inspection without consuming the original. Shows both Ok and Err cases. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Example for Result::is_err Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Demonstrates checking if a `Result` is `Err`. ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### as_deref_mut example: mutable deref Ok value Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Shows as_deref_mut, which converts Result to Result<&mut T::Target, &mut E> by mutably dereferencing the Ok value. The example mutates the dereferenced value. ```rust let mut s = "HELLO".to_string(); let mut x: Result = Ok("hello".to_string()); let y: Result<&mut str, &mut u32> = Ok(&mut s); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); let mut i = 42; let mut x: Result = Err(42); let y: Result<&mut str, &mut u32> = Err(&mut i); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); ``` -------------------------------- ### enable Source: https://docs.rs/calloop/latest/calloop/struct.LoopHandle.html Enables a previously disabled event source, causing it to start generating events again. ```APIDOC ## enable ### Description Enables a previously disabled event source. This previously disabled source will start generating events again. ### Method N/A (Rust method) ### Endpoint N/A ### Parameters #### Method Parameters - `token` (&RegistrationToken) - Required - The token of the source to enable. ### Request Example ```rust handle.enable(&token)?; ``` ### Response #### Success Response - `Result<()>` - Ok if the operation succeeded, Err otherwise. #### Response Example ```rust handle.enable(&token)?; ``` ``` -------------------------------- ### process_events with TransientSource Source: https://docs.rs/calloop/latest/calloop/transient/struct.TransientSource.html Example process_events implementation that delegates to the TransientSource's process_events and returns its PostAction. The TransientSource only returns PostAction::Continue or PostAction::Reregister. ```rust fn process_events( &mut self, readiness: calloop::Readiness, token: calloop::Token, callback: F, ) -> Result where F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret, { let channel_return = self.mpsc_receiver.process_events(readiness, token, callback)?; // Perform other logic here... Ok(channel_return) } ``` -------------------------------- ### and with Ok and Err combinations Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Shows and returning res if the result is Ok, otherwise returning the Err value of self. The examples cover all combinations of Ok and Err inputs. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### unwrap on Ok value Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Shows basic usage of unwrap on an Ok value, returning the contained value. The example asserts the result equals 2. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### reregister with TransientSource Source: https://docs.rs/calloop/latest/calloop/transient/struct.TransientSource.html Example reregister implementation that delegates to the TransientSource's reregister. The TransientSource handles updating registration, including unregistering or initial registration as needed. ```rust fn reregister( &mut self, poll: &mut calloop::Poll, token_factory: &mut calloop::TokenFactory, ) -> crate::Result<()> { self.mpsc_receiver.reregister(poll, token_factory)?; // Other registration actions... Ok(()) } ``` -------------------------------- ### Result::ok example Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Converts a Result to Option, discarding the error and keeping the Ok value if present, otherwise returning None. Shown with Ok and Err cases. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### Result::as_mut example Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Converts a mutable reference to Result into a Result of mutable references, enabling mutation of the contained value. Demonstrates modifying both Ok and Err cases. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### FromIterator collecting Results with checked_add Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Shows how to collect an iterator of Results into a Result. The example increments each integer and checks for overflow, returning Ok if all succeed. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` -------------------------------- ### iter_mut example: mutate Ok value via iterator Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Shows iter_mut, which returns a mutable iterator over the possibly contained value. The example mutates the Ok value through the iterator. ```rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### map_err example: stringify error Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Shows how map_err applies a function to the Err value, leaving Ok untouched. The example defines a stringify function and asserts the results for both Ok and Err cases. ```rust fn stringify(x: u32) -> String { format!("error code: {x}") } let x: Result = Ok(2); assert_eq!(x.map_err(stringify), Ok(2)); let x: Result = Err(13); assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); ``` -------------------------------- ### inspect_err example: read file with error logging Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Shows inspect_err, which calls a closure with a reference to the Err value and returns the original result. The example reads a file and logs an error message on failure. ```rust use std::{fs, io}; fn read() -> io::Result { fs::read_to_string("address.txt") .inspect_err(|e| eprintln!("failed to read file: {e}")) } ``` -------------------------------- ### Create an EventLoop with a Timer and LoopSignal Source: https://docs.rs/calloop/latest/calloop/index.html Runnable example that creates an EventLoop with a LoopSignal, inserts a Timer source that fires after 2 seconds, and stops the loop from the callback. The loop runs with a 20ms timeout between dispatches, and the callback prints the expired deadline and returns TimeoutAction::Drop to drop the timer. Requires the calloop crate and uses the timer feature. ```rust use calloop::{timer::{Timer, TimeoutAction}, EventLoop, LoopSignal}; fn main() { // Create the event loop. The loop is parameterised by the kind of shared // data you want the callbacks to use. In this case, we want to be able to // stop the loop when the timer fires, so we provide the loop with a // LoopSignal, which has the ability to stop the loop from within events. We // just annotate the type here; the actual data is provided later in the // run() call. let mut event_loop: EventLoop = EventLoop::try_new().expect("Failed to initialize the event loop!"); // Retrieve a handle. It is used to insert new sources into the event loop // It can be cloned, allowing you to insert sources from within source // callbacks. let handle = event_loop.handle(); // Create our event source, a timer, that will expire in 2 seconds let source = Timer::from_duration(std::time::Duration::from_secs(2)); // Inserting an event source takes this general form. It can also be done // from within the callback of another event source. handle .insert_source( // a type which implements the EventSource trait source, // a callback that is invoked whenever this source generates an event |event, _metadata, shared_data| { // This callback is given 3 values: // - the event generated by the source (in our case, timer events are the Instant // representing the deadline for which it has fired) // - &mut access to some metadata, specific to the event source (in our case, a // timer handle) // - &mut access to the global shared data that was passed to EventLoop::run or // EventLoop::dispatch (in our case, a LoopSignal object to stop the loop) // // The return type is just () because nothing uses it. Some // sources will expect a Result of some kind instead. println!("Timeout for {:?} expired!", event); // notify the event loop to stop running using the signal in the shared data // (see below) shared_data.stop(); // The timer event source requires us to return a TimeoutAction to // specify if the timer should be rescheduled. In our case we just drop it. TimeoutAction::Drop }, ) .expect("Failed to insert event source!"); // Create the shared data for our loop. let mut shared_data = event_loop.get_signal(); // Actually run the event loop. This will dispatch received events to their // callbacks, waiting at most 20ms for new events between each invocation of // the provided callback (pass None for the timeout argument if you want to // wait indefinitely between events). // // This is where we pass the *value* of the shared data, as a mutable // reference that will be forwarded to all your callbacks, allowing them to // share some state event_loop .run( std::time::Duration::from_millis(20), &mut shared_data, |_shared_data| { // Finally, this is where you can insert the processing you need // to do do between each waiting event eg. drawing logic if // you're doing a GUI app. }, ) .expect("Error during event loop!"); } ``` -------------------------------- ### Result::is_err_and example Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Checks if a Result is Err and its error value satisfies a predicate. The example demonstrates usage with io::Error and String errors, including checking borrowed references. The last case shows that the original Result is still usable after borrowing. ```rust use std::io::{Error, ErrorKind}; let x: Result = Err(Error::new(ErrorKind::NotFound, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true); let x: Result = Err(Error::new(ErrorKind::PermissionDenied, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Ok(123); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Err("ownership".to_string()); assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Generic::new Source: https://docs.rs/calloop/latest/calloop/generic/index.html Creates a new `Generic` event source wrapping an IO object or file descriptor, registering for specified interests and mode. The callback receives a `Readiness` and a mutable reference to the object, and must return a `Result`. ```APIDOC ## Generic::new ### Description Creates a new `Generic` event source that wraps an IO object or file descriptor, registering for the specified interests and mode. The event source generates `Readiness` notifications and provides the monitored object to the callback. ### Method Constructor ### Endpoint `Generic::new(io_object, interest, mode)` ### Parameters - **io_object** (impl AsFd) - Required - The IO object or file descriptor to monitor. - **interest** (Interest) - Required - The interest to register (e.g., `Interest::READ`). - **mode** (Mode) - Required - The triggering mode (e.g., `Mode::Level`). ### Callback Signature `|readiness: Readiness, io_object: &mut T, shared_data: &mut S| -> Result` ### Description of Callback Arguments - **readiness** (Readiness) - The readiness notification. - **io_object** (&mut T) - A mutable reference to the wrapped object. - **shared_data** (&mut S) - Shared data provided by the event loop. ### Return Value - **Result** - The callback must return a `PostAction` or an error. If an error is returned, the event loop treats the event source as erroring and reports it to the user. ### Example ```rust use calloop::{generic::Generic, Interest, Mode, PostAction}; handle.insert_source( Generic::new(io_object, Interest::READ, Mode::Level), |readiness, io_object, shared_data| { // The first argument is a Readiness // The second is a &mut reference to your object Ok(PostAction::Continue) } ); ``` ``` -------------------------------- ### adapt_io Source: https://docs.rs/calloop/latest/calloop/struct.LoopHandle.html Wraps an IO object into an async adapter, making it async-aware and driven by the event loop. ```APIDOC ## adapt_io ### Description Wraps an IO object into an async adapter. This adapter turns the IO object into an async-aware one that can be used in futures. The readiness of these futures will be driven by the event loop. ### Method N/A (Rust method) ### Endpoint N/A ### Parameters #### Method Parameters - `fd` (F) - Required - The IO object to adapt (must implement AsFd). ### Request Example ```rust let async_io = handle.adapt_io(fd)?; ``` ### Response #### Success Response - `Result>` - Ok containing the async adapter, or Err if adaptation fails. #### Response Example ```rust let async_io = handle.adapt_io(fd)?; ``` ``` -------------------------------- ### batch_register! Source: https://docs.rs/calloop/latest/calloop/macro.batch_register.html Registers a set of event sources by calling EventSource::register() for each source. It takes a poll instance, a token factory, and a list of sources. Error handling is early-return in the order sources are listed. ```APIDOC ## Macro batch_register! ### Description Registers a set of event sources. Effectively calls `EventSource::register()` for all the sources provided. ### Syntax ```rust macro_rules! batch_register { ($poll:ident, $token_fac:ident, $( $source:expr ),* $(,)?) => { ... }; } ``` ### Parameters - **$poll** (ident) - Required - The poll instance to register the sources with. - **$token_fac** (ident) - Required - The token factory to use for registration. - **$source** (expr) - Required - One or more event sources to register. Multiple sources can be provided, separated by commas. ### Usage Example ```rust calloop::batch_register!( poll, token_factory, self.source_one, self.source_two, self.source_three, self.source_four, ) ``` ### Notes - There is no scope for customization; if you need to do special things with a particular source, you’ll need to leave it off the list. - This only does try-or-early-return error handling in the order that you list the sources; if you need anything else, don’t use this macro. ``` -------------------------------- ### EventLoop::get_signal Source: https://docs.rs/calloop/latest/calloop/struct.EventLoop.html Gets a signal to stop this event loop from running. To be used in conjunction with the run() method. ```APIDOC ## EventLoop::get_signal ### Description Gets a signal to stop this event loop from running. To be used in conjunction with the run() method. ### Method `pub fn get_signal(&self) -> LoopSignal` ### Parameters None ### Returns - `LoopSignal` - A signal that can be used to stop or wakeup the event loop. ``` -------------------------------- ### Result Methods Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Documentation for the `Result` type methods: unwrap, unwrap_or_default, expect_err, unwrap_err, into_ok, into_err, and, and_then. ```APIDOC ## unwrap ### Description Returns the contained `Ok` value, consuming the `self` value. This method panics if the value is an `Err`, with a panic message provided by the `Err`'s value. It is generally discouraged; prefer using the `?` operator or pattern matching. ### Signature ```rust pub fn unwrap(self) -> T where E: Debug, ``` ### Parameters - `self` (Result) - The result to unwrap. ### Returns - `T` - The contained `Ok` value. ### Panics Panics if the value is an `Err`, with a panic message provided by the `Err`'s value. ### Examples ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` ``` ```APIDOC ## unwrap_or_default ### Description Returns the contained `Ok` value or a default. Consumes the `self` argument then, if `Ok`, returns the contained value, otherwise if `Err`, returns the default value for that type. ### Signature ```rust pub fn unwrap_or_default(self) -> T where T: Default, ``` ### Parameters - `self` (Result) - The result to unwrap. ### Returns - `T` - The contained `Ok` value or the default value for `T`. ### Examples ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` ``` ```APIDOC ## expect_err ### Description Returns the contained `Err` value, consuming the `self` value. Panics if the value is an `Ok`, with a panic message including the passed message and the content of the `Ok`. ### Signature ```rust pub fn expect_err(self, msg: &str) -> E where T: Debug, ``` ### Parameters - `self` (Result) - The result to extract the error from. - `msg` (&str) - The panic message to include if the value is `Ok`. ### Returns - `E` - The contained `Err` value. ### Panics Panics if the value is an `Ok`, with a panic message including the passed message and the content of the `Ok`. ### Examples ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` ``` ```APIDOC ## unwrap_err ### Description Returns the contained `Err` value, consuming the `self` value. Panics if the value is an `Ok`, with a custom panic message provided by the `Ok`'s value. ### Signature ```rust pub fn unwrap_err(self) -> E where T: Debug, ``` ### Parameters - `self` (Result) - The result to unwrap. ### Returns - `E` - The contained `Err` value. ### Panics Panics if the value is an `Ok`, with a custom panic message provided by the `Ok`'s value. ### Examples ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` ``` ```APIDOC ## into_ok ### Description Returns the contained `Ok` value, but never panics. Unlike `unwrap`, this method is known to never panic on the result types it is implemented for. It can be used as a maintainability safeguard that will fail to compile if the error type is later changed to an error that can actually occur. ### Signature ```rust pub fn into_ok(self) -> T where E: Into, ``` ### Parameters - `self` (Result) - The result to extract the `Ok` value from. ### Returns - `T` - The contained `Ok` value. ### Examples ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ``` ```APIDOC ## into_err ### Description Returns the contained `Err` value, but never panics. Unlike `unwrap_err`, this method is known to never panic on the result types it is implemented for. It can be used as a maintainability safeguard that will fail to compile if the ok type is later changed to a type that can actually occur. ### Signature ```rust pub fn into_err(self) -> E where T: Into, ``` ### Parameters - `self` (Result) - The result to extract the `Err` value from. ### Returns - `E` - The contained `Err` value. ### Examples ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` ``` ```APIDOC ## and ### Description Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`. Arguments passed to `and` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use `and_then`, which is lazily evaluated. ### Signature ```rust pub fn and(self, res: Result) -> Result ``` ### Parameters - `self` (Result) - The first result. - `res` (Result) - The second result. ### Returns - `Result` - `res` if `self` is `Ok`, otherwise the `Err` value of `self`. ### Examples ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` ``` ```APIDOC ## and_then ### Description Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`. This function can be used for control flow based on `Result` values. ### Signature ```rust pub fn and_then(self, op: F) -> Result where F: FnOnce(T) -> Result, ``` ### Parameters - `self` (Result) - The result to operate on. - `op` (F) - A function that takes the `Ok` value and returns a `Result`. ### Returns - `Result` - The result of `op` if `self` is `Ok`, otherwise the `Err` value of `self`. ### Examples ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } ``` ``` -------------------------------- ### Dispatcher::new Source: https://docs.rs/calloop/latest/calloop/struct.Dispatcher.html Builds a new Dispatcher with the given event source and callback. ```APIDOC ## [CONSTRUCTOR] Dispatcher::new ### Description Builds a dispatcher with the provided event source and callback. ### Method Constructor ### Signature ```rust pub fn new(source: S, callback: F) -> Self where F: FnMut(S::Event, &mut S::Metadata, &mut Data) -> S::Ret + 'a, S: EventSource + 'a, ``` ### Parameters - **source** (S) - Required - The event source to wrap. - **callback** (F) - Required - The callback invoked when events are dispatched. ### Returns - **Self** - The newly constructed Dispatcher. ``` -------------------------------- ### IntoIterator for Result Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Shows that IntoIterator for Result yields one value if Ok, otherwise none. The examples collect into a Vec. ```rust let x: Result = Ok(5); let v: Vec = x.into_iter().collect(); assert_eq!(v, [5]); let x: Result = Err("nothing!"); let v: Vec = x.into_iter().collect(); assert_eq!(v, []); ``` -------------------------------- ### make_ping Source: https://docs.rs/calloop/latest/calloop/ping/fn.make_ping.html Documentation for the make_ping function, which creates a new ping event source. ```APIDOC ## make_ping ### Description Creates a new ping event source. Returns a `Ping` instance that can be cloned and used to ping the event loop, and a `PingSource` that can be inserted into the event loop to receive the pings. ### Function Signature ```rust pub fn make_ping() -> Result<(Ping, PingSource)> ``` ### Parameters None. ### Returns - `Result<(Ping, PingSource)>` - A result containing a tuple of `Ping` and `PingSource` on success, or an error on failure. ``` -------------------------------- ### Signals::new Source: https://docs.rs/calloop/latest/calloop/signals/struct.Signals.html Creates a new signal event source listening on the specified list of signals. ```APIDOC ## [RUST] Signals::new ### Description Creates a new signal event source listening on the specified list of signals. ### Method Rust associated function ### Endpoint `Signals::new(signals: &[Signal]) -> Result` ### Parameters #### Arguments - **signals** (`&[Signal]`) - Required - The list of signals to listen for. ### Returns - **Result** - A new `Signals` instance on success, or an error if creation fails. ### Errors Returns an error if the signal source cannot be created. ``` -------------------------------- ### unwrap_err_unchecked on Ok value (undefined behavior) Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Warns that calling unwrap_err_unchecked on an Ok is undefined behavior. The example shows the call but notes it is unsafe. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` -------------------------------- ### and_then: chain fallible operations Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Shows how `and_then` chains a fallible operation that returns `Result`. The example uses a function `sq_then_to_string` that returns `Result` and demonstrates success, overflow, and error propagation. ```rust assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string())); assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed")); assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number")); ``` -------------------------------- ### unwrap_unchecked on Err value (undefined behavior) Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Warns that calling unwrap_unchecked on an Err is undefined behavior. The example shows the call but notes it is unsafe. ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Readiness::EMPTY Source: https://docs.rs/calloop/latest/calloop/struct.Readiness.html A constant representing an empty readiness state, where all flags are false. ```APIDOC ## Readiness::EMPTY ### Description A constant representing an empty readiness state, where all flags are false. ### Signature `pub const EMPTY: Readiness` ### Fields - `readable` (bool) - false - `writable` (bool) - false - `error` (bool) - false ### Usage Use this constant to initialize a Readiness with no flags set. ``` -------------------------------- ### Timer Methods Source: https://docs.rs/calloop/latest/calloop/timer/struct.Timer.html Methods for creating and managing a Timer event source in the calloop library. ```APIDOC ## Timer::immediate() ### Description Creates a timer that will fire immediately when inserted into the event loop. ### Method Constructor ### Signature ```rust pub fn immediate() -> Timer ``` ### Returns - **Timer** - A new timer that fires immediately. ``` ```APIDOC ## Timer::from_duration(duration: Duration) ### Description Creates a timer that will fire after a given duration from now. ### Method Constructor ### Signature ```rust pub fn from_duration(duration: Duration) -> Timer ``` ### Parameters - **duration** (Duration) - Required - The duration to wait before firing. ``` ```APIDOC ## Timer::from_deadline(deadline: Instant) ### Description Creates a timer that will fire at a given instant. ### Method Constructor ### Signature ```rust pub fn from_deadline(deadline: Instant) -> Timer ``` ### Parameters - **deadline** (Instant) - Required - The instant at which the timer should fire. ``` ```APIDOC ## Timer::set_deadline(&mut self, deadline: Instant) ### Description Changes the deadline of this timer to an `Instant`. If the timer is currently registered in the event loop, it needs to be re-registered for this change to take effect. ### Method Method ### Signature ```rust pub fn set_deadline(&mut self, deadline: Instant) ``` ### Parameters - **deadline** (Instant) - Required - The new deadline for the timer. ``` ```APIDOC ## Timer::set_duration(&mut self, duration: Duration) ### Description Changes the deadline of this timer to a `Duration` from now. If the timer is currently registered in the event loop, it needs to be re-registered for this change to take effect. ### Method Method ### Signature ```rust pub fn set_duration(&mut self, duration: Duration) ``` ### Parameters - **duration** (Duration) - Required - The new duration from now for the timer. ``` ```APIDOC ## Timer::current_deadline(&self) -> Option ### Description Gets the current deadline of this timer. Returns `None` if the timer has overflowed. ### Method Method ### Signature ```rust pub fn current_deadline(&self) -> Option ``` ### Returns - **Option** - The current deadline, or `None` if the timer has overflowed. ``` -------------------------------- ### unwrap_err on Err value Source: https://docs.rs/calloop/latest/calloop/error/type.Result.html Shows unwrap_err returning the contained Err value when called on an Err. The example asserts the result equals 'emergency failure'. ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ```