Skip to content
/ rust Public
forked from rust-lang/rust

Commit

Permalink
Rollup merge of rust-lang#136749 - mzeitlin11:extend-asciichar, r=sco…
Browse files Browse the repository at this point in the history
…ttmcm

Implement Extend<AsciiChar> for String

Implement `Extend<AsciiChar>` for `String` as suggested in rust-lang#110998 (comment). Also implements `Extend<&AsciiChar>` since there's an analogous impl for `Extend<&char>`, but happy to remove if not thought useful.

r? `@scottmcm`
since you requested it, but no pressure to review!
  • Loading branch information
jhpratt authored Feb 15, 2025
2 parents 92adb92 + d566b5d commit 26be558
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
26 changes: 26 additions & 0 deletions library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2442,6 +2442,32 @@ impl<'a> Extend<Cow<'a, str>> for String {
}
}

#[cfg(not(no_global_oom_handling))]
#[unstable(feature = "ascii_char", issue = "110998")]
impl Extend<core::ascii::Char> for String {
fn extend<I: IntoIterator<Item = core::ascii::Char>>(&mut self, iter: I) {
self.vec.extend(iter.into_iter().map(|c| c.to_u8()));
}

#[inline]
fn extend_one(&mut self, c: core::ascii::Char) {
self.vec.push(c.to_u8());
}
}

#[cfg(not(no_global_oom_handling))]
#[unstable(feature = "ascii_char", issue = "110998")]
impl<'a> Extend<&'a core::ascii::Char> for String {
fn extend<I: IntoIterator<Item = &'a core::ascii::Char>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned());
}

#[inline]
fn extend_one(&mut self, c: &'a core::ascii::Char) {
self.vec.push(c.to_u8());
}
}

/// A convenience impl that delegates to the impl for `&str`.
///
/// # Examples
Expand Down
12 changes: 12 additions & 0 deletions library/coretests/tests/ascii_char.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,15 @@ fn test_debug_control() {
assert_eq!(want, format!("{chr:?}"), "byte: {byte}");
}
}

/// Tests Extend implementation for ascii::Char.
#[test]
fn test_extend() {
let mut s = String::from("abc");
s.extend_one(Char::SmallD);
assert_eq!(s, String::from("abcd"));

let mut s = String::from("abc");
s.extend(Char::CapitalA..=Char::CapitalC);
assert_eq!(s, String::from("abcABC"));
}
1 change: 1 addition & 0 deletions library/coretests/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#![feature(duration_constructors)]
#![feature(error_generic_member_access)]
#![feature(exact_size_is_empty)]
#![feature(extend_one)]
#![feature(extern_types)]
#![feature(float_minimum_maximum)]
#![feature(flt2dec)]
Expand Down

0 comments on commit 26be558

Please sign in to comment.