algosul_core/utils/
std.rs

1use std::{
2  borrow::Cow,
3  ffi::{OsStr, OsString},
4};
5
6#[macro_export]
7macro_rules! cows {
8  [] => {
9    []
10  };
11  [$($elem:expr),+ $(,)?] => {
12    [
13      $(
14        $crate::cow!($elem)
15      ),+
16    ]
17  };
18  [$elem:expr; $n:expr] => (
19    [$crate::cow!($elem); $n]
20  );
21}
22#[macro_export]
23macro_rules! cow {
24  ($expr:expr) => {
25    ::std::borrow::Cow::<'_, _>::from($expr)
26  };
27}
28pub trait MapToArg<'b>
29{
30  fn map_to_arg(self) -> Cow<'b, OsStr>;
31}
32pub trait MapToArgs<'b>
33{
34  fn map_to_args(self) -> impl Iterator<Item = Cow<'b, OsStr>>;
35}
36
37/// [issue: #1958](https://github.com/rust-lang/reference/issues/1958)
38pub trait CowExt<'a, T: ?Sized + ToOwned + 'a>
39{
40  fn map_ref_or_owned<'b, U: ?Sized + ToOwned, B, O>(
41    self, b: B, o: O,
42  ) -> Cow<'b, U>
43  where
44    B: FnOnce(&'a T) -> &'b U,
45    O: FnOnce(T::Owned) -> U::Owned;
46  fn map_to_cow<'b, U: ?Sized + ToOwned, B, O>(self, b: B, o: O) -> Cow<'b, U>
47  where
48    B: FnOnce(&'a T) -> Cow<'b, U>,
49    O: FnOnce(T::Owned) -> Cow<'b, U>;
50}
51impl<'a, T: ?Sized + ToOwned> CowExt<'a, T> for Cow<'a, T>
52{
53  #[inline]
54  fn map_ref_or_owned<'b, U: ?Sized + ToOwned, B, O>(
55    self, b: B, o: O,
56  ) -> Cow<'b, U>
57  where
58    B: FnOnce(&'a T) -> &'b U,
59    O: FnOnce(T::Owned) -> U::Owned,
60  {
61    match self
62    {
63      Cow::Borrowed(borrow) => Cow::Borrowed(b(borrow)),
64      Cow::Owned(owned) => Cow::Owned(o(owned)),
65    }
66  }
67
68  #[inline]
69  fn map_to_cow<'b, U: ?Sized + ToOwned, B, O>(self, b: B, o: O) -> Cow<'b, U>
70  where
71    B: FnOnce(&'a T) -> Cow<'b, U>,
72    O: FnOnce(T::Owned) -> Cow<'b, U>,
73  {
74    match self
75    {
76      Cow::Borrowed(borrow) => b(borrow),
77      Cow::Owned(owned) => o(owned),
78    }
79  }
80}
81impl<'a: 'b, 'b, S> MapToArg<'b> for Cow<'a, S>
82where
83  S: ?Sized + ToOwned + AsRef<OsStr> + 'a,
84  S::Owned: Into<OsString>,
85{
86  #[inline]
87  fn map_to_arg(self) -> Cow<'b, OsStr>
88  {
89    self.map_ref_or_owned(OsStr::new, Into::into)
90  }
91}
92impl<'a: 'b, 'b, T, S> MapToArgs<'b> for T
93where
94  S: ?Sized + ToOwned + AsRef<OsStr> + 'a,
95  S::Owned: Into<OsString>,
96  T: IntoIterator<Item = Cow<'a, S>>,
97{
98  #[inline]
99  fn map_to_args(self) -> impl Iterator<Item = Cow<'b, OsStr>>
100  {
101    self.into_iter().map(MapToArg::map_to_arg)
102  }
103}
104
105#[cfg(test)]
106mod tests
107{
108  use std::ffi::OsStr;
109
110  use super::*;
111  #[test]
112  fn test_demo()
113  {
114    demo("test");
115  }
116
117  fn demo(input: &str)
118  {
119    let cow: Cow<'_, str> = Cow::Borrowed(input);
120
121    {
122      let result: Cow<'_, OsStr> = cow.map_ref_or_owned(OsStr::new, Into::into);
123
124      println!("{:?}", result);
125    }
126  }
127}