Skip to content

Commit cafda41

Browse files
authored
Rollup merge of rust-lang#141445 - yotamofek:pr/library/from-iter-char-string, r=the8472,joshtriplett
Add `FromIterator` impls for `ascii::Char`s to `String`s Wanted to `collect` ascii chars into a `String` while working on rust-lang#141369 , and was surprised these impls don't exist. Seems to me to be simply oversight. BTW, I only added `impl FromIterator<ascii::Char> for Cow<'_, str>`, without a corresponding `FromIterator<&Char>` impl, because there's no existing impl for `FromIterator<&char>`, but that might be oversight too. cc rust-lang#110998
2 parents 18d39c9 + bfa6fa4 commit cafda41

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

alloc/src/string.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2378,6 +2378,28 @@ impl<'a> FromIterator<Cow<'a, str>> for String {
23782378
}
23792379
}
23802380

2381+
#[cfg(not(no_global_oom_handling))]
2382+
#[unstable(feature = "ascii_char", issue = "110998")]
2383+
impl FromIterator<core::ascii::Char> for String {
2384+
fn from_iter<T: IntoIterator<Item = core::ascii::Char>>(iter: T) -> Self {
2385+
let buf = iter.into_iter().map(core::ascii::Char::to_u8).collect();
2386+
// SAFETY: `buf` is guaranteed to be valid UTF-8 because the `core::ascii::Char` type
2387+
// only contains ASCII values (0x00-0x7F), which are valid UTF-8.
2388+
unsafe { String::from_utf8_unchecked(buf) }
2389+
}
2390+
}
2391+
2392+
#[cfg(not(no_global_oom_handling))]
2393+
#[unstable(feature = "ascii_char", issue = "110998")]
2394+
impl<'a> FromIterator<&'a core::ascii::Char> for String {
2395+
fn from_iter<T: IntoIterator<Item = &'a core::ascii::Char>>(iter: T) -> Self {
2396+
let buf = iter.into_iter().copied().map(core::ascii::Char::to_u8).collect();
2397+
// SAFETY: `buf` is guaranteed to be valid UTF-8 because the `core::ascii::Char` type
2398+
// only contains ASCII values (0x00-0x7F), which are valid UTF-8.
2399+
unsafe { String::from_utf8_unchecked(buf) }
2400+
}
2401+
}
2402+
23812403
#[cfg(not(no_global_oom_handling))]
23822404
#[stable(feature = "rust1", since = "1.0.0")]
23832405
impl Extend<char> for String {
@@ -3184,6 +3206,14 @@ impl<'a> FromIterator<String> for Cow<'a, str> {
31843206
}
31853207
}
31863208

3209+
#[cfg(not(no_global_oom_handling))]
3210+
#[unstable(feature = "ascii_char", issue = "110998")]
3211+
impl<'a> FromIterator<core::ascii::Char> for Cow<'a, str> {
3212+
fn from_iter<T: IntoIterator<Item = core::ascii::Char>>(it: T) -> Self {
3213+
Cow::Owned(FromIterator::from_iter(it))
3214+
}
3215+
}
3216+
31873217
#[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
31883218
impl From<String> for Vec<u8> {
31893219
/// Converts the given [`String`] to a vector [`Vec`] that holds values of type [`u8`].

0 commit comments

Comments
 (0)