### FromIterator implementation examples Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html?search=std%3A%3Avec Examples showing how Result implements FromIterator to collect results, including short-circuiting behavior on Err. ```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])); ``` ```rust let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` -------------------------------- ### Result::is_ok example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Example for `Result::is_ok`, which returns `true` if the 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); ``` -------------------------------- ### btleplug Usage Example Source: https://docs.rs/btleplug/latest/btleplug/index.html An example demonstrating how to use btleplug to control BLE smart lights, including scanning, connecting, discovering services, and writing characteristics. ```APIDOC ## btleplug Usage Example ### Description This example shows how to use the btleplug library to scan for BLE devices, connect to a specific device, discover its services and characteristics, and write data to a characteristic. ### Usage ```rust use btleplug::api::{bleuuid::uuid_from_u16, Central, Manager as _, Peripheral as _, ScanFilter, WriteType}; use btleplug::platform::{Adapter, Manager, Peripheral}; use rand::{RngExt, rng}; use std::error::Error; use std::thread; use std::time::Duration; use tokio::time; use uuid::Uuid; const LIGHT_CHARACTERISTIC_UUID: Uuid = uuid_from_u16(0xFFE9); #[tokio::main] async fn main() -> Result<(), Box> { let manager = Manager::new().await.unwrap(); // get the first bluetooth adapter let adapters = manager.adapters().await?; let central = adapters.into_iter().nth(0).unwrap(); // start scanning for devices central.start_scan(ScanFilter::default()).await?; // instead of waiting, you can use central.events() to get a stream which will // notify you of new devices, for an example of that see examples/event_driven_discovery.rs time::sleep(Duration::from_secs(2)).await; // find the device we're interested in let light = find_light(¢ral).await.unwrap(); // connect to the device light.connect().await?; // discover services and characteristics light.discover_services().await?; // find the characteristic we want let chars = light.characteristics(); let cmd_char = chars.iter().find(|c| c.uuid == LIGHT_CHARACTERISTIC_UUID).unwrap(); // dance party let mut rng = rng(); for _ in 0..20 { let color_cmd = vec![0x56, rng.random(), rng.random(), rng.random(), 0x00, 0xF0, 0xAA]; light.write(&cmd_char, &color_cmd, WriteType::WithoutResponse).await?; time::sleep(Duration::from_millis(200)).await; } Ok(()) } async fn find_light(central: &Adapter) -> Option { for p in central.peripherals().await.unwrap() { if p.properties() .await .unwrap() .unwrap() .local_name .iter() .any(|name| name.contains("LEDBlue")) { return Some(p); } } None } ``` ### Key Operations - **Manager::new()** - Create a new manager instance. - **manager.adapters()** - Get the list of Bluetooth adapters. - **central.start_scan(ScanFilter::default())** - Start scanning for BLE devices. - **central.peripherals()** - Get the list of discovered peripherals. - **peripheral.properties()** - Get the properties of a peripheral. - **peripheral.connect()** - Connect to the peripheral. - **peripheral.discover_services()** - Discover services and characteristics. - **peripheral.characteristics()** - Get the characteristics of the peripheral. - **peripheral.write(&characteristic, &data, WriteType::WithoutResponse)** - Write data to a characteristic. ``` -------------------------------- ### Result::is_ok_and example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Example for `Result::is_ok_and`, which returns `true` if the result is `Ok` and the value inside 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); ``` -------------------------------- ### Result::transpose example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Example for `Result::transpose`, which transposes 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); ``` -------------------------------- ### Result::cloned example for &T Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Example for `Result::cloned` on `Result<&T, E>`, which clones the contents of the `Ok` part. ```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)); ``` -------------------------------- ### and_then example with Path metadata Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Demonstrates using and_then to chain metadata() and modified() on a Path. Shows that on Windows, "/" maps to "C:\". The example checks that a valid path returns Ok and an invalid path returns Err with ErrorKind::NotFound. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Result::copied example for &mut T Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Example for `Result::copied` on `Result<&mut T, E>`, which copies the contents of the `Ok` part. ```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)); ``` -------------------------------- ### Result::cloned example for &mut T Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Example for `Result::cloned` on `Result<&mut T, E>`, which clones the contents of the `Ok` part. ```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)); ``` -------------------------------- ### Result::copied example for &T Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Example for `Result::copied` on `Result<&T, E>`, which copies the contents of the `Ok` part. ```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)); ``` -------------------------------- ### as_mut example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Demonstrates Result::as_mut, which converts a &mut Result into a Result<&mut T, &mut E>, allowing mutation of the contained value. The example defines a mutate function that sets Ok to 42 and Err to 0. ```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); ``` -------------------------------- ### expect recommended message style example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html?search=u32+-%3E+bool Shows the recommended style for expect messages, describing the reason you expect the Result to be Ok. ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Example for Result::flatten with nested nesting Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html?search= Example showing that flatten only removes one level of nesting at a time. ```rust let x: Result, u32>, u32> = Ok(Ok(Ok("hello"))); assert_eq!(Ok(Ok("hello")), x.flatten()); assert_eq!(Ok("hello"), x.flatten().flatten()); ``` -------------------------------- ### ok example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Demonstrates Result::ok, which converts a Result into an Option, returning Some(value) for Ok and None for Err. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### Control BLE smart lights with btleplug Source: https://docs.rs/btleplug/latest/btleplug/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example from the crate documentation showing how to use btleplug to scan for a BLE device, connect, discover services, and write color commands to a characteristic. Requires the `rand` and `tokio` crates. The example uses `uuid_from_u16(0xFFE9)` for the light characteristic and looks for a device with local name containing "LEDBlue". ```rust use btleplug::api::{bleuuid::uuid_from_u16, Central, Manager as _, Peripheral as _, ScanFilter, WriteType}; use btleplug::platform::{Adapter, Manager, Peripheral}; use rand::{RngExt, rng}; use std::error::Error; use std::thread; use std::time::Duration; use tokio::time; use uuid::Uuid; const LIGHT_CHARACTERISTIC_UUID: Uuid = uuid_from_u16(0xFFE9); #[tokio::main] async fn main() -> Result<(), Box> { let manager = Manager::new().await.unwrap(); // get the first bluetooth adapter let adapters = manager.adapters().await?; let central = adapters.into_iter().nth(0).unwrap(); // start scanning for devices central.start_scan(ScanFilter::default()).await?; // instead of waiting, you can use central.events() to get a stream which will // notify you of new devices, for an example of that see examples/event_driven_discovery.rs time::sleep(Duration::from_secs(2)).await; // find the device we're interested in let light = find_light(¢ral).await.unwrap(); // connect to the device light.connect().await?; // discover services and characteristics light.discover_services().await?; // find the characteristic we want let chars = light.characteristics(); let cmd_char = chars.iter().find(|c| c.uuid == LIGHT_CHARACTERISTIC_UUID).unwrap(); // dance party let mut rng = rng(); for _ in 0..20 { let color_cmd = vec![0x56, rng.random(), rng.random(), rng.random(), 0x00, 0xF0, 0xAA]; light.write(&cmd_char, &color_cmd, WriteType::WithoutResponse).await?; time::sleep(Duration::from_millis(200)).await; } Ok(()) } async fn find_light(central: &Adapter) -> Option { for p in central.peripherals().await.unwrap() { if p.properties() .await .unwrap() .unwrap() .local_name .iter() .any(|name| name.contains("LEDBlue")) { return Some(p); } } None } ``` -------------------------------- ### Example for Result::flatten Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html?search= Example usage of the `flatten` method to remove one level of nesting from a Result. ```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()); ``` -------------------------------- ### map example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Shows Result::map, which applies a function to the Ok value, leaving Err untouched. The example parses each line of a string and prints the doubled number. ```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(..) => {} } } ``` -------------------------------- ### unwrap_or_else example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Shows how to use unwrap_or_else to provide a fallback value for Ok and Err cases. ```rust assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### inspect example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Calls a function with a reference to the contained value if Ok, returning the original result. The example chains inspect with 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`"); ``` -------------------------------- ### expect example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Returns the contained Ok value, consuming self, but panics if the value is Err with a message including the passed message and the Err content. The first example shows a panic, the second shows a recommended message style. ```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`"); ``` -------------------------------- ### as_ref example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Shows Result::as_ref, which converts a &Result into a Result<&T, &E>, leaving the original in place. ```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")); ``` -------------------------------- ### Central::start_scan Source: https://docs.rs/btleplug/latest/btleplug/api/trait.Central.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts scanning for BLE peripherals using the provided filter. ```APIDOC ## Central::start_scan ### Description Starts scanning for BLE peripherals using the provided filter. ### Method async fn start_scan(&self, filter: ScanFilter) -> Result<()> ### Parameters - **filter** (ScanFilter) - Required - The scan filter to apply. ### Returns - **Result<()>** - Ok(()) on success, or an error. ``` -------------------------------- ### Manager::adapters() Source: https://docs.rs/btleplug/latest/btleplug/api/trait.Manager.html Get a list of all Bluetooth adapters on the system. Each adapter implements the Central trait. ```APIDOC ## [RUST] Manager::adapters() ### Description Get a list of all Bluetooth adapters on the system. Each adapter implements the `Central` trait. ### Method `fn adapters<'life0, 'async_trait>(&'life0 self) -> Pin>> + Send + 'async_trait>>` ### Parameters - **self** (`&'life0 self`) - Required - The manager instance. ### Return Value - **Result>** - A future that resolves to a vector of adapters, or an error. ### Usage Example ```rust use btleplug::api::Manager as _; use btleplug::platform::Manager; let manager = Manager::new().await?; let adapter_list = manager.adapters().await?; if adapter_list.is_empty() { eprintln!("No Bluetooth adapters"); } ``` ### Notes - This trait is dyn compatible. - The associated type `Adapter` must implement `Central`. ``` -------------------------------- ### is_err_and example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Shows how to use Result::is_err_and to check if the result is an Err and its error value matches a predicate. The example uses std::io::Error and demonstrates true/false outcomes for different error kinds and an Ok value. ```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); ``` -------------------------------- ### unwrap_or_else example with count function Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Demonstrates the unwrap_or_else method, which returns the contained Ok value or computes it from a closure. The example uses a count function that returns the length of a string. ```rust fn count(x: &str) -> usize { x.len() } ``` -------------------------------- ### Result::flatten examples Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Examples for `Result::flatten`, which converts from `Result, E>` to `Result`, including a note that flattening only removes one level of nesting at a time. ```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()); ``` -------------------------------- ### as_deref_mut example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Converts from Result to Result<&mut ::Target, &mut E> by coercing the Ok variant via DerefMut. The example shows both Ok and Err cases with mutation. ```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); ``` -------------------------------- ### err example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Demonstrates Result::err, which converts a Result into an Option, returning Some(error) for Err and None for Ok. ```rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` -------------------------------- ### Trait Manager Source: https://docs.rs/btleplug/latest/btleplug/api/trait.Manager.html?search= Documentation for the Manager trait, including its required method adapters and usage example. ```APIDOC ## Trait Manager ### Description The `Manager` trait is the entry point for the btleplug library, providing access to all Bluetooth adapters on the system. It defines a single method to retrieve the list of adapters. ### Method `adapters` ### Signature ```rust fn adapters<'life0, 'async_trait>( &'life0 self, ) -> Pin>> + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait, ``` ### Parameters - `self` - The manager instance. ### Returns - `Result>` - A future that resolves to a list of all Bluetooth adapters on the system. Each adapter implements the `Central` trait. ### Usage Example ```rust use btleplug::api::Manager as _; use btleplug::platform::Manager; let manager = Manager::new().await?; let adapter_list = manager.adapters().await?; if adapter_list.is_empty() { eprintln!("No Bluetooth adapters"); } ``` ``` -------------------------------- ### Result::is_err example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Example for `Result::is_err`, which returns `true` if the 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); ``` -------------------------------- ### Usage example for Manager Source: https://docs.rs/btleplug/latest/btleplug/api/trait.Manager.html?search=std%3A%3Avec Shows how to obtain a Manager instance and retrieve the list of Bluetooth adapters. Prints an error message if no adapters are found. ```rust use btleplug::api::Manager as _; use btleplug::platform::Manager; let manager = Manager::new().await?; let adapter_list = manager.adapters().await?; if adapter_list.is_empty() { eprintln!("No Bluetooth adapters"); } ``` -------------------------------- ### or example with Result values Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Shows the behavior of the or method, which returns the Ok value of self if self is Ok, otherwise returns the provided res. Demonstrates various combinations of Ok and Err. ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### Manager::new Source: https://docs.rs/btleplug/latest/btleplug/platform/struct.Manager.html?search=u32+-%3E+bool Creates a new Manager instance asynchronously. This is the entry point for interacting with Bluetooth adapters. ```APIDOC ## Manager::new ### Description Creates a new Manager instance asynchronously. ### Method `pub async fn new() -> Result` ### Parameters None ### Returns - `Result` - A result containing the new Manager instance or an error. ``` -------------------------------- ### iter example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Returns an iterator over the possibly contained value, yielding one value if Ok, otherwise none. The example shows both Ok and Err cases. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Central::adapter_info Source: https://docs.rs/btleplug/latest/btleplug/api/trait.Central.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns information about the adapter. ```APIDOC ## Central::adapter_info ### Description Returns information about the adapter. ### Method async fn adapter_info(&self) -> Result ### Parameters None ### Returns - **Result** - A string containing adapter information. ``` -------------------------------- ### as_deref example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Converts from Result to Result<&::Target, &E> by coercing the Ok variant via Deref. 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); ``` -------------------------------- ### inspect_err example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Calls a function with a reference to the contained value if Err, returning the original result. The example shows reading a file and printing 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}")) } ``` -------------------------------- ### or_else example with sq and err functions Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Demonstrates the or_else method for control flow based on result values. Uses sq and err functions to show how or_else chains operations on Err values. ```rust fn sq(x: u32) -> Result { Ok(x * x) } fn err(x: u32) -> Result { Err(x) } assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9)); assert_eq!(Err(3).or_else(err).or_else(err), Err(3)); ``` -------------------------------- ### map_or_else example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Shows Result::map_or_else, which applies a fallback function to the Err value or a function to the Ok value. The example uses a constant k to compute the fallback. ```rust let k = 21; let x : Result<_, &str> = Ok("foo"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); let x : Result<&str, _> = Err("bar"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); ``` -------------------------------- ### unwrap_or example with default value Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Shows the unwrap_or method, which returns the contained Ok value or a provided default. Demonstrates both Ok and Err cases. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### iter_mut example Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Returns a mutable iterator over the possibly contained value, yielding one value if Ok, otherwise none. The example shows modifying the value and the Err case. ```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 Source: https://docs.rs/btleplug/latest/btleplug/type.Result.html Maps a Result to Result by applying a function to a contained Err value, leaving Ok untouched. The example shows 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())); ``` -------------------------------- ### Manager::new Source: https://docs.rs/btleplug/latest/btleplug/platform/struct.Manager.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new Manager instance. This is an asynchronous constructor that returns a Result. ```APIDOC ## Manager::new ### Description Creates a new Manager instance. This is an asynchronous constructor that returns a Result. ### Method async fn new() -> Result ### Parameters None ### Returns Result - A Result containing the new Manager instance or an error. ```