### Precision Formatting Source: https://docs.rs/numfmt Examples demonstrating how to control the precision of number formatting, including fixed decimal places, arbitrary precision, and significant figures. ```APIDOC ## Precision Formatting Examples ### Description Examples showing how to set the precision for number formatting. ### Examples ```rust let mut f: Formatter; f = "[.2]".parse().unwrap(); // use two decimal places assert_eq!(f.fmt(1.2345), "1.23"); f = "[,2]".parse().unwrap(); // use two decimal places with comma assert_eq!(f.fmt(1.2345), "1,23"); f = "[.0]".parse().unwrap(); // use zero decimal places assert_eq!(f.fmt(10.234), "10"); f = "[.*]".parse().unwrap(); // arbitrary precision assert_eq!(f.fmt(1.234), "1.234"); assert_eq!(f.fmt(12.2), "12.2"); f = "[,*]".parse().unwrap(); // arbitrary precision with comma assert_eq!(f.fmt(1.234), "1,234"); f = "[~3]".parse().unwrap(); // 3 significant figures assert_eq!(f.fmt(1.234), "1.23"); assert_eq!(f.fmt(10.234), "10.2"); f = "[~3/.]".parse().unwrap(); // 3 significant figures with comma assert_eq!(f.fmt(1.234), "1,23"); ``` ``` -------------------------------- ### Create a percentage formatter Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Formatter.html Initialize a formatter for percentage output, including optional precision adjustments. ```rust let mut f = Formatter::percentage(); assert_eq!(f.fmt(0.678912), "67.8912%"); assert_eq!(f.fmt(1.23), "123.0%"); assert_eq!(f.fmt(1.2), "120.0%"); f = f.precision(Precision::Decimals(2)); assert_eq!(f.fmt(0.01234), "1.23%"); ``` -------------------------------- ### Customize Formatter settings Source: https://docs.rs/numfmt/1.2.0/numfmt/index.html Demonstrates creating a custom currency formatter by chaining configuration methods. ```rust let mut f = Formatter::new() // start with blank representation .separator(',').unwrap() .prefix("AU$").unwrap() .precision(Precision::Decimals(2)); assert_eq!(f.fmt(0.52), "AU$0.52"); assert_eq!(f.fmt(1234.567), "AU$1,234.56"); assert_eq!(f.fmt(12345678900.0), "AU$12,345,678,900.0"); ``` -------------------------------- ### Use Short Scaling Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Scales.html Demonstrates the default short scaling method using a base of 1000. ```rust let mut f = Formatter::default() .scales(Scales::short()) .precision(Precision::Decimals(1)); assert_eq!(f.fmt(12.34e0), "12.3"); assert_eq!(f.fmt(12.34e3), "12.3 K"); assert_eq!(f.fmt(12.34e6), "12.3 M"); assert_eq!(f.fmt(12.34e9), "12.3 B"); assert_eq!(f.fmt(12.34e12), "12.3 T"); assert_eq!(f.fmt(12.34e15), "12.3 P"); assert_eq!(f.fmt(12.34e18), "12.3 E"); assert_eq!(f.fmt(12.34e21), "12.3 Z"); assert_eq!(f.fmt(12.34e24), "12.3 Y"); assert_eq!(f.fmt(12.34e27), "12,339.9 Y"); ``` -------------------------------- ### Create a currency formatter Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Formatter.html Initialize a formatter configured for currency output with a specific prefix. ```rust let mut f = Formatter::currency("$").unwrap(); assert_eq!(f.fmt(12345.6789), "$12,345.67"); assert_eq!(f.fmt(1234_f64), "$1,234.0"); ``` -------------------------------- ### Use Binary Scaling Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Scales.html Demonstrates binary scaling with a base of 1024. ```rust let mut f = Formatter::new().scales(Scales::binary()); assert_eq!(f.fmt(1024.0 * 1024.0), "1.0 Mi"); assert_eq!(f.fmt(3.14 * 1024.0 * 1024.0), "3.14 Mi"); ``` -------------------------------- ### Formatter Initialization Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Formatter.html Provides methods for creating new Formatter instances. ```APIDOC ## Formatter Initialization ### Description Methods for creating and initializing `Formatter` instances. ### Methods #### `Formatter::new()` ##### Description Construct a new formatter. No scaling is set, so this only does a single allocation for the buffer. ##### Example ```rust let mut f = Formatter::new(); assert_eq!(f.fmt(12345.6789), "12345.6789"); ``` #### `Formatter::currency(prefix: &str)` ##### Description Create a formatter that formats numbers as a currency. ##### Example ```rust let mut f = Formatter::currency("$").unwrap(); assert_eq!(f.fmt(12345.6789), "$12,345.67"); assert_eq!(f.fmt(1234_f64), "$1,234.0"); ``` #### `Formatter::percentage()` ##### Description Create a formatter that formats numbers as a percentage. ##### Example ```rust let mut f = Formatter::percentage(); assert_eq!(f.fmt(0.678912), "67.8912%"); assert_eq!(f.fmt(1.23), "123.0%"); f = f.precision(Precision::Decimals(2)); assert_eq!(f.fmt(0.01234), "1.23%"); ``` ``` -------------------------------- ### Use Metric Scaling Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Scales.html Demonstrates SI metric scaling with a base of 1000. ```rust let mut f = Formatter::new().scales(Scales::metric()); assert_eq!(f.fmt(123456.0), "123.456 k"); assert_eq!(f.fmt(123456789.0), "123.456789 M"); ``` -------------------------------- ### Create and use a default Formatter Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Formatter.html Construct a new formatter with default settings and apply it to a number. ```rust let mut f = Formatter::new(); assert_eq!(f.fmt(12345.6789), "12345.6789"); ``` -------------------------------- ### Scaling Options Source: https://docs.rs/numfmt Demonstrates various scaling options available in the numfmt library, including SI, percentage, metric, binary, and no scaling. ```APIDOC ## Scaling Options ### Description Examples illustrating different scaling methods supported by the formatter. ### Supported Scaling Characters - `s`: SI scaling (`Scales::short`) - `%`: Percentage scaling (`Formatter::percentage`) - `m`: Metric scaling (`Scales::metric`) - `b`: Binary scaling (`Scales::binary`) - `n`: No scaling (`Scales::none`) ### Examples ```rust let mut f: Formatter; f = "".parse().unwrap(); // default si scaling used assert_eq!(f.fmt(12345.0), "12.345 K"); f = "[n]".parse().unwrap(); // turn off scaling assert_eq!(f.fmt(12345.0), "12,345.0"); f = "[%.2]".parse().unwrap(); // format as percentages with 2 decimal places assert_eq!(f.fmt(0.234), "23.40%"); f = "[b]".parse().unwrap(); // use a binary scaler assert_eq!(f.fmt(3.14 * 1024.0 * 1024.0), "3.14 Mi"); ``` ``` -------------------------------- ### Create a file size formatter Source: https://docs.rs/numfmt/1.2.0/numfmt/index.html Combines binary scales, significant figures, and a suffix to format file sizes. ```rust let mut f = Formatter::new() .scales(Scales::binary()) .precision(Precision::Significance(3)) .suffix("B").unwrap(); assert_eq!(f.fmt(123_f64), "123 B"); assert_eq!(f.fmt(1234_f64), "1.20 kiB"); assert_eq!(f.fmt(1_048_576_f64), "1.0 MiB"); assert_eq!(f.fmt(123456789876543_f64), "112 TiB"); ``` -------------------------------- ### Apply number scaling Source: https://docs.rs/numfmt/1.2.0/numfmt/index.html Shows how to apply SI, percentage, binary, or no scaling to numeric values. ```rust let mut f: Formatter; f = "".parse().unwrap(); // default si scaling used assert_eq!(f.fmt(12345.0), "12.345 K"); f = "[n]".parse().unwrap(); // turn off scaling assert_eq!(f.fmt(12345.0), "12,345.0"); f = "[%.2]".parse().unwrap(); // format as percentages with 2 decimal places assert_eq!(f.fmt(0.234), "23.40%"); f = "[b]".parse().unwrap(); // use a binary scaler assert_eq!(f.fmt(3.14 * 1024.0 * 1024.0), "3.14 Mi"); ``` -------------------------------- ### Parse format strings Source: https://docs.rs/numfmt/1.2.0/numfmt/index.html Demonstrates parsing string patterns into a Formatter, including handling of prefixes, suffixes, and bracket escaping. ```rust let mut f: Formatter; f = "".parse().unwrap(); assert_eq!(f.fmt(1.234), "1.234"); f = "prefix ".parse().unwrap(); assert_eq!(f.fmt(1.234), "prefix 1.234"); f = "[] suffix".parse().unwrap(); assert_eq!(f.fmt(1.234), "1.234 suffix"); f = "[[prefix [] suffix]]".parse().unwrap(); assert_eq!(f.fmt(1.234), "[prefix 1.234 suffix]"); ``` -------------------------------- ### Composing Formats Source: https://docs.rs/numfmt Illustrates how to combine different formatting options like precision, scaling, and separators, along with prefixes and suffixes. ```APIDOC ## Composing Formats ### Description Examples showing how to combine various formatting specifiers, including prefixes, suffixes, precision, scaling, and separators. ### General Rule The format must adhere to the `prefix[num]suffix` order. The ordering within the `[num]` part is arbitrary, but consistency is recommended. ### Various Composed Examples ```rust let mut f: Formatter; // Percentages to two decimal places f = "[.2%]".parse().unwrap(); assert_eq!(f.fmt(0.012345), "1.23%"); // Currency to zero decimal places // notice the `n` for no scaling f = "$[.0n] USD".parse().unwrap(); assert_eq!(f.fmt(123_456_789.12345), "$123,456,789 USD"); // Formatting file sizes f = "[~3b]B".parse().unwrap(); assert_eq!(f.fmt(123_456_789.0), "117 MiB"); // Units to 1 decimal place f = "[.1n] m/s".parse().unwrap(); assert_eq!(f.fmt(12345.68), "12,345.6 m/s"); // Using custom separator and period for decimals f = "[,1n/_]".parse().unwrap(); assert_eq!(f.fmt(12345.68), "12_345,6"); ``` ``` -------------------------------- ### Configure number precision Source: https://docs.rs/numfmt/1.2.0/numfmt/index.html Demonstrates how to set decimal places, arbitrary precision, and significant figures using the Formatter parser. ```rust let mut f: Formatter; f = "[.2]".parse().unwrap(); // use two decimal places assert_eq!(f.fmt(1.2345), "1.23"); f = "[,2]".parse().unwrap(); // use two decimal places with comma assert_eq!(f.fmt(1.2345), "1,23"); f = "[.0]".parse().unwrap(); // use zero decimal places assert_eq!(f.fmt(10.234), "10"); f = "[.*]".parse().unwrap(); // arbitrary precision assert_eq!(f.fmt(1.234), "1.234"); assert_eq!(f.fmt(12.2), "12.2"); f = "[,*]".parse().unwrap(); // arbitrary precision with comma assert_eq!(f.fmt(1.234), "1,234"); f = "[~3]".parse().unwrap(); // 3 significant figures assert_eq!(f.fmt(1.234), "1.23"); assert_eq!(f.fmt(10.234), "10.2"); f = "[~3/.]".parse().unwrap(); // 3 significant figures with comma assert_eq!(f.fmt(1.234), "1,23"); ``` -------------------------------- ### Set Number Precision Source: https://docs.rs/numfmt Demonstrates setting the precision for number formatting. Use '.2' for two decimal places, '.0' for zero, and '.*' for arbitrary precision. ```rust let mut f: Formatter; f = "[.2]".parse().unwrap(); // use two decimal places assert_eq!(f.fmt(1.2345), "1.23"); ``` ```rust f = "[,2]".parse().unwrap(); // use two decimal places with comma assert_eq!(f.fmt(1.2345), "1,23"); ``` ```rust f = "[.0]".parse().unwrap(); // use zero decimal places assert_eq!(f.fmt(10.234), "10"); ``` ```rust f = "[.*]".parse().unwrap(); // arbitrary precision assert_eq!(f.fmt(1.234), "1.234"); assert_eq!(f.fmt(12.2), "12.2"); ``` ```rust f = "[,*]".parse().unwrap(); // arbitrary precision with comma assert_eq!(f.fmt(1.234), "1,234"); ``` ```rust f = "[~3]".parse().unwrap(); // 3 significant figures assert_eq!(f.fmt(1.234), "1.23"); assert_eq!(f.fmt(10.234), "10.2"); ``` ```rust f = "[~3/.]".parse().unwrap(); // 3 significant figures with comma assert_eq!(f.fmt(1.234), "1,23"); ``` -------------------------------- ### Separator Configuration Source: https://docs.rs/numfmt Shows how to configure custom separators for number formatting, including using spaces, underscores, or periods, and how periods affect decimal separators. ```APIDOC ## Separator Configuration ### Description Examples demonstrating the use of custom separators and how they interact with decimal formatting. ### Separator Syntax A separator character can be specified using a forward slash `/` followed by the character. If the character is `]`, the separator is set to `None`. The default separator is a comma. A period `.` as a separator signals the use of a comma `,` as the decimal signifier. ### Examples ```rust let mut f: Formatter; f = "[n]".parse().unwrap(); // turn off scaling to see separator assert_eq!(f.fmt(12345.0), "12,345.0"); f = "[n/]".parse().unwrap(); // use no separator assert_eq!(f.fmt(12345.0), "12345.0"); f = "[n/_]".parse().unwrap(); // use an underscore assert_eq!(f.fmt(12345.0), "12_345.0"); f = "[n/ ]".parse().unwrap(); // use a space assert_eq!(f.fmt(12345.0), "12 345.0"); f = "[n/.]".parse().unwrap(); // use period as separator and comma as decimal assert_eq!(f.fmt(12345.0), "12.345,0"); ``` ``` -------------------------------- ### Configure precision settings Source: https://docs.rs/numfmt/1.2.0/numfmt/index.html Shows how to switch between decimal places and significant figures using the Precision enum. ```rust let mut f = Formatter::new(); assert_eq!(f.fmt(1234.56789), "1234.56789"); f = f.precision(Precision::Decimals(2)); assert_eq!(f.fmt(1234.56789), "1234.56"); f = f.precision(Precision::Significance(5)); assert_eq!(f.fmt(1234.56789), "1234.5"); ``` -------------------------------- ### Apply Number Scaling Source: https://docs.rs/numfmt Configures number scaling using specific characters: 's' for SI, '%' for percentage, 'm' for metric, 'b' for binary, and 'n' for no scaling. Default is SI. ```rust let mut f: Formatter; f = "".parse().unwrap(); // default si scaling used assert_eq!(f.fmt(12345.0), "12.345 K"); ``` ```rust f = "[n]".parse().unwrap(); // turn off scaling assert_eq!(f.fmt(12345.0), "12,345.0"); ``` ```rust f = "[%.2]".parse().unwrap(); // format as percentages with 2 decimal places assert_eq!(f.fmt(0.234), "23.40%"); ``` ```rust f = "[b]".parse().unwrap(); // use a binary scaler assert_eq!(f.fmt(3.14 * 1024.0 * 1024.0), "3.14 Mi"); ``` -------------------------------- ### into_ok Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Returns the contained `Ok` value, but never panics. This is an experimental API. Unlike `unwrap`, this method is known to never panic on the result types it is implemented for, making it a maintainability safeguard. ```APIDOC ## GET /api/health ### Description Checks the health of the application or service. ### Method GET ### Endpoint /api/health ### Response #### Success Response (200) - **healthy** (boolean) - Indicates if the service is healthy. #### Response Example ```json { "healthy": true } ``` ``` -------------------------------- ### Format numbers with default settings Source: https://docs.rs/numfmt/1.2.0/numfmt/index.html Uses the default Formatter configuration, which includes short scaling, comma separators, and 3 decimal places. ```rust let mut f = Formatter::default(); assert_eq!(f.fmt(0.0), "0"); assert_eq!(f.fmt(12345.6789), "12.345 K"); assert_eq!(f.fmt(0.00012345), "1.234e-4"); assert_eq!(f.fmt(123456e22), "1,234.559 Y"); ``` -------------------------------- ### Result Methods Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Provides documentation for common methods available on the `Result` type, including checking status, converting to Option, and mapping values. ```APIDOC ## Implementations ### impl Result #### pub const fn is_ok(&self) -> bool Returns `true` if the result is `Ok`. ##### Examples ```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); ``` #### pub fn is_ok_and(self, f: F) -> bool where F: FnOnce(T) -> bool, Returns `true` if the result is `Ok` and the value inside of it matches a predicate. ##### Examples ```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); ``` #### pub const fn is_err(&self) -> bool Returns `true` if the result is `Err`. ##### Examples ```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); ``` #### pub fn is_err_and(self, f: F) -> bool where F: FnOnce(E) -> bool, Returns `true` if the result is `Err` and the value inside of it matches a predicate. ##### Examples ```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); ``` #### pub fn ok(self) -> Option Converts from `Result` to `Option`. Converts `self` into an `Option`, consuming `self`, and discarding the error, if any. ##### Examples ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` #### pub fn err(self) -> Option Converts from `Result` to `Option`. Converts `self` into an `Option`, consuming `self`, and discarding the success value, if any. ##### Examples ```rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` #### pub const fn as_ref(&self) -> Result<&T, &E> Converts from `&Result` to `Result<&T, &E>`. Produces a new `Result`, containing a reference into the original, leaving the original in place. ##### Examples ```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")); ``` #### pub const fn as_mut(&mut self) -> Result<&mut T, &mut E> Converts from `&mut Result` to `Result<&mut T, &mut E>`. ##### Examples ```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); ``` #### pub fn map(self, op: F) -> Result where F: FnOnce(T) -> U, Maps a `Result` to `Result` by applying a function to a contained `Ok` value, leaving an `Err` value untouched. This function can be used to compose the results of two functions. ##### Examples Print the numbers on each line of a string multiplied by two. ```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(..) => {{}} } } ``` ``` -------------------------------- ### Formatter Configuration Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Formatter.html Methods for configuring the behavior of the Formatter. ```APIDOC ## Formatter Configuration ### Description Methods to customize number formatting, including precision, scaling, separators, and prefixes/suffixes. ### Methods #### `Formatter::convert(self, f: fn(f64) -> f64)` ##### Description Set the value converter. Use a converter to transform the input number into another number before formatting. #### `Formatter::precision(self, precision: Precision)` ##### Description Set the precision for the number formatting. #### `Formatter::scales(self, scales: Scales)` ##### Description Set the scaling for the number formatting. #### `Formatter::build_scales(self, base: u16, units: Vec<&'static str>)` ##### Description Set the scaling via `Scales::new`. #### `Formatter::separator>>(self, sep: S)` ##### Description Set the thousands separator. If the separator is a period `.`, this signals to use a comma for the decimal marker. ##### Example ```rust let mut f = Formatter::new().separator(',').unwrap(); // use a comma assert_eq!(f.fmt(12345.67), "12,345.67"); f = f.separator(' ').unwrap(); // use a space assert_eq!(f.fmt(12345.67), "12 345.67"); f = f.separator(None).unwrap(); // no separator assert_eq!(f.fmt(12345.67), "12345.67"); f = f.separator('.').unwrap(); // use a period separator and comma for decimal assert_eq!(f.fmt(12345.67), "12.345,67"); ``` #### `Formatter::comma(self, comma: bool)` ##### Description Set the comma option. If set to true, it will use a comma instead of a period for the decimal separator. If a comma is the thousands separator, a period will be used instead. ##### Example ```rust let mut f = Formatter::new(); assert_eq!(f.fmt(12345.67), "12345.67"); f = f.comma(true); assert_eq!(f.fmt(12345.67), "12345,67"); f = f.separator('.').unwrap(); assert_eq!(f.fmt(12345.67), "12.345,67"); ``` #### `Formatter::prefix(self, prefix: &str)` ##### Description Sets the prefix for the formatted number. Returns an error if the prefix is longer than the supported length. #### `Formatter::suffix(self, suffix: &str)` ##### Description Set the suffix for the formatted number. Returns an error if the suffix is longer than the supported length. ``` -------------------------------- ### Try Implementation for Result Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Experimental API for the `?` operator's behavior with Result. ```APIDOC ## Try Implementation for Result ### `type Output = T` The type of the value produced by `?` when _not_ short-circuiting. ### `type Residual = Result` The type of the value passed to `FromResidual::from_residual` as part of `?` when short-circuiting. ### `from_output(output: as Try>::Output) -> Result` Constructs the type from its `Output` type. ### `branch(self) -> ControlFlow< as Try>::Residual, as Try>::Output>` Used in `?` to decide whether the operator should produce a value (because this returned `ControlFlow::Continue`) or propagate a value back to the caller (because this returned `ControlFlow::Break`). ``` -------------------------------- ### Formatter::from_str Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Formatter.html Parses a string into a Formatter instance. ```APIDOC ## fn from_str(s: &str) -> Result ### Description Parses a string `s` to return a value of this type. ### Parameters #### Request Body - **s** (str) - Required - The string to parse into a Formatter. ### Response #### Success Response (200) - **Result** - Returns the parsed Formatter instance or a ParseError. ``` -------------------------------- ### Into Ok value Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Extracts the Ok value without panicking, useful for infallible results. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Validate Result with is_ok_and Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Check if a Result is Ok and matches a specific 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); ``` -------------------------------- ### Product Implementation for Result Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Enables calculating the product of an iterator of Result values. ```APIDOC ## Product> Implementation for Result ### `product(iter: I) -> Result` Takes each element in the `Iterator`: if it is an `Err`, no further elements are taken, and the `Err` is returned. Should no `Err` occur, the product of all elements is returned. #### Examples This multiplies each number in a vector of strings, if a string could not be parsed the operation returns `Err`: ``` let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` ``` -------------------------------- ### TryFrom Trait Implementation Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Scales.html Documentation for the TryFrom trait used for fallible type conversions. ```APIDOC ## impl TryFrom for T ### Description Performs a fallible conversion from type U to type T. ### Associated Types - **Error** (Infallible) - The type returned in the event of a conversion error. ### Methods - **try_from(value: U) -> Result>::Error>** - Performs the conversion. ``` -------------------------------- ### Compose Number Formats Source: https://docs.rs/numfmt Combines various formatting options like precision, scaling, and separators with prefixes and suffixes. The order within the number format is arbitrary, but precision, scaling, and separator is recommended. ```rust let mut f: Formatter; // Percentages to two decimal places f = "[.2%]”.parse().unwrap(); assert_eq!(f.fmt(0.012345), "1.23%"); ``` ```rust // Currency to zero decimal places // notice the `n` for no scaling f = "$[.0n] USD".parse().unwrap(); assert_eq!(f.fmt(123_456_789.12345), "$123,456,789 USD"); ``` ```rust // Formatting file sizes f = "[~3b]B".parse().unwrap(); assert_eq!(f.fmt(123_456_789.0), "117 MiB"); ``` ```rust // Units to 1 decimal place f = "[.1n] m/s".parse().unwrap(); assert_eq!(f.fmt(12345.68), "12,345.6 m/s"); ``` ```rust // Using custom separator and period for decimals f = "[,1n/_]".parse().unwrap(); assert_eq!(f.fmt(12345.68), "12_345,6"); ``` -------------------------------- ### TryInto Trait Implementation Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Scales.html Documentation for the TryInto trait used for fallible type conversions. ```APIDOC ## impl TryInto for T ### Description Performs a fallible conversion from type T to type U. ### Associated Types - **Error** (>::Error) - The type returned in the event of a conversion error. ### Methods - **try_into(self) -> Result>::Error>** - Performs the conversion. ``` -------------------------------- ### Compose complex formats Source: https://docs.rs/numfmt/1.2.0/numfmt/index.html Combines prefixes, suffixes, precision, scaling, and separators into a single format string. ```rust let mut f: Formatter; // Percentages to two decimal places f = "[.2%]".parse().unwrap(); assert_eq!(f.fmt(0.012345), "1.23%"); // Currency to zero decimal places // notice the `n` for no scaling f = "$[.0n] USD".parse().unwrap(); assert_eq!(f.fmt(123_456_789.12345), "$123,456,789 USD"); // Formatting file sizes f = "[~3b]B".parse().unwrap(); assert_eq!(f.fmt(123_456_789.0), "117 MiB"); // Units to 1 decimal place f = "[.1n] m/s".parse().unwrap(); assert_eq!(f.fmt(12345.68), "12,345.6 m/s"); // Using custom separator and period for decimals f = "[,1n/_]".parse().unwrap(); assert_eq!(f.fmt(12345.68), "12_345,6"); ``` -------------------------------- ### PartialEq Implementation for Result Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Provides methods for equality comparison between two Result types. ```APIDOC ## PartialEq Implementation for Result ### `eq(&self, other: &Result) -> bool` Tests for `self` and `other` values to be equal, and is used by `==`. ### `ne(&self, other: &Rhs) -> bool` Tests for `!=`. ``` -------------------------------- ### Provide default value with unwrap_or Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Returns the contained Ok value or a provided default value. Arguments are eagerly evaluated. ```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); ``` -------------------------------- ### Clone Trait Implementation Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Scales.html Documentation for the clone_into method used for replacing owned data with borrowed data. ```APIDOC ## fn clone_into(&self, target: &mut T) ### Description Uses borrowed data to replace owned data, usually by cloning. ``` -------------------------------- ### StructuralPartialEq Implementation for Result Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Provides structural partial equality comparison for Result. ```APIDOC ## StructuralPartialEq Implementation for Result Provides structural partial equality comparison for `Result`. ``` -------------------------------- ### Unwrap with default value Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Returns the Ok value or a default value if the result is Err. ```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); ``` -------------------------------- ### Copy Implementation for Result Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Indicates that Result can be copied if its components can. ```APIDOC ## Copy Implementation for Result Indicates that `Result` can be copied if both `T` and `E` implement `Copy`. ``` -------------------------------- ### Result Trait Implementations Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Details various trait implementations for the Result type, enabling common operations and conversions. ```APIDOC ### impl Clone for Result #### fn clone(&self) -> Result Returns a duplicate of the value. #### fn clone_from(&mut self, source: &Result) Performs copy-assignment from `source`. ### impl Debug for Result #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> Formats the value using the given formatter. ### impl FromIterator> for Result #### fn from_iter(iter: I) -> Result Takes each element in the `Iterator`: if it is an `Err`, no further elements are taken, and the `Err` is returned. Should no `Err` occur, a container with the values of each `Result` is returned. ### impl FromResidual> for Result #### fn from_residual(residual: Result) -> Result Constructs the type from a compatible `Residual` type. (Nightly-only experimental API) ### impl FromResidual> for Result #### fn from_residual(_: Yeet) -> Result Constructs the type from a compatible `Residual` type. (Nightly-only experimental API) ### impl Hash for Result #### fn hash<__H>(&self, state: &mut __H) Feeds this value into the given `Hasher`. #### fn hash_slice(data: &[Self], state: &mut H) Feeds a slice of this type into the given `Hasher`. ### impl IntoIterator for Result #### fn into_iter(self) -> IntoIter Returns a consuming iterator over the possibly contained value. The iterator yields one value if the result is `Result::Ok`, otherwise none. #### type Item = T The type of the elements being iterated over. #### type IntoIter = IntoIter Which kind of iterator are we turning this into? ### impl Ord for Result #### fn cmp(&self, other: &Result) -> Ordering Compares and returns an `Ordering` between `self` and `other`. #### fn max(self, other: Self) -> Self Compares and returns the maximum of two values. ``` -------------------------------- ### Result::unwrap_or Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Returns the contained Ok value or a provided default. ```APIDOC ## unwrap_or ### Description Returns the contained `Ok` value or a provided default. ### Parameters - **default** (T) - Required - The default value to return if the result is Err. ### Response - **T** - The contained value or the default. ``` -------------------------------- ### Scales Trait Implementations Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Scales.html Details on the traits implemented for the Scales struct, including Clone, Debug, Hash, PartialEq, and Eq. ```APIDOC ### `impl Clone for Scales` #### `fn clone(&self) -> Scales` Returns a duplicate of the value. #### `fn clone_from(&mut self, source: &Self)` Performs copy-assignment from `source`. ### `impl Debug for Scales` #### `fn fmt(&self, f: &mut Formatter<'_>) -> Result` Formats the value using the given formatter. ### `impl Hash for Scales` #### `fn hash<__H: Hasher>(&self, state: &mut __H)` Feeds this value into the given `Hasher`. #### `fn hash_slice(data: &[Self], state: &mut H)` where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. ### `impl PartialEq for Scales` #### `fn eq(&self, other: &Scales) -> bool` Tests for `self` and `other` values to be equal, and is used by `==`. #### `fn ne(&self, other: &Rhs) -> bool` Tests for `!=`. ### `impl Eq for Scales` ``` -------------------------------- ### Formatter Equality Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Formatter.html Trait implementations for equality testing. ```APIDOC ## fn eq(&self, other: &Self) -> bool ### Description Tests for `self` and `other` values to be equal, and is used by `==`. ## fn ne(&self, other: &Rhs) -> bool ### Description Tests for `!=`. ``` -------------------------------- ### Configure comma usage Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Formatter.html Toggle the use of a comma as a decimal marker. ```rust let mut f = Formatter::new(); assert_eq!(f.fmt(12345.67), "12345.67"); f = f.comma(true); assert_eq!(f.fmt(12345.67), "12345,67"); f = f.separator('.').unwrap(); assert_eq!(f.fmt(12345.67), "12.345,67"); ``` -------------------------------- ### is_zero Method Implementation Source: https://docs.rs/numfmt/1.2.0/numfmt/trait.Numeric.html Checks if a number is zero. The default implementation converts the number to f64 and performs the test. ```rust fn is_zero(&self) -> bool { ... } ``` -------------------------------- ### Formatter Hashing Source: https://docs.rs/numfmt/1.2.0/numfmt/struct.Formatter.html Methods for feeding Formatter data into a Hasher. ```APIDOC ## fn hash(&self, hasher: &mut H) ### Description Feeds this value into the given `Hasher`. ## fn hash_slice(data: &[Self], state: &mut H) ### Description Feeds a slice of this type into the given `Hasher`. ``` -------------------------------- ### PartialOrd Implementation for Result Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Provides methods for partial ordering comparisons between two Result types. ```APIDOC ## PartialOrd Implementation for Result ### `partial_cmp(&self, other: &Result) -> Option` This method returns an ordering between `self` and `other` values if one exists. ### `lt(&self, other: &Rhs) -> bool` Tests less than (for `self` and `other`) and is used by the `<` operator. ### `le(&self, other: &Rhs) -> bool` Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. ### `gt(&self, other: &Rhs) -> bool` Tests greater than (for `self` and `other`) and is used by the `>` operator. ### `ge(&self, other: &Rhs) -> bool` Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. ``` -------------------------------- ### Result::or Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Returns the provided result if the current result is Err, otherwise returns the current Ok. ```APIDOC ## or ### Description Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`. ### Parameters - **res** (Result) - Required - The fallback result. ### Response - **Result** - The result of the operation. ``` -------------------------------- ### Fallback to alternative Result with or Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Returns the provided result if the current result is Err, otherwise returns the Ok value. Arguments are eagerly evaluated. ```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)); ``` -------------------------------- ### UseCloned Implementation for Result Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Indicates that Result can use cloning if its components can. ```APIDOC ## UseCloned Implementation for Result Indicates that `Result` can use cloning if both `T` and `E` implement `UseCloned`. ``` -------------------------------- ### Expect a Result value Source: https://docs.rs/numfmt/1.2.0/numfmt/type.Result.html Extracts the Ok value or panics with a custom message if the result is Err. ```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`"); ``` -------------------------------- ### is_negative Method Implementation Source: https://docs.rs/numfmt/1.2.0/numfmt/trait.Numeric.html Checks if a number is negative. The default implementation converts the number to f64 and performs the test. ```rust fn is_negative(&self) -> bool { ... } ``` -------------------------------- ### Define formatting grammar Source: https://docs.rs/numfmt/1.2.0/numfmt/index.html Visual representation of the string parsing grammar used to define a Formatter. ```text prefix[[.#|,#|~#|.*|,*][%|s|b|n][/]]suffix ^----^ ^--------------^^-------^^-------^ ^----^ prefix precision scale separator suffix ```