Skip to content

Commit bcea989

Browse files
authored
Rollup merge of #106823 - m-ou-se:format-args-as-str-guarantees, r=dtolnay
Allow fmt::Arguments::as_str() to return more Some(_). This adjusts the documentation to allow optimization of format_args!() to be visible through fmt::Arguments::as_str(). This allows for future changes like rust-lang/rust#106824.
2 parents a52c41a + 15da903 commit bcea989

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

core/src/fmt/mod.rs

+20-3
Original file line numberDiff line numberDiff line change
@@ -489,9 +489,26 @@ pub struct Arguments<'a> {
489489
}
490490

491491
impl<'a> Arguments<'a> {
492-
/// Get the formatted string, if it has no arguments to be formatted.
492+
/// Get the formatted string, if it has no arguments to be formatted at runtime.
493493
///
494-
/// This can be used to avoid allocations in the most trivial case.
494+
/// This can be used to avoid allocations in some cases.
495+
///
496+
/// # Guarantees
497+
///
498+
/// For `format_args!("just a literal")`, this function is guaranteed to
499+
/// return `Some("just a literal")`.
500+
///
501+
/// For most cases with placeholders, this function will return `None`.
502+
///
503+
/// However, the compiler may perform optimizations that can cause this
504+
/// function to return `Some(_)` even if the format string contains
505+
/// placeholders. For example, `format_args!("Hello, {}!", "world")` may be
506+
/// optimized to `format_args!("Hello, world!")`, such that `as_str()`
507+
/// returns `Some("Hello, world!")`.
508+
///
509+
/// The behavior for anything but the trivial case (without placeholders)
510+
/// is not guaranteed, and should not be relied upon for anything other
511+
/// than optimization.
495512
///
496513
/// # Examples
497514
///
@@ -512,7 +529,7 @@ impl<'a> Arguments<'a> {
512529
/// ```rust
513530
/// assert_eq!(format_args!("hello").as_str(), Some("hello"));
514531
/// assert_eq!(format_args!("").as_str(), Some(""));
515-
/// assert_eq!(format_args!("{}", 1).as_str(), None);
532+
/// assert_eq!(format_args!("{:?}", std::env::current_dir()).as_str(), None);
516533
/// ```
517534
#[stable(feature = "fmt_as_str", since = "1.52.0")]
518535
#[rustc_const_unstable(feature = "const_arguments_as_str", issue = "103900")]

0 commit comments

Comments
 (0)