@@ -248,6 +248,8 @@ impl PathExt for Path {
248
248
pub trait PathBufExt {
249
249
fn from_slash < S : AsRef < str > > ( s : S ) -> Self ;
250
250
fn from_slash_lossy < S : AsRef < OsStr > > ( s : S ) -> Self ;
251
+ fn from_backslash < S : AsRef < str > > ( s : S ) -> Self ;
252
+ fn from_backslash_lossy < S : AsRef < OsStr > > ( s : S ) -> Self ;
251
253
fn to_slash ( & self ) -> Option < String > ;
252
254
fn to_slash_lossy ( & self ) -> String ;
253
255
}
@@ -313,6 +315,43 @@ impl PathBufExt for PathBuf {
313
315
PathBuf :: from ( s)
314
316
}
315
317
318
+ /// Convert the backslash path (path separated with '\') to [`std::path::PathBuf`].
319
+ ///
320
+ /// Any '\' in the slash path is replaced with the file path separator.
321
+ /// The replacements only happen on non-Windows.
322
+ #[ cfg( not( target_os = "windows" ) ) ]
323
+ fn from_backslash < S : AsRef < str > > ( s : S ) -> Self {
324
+ use std:: path;
325
+
326
+ let s = s
327
+ . as_ref ( )
328
+ . chars ( )
329
+ . map ( |c| match c {
330
+ '\\' => path:: MAIN_SEPARATOR ,
331
+ c => c,
332
+ } )
333
+ . collect :: < String > ( ) ;
334
+ PathBuf :: from ( s)
335
+ }
336
+
337
+ #[ cfg( target_os = "windows" ) ]
338
+ fn from_backslash < S : AsRef < str > > ( s : S ) -> Self {
339
+ PathBuf :: from ( s. as_ref ( ) )
340
+ }
341
+
342
+ /// Convert the backslash path (path separated with '\') to [`std::path::PathBuf`].
343
+ ///
344
+ /// Any '\' in the slash path is replaced with the file path separator.
345
+ #[ cfg( not( target_os = "windows" ) ) ]
346
+ fn from_backslash_lossy < S : AsRef < OsStr > > ( s : S ) -> Self {
347
+ PathBuf :: from ( s. as_ref ( ) . to_string_lossy ( ) . replace ( r"\" , "/" ) . chars ( ) . as_str ( ) )
348
+ }
349
+
350
+ #[ cfg( target_os = "windows" ) ]
351
+ fn from_backslash_lossy < S : AsRef < OsStr > > ( s : S ) -> Self {
352
+ PathBuf :: from ( s. as_ref ( ) )
353
+ }
354
+
316
355
/// Convert the slash path (path separated with '/') to [`std::path::PathBuf`].
317
356
///
318
357
/// Any '/' in the slash path is replaced with the file path separator.
0 commit comments