Module pfmt::extras

source ·
Expand description

Non-essential niceties

Closures support

There are several struct wrappers over closures which allow using closures as Fmts. All of them are defined for FnMut closures. The simplest form of these is Lazy, which wraps a closure producing a single Fmt to actually control the formatting. There are also several AdHoc* structures, with arguments of each being a subset of arguments of the format method on Fmt. The intent is to provide a way to get some quick-and-dirty formatting without defining a new data type.

Since all of these are defined not just for Fns, but for FnMuts, it’s possible to do neat things like self-incrementing lists:

use std::collections::HashMap;
 
use pfmt::{Fmt, FormatTable};
use pfmt::extras::Lazy;
 
let mut index = 0;
let mut counter = Lazy::new(move || { index += 1; index });
let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
table.insert("i", &counter);
let s = table.format("{i} - spam\n{i} - eggs").unwrap();
assert_eq!(&s, "1 - spam\n2 - eggs");

Single-entry format tables

Sometimes all you need is a quick and dirty formatting, which clashes somewhat with the nature of the format tables in the main module - their construction is quite burdensome. Enter Mono and tuples. A Mono is a tuple struct with a string key (or anything that derefs to a str) and some Fmt value. It is also a format table. The following works:

use pfmt::FormatTable;
use pfmt::extras::Mono;
 
let a = Mono("a", 5);
let b = Mono("b", "foobar");
let s = (&a, &b).format("{a}, {b}").unwrap();
assert_eq!(&s, "5, foobar");

They can be combined with hash tables and vectors in the same fashion, the main module docs have an example.

Structs

A wrapper over a closure that accepts full_name, name and args parameters of the format method on Fmt.
A wrapper over a closure that accepts full_name, name, flags and options parameters of the format method on Fmt.
A wrapper over a closure with the same signature as the format method on Fmt.
A wrapper over a closure that accepts full_name, name and options parameters of the format method on Fmt.
A wrapper over a closure producing a Fmt.
A format table with a single entry, accessed by a string key.