diff options
| author | Ryan Lopopolo <rjl@hyperbo.la> | 2021-03-03 11:52:14 -0800 |
|---|---|---|
| committer | Ryan Lopopolo <rjl@hyperbo.la> | 2021-03-03 11:52:14 -0800 |
| commit | 05ea200213fe30967fff38ebac887c52803aabd5 (patch) | |
| tree | 7cff92e046095b61ae4e78044215224402723eab | |
| parent | 2fcb8b5c201d22060f1ba46cc2291cacca593e02 (diff) | |
| download | rust-05ea200213fe30967fff38ebac887c52803aabd5.tar.gz rust-05ea200213fe30967fff38ebac887c52803aabd5.zip | |
Add impls for iterators of Cow<OsStr>
| -rw-r--r-- | library/std/src/ffi/os_str.rs | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/library/std/src/ffi/os_str.rs b/library/std/src/ffi/os_str.rs index 8240aafae74..8bdd9a88473 100644 --- a/library/std/src/ffi/os_str.rs +++ b/library/std/src/ffi/os_str.rs @@ -1205,6 +1205,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] fn from_iter<I: IntoIterator<Item = OsString>>(iter: I) -> Self { @@ -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 + } + } + } +} |
