@@ -591,6 +591,10 @@ impl<'a> ToGlibPtr<'a, *mut c_char> for GStr {
591
591
}
592
592
}
593
593
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
+
594
598
// rustdoc-stripper-ignore-next
595
599
/// A type representing an owned, C-compatible, nul-terminated UTF-8 string.
596
600
///
@@ -627,6 +631,22 @@ impl GString {
627
631
Self ( Inner :: Native ( None ) )
628
632
}
629
633
// 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
+ }
630
650
// rustdoc-stripper-ignore-next
631
651
/// Creates a GLib string by consuming a byte vector.
632
652
///
@@ -884,6 +904,16 @@ impl GString {
884
904
}
885
905
}
886
906
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
+
887
917
// rustdoc-stripper-ignore-next
888
918
/// Error type indicating that a buffer did not have a trailing nul-byte.
889
919
///
@@ -1971,4 +2001,10 @@ mod tests {
1971
2001
assert_ne ! ( ptr, gstring. as_ptr( ) as * const _) ;
1972
2002
}
1973
2003
}
2004
+
2005
+ #[ test]
2006
+ fn gformat ( ) {
2007
+ let s = gformat ! ( "bla bla {} bla" , 123 ) ;
2008
+ assert_eq ! ( s, "bla bla 123 bla" ) ;
2009
+ }
1974
2010
}
0 commit comments