From d566b5db9bacd68c696d456a6d18569a50e7cb58 Mon Sep 17 00:00:00 2001 From: Matthew Zeitlin <37011898+mzeitlin11@users.noreply.github.com> Date: Sat, 8 Feb 2025 16:51:04 -0500 Subject: [PATCH] Implement Extend for String --- library/alloc/src/string.rs | 26 ++++++++++++++++++++++++++ library/coretests/tests/ascii_char.rs | 12 ++++++++++++ library/coretests/tests/lib.rs | 1 + 3 files changed, 39 insertions(+) diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index b29f740ef0f2a..154da69107884 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -2442,6 +2442,32 @@ impl<'a> Extend> for String { } } +#[cfg(not(no_global_oom_handling))] +#[unstable(feature = "ascii_char", issue = "110998")] +impl Extend for String { + fn extend>(&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>(&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 diff --git a/library/coretests/tests/ascii_char.rs b/library/coretests/tests/ascii_char.rs index 75b5fd4b9e61d..f5a15a9469f3f 100644 --- a/library/coretests/tests/ascii_char.rs +++ b/library/coretests/tests/ascii_char.rs @@ -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")); +} diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index f1bbed3de3017..03527f237c151 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -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)]