Skip to content

Commit

Permalink
Rollup merge of rust-lang#76525 - fusion-engineering-forks:string-dra…
Browse files Browse the repository at this point in the history
…in, r=dtolnay

Add as_str() to string::Drain.

Vec's Drain recently [had its `.as_slice()` stabilized](rust-lang#72584), but String's Drain was still missing the analogous `.as_str()`. This adds that.

Also improves the Debug implementation, which now shows the remaining data instead of just `"Drain { .. }"`.
  • Loading branch information
RalfJung committed Sep 19, 2020
2 parents fef3324 + 15eb638 commit 46bb884
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2440,7 +2440,7 @@ pub struct Drain<'a> {
#[stable(feature = "collection_debug", since = "1.17.0")]
impl fmt::Debug for Drain<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("Drain { .. }")
f.debug_tuple("Drain").field(&self.as_str()).finish()
}
}

Expand All @@ -2463,6 +2463,40 @@ impl Drop for Drain<'_> {
}
}

impl<'a> Drain<'a> {
/// Returns the remaining (sub)string of this iterator as a slice.
///
/// # Examples
///
/// ```
/// #![feature(string_drain_as_str)]
/// let mut s = String::from("abc");
/// let mut drain = s.drain(..);
/// assert_eq!(drain.as_str(), "abc");
/// let _ = drain.next().unwrap();
/// assert_eq!(drain.as_str(), "bc");
/// ```
#[unstable(feature = "string_drain_as_str", issue = "76905")] // Note: uncomment AsRef impls below when stabilizing.
pub fn as_str(&self) -> &str {
self.iter.as_str()
}
}

// Uncomment when stabilizing `string_drain_as_str`.
// #[unstable(feature = "string_drain_as_str", issue = "76905")]
// impl<'a> AsRef<str> for Drain<'a> {
// fn as_ref(&self) -> &str {
// self.as_str()
// }
// }
//
// #[unstable(feature = "string_drain_as_str", issue = "76905")]
// impl<'a> AsRef<[u8]> for Drain<'a> {
// fn as_ref(&self) -> &[u8] {
// self.as_str().as_bytes()
// }
// }

#[stable(feature = "drain", since = "1.6.0")]
impl Iterator for Drain<'_> {
type Item = char;
Expand Down

0 comments on commit 46bb884

Please sign in to comment.