custom-format
This crate extends the standard formatting syntax with custom format specifiers, by providing custom formatting macros.
It uses :
(a space and a colon) as a separator before the format specifier, which is not a syntax currently accepted and allows supporting standard specifiers in addition to custom specifiers. It also supports format args capture even on older versions of Rust, since it manually adds the named parameter if missing.
This library comes in two flavors, corresponding to the following features:
-
compile-time
(enabled by default)The set of possible custom format specifiers is defined at compilation, so invalid specifiers can be checked at compile-time. This allows the library to have the same performance as when using the standard library formatting traits.
-
runtime
(enabled by default)The formatting method dynamically checks the format specifier at runtime for each invocation. This is a slower version, but it has additional flexibility.
Documentation
Documentation is hosted on docs.rs.
Example
use custom_format as cfmt;
use fmt;
) => ;
}
// Static format specifiers, checked at compile-time
impl_custom_format_for_datetime!;
// Dynamic format specifiers, checked at runtime
let dt = DateTime ;
// Expands to:
//
// match (&("DateTime"), &dt) {
// (arg0, arg1) => ::std::println!(
// "The {0:?} is: {1}-{2}-{3} {4}:{5}:{6}.{7}",
// arg0,
// ::custom_format::custom_formatter!("%Y", arg1),
// ::custom_format::custom_formatter!("%m", arg1),
// ::custom_format::custom_formatter!("%d", arg1),
// ::custom_format::custom_formatter!("%H", arg1),
// ::custom_format::custom_formatter!("%M", arg1),
// ::custom_format::custom_formatter!("%S", arg1),
// ::custom_format::runtime::CustomFormatter::new("%6N", arg1)
// ),
// }
//
// Output: `The "DateTime" is: 1836-05-18 23:45:54.123456`
//
// The custom format specifier is interpreted as a compile-time specifier by default,
// or as a runtime specifier if it is inside "<>".
println!;
// Compile-time error since "%h" is not a valid format specifier
// cfmt::println!("{0 :%h}", dt);
// Panic at runtime since "%h" is not a valid format specifier
// cfmt::println!("{0 :<%h>}", dt);
Compiler support
Requires rustc 1.56+
.
License
This project is licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.