[][src]Crate lazy_format

lazy_format is a collection of format!-style macros which lazily formatting their arguments its arguments. That is, rather than immediatly formatting them into a String (which is what format!) does, it captures its arguments and returns an opaque struct with a Display implementation, so that the actual formatting can happen directly into its final destination buffer (such as a file or string).

use std::fmt::Display;

use lazy_format::prelude::*;

// NOTE: This is obviously profoundly unsafe and you should never actually
// render HTML without escape guards, code injection prevention, etc.
fn html_tag<'a>(tag: &'a str, content: impl Display + 'a) -> impl Display + 'a {
    lazy_format!("<{tag}>{content}</{tag}>", tag=tag, content=content)
}

let result = html_tag("div", html_tag("p", "Hello, World!")).to_string();
assert_eq!(result, "<div><p>Hello, World!</p></div>");

This library contains two lazy formatting macros:

  • lazy_format!, a completely lazy formatter. It captures the expressions passed as arguments in a closure, and doesn't evaluate them until the instance is actually written to a destination (like a string or file). This means that the expressions are evaluated every time the instance is written somewhere.
  • semi_lazy_format! is partially lazy. It fully evaluates all of its arguments when it is invoked, but it stores them inside the returned instance and formats them when the instance is written.

Modules

prelude

Macros

lazy_format

Lazily format something.

semi_lazy_format

Lazily format something, but eagerly evaluate the arguments ahead of time.