### Signifix Customization Test Source: https://docs.rs/signifix/latest/src/signifix/lib.rs.html Example usage of the customization function to format numeric values. ```rust assert_eq!(customization(&[ 1.234E-06, 12.34E+00, -123.4E+24, ]), Ok(concat!( " Int Fra 10³\n", "---- ---- ----\n", " 1 234 -2\n", " 12 34 0\n", "-123 4 8\n", ).into())); ``` -------------------------------- ### Demonstrate Signifix Notations Source: https://docs.rs/signifix/latest/src/signifix/lib.rs.html This example demonstrates the different Signifix notations for metric prefixes, showcasing how the decimal mark position changes to maintain four significant figures across different powers of ten. It requires importing `metric`, `binary`, and `Result` from the `signifix` crate. ```rust use std::convert::TryFrom; use signifix::{metric, binary, Result}; let metric = |number| -> Result<(String, String)> { let number = metric::Signifix::try_from(number)?; Ok((format!("{}", number), format!("{:#}", number))) }; let binary = |number| -> Result { let number = binary::Signifix::try_from(number)?; Ok(format!("{}", number)) }; // Three different decimal mark positions covering the three powers of ten // of a particular metric prefix. assert_eq!(metric(1E-04), Ok(("100.0 µ".into(), "100µ0".into()))); // 3rd assert_eq!(metric(1E-03), Ok(("1.000 m".into(), "1m000".into()))); // 1st assert_eq!(metric(1E-02), Ok(("10.00 m".into(), "10m00".into()))); // 2nd assert_eq!(metric(1E-01), Ok(("100.0 m".into(), "100m0".into()))); // 3rd ``` -------------------------------- ### Format Metric and Binary Notations Source: https://docs.rs/signifix/latest/signifix Demonstrates the conversion of numbers into formatted metric and binary strings using Signifix. Includes examples for various decimal mark positions and powers of ten, as well as handling rounding over prefixes. ```rust use std::convert::TryFrom; use signifix::{metric, binary, Result}; let metric = |number| -> Result<(String, String)> { let number = metric::Signifix::try_from(number)?; Ok((format!("{}", number), format!("{:#}", number))) }; let binary = |number| -> Result { let number = binary::Signifix::try_from(number)?; Ok(format!("{}", number)) }; // Three different decimal mark positions covering the three powers of ten // of a particular metric prefix. assert_eq!(metric(1E-04), Ok(("100.0 µ".into(), "100µ0".into()))); // 3rd assert_eq!(metric(1E-03), Ok(("1.000 m".into(), "1m000".into()))); // 1st assert_eq!(metric(1E-02), Ok(("10.00 m".into(), "10m00".into()))); // 2nd assert_eq!(metric(1E-01), Ok(("100.0 m".into(), "100m0".into()))); // 3rd assert_eq!(metric(1E+00), Ok(("1.000 ".into(), "1#000".into()))); // 1st assert_eq!(metric(1E+01), Ok(("10.00 ".into(), "10#00".into()))); // 2nd assert_eq!(metric(1E+02), Ok(("100.0 ".into(), "100#0".into()))); // 3rd assert_eq!(metric(1E+03), Ok(("1.000 k".into(), "1k000".into()))); // 1st assert_eq!(metric(1E+04), Ok(("10.00 k".into(), "10k00".into()))); // 2nd assert_eq!(metric(1E+05), Ok(("100.0 k".into(), "100k0".into()))); // 3rd assert_eq!(metric(1E+06), Ok(("1.000 M".into(), "1M000".into()))); // 1st // Three different decimal mark positions and a thousands separator covering // the four powers of ten of a particular binary prefix. assert_eq!(binary(1_024f64.powi(0) * 1E+00), Ok("1.000 ".into())); // 1st assert_eq!(binary(1_024f64.powi(0) * 1E+01), Ok("10.00 ".into())); // 2nd assert_eq!(binary(1_024f64.powi(0) * 1E+02), Ok("100.0 ".into())); // 3rd assert_eq!(binary(1_024f64.powi(0) * 1E+03), Ok("1 000 ".into())); // 4th assert_eq!(binary(1_024f64.powi(1) * 1E+00), Ok("1.000 Ki".into())); // 1st assert_eq!(binary(1_024f64.powi(1) * 1E+01), Ok("10.00 Ki".into())); // 2nd assert_eq!(binary(1_024f64.powi(1) * 1E+02), Ok("100.0 Ki".into())); // 3rd assert_eq!(binary(1_024f64.powi(1) * 1E+03), Ok("1 000 Ki".into())); // 4th assert_eq!(binary(1_024f64.powi(2) * 1E+00), Ok("1.000 Mi".into())); // 1st // Rounding over prefixes is safe against floating-point inaccuracies. assert_eq!(metric(999.949_999_999_999_8), Ok(("999.9 ".into(), "999#9".into()))); assert_eq!(metric(999.949_999_999_999_9), Ok(("1.000 k".into(), "1k000".into()))); assert_eq!(binary(1_023.499_999_999_999_94), Ok("1 023 ".into())); assert_eq!(binary(1_023.499_999_999_999_95), Ok("1.000 Ki".into())); ``` -------------------------------- ### Get a reference to the Ok value Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Use `as_ref()` to convert a `&Result` into a `Result<&T, &E>`. This allows borrowing the contents without consuming the original Result. ```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")); ``` -------------------------------- ### Handling File Metadata with `and_then` Source: https://docs.rs/signifix/latest/signifix/binary/type.Result.html Demonstrates using `and_then` to chain fallible operations like getting file metadata and its modification time. Useful for sequential file system interactions. ```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); ``` -------------------------------- ### Get Integer and Fractional Parts Source: https://docs.rs/signifix/latest/signifix/binary/struct.Signifix.html Retrieves both the signed integer and fractional parts of the significand as a tuple. ```rust pub fn parts(&self) -> (i32, i32) ``` -------------------------------- ### Safely Unwrap Ok Value (Never Panics) Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Use `into_ok` to get the contained `Ok` value. This method is guaranteed not to panic, making it a compile-time safeguard against unexpected errors. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Chain fallible operations with and_then Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Use and_then to chain operations that return a Result. The first example demonstrates mapping a successful value, while the second shows file system metadata retrieval. ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } 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")); ``` ```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); ``` -------------------------------- ### Unwrap with Panic on Error Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Use `unwrap` to get the contained `Ok` value. This example shows it panics with a custom message when the `Result` is an `Err`. ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### Get Fractional Part Source: https://docs.rs/signifix/latest/signifix/binary/struct.Signifix.html Retrieves the fractional part of the significand, ranging from 0 to 999. ```rust pub fn fractional(&self) -> i32 ``` -------------------------------- ### Format Metric and Binary Prefixes Source: https://docs.rs/signifix/latest/src/signifix/lib.rs.html Demonstrates the use of metric and binary formatting functions with various powers of ten and binary prefixes, including handling of floating-point rounding. ```rust assert_eq!(metric(1E+00), Ok(("1.000 ".into(), "1#000".into()))); // 1st assert_eq!(metric(1E+01), Ok(("10.00 ".into(), "10#00".into()))); // 2nd assert_eq!(metric(1E+02), Ok(("100.0 ".into(), "100#0".into()))); // 3rd assert_eq!(metric(1E+03), Ok(("1.000 k".into(), "1k000".into()))); // 1st assert_eq!(metric(1E+04), Ok(("10.00 k".into(), "10k00".into()))); // 2nd assert_eq!(metric(1E+05), Ok(("100.0 k".into(), "100k0".into()))); // 3rd assert_eq!(metric(1E+06), Ok(("1.000 M".into(), "1M000".into()))); // 1st // Three different decimal mark positions and a thousands separator covering // the four powers of ten of a particular binary prefix. assert_eq!(binary(1_024f64.powi(0) * 1E+00), Ok("1.000 ".into())); // 1st assert_eq!(binary(1_024f64.powi(0) * 1E+01), Ok("10.00 ".into())); // 2nd assert_eq!(binary(1_024f64.powi(0) * 1E+02), Ok("100.0 ".into())); // 3rd assert_eq!(binary(1_024f64.powi(0) * 1E+03), Ok("1 000 ".into())); // 4th assert_eq!(binary(1_024f64.powi(1) * 1E+00), Ok("1.000 Ki".into())); // 1st assert_eq!(binary(1_024f64.powi(1) * 1E+01), Ok("10.00 Ki".into())); // 2nd assert_eq!(binary(1_024f64.powi(1) * 1E+02), Ok("100.0 Ki".into())); // 3rd assert_eq!(binary(1_024f64.powi(1) * 1E+03), Ok("1 000 Ki".into())); // 4th assert_eq!(binary(1_024f64.powi(2) * 1E+00), Ok("1.000 Mi".into())); // 1st // Rounding over prefixes is safe against floating-point inaccuracies. assert_eq!(metric(999.949_999_999_999_8), Ok(("999.9 ".into(), "999#9".into()))); assert_eq!(metric(999.949_999_999_999_9), Ok(("1.000 k".into(), "1k000".into()))); assert_eq!(binary(1_023.499_999_999_999_94), Ok("1 023 ".into())); assert_eq!(binary(1_023.499_999_999_999_95), Ok("1.000 Ki".into())); ``` -------------------------------- ### Get Denominator Source: https://docs.rs/signifix/latest/signifix/binary/struct.Signifix.html Retrieves the denominator of the significand, which can be 1, 10, 100, or 1 000. ```rust pub fn denominator(&self) -> i32 ``` -------------------------------- ### Implement TryFrom for f64 Source: https://docs.rs/signifix/latest/src/signifix/binary.rs.html Conversion logic from f64 to Signifix, handling scaling and bounds checking. ```rust impl TryFrom for Signifix { type Error = Error; fn try_from(number: f64) -> Result { let (numerator, prefix) = { let number = number.abs(); let prefix = match FACTORS[1..].binary_search_by(|factor| factor.partial_cmp(&number).unwrap_or(Ordering::Less) ) { Ok(prefix) => prefix, Err(prefix) => prefix }; (number / FACTORS[prefix], prefix) }; let scaled = |pow: f64| (numerator * pow).round(); let signed = |abs: f64| if number.is_sign_negative() { -abs } else { abs }; let middle = scaled(1E+02); if middle < 1E+04 { let lower = scaled(1E+03); if lower < 1E+04 { if lower < 1E+03 { Err(Error::OutOfLowerBound(number)) } else { Ok(Self { number: super::Signifix { numerator: signed(lower) as i16, exponent: 3, prefix: prefix as u8, } }) } } else { Ok(Self { number: super::Signifix { numerator: signed(middle) as i16, exponent: 2, prefix: prefix as u8, } }) } } else { let upper = scaled(1E+01); if upper < 1E+04 { Ok(Self { number: super::Signifix { numerator: signed(upper) as i16, exponent: 1, prefix: prefix as u8, } }) } else { let above = numerator.round(); if above < 1.024E+03 { Ok(Self { number: super::Signifix { numerator: signed(above) as i16, exponent: 0, prefix: prefix as u8, } }) } else { let prefix = prefix + 1; if prefix < FACTORS.len() { Ok(Self { number: super::Signifix { numerator: signed(1E+03) as i16, exponent: 3, prefix: prefix as u8, } }) } else { if number.is_nan() { Err(Error::Nan) } else { Err(Error::OutOfUpperBound(number)) } } } } } } } ``` -------------------------------- ### unwrap_err() - Get Err value Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Returns the contained `Err` value. Panics if the `Result` is an `Ok`. ```APIDOC ## PUT /api/products/{product_id} ### Description Updates an existing product's information. ### Method PUT ### Endpoint /api/products/{product_id} ### Parameters #### Path Parameters - **product_id** (string) - Required - The ID of the product to update. #### Request Body - **name** (string) - Optional - The updated name of the product. - **description** (string) - Optional - The updated description of the product. - **price** (number) - Optional - The updated price of the product. ### Request Example ```json { "price": 25.50, "description": "An improved version of the widget." } ``` ### Response #### Success Response (200) - **id** (string) - The product's unique identifier. - **name** (string) - The name of the product. - **description** (string) - A brief description of the product. - **price** (number) - The price of the product. #### Response Example ```json { "id": "prod789", "name": "Updated Widget", "description": "An improved version of the widget.", "price": 25.50 } ``` ``` -------------------------------- ### into_ok() - Convert Result to Ok value (Nightly) Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Returns the contained `Ok` value. This is a nightly-only experimental API that is guaranteed not to panic. ```APIDOC ## POST /api/orders ### Description Creates a new order. ### Method POST ### Endpoint /api/orders ### Parameters None ### Request Body - **user_id** (string) - Required - The ID of the user placing the order. - **items** (array) - Required - A list of items in the order. - **product_id** (string) - Required - The ID of the product. - **quantity** (integer) - Required - The number of units of the product. ### Request Example ```json { "user_id": "user123", "items": [ { "product_id": "prod789", "quantity": 2 }, { "product_id": "item456", "quantity": 1 } ] } ``` ### Response #### Success Response (201) - **order_id** (string) - The unique identifier for the newly created order. - **status** (string) - The current status of the order (e.g., "pending", "processing"). - **total_amount** (number) - The total cost of the order. #### Response Example ```json { "order_id": "ord001", "status": "pending", "total_amount": 50.00 } ``` ``` -------------------------------- ### Visualize Filesize Differences Source: https://docs.rs/signifix/latest/src/signifix/lib.rs.html Imports necessary modules for visualizing file size changes, typically used to handle signed differences. ```rust use std::convert::TryFrom; use signifix::metric::{Signifix, Error, Result}; ``` -------------------------------- ### Get Exponent Source: https://docs.rs/signifix/latest/signifix/binary/struct.Signifix.html Retrieves the exponent of the significand's denominator, which can be 0, 1, 2, or 3. ```rust pub fn exponent(&self) -> usize ``` -------------------------------- ### Create Custom Display Tables Source: https://docs.rs/signifix/latest/src/signifix/lib.rs.html Extracts internal parts of Signifix to build custom formatted output tables. ```rust use std::convert::TryFrom; use signifix::metric::{Signifix, Result}; struct SignifixTable<'a>(&'a[Signifix]); impl<'a> std::fmt::Display for SignifixTable<'a> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.pad(" Int Fra 10³\n")?; f.pad("---- ---- ----\n")?; for entry in self.0 { let (integer, fractional) = entry.parts(); f.pad(&format!("{:4} {:<3} {:2}\n", integer, fractional, entry.prefix() as i32 - 8))?; } Ok(()) } } let customization = |entries: &[_]| -> Result { let mut table = Vec::with_capacity(entries.len()); for entry in entries { table.push(Signifix::try_from(*entry)?); } Ok(SignifixTable(&table).to_string()) }; ``` -------------------------------- ### Get Numerator Source: https://docs.rs/signifix/latest/signifix/binary/struct.Signifix.html Retrieves the signed numerator of the significand, ranging from ±1 000 to ±9 999. ```rust pub fn numerator(&self) -> i32 ``` -------------------------------- ### TryFrom for Signifix Source: https://docs.rs/signifix/latest/signifix/metric/struct.Signifix.html Conversion from f32 to Signifix. ```APIDOC ## try_from(number: f32) ### Description Attempts to convert a given f32 number into a Signifix instance by determining the appropriate metric prefix and normalized significand. ### Parameters - **number** (f32) - The input number to convert. ### Response - **Result** - Returns a Signifix instance or an Error if conversion fails. ``` -------------------------------- ### Unwrap Error Value Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Use `unwrap_err` to get the contained `Err` value. Panics if the value is an `Ok`. ```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"); ``` -------------------------------- ### TryFrom Macros for Signifix Source: https://docs.rs/signifix/latest/src/signifix/binary.rs.html Macros for implementing TryFrom for various integer and floating-point types. ```rust try_from! { i8, i16, i32, i64, i128, isize } try_from! { u8, u16, u32, u64, u128, usize } try_from! { f32 } ``` -------------------------------- ### Unwrap Ok Value Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Use `unwrap` to get the contained `Ok` value. Panics if the value is an `Err`. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### Create Custom Formatting Tables Source: https://docs.rs/signifix/latest/signifix Extracts numeric components using parts() and prefix() methods to build custom display tables. ```rust use std::convert::TryFrom; use signifix::metric::{Signifix, Result}; struct SignifixTable<'a>(&'a[Signifix]); impl<'a> std::fmt::Display for SignifixTable<'a> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.pad(" Int Fra 10³\n")?; f.pad("---- ---- ----\n")?; for entry in self.0 { let (integer, fractional) = entry.parts(); f.pad(&format!("{:4} {:<3} {:2}\n", integer, fractional, entry.prefix() as i32 - 8))?; } Ok(()) } } let customization = |entries: &[_]| -> Result { let mut table = Vec::with_capacity(entries.len()); for entry in entries { table.push(Signifix::try_from(*entry)?); } Ok(SignifixTable(&table).to_string()) }; assert_eq!(customization(&[ 1.234E-06, 12.34E+00, -123.4E+24, ]), Ok(concat!( " Int Fra 10³\n", "---- ---- ----\n", " 1 234 -2\n", " 12 34 0\n", "-123 4 8\n", ).into())); ``` -------------------------------- ### Get Binary Prefix Factor Source: https://docs.rs/signifix/latest/signifix/binary/struct.Signifix.html Retrieves the factor of the binary prefix, which is a power of 1024 (from 1024^0 to 1024^8). ```rust pub fn factor(&self) -> f64 ``` -------------------------------- ### Get Integer Part Source: https://docs.rs/signifix/latest/signifix/binary/struct.Signifix.html Retrieves the signed integer part of the significand, ranging from ±1 to ±1 023. ```rust pub fn integer(&self) -> i32 ``` -------------------------------- ### Signifix Helper Methods Source: https://docs.rs/signifix/latest/src/signifix/lib.rs.html Methods for calculating significand, integer parts, and fractional components of a Signifix instance. ```rust impl Signifix { fn significand(&self) -> f64 { self.numerator() as f64 * [1E-00, 1E-01, 1E-02, 1E-03][self.exponent()] } fn numerator(&self) -> i32 { self.numerator.into() } fn denominator(&self) -> i32 { [1, 10, 100, 1_000][self.exponent()] } fn exponent(&self) -> usize { self.exponent.into() } fn integer(&self) -> i32 { self.numerator() / self.denominator() } fn fractional(&self) -> i32 { self.numerator().abs() % self.denominator() } fn parts(&self) -> (i32, i32) { let trunc = self.numerator() / self.denominator(); let fract = self.numerator() - self.denominator() * trunc; (trunc, fract.abs()) } fn prefix(&self) -> usize { self.prefix.into() } } ``` -------------------------------- ### Get Significand Source: https://docs.rs/signifix/latest/signifix/binary/struct.Signifix.html Retrieves the signed significand of the Signifix number, normalized within the range of ±1.000 to ±999.9. ```rust pub fn significand(&self) -> f64 ``` -------------------------------- ### Visualize Filesize Differences Source: https://docs.rs/signifix/latest/signifix Uses the metric Signifix module to format numeric differences, including handling for constant values. ```rust use std::convert::TryFrom; use signifix::metric::{Signifix, Error, Result}; let filesize_diff = |curr, prev| -> Result { Signifix::try_from(curr - prev).map(|diff| format!("{:+#}", diff)) .or_else(|case| if case == Error::OutOfLowerBound(0f64) { Ok("=const".into()) } else { Err(case) }) }; assert_eq!(filesize_diff(78_346, 57_393), Ok("+20k95".into())); assert_eq!(filesize_diff(93_837, 93_837), Ok("=const".into())); assert_eq!(filesize_diff(27_473, 36_839), Ok("-9k366".into())); ``` -------------------------------- ### Expect Error with Custom Panic Message Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Use `expect_err` to get the contained `Err` value. Panics with a custom message if the `Result` is an `Ok`. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Get Binary Prefix Symbol Source: https://docs.rs/signifix/latest/signifix/binary/struct.Signifix.html Retrieves the symbol of the binary prefix, such as 'Ki' or 'Yi', as an Option<&str>. Returns None if no symbol is applicable. ```rust pub fn symbol(&self) -> Option<&str> ``` -------------------------------- ### Comparison Implementations (Ord) Source: https://docs.rs/signifix/latest/signifix/binary/struct.Signifix.html Provides comparison methods for the Signifix struct, including `cmp` for ordering, and utility methods like `max`, `min`, and `clamp`. ```rust fn cmp(&self, other: &Signifix) -> Ordering ``` ```rust fn max(self, other: Self) -> Self ``` ```rust fn min(self, other: Self) -> Self ``` ```rust fn clamp(self, min: Self, max: Self) -> Self ``` -------------------------------- ### Collect Results with from_iter Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Demonstrates how from_iter short-circuits on the first Err encountered during collection. ```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); ``` -------------------------------- ### unwrap() - Get Ok value or panic Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Retrieves the contained `Ok` value. Panics if the `Result` is an `Err`, using the error's value as the panic message. ```APIDOC ## POST /api/users ### Description Retrieves the contained `Ok` value. Panics if the `Result` is an `Err`, using the error's value as the panic message. ### Method POST ### Endpoint /api/users ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user to retrieve. #### Query Parameters - **include_details** (boolean) - Optional - Whether to include additional user details. ### Request Body None ### Request Example None ### Response #### Success Response (200) - **id** (string) - The user's unique identifier. - **name** (string) - The user's full name. - **email** (string) - The user's email address. #### Response Example ```json { "id": "user123", "name": "John Doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### TryFrom Macro Source: https://docs.rs/signifix/latest/src/signifix/lib.rs.html Macro to implement TryFrom for various numeric types into Signifix. ```rust macro_rules! try_from { ($($t:ty),*) => ( $( impl TryFrom<$t> for Signifix { type Error = Error; fn try_from(number: $t) -> Result { Self::try_from(number as f64) } } )* ); } ``` -------------------------------- ### Test Formatting Options Source: https://docs.rs/signifix/latest/src/signifix/binary.rs.html Tests various formatting options including signs, spacing, and different magnitudes. ```rust assert_eq!(fmt(-1E+00), Ok("-1.000 ".into())); assert_eq!(fmt( 1E+00), Ok( "1.000 ".into())); assert_eq!(fmt(-1E+03), Ok("-1 000 ".into())); assert_eq!(fmt( 1E+03), Ok( "1 000 ".into())); ``` ```rust assert_eq!(pos(-1E+00), Ok("-1.000 ".into())); assert_eq!(pos( 1E+00), Ok("+1.000 ".into())); assert_eq!(pos(-1E+03), Ok("-1 000 ".into())); assert_eq!(pos( 1E+03), Ok("+1 000 ".into())); ``` ```rust assert_eq!(pad(-1E+00), Ok("-1.000 ".into())); assert_eq!(pad( 1E+00), Ok(" 1.000 ".into())); assert_eq!(pad(-1E+03), Ok("-1 000 ".into())); assert_eq!(pad( 1E+03), Ok(" 1 000 ".into())); ``` -------------------------------- ### Collect into Result with Checked Addition Source: https://docs.rs/signifix/latest/signifix/type.Result.html Collects results from an iterator, returning the first error encountered or a collection of successful values. This example demonstrates checking for overflow during addition. ```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])); ``` -------------------------------- ### unwrap_or_default() - Get Ok value or default Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Returns the contained `Ok` value or the default value for the type if the `Result` is an `Err`. Requires the type `T` to implement the `Default` trait. ```APIDOC ## GET /api/items/{item_id} ### Description Retrieves a specific item by its ID. ### Method GET ### Endpoint /api/items/{item_id} ### Parameters #### Path Parameters - **item_id** (string) - Required - The unique identifier of the item. #### Query Parameters - **fields** (string) - Optional - Comma-separated list of fields to include in the response. ### Request Body None ### Request Example None ### Response #### Success Response (200) - **id** (string) - The item's unique identifier. - **name** (string) - The name of the item. - **description** (string) - A brief description of the item. - **price** (number) - The price of the item. #### Response Example ```json { "id": "item456", "name": "Example Widget", "description": "A sample widget for demonstration purposes.", "price": 19.99 } ``` ``` -------------------------------- ### DEF_MIN_LEN Constant Source: https://docs.rs/signifix/latest/signifix/metric/constant.DEF_MIN_LEN.html Documentation for the DEF_MIN_LEN constant used in the signifix crate. ```APIDOC ## Constant: DEF_MIN_LEN ### Description Represents the number of characters in the default notation when no sign is prefixed. ### Definition `pub const DEF_MIN_LEN: usize = 7;` ``` -------------------------------- ### Get a mutable reference to the value Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Use `as_mut()` to convert a `&mut Result` into a `Result<&mut T, &mut E>`. This enables in-place modification of the contained value. ```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); ``` -------------------------------- ### TryFrom Implementations for Signifix Source: https://docs.rs/signifix/latest/signifix/metric/struct.Signifix.html The Signifix type implements TryFrom for various numeric types including f64, i128, i16, i32, i64, i8, isize, u128, u16, u32, u64, u8, and usize. ```APIDOC ## TryFrom for Signifix ### Description Converts a numeric type into a Signifix instance. Returns a Result containing the Signifix instance or an Error if the conversion fails. ### Parameters #### Request Body - **number** (f64, i128, i16, i32, i64, i8, isize, u128, u16, u32, u64, u8, usize) - Required - The numeric value to convert. ### Response #### Success Response (200) - **Signifix** (Object) - The successfully converted Signifix instance. #### Error Response - **Error** (Type) - The error returned in the event of a conversion failure. ``` -------------------------------- ### Result Methods for Chaining Operations Source: https://docs.rs/signifix/latest/signifix/type.Result.html Demonstrates how to chain fallible operations using methods like `and_then`. ```APIDOC ## `and_then` ### Description Chains fallible operations that may return `Err`. ### Method `and_then` ### Example Usage ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } 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")); ``` ### Example with File Paths ```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); ``` ``` -------------------------------- ### Collect into Result with Checked Subtraction (Underflow) Source: https://docs.rs/signifix/latest/signifix/type.Result.html Collects results from an iterator, returning the first error encountered or a collection of successful values. This example demonstrates checking for underflow during subtraction. ```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!")); ``` -------------------------------- ### Result Methods for Chaining Operations Source: https://docs.rs/signifix/latest/signifix/binary/type.Result.html Demonstrates how to chain fallible operations using methods like `and_then`. ```APIDOC ## `and_then` ### Description Chains fallible operations that may return `Err`. ### Method `and_then` ### Example Usage ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } 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")); ``` ``` -------------------------------- ### Test KiB Formatting Source: https://docs.rs/signifix/latest/src/signifix/binary.rs.html Verifies the correct formatting of values in the KiB range. ```rust assert_eq!(fmt(1_024f64.powi(1) * 100.0f64), Ok("100.0 Ki".into())); assert_eq!(fmt(1_024f64.powi(1) * 123.4f64), Ok("123.4 Ki".into())); assert_eq!(fmt(1_024f64.powi(1) * 1_000f64), Ok("1 000 Ki".into())); assert_eq!(fmt(1_024f64.powi(1) * 1_002f64), Ok("1 002 Ki".into())); assert_eq!(fmt(1_024f64.powi(1) * 1_023f64), Ok("1 023 Ki".into())); ``` ```rust assert_eq!(fmt(1_024f64.powi(2) * 1.000f64), Ok("1.000 Mi".into())); assert_eq!(fmt(1_024f64.powi(2) * 1.234f64), Ok("1.234 Mi".into())); ``` -------------------------------- ### Safely Unwrap Error Value (Never Panics) Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Use `into_err` to get the contained `Err` value. This method is guaranteed not to panic, serving as a compile-time safeguard against unexpected success values. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Signifix Methods for Accessing Components Source: https://docs.rs/signifix/latest/src/signifix/binary.rs.html Provides methods to access various components of the Signifix type, including significand, numerator, denominator, exponent, integer and fractional parts, and the binary prefix index. ```rust impl Signifix { /// Signed significand normalized from `±1.000` over `±999.9` to `±1 023`. pub fn significand(&self) -> f64 { self.number.significand() } /// Signed significand numerator from `±1 000` to `±9 999`. pub fn numerator(&self) -> i32 { self.number.numerator() } /// Significand denominator of either `1`, `10`, `100`, or `1 000`. pub fn denominator(&self) -> i32 { self.number.denominator() } /// Exponent of significand denominator of either `0`, `1`, `2`, or `3`. pub fn exponent(&self) -> usize { self.number.exponent() } /// Signed integer part of significand from `±1` to `±1 023`. pub fn integer(&self) -> i32 { self.number.integer() } /// Fractional part of significand from `0` to `999`. pub fn fractional(&self) -> i32 { self.number.fractional() } /// Signed integer and fractional part at once, in given order. pub fn parts(&self) -> (i32, i32) { self.number.parts() } /// Binary prefix as `NAMES`, `SYMBOLS`, and `FACTORS` array index from `0` /// to `8`. pub fn prefix(&self) -> usize { self.number.prefix() } /// Symbol of binary prefix from `Some("Ki")` to `Some("Yi")`, or `None`. pub fn symbol(&self) -> Option<&str> { SYMBOLS[self.prefix()] } /// Factor of binary prefix from `1 024 ^ 1` to `1 024 ^ 8`, or `1 024 ^ 0`. pub fn factor(&self) -> f64 { FACTORS[self.prefix()] } /// Format trait implementation allowing explicit localization. /// /// Until there is a recommended and possibly implicit localization system /// for Rust, explicit localization can be achieved by wrapping the /// `Signifix` type into a locale-sensitive newtype which implements the /// `Display` trait via this method. Used by this type's `Display` trait /// implementation with a decimal point as `decimal_mark` and a whitespace ``` -------------------------------- ### Implement Signifix Methods in Rust Source: https://docs.rs/signifix/latest/src/signifix/metric.rs.html Provides methods to access the components of a normalized `Signifix` number, including its significand, numerator, denominator, exponent, integer and fractional parts, and the corresponding metric prefix index. ```rust impl Signifix { /// Signed significand normalized from `±1.000` to `±999.9`. pub fn significand(&self) -> f64 { self.number.significand() } /// Signed significand numerator from `±1 000` to `±9 999`. pub fn numerator(&self) -> i32 { self.number.numerator() } /// Significand denominator of either `10`, `100`, or `1 000`. pub fn denominator(&self) -> i32 { self.number.denominator() } /// Exponent of significand denominator of either `1`, `2`, or `3`. pub fn exponent(&self) -> usize { self.number.exponent() } /// Signed integer part of significand from `±1` to `±999`. pub fn integer(&self) -> i32 { self.number.integer() } /// Fractional part of significand from `0` to `999`. pub fn fractional(&self) -> i32 { self.number.fractional() } /// Signed integer and fractional part at once, in given order. pub fn parts(&self) -> (i32, i32) { self.number.parts() } /// Metric prefix as `NAMES`, `SYMBOLS`, and `FACTORS` array index from `0` /// to `16`. pub fn prefix(&self) -> usize { self.number.prefix() } /// Symbol of metric prefix from `Some("y")` to `Some("Y")`, or `None`. pub fn symbol(&self) -> Option<&str> { SYMBOLS[self.prefix()] } /// Factor of metric prefix from `1E-24` to `1E+24`, or `1E+00`. pub fn factor(&self) -> f64 { FACTORS[self.prefix()] } /// Format trait implementation allowing explicit localization. /// ``` -------------------------------- ### expect_err() - Get Err value or panic with custom message Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Returns the contained `Err` value. Panics if the `Result` is an `Ok`, including the provided message and the `Ok`'s content in the panic message. ```APIDOC ## DELETE /api/users/{user_id} ### Description Deletes a user by their ID. ### Method DELETE ### Endpoint /api/users/{user_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user to delete. ### Request Body None ### Request Example None ### Response #### Success Response (204) No content. Indicates the user was successfully deleted. #### Response Example None ``` -------------------------------- ### Unwrap or Default Value Source: https://docs.rs/signifix/latest/signifix/metric/type.Result.html Use `unwrap_or_default` to get the contained `Ok` value or the default value for the type if it's an `Err`. This is useful for converting strings to numbers, providing 0 for invalid input. ```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); ```