Skip to main content

lazy_format

Macro lazy_format 

Source
macro_rules! lazy_format {
    (move, $($arg:tt)*) => { ... };
    ($($arg:tt)*) => { ... };
}
Expand description

A macro that behaves like format! but constructs a LazyString to defer string formatting until the result is actually displayed. If the LazyString is never displayed, this construct has minimal overhead.

use diskann_utils::lazy_format;

let a: f32 = 10.5;
let b: usize = 20;

let lazy_string = lazy_format!("This is a test. A = {}, B = {}", a, b);
assert_eq!(lazy_string.to_string(), "This is a test. A = 10.5, B = 20");

// Formatting of captured members is deferred until the created `LazyString` is formatted.
#[derive(Default)]
struct Formatted(std::cell::Cell<bool>);

impl Formatted {
    fn was_formatted(&self) -> bool {
        self.0.get()
    }

    fn mark_as_formatted(&self) {
        self.0.set(true)
    }
}

impl std::fmt::Display for Formatted {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.was_formatted() {
            f.write_str("yes")
        } else {
            self.mark_as_formatted();
            f.write_str("not yet")
        }
    }
}

let f = Formatted::default();
let lazy = lazy_format!("Was this formatted: {f}");

assert!(!f.was_formatted(), "string formatting should be deferred");
assert_eq!(lazy.to_string(), "Was this formatted: not yet");

assert!(f.was_formatted());
assert_eq!(lazy.to_string(), "Was this formatted: yes");

§Creating lazily formatted 'static error messages

The default LazyString created by this macro borrows from its formatted arguments and thus has a lifetime constrained to its arguments.

If a lazily formatted 'static compliant variation is needed, the “move” variant can be used (assuming all captured arguments are 'static):

use diskann_utils::lazy_format;

fn assert_static<T: 'static>(_: &T) {}

let x = 10;

let lazy = lazy_format!(move, "x = {x}");
assert_static(&lazy);
assert_eq!(lazy.to_string(), "x = 10");