bpaf/
from_os_str.rs

1use std::{
2    any::{Any, TypeId},
3    ffi::OsString,
4    path::PathBuf,
5    str::FromStr,
6};
7
8pub(crate) fn parse_os_str<T>(os: OsString) -> Result<T, String>
9where
10    T: FromStr + 'static,
11    <T as std::str::FromStr>::Err: std::fmt::Display,
12{
13    if TypeId::of::<T>() == TypeId::of::<OsString>() {
14        let anybox: Box<dyn Any> = Box::new(os);
15        Ok(*(anybox.downcast::<T>().unwrap()))
16    } else if TypeId::of::<T>() == TypeId::of::<PathBuf>() {
17        let anybox: Box<dyn Any> = Box::new(PathBuf::from(os));
18        Ok(*(anybox.downcast::<T>().unwrap()))
19    } else {
20        match os.to_str() {
21            Some(s) => T::from_str(s).map_err(|e| e.to_string()),
22            None => Err(format!("{} is not a valid utf8", os.to_string_lossy())),
23        }
24    }
25}