Skip to content

Commit a37b484

Browse files
committed
Allow fmt::Arguments::as_str() to return more Some(_).
1 parent 222d1ff commit a37b484

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

library/core/src/fmt/mod.rs

+20-3
Original file line numberDiff line numberDiff line change
@@ -484,9 +484,26 @@ pub struct Arguments<'a> {
484484
}
485485

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

0 commit comments

Comments
 (0)