Skip to main content

vk_graph/
lazy_str.rs

1use std::{cell::OnceCell, fmt::Arguments};
2
3/// Creates a [`LazyStr`] from `format_args!` without eagerly allocating a `String`.
4#[macro_export]
5macro_rules! lazy_str {
6    ($($arg:tt)*) => {
7        $crate::LazyStr::new(format_args!($($arg)*))
8    };
9}
10
11/// Lazily formats string arguments on first string access.
12pub struct LazyStr<'a> {
13    args: Arguments<'a>,
14    value: OnceCell<String>,
15}
16
17impl<'a> LazyStr<'a> {
18    /// Creates a lazily formatted string from prebuilt formatting arguments.
19    pub fn new(args: Arguments<'a>) -> Self {
20        Self {
21            args,
22            value: OnceCell::new(),
23        }
24    }
25}
26
27impl AsRef<str> for LazyStr<'_> {
28    fn as_ref(&self) -> &str {
29        self.value.get_or_init(|| self.args.to_string()).as_str()
30    }
31}