Skip to content

Commit

Permalink
Add impls for iterators of Cow<OsStr>
Browse files Browse the repository at this point in the history
  • Loading branch information
lopopolo committed Mar 3, 2021
1 parent 2fcb8b5 commit 05ea200
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions library/std/src/ffi/os_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1204,6 +1204,16 @@ impl<'a> Extend<&'a OsStr> for OsString {
}
}

#[stable(feature = "osstring_extend", since = "1.52.0")]
impl<'a> Extend<Cow<'a, OsStr>> for OsString {
#[inline]
fn extend<T: IntoIterator<Item = Cow<'a, OsStr>>>(&mut self, iter: T) {
for s in iter {
self.push(&s);
}
}
}

#[stable(feature = "osstring_extend", since = "1.52.0")]
impl FromIterator<OsString> for OsString {
#[inline]
Expand Down Expand Up @@ -1234,3 +1244,27 @@ impl<'a> FromIterator<&'a OsStr> for OsString {
buf
}
}

#[stable(feature = "osstring_extend", since = "1.52.0")]
impl<'a> FromIterator<Cow<'a, OsStr>> for OsString {
#[inline]
fn from_iter<I: IntoIterator<Item = Cow<'a, OsStr>>>(iter: I) -> Self {
let mut iterator = iter.into_iter();

// Because we're iterating over `OsString`s, we can avoid at least
// one allocation by getting the first owned string from the iterator
// and appending to it all the subsequent strings.
match iterator.next() {
None => OsString::new(),
Some(Cow::Owned(mut buf)) => {
buf.extend(iterator);
buf
}
Some(Cow::Borrowed(buf)) => {
let mut buf = OsString::from(buf);
buf.extend(iterator);
buf
}
}
}
}

0 comments on commit 05ea200

Please sign in to comment.