### Basic Usage of NoopFormat in Rust Source: https://github.com/dathere/dynfmt2/blob/master/README.md Demonstrates the basic usage of the `NoopFormat` for simple string formatting. No arguments are actually used in this example. ```rust use dynfmt2::{Format, NoopFormat}; let formatted = NoopFormat.format("hello, world", &["unused"]); assert_eq!("hello, world", formatted.expect("formatting failed")); ``` -------------------------------- ### Format Trait Examples: SimpleCurly, Python, Noop Source: https://context7.com/dathere/dynfmt2/llms.txt Demonstrates the usage of SimpleCurlyFormat, PythonFormat, and NoopFormat with various argument types and formatting options. Ensure the respective Cargo features are enabled. ```rust use dynfmt2::{Format, SimpleCurlyFormat, PythonFormat, NoopFormat}; // --- SimpleCurlyFormat: positional auto, by index, by name --- let s = SimpleCurlyFormat.format("Hello, {}!", &["world"]).unwrap(); assert_eq!(s, "Hello, world!"); let s = SimpleCurlyFormat.format("{0} + {0} = {1}", &[2_i32, 4_i32]).unwrap(); assert_eq!(s, "2 + 2 = 4"); let mut map = std::collections::BTreeMap::new(); map.insert("lang", "Rust"); map.insert("version", "1.70"); let s = SimpleCurlyFormat.format("{lang} {version}", map).unwrap(); assert_eq!(s, "Rust 1.70"); // --- PythonFormat: %s, %d, numeric radix, width, named keys --- let s = PythonFormat.format("int=%d hex=%x oct=%o", &[255_u32, 255_u32, 255_u32]).unwrap(); assert_eq!(s, "int=255 hex=ff oct=377"); let s = PythonFormat.format("alt-hex=%#x alt-oct=%#o", &[42_u32, 42_u32]).unwrap(); assert_eq!(s, "alt-hex=0x2a alt-oct=0o52"); // Width and alignment let s = PythonFormat.format("[%5s] [%-5s] [%05s]", &["ab", "cd", "7"]).unwrap(); assert_eq!(s, "[ ab] [cd ] [00007]"); // Named mapping-key syntax: %(key)s let mut args = std::collections::BTreeMap::new(); args.insert("name", "Alice"); args.insert("score", "99"); let s = PythonFormat.format("%(name)s scored %(score)s", args).unwrap(); assert_eq!(s, "Alice scored 99"); // Width read from the next argument (*) let s = PythonFormat.format("[%*s]", &[6_usize, 42_i32]).unwrap(); assert_eq!(s, "[ 42]"); // --- NoopFormat: returns format string unchanged, ignores args --- let s = NoopFormat.format("no placeholders here", &["ignored"]).unwrap(); assert_eq!(s, "no placeholders here"); ``` -------------------------------- ### Implementing a Custom HashFormat in Rust Source: https://github.com/dathere/dynfmt2/blob/master/README.md Shows how to implement the `Format` trait to create a custom formatting logic. This example defines a `HashFormat` that replaces '#' characters with provided arguments. ```rust use std::str::MatchIndices; use dynfmt2::{ArgumentSpec, Format, Error}; struct HashFormat; impl<'f> Format<'f> for HashFormat { type Iter = HashIter<'f>; fn iter_args(&self, format: &'f str) -> Result> { Ok(HashIter(format.match_indices('#'))) } } struct HashIter<'f>(MatchIndices<'f, char>); impl<'f> Iterator for HashIter<'f> { type Item = Result, Error<'f>>; fn next(&mut self) -> Option { self.0.next().map(|(index, _)| Ok(ArgumentSpec::new(index, index + 1))) } } let formatted = HashFormat.format("hello, #", &["world"]); assert_eq!("hello, world", formatted.expect("formatting failed")); ``` -------------------------------- ### Cargo.toml - dynfmt2 Dependency Source: https://context7.com/dathere/dynfmt2/llms.txt Example of how to add dynfmt2 as a dependency in your Cargo.toml file. The default features include JSON support and all built-in formats. ```toml # Cargo.toml [dependencies] # Default: json + all built-in formats dynfmt2 = "0.3" ``` -------------------------------- ### Enable All Features in Dynfmt2 Source: https://context7.com/dathere/dynfmt2/llms.txt Activate all available features for Dynfmt2, including JSON, Python printf-style, and curly-brace formatting. ```toml dynfmt2 = { version = "0.3", features = ["json", "python", "curly"] } ``` -------------------------------- ### SimpleCurlyFormat - Named Keys Source: https://context7.com/dathere/dynfmt2/llms.txt Illustrates formatting with named keys using a BTreeMap with SimpleCurlyFormat. Requires the `curly` feature. ```rust use dynfmt2::{Format, SimpleCurlyFormat}; use std::collections::BTreeMap; // Named keys via BTreeMap let mut ctx = BTreeMap::new(); ctx.insert("host", "localhost"); ctx.insert("port", "8080"); let s = SimpleCurlyFormat.format("http://{host}:{port}/api", ctx).unwrap(); assert_eq!(s, "http://localhost:8080/api"); ``` -------------------------------- ### Enable Python Printf-Style Formatting in Dynfmt2 Source: https://context7.com/dathere/dynfmt2/llms.txt Configure Dynfmt2 to use Python's printf-style formatting. This option pulls in the `regex` crate as a dependency. ```toml dynfmt2 = { version = "0.3", default-features = false, features = ["python"] } ``` -------------------------------- ### ArgumentSpec - Custom Format Implementation Source: https://context7.com/dathere/dynfmt2/llms.txt Illustrates implementing a custom `Format` trait using `ArgumentSpec` and its builder API, with '#' as a positional placeholder. ```rust use std::str::MatchIndices; use dynfmt2::{ArgumentSpec, Format, FormatType, Alignment, Count, Position, Error}; /// A format that uses `#` as a positional placeholder. struct HashFormat; struct HashIter<'f>(MatchIndices<'f, char>); impl<'f> Iterator for HashIter<'f> { type Item = Result, Error<'f>>; fn next(&mut self) -> Option { self.0.next().map(|(i, _)| { Ok(ArgumentSpec::new(i, i + 1) .with_position(Position::Auto) .with_format(FormatType::Display)) }) } } impl<'f> Format<'f> for HashFormat { type Iter = HashIter<'f>; fn iter_args(&self, format: &'f str) -> Result> { Ok(HashIter(format.match_indices('#'))) } } let s = HashFormat.format("# plus # equals #", &[1_i32, 2_i32, 3_i32]).unwrap(); assert_eq!(s, "1 plus 2 equals 3"); ``` -------------------------------- ### SimpleCurlyFormat - Auto Positional Arguments Source: https://context7.com/dathere/dynfmt2/llms.txt Demonstrates auto-positional argument formatting using SimpleCurlyFormat. Requires the `curly` feature. ```rust use dynfmt2::{Format, SimpleCurlyFormat}; use std::collections::BTreeMap; // Auto positional let s = SimpleCurlyFormat.format("{} {}", &["one", "two"]).unwrap(); assert_eq!(s, "one two"); ``` -------------------------------- ### Enable JSON Serialization Helper in Dynfmt2 Source: https://context7.com/dathere/dynfmt2/llms.txt Use this configuration to enable only the JSON serialization helper for Dynfmt2. This is useful when you need JSON output but not specific formatting syntaxes. ```toml dynfmt2 = { version = "0.3", default-features = false, features = ["json"] } ``` -------------------------------- ### Format Trait - format method Source: https://context7.com/dathere/dynfmt2/llms.txt The primary entry point for all formatting operations. It accepts a format string and a value implementing FormatArgs, returning a formatted string or an error. If the format string has no placeholders, the original string is returned without allocation. ```APIDOC ## `Format` trait — `format` method ### Description The primary entry point for all formatting. Accepts a format string and any value implementing `FormatArgs`, returns `Ok(Cow)` on success or an `Error` on failure. When the format string contains no argument placeholders the original `&str` is returned without allocation. ### Method Signature `fn format(&self, fmt: &str, args: &impl FormatArgs) -> Result, Error>` ### Usage Examples #### SimpleCurlyFormat ```rust use dynfmt2::{Format, SimpleCurlyFormat}; let s = SimpleCurlyFormat.format("Hello, {}!", &["world"]).unwrap(); assert_eq!(s, "Hello, world!"); let s = SimpleCurlyFormat.format("{0} + {0} = {1}", &[2_i32, 4_i32]).unwrap(); assert_eq!(s, "2 + 2 = 4"); let mut map = std::collections::BTreeMap::new(); map.insert("lang", "Rust"); map.insert("version", "1.70"); let s = SimpleCurlyFormat.format("{lang} {version}", map).unwrap(); assert_eq!(s, "Rust 1.70"); ``` #### PythonFormat ```rust use dynfmt2::{Format, PythonFormat}; let s = PythonFormat.format("int=%d hex=%x oct=%o", &[255_u32, 255_u32, 255_u32]).unwrap(); assert_eq!(s, "int=255 hex=ff oct=377"); let s = PythonFormat.format("alt-hex=%#x alt-oct=%#o", &[42_u32, 42_u32]).unwrap(); assert_eq!(s, "alt-hex=0x2a alt-oct=0o52"); // Width and alignment let s = PythonFormat.format("[%5s] [%-5s] [%05s]", &["ab", "cd", "7"]).unwrap(); assert_eq!(s, "[ ab] [cd ] [00007]"); // Named mapping-key syntax: %(key)s let mut args = std::collections::BTreeMap::new(); args.insert("name", "Alice"); args.insert("score", "99"); let s = PythonFormat.format("%(name)s scored %(score)s", args).unwrap(); assert_eq!(s, "Alice scored 99"); // Width read from the next argument (*) let s = PythonFormat.format("[%*s]", &[6_usize, 42_i32]).unwrap(); assert_eq!(s, "[ 42]"); ``` #### NoopFormat ```rust use dynfmt2::{Format, NoopFormat}; let s = NoopFormat.format("no placeholders here", &["ignored"]).unwrap(); assert_eq!(s, "no placeholders here"); ``` ``` -------------------------------- ### PythonFormat JSON/repr Output Source: https://context7.com/dathere/dynfmt2/llms.txt Illustrates how PythonFormat serializes complex types as JSON using %s (Display) and %r (JSON representation). The '#' flag enables pretty-printing. Requires the 'json' feature. ```rust use dynfmt2::{Format, PythonFormat}; use std::collections::BTreeMap; // Slice serialized as JSON array let s = PythonFormat.format("array = %s", &[[1_i32, 2, 3]]).unwrap(); assert_eq!(s, "array = [1,2,3]"); // %r forces JSON repr even for strings (adds quotes) let s = PythonFormat.format("repr = %r", &["hello"]).unwrap(); assert_eq!(s, "repr = \"hello\""); // %#r pretty-prints JSON let s = PythonFormat.format("pretty = %#r", &[[1_i32, 2, 3]]).unwrap(); assert_eq!(s, "pretty = [ 1, 2, 3 ]"); // Map serialized as JSON object let mut m = BTreeMap::new(); m.insert("key", "value"); let s = PythonFormat.format("obj = %r", [m]).unwrap(); assert_eq!(s, "obj = {\"key\":\"value\"}"); ``` -------------------------------- ### FormatArgs - Custom Struct for Named Arguments Source: https://context7.com/dathere/dynfmt2/llms.txt Shows how to implement the `FormatArgs` trait for a custom struct to be used as a named argument source in formatting. ```rust use dynfmt2::{Argument, FormatArgs, Format, SimpleCurlyFormat}; use serde::Serialize; // Custom two-field struct as a named argument source struct Config { host: String, port: u16, } impl FormatArgs for Config { fn get_key(&self, key: &str) -> Result>, ()> { match key { "host" => Ok(Some(&self.host as Argument<'_>)), "port" => Ok(Some(&self.port as Argument<'_>)), _ => Ok(None), } } } let cfg = Config { host: "db.example.com".into(), port: 5432 }; let s = SimpleCurlyFormat.format("connecting to {host}:{port}", cfg).unwrap(); assert_eq!(s, "connecting to db.example.com:5432"); ``` -------------------------------- ### Enable Curly-Brace Formatting in Dynfmt2 Source: https://context7.com/dathere/dynfmt2/llms.txt Enable the curly-brace formatting syntax for Dynfmt2. This feature also requires the `regex` crate. ```toml dynfmt2 = { version = "0.3", default-features = false, features = ["curly"] } ``` -------------------------------- ### PythonFormat - JSON / repr output Source: https://context7.com/dathere/dynfmt2/llms.txt Demonstrates how PythonFormat can serialize serde::Serialize values as JSON. The `%s` verb uses the Display representation (delegating to JSON for collections/maps), while `%r` always uses the JSON representation. The `#` flag enables pretty-printed JSON. Requires the `json` feature. ```APIDOC ## `PythonFormat` — JSON / repr output (`%r`, `%s` on complex types) ### Description `PythonFormat` can serialize any `serde::Serialize` value as compact or pretty JSON. `%s` invokes the `Display` representation (delegates to JSON for collections/maps), while `%r` always uses the JSON representation. The `#` flag switches to pretty-printed JSON. Requires the `json` feature (default). ### Usage Examples #### Slice serialized as JSON array ```rust use dynfmt2::{Format, PythonFormat}; let s = PythonFormat.format("array = %s", &[[1_i32, 2, 3]]).unwrap(); assert_eq!(s, "array = [1,2,3]"); ``` #### `%r` forces JSON repr even for strings (adds quotes) ```rust use dynfmt2::{Format, PythonFormat}; let s = PythonFormat.format("repr = %r", &["hello"]).unwrap(); assert_eq!(s, "repr = \"hello\""); ``` #### `%#r` pretty-prints JSON ```rust use dynfmt2::{Format, PythonFormat}; let s = PythonFormat.format("pretty = %#r", &[[1_i32, 2, 3]]).unwrap(); assert_eq!(s, "pretty = [\n 1,\n 2,\n 3\n]"); ``` #### Map serialized as JSON object ```rust use dynfmt2::{Format, PythonFormat}; use std::collections::BTreeMap; let mut m = BTreeMap::new(); m.insert("key", "value"); let s = PythonFormat.format("obj = %r", [m]).unwrap(); assert_eq!(s, "obj = {\"key\":\"value\"}"); ``` ``` -------------------------------- ### SimpleCurlyFormat - Explicit Index and Reuse Source: https://context7.com/dathere/dynfmt2/llms.txt Shows explicit indexing and argument reuse with SimpleCurlyFormat. Requires the `curly` feature. ```rust use dynfmt2::{Format, SimpleCurlyFormat}; use std::collections::BTreeMap; // Explicit index (reuse) let s = SimpleCurlyFormat.format("{0}/{0}/{1}", &["ping", "pong"]).unwrap(); assert_eq!(s, "ping/ping/pong"); ``` -------------------------------- ### Error Enum - Runtime Formatting Errors Source: https://context7.com/dathere/dynfmt2/llms.txt Demonstrates various `Error` variants for runtime formatting failures, including missing arguments and incorrect container types. ```rust use std::borrow::Cow; use dynfmt2::{Error, FormatType, Position, Format, SimpleCurlyFormat}; // Missing argument let result = SimpleCurlyFormat.format("{} and {}", &["only-one"]); assert!(matches!(result, Err(Error::MissingArg(Position::Index(1))))) ``` ```rust use std::borrow::Cow; use dynfmt2::{Error, FormatType, Position, Format, SimpleCurlyFormat}; // Attempt named access on an indexed container let result = SimpleCurlyFormat.format("{name}", &["val"]); assert!(matches!(result, Err(Error::MapRequired))) ``` ```rust use std::borrow::Cow; use dynfmt2::{Error, FormatType, Position, Format, SimpleCurlyFormat}; // Display rendering of each variant assert_eq!(format!("{}", Error::BadFormat('q')), "unsupported format 'q'"); assert_eq!(format!("{}", Error::ListRequired), "format requires an argument list"); assert_eq!(format!("{}", Error::MapRequired), "format requires an argument map"); assert_eq!(format!("{}", Error::MissingArg(Position::Index(2))), "missing argument: 2"); assert_eq!( format!("{}", Error::BadArg(Position::Key("x"), FormatType::Object)), "argument 'x' cannot be formatted as object" ); assert_eq!( format!("{}", Error::BadData(Position::Auto, "overflow".into())), "error formatting argument '{next}': overflow" ); ``` -------------------------------- ### SimpleCurlyFormat - Mixed Numeric Types Source: https://context7.com/dathere/dynfmt2/llms.txt Demonstrates formatting of mixed numeric types (float, integer, boolean) using SimpleCurlyFormat. Requires the `curly` feature. ```rust use dynfmt2::{Format, SimpleCurlyFormat}; use std::collections::BTreeMap; // Mixed numeric types let s = SimpleCurlyFormat.format("f={} i={} b={}", &[3.14_f64, 42_i32, true]).unwrap(); assert_eq!(s, "f=3.14 i=42 b=true"); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.