Skip to content

Commit 3caed0f

Browse files
jf2048sdroege
authored andcommitted
glib: add gformat! for directly formatting into a GString
1 parent 9753a72 commit 3caed0f

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

glib/src/gstring.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -591,6 +591,10 @@ impl<'a> ToGlibPtr<'a, *mut c_char> for GStr {
591591
}
592592
}
593593

594+
// size_of::<Inner>() minus two bytes for length and enum discriminant
595+
const INLINE_LEN: usize =
596+
mem::size_of::<Option<Box<str>>>() + mem::size_of::<usize>() - mem::size_of::<u8>() * 2;
597+
594598
// rustdoc-stripper-ignore-next
595599
/// A type representing an owned, C-compatible, nul-terminated UTF-8 string.
596600
///
@@ -627,6 +631,22 @@ impl GString {
627631
Self(Inner::Native(None))
628632
}
629633
// rustdoc-stripper-ignore-next
634+
/// Formats an [`Arguments`](std::fmt::Arguments) into a [`GString`].
635+
///
636+
/// This function is the same as [`std::fmt::format`], except it returns a [`GString`]. The
637+
/// [`Arguments`](std::fmt::Arguments) instance can be created with the
638+
/// [`format_args!`](std::format_args) macro.
639+
///
640+
/// Please note that using [`gformat!`] might be preferable.
641+
pub fn format(args: fmt::Arguments) -> Self {
642+
if let Some(s) = args.as_str() {
643+
return Self::from(s);
644+
}
645+
646+
let mut s = crate::GStringBuilder::default();
647+
fmt::Write::write_fmt(&mut s, args).unwrap();
648+
s.into_string()
649+
}
630650
// rustdoc-stripper-ignore-next
631651
/// Creates a GLib string by consuming a byte vector.
632652
///
@@ -884,6 +904,16 @@ impl GString {
884904
}
885905
}
886906

907+
// rustdoc-stripper-ignore-next
908+
/// Creates a [`GString`] using interpolation of runtime expressions.
909+
///
910+
/// This macro is the same as [`std::format!`] except it returns a [`GString`]. It is faster than
911+
/// creating a [`String`] and then converting it manually to a [`GString`].
912+
#[macro_export]
913+
macro_rules! gformat {
914+
($($arg:tt)*) => { GString::format(std::format_args!($($arg)*)) };
915+
}
916+
887917
// rustdoc-stripper-ignore-next
888918
/// Error type indicating that a buffer did not have a trailing nul-byte.
889919
///
@@ -1971,4 +2001,10 @@ mod tests {
19712001
assert_ne!(ptr, gstring.as_ptr() as *const _);
19722002
}
19732003
}
2004+
2005+
#[test]
2006+
fn gformat() {
2007+
let s = gformat!("bla bla {} bla", 123);
2008+
assert_eq!(s, "bla bla 123 bla");
2009+
}
19742010
}

0 commit comments

Comments
 (0)