Join for slice of OsString/OsStr?

How do I join a slice of OsStrings? The join function does not work as there is no implementation for std::slice::join. Is there some other way or is this an omission in the standard library? It looks like implementing the trait should be straightforward.

I'm guessing there enough desire up until now to justify the effort required to implement and standardize a impl std::slice::Join for OsString.

That said, you could always write your own extension trait which will do what you want. For example,

use std::ffi::{OsStr, OsString};

trait OsStrJoin {
    fn join_os_str<Sep>(&self, separator: Sep) -> OsString
    where
        Sep: AsRef<OsStr>;
}

impl<S> OsStrJoin for [S]
where
    S: AsRef<OsStr>,
{
    fn join_os_str<Sep>(&self, separator: Sep) -> OsString
    where
        Sep: AsRef<OsStr>,
    {
        let mut buffer = OsString::new();
        let separator = separator.as_ref();

        for (i, item) in self.iter().enumerate() {
            if i > 0 {
                buffer.push(separator);
            }
            buffer.push(item.as_ref());
        }

        buffer
    }
}

(playground)

I ended up doing something like that, but as a regular function. The extension trait doesn't add much over a plain function. Too bad there isn't something in the stdlib.

Why not make a PR to std?

I might give that a try. The main thing keeping me is that I haven't contributed to Rust before so I'll need to find out what is required, and I don't know if such a PR would be acceptable or if this would require an RFC with accompanying discussion time.

For something like this, a PR would suffice. Make sure to mark it as unstable with a feature gate for now, to allow evaluating it in nightly for a while.

In this case the feature gate is not so straightforward. The current api has a stable [T].join function, but the Join trait which that function defers to is unstable and feature gated. It is accessible anyway because it is part of the prelude. (Tracking issue for `slice_concat_ext` stabilization · Issue #27747 · rust-lang/rust · GitHub) I think if I add another featuregated impl it will also be exposed in the prelude. Not sure how that works.