1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![allow(clippy::cognitive_complexity)] // See arti#2556
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![warn(clippy::or_fun_call)]
28
#![deny(clippy::print_stderr)]
29
#![deny(clippy::print_stdout)]
30
#![warn(clippy::rc_buffer)]
31
#![deny(clippy::ref_option_ref)]
32
#![warn(clippy::semicolon_if_nothing_returned)]
33
#![warn(clippy::trait_duplication_in_bounds)]
34
#![deny(clippy::unchecked_time_subtraction)]
35
#![deny(clippy::unnecessary_wraps)]
36
#![warn(clippy::unseparated_literal_suffix)]
37
#![deny(clippy::unwrap_used)]
38
#![deny(clippy::mod_module_files)]
39
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40
#![allow(clippy::uninlined_format_args)]
41
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44
#![allow(clippy::needless_lifetimes)] // See arti#1765
45
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46
#![allow(clippy::collapsible_if)] // See arti#2342
47
#![deny(clippy::unused_async)]
48
#![deny(clippy::string_slice)] // See arti#2571
49
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51

            
52
// TODO: add to the list maintained by maint/add_warning once it's available on all crates
53
#![warn(unnameable_types)]
54

            
55
use std::collections::HashMap;
56
use std::path::{Path, PathBuf};
57

            
58
use serde::{Deserialize, Serialize};
59
use std::borrow::Cow;
60
#[cfg(feature = "expand-paths")]
61
use {directories::BaseDirs, std::sync::LazyLock};
62

            
63
use tor_error::{ErrorKind, HasKind};
64

            
65
#[cfg(all(test, feature = "expand-paths"))]
66
use std::ffi::OsStr;
67

            
68
#[cfg(feature = "address")]
69
pub mod addr;
70

            
71
#[cfg(feature = "arti-client")]
72
mod arti_client_paths;
73

            
74
#[cfg(feature = "arti-client")]
75
pub use arti_client_paths::arti_client_base_resolver;
76

            
77
/// A path in a configuration file: tilde expansion is performed, along
78
/// with expansion of variables provided by a [`CfgPathResolver`].
79
///
80
/// The tilde expansion is performed using the home directory given by the
81
/// `directories` crate, which may be based on an environment variable. For more
82
/// information, see [`BaseDirs::home_dir`](directories::BaseDirs::home_dir).
83
///
84
/// Alternatively, a `CfgPath` can contain literal `PathBuf`, which will not be expanded.
85
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
86
#[serde(transparent)]
87
pub struct CfgPath(PathInner);
88

            
89
/// Inner implementation of CfgPath
90
///
91
/// `PathInner` exists to avoid making the variants part of the public Rust API
92
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
93
#[serde(untagged)]
94
enum PathInner {
95
    /// A path that should be used literally, with no expansion.
96
    Literal(LiteralPath),
97
    /// A path that should be expanded from a string using ShellExpand.
98
    Shell(String),
99
}
100

            
101
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
102
/// Inner implementation of PathInner:Literal
103
///
104
/// `LiteralPath` exists to arrange that `PathInner::Literal`'s (de)serialization
105
/// does not overlap with `PathInner::Shell`'s.
106
struct LiteralPath {
107
    /// The underlying `PathBuf`.
108
    literal: PathBuf,
109
}
110

            
111
/// An error that has occurred while expanding a path.
112
#[derive(thiserror::Error, Debug, Clone)]
113
#[non_exhaustive]
114
#[cfg_attr(test, derive(PartialEq))]
115
pub enum CfgPathError {
116
    /// The path contained a variable we didn't recognize.
117
    #[error("Unrecognized variable {0} in path")]
118
    UnknownVar(String),
119
    /// We couldn't construct a ProjectDirs object.
120
    #[error(
121
        "Couldn't determine XDG Project Directories, needed to resolve a path; probably, unable to determine HOME directory"
122
    )]
123
    NoProjectDirs,
124
    /// We couldn't construct a BaseDirs object.
125
    #[error("Can't construct base directories to resolve a path element")]
126
    NoBaseDirs,
127
    /// We couldn't find our current binary path.
128
    #[error("Can't find the path to the current binary")]
129
    NoProgramPath,
130
    /// We couldn't find the directory path containing the current binary.
131
    #[error("Can't find the directory of the current binary")]
132
    NoProgramDir,
133
    /// We couldn't convert a string to a valid path on the OS.
134
    //
135
    // NOTE: This is not currently generated. Shall we remove it?
136
    #[error("Invalid path string: {0:?}")]
137
    InvalidString(String),
138
    /// Variable interpolation (`$`) attempted, but not compiled in
139
    #[error(
140
        "Variable interpolation $ is not supported (tor-config/expand-paths feature disabled)); $ must still be doubled"
141
    )]
142
    VariableInterpolationNotSupported(String),
143
    /// Home dir interpolation (`~`) attempted, but not compiled in
144
    #[error("Home dir ~/ is not supported (tor-config/expand-paths feature disabled)")]
145
    HomeDirInterpolationNotSupported(String),
146
}
147

            
148
impl HasKind for CfgPathError {
149
    fn kind(&self) -> ErrorKind {
150
        use CfgPathError as E;
151
        use ErrorKind as EK;
152
        match self {
153
            E::UnknownVar(_) | E::InvalidString(_) => EK::InvalidConfig,
154
            E::NoProjectDirs | E::NoBaseDirs => EK::NoHomeDirectory,
155
            E::NoProgramPath | E::NoProgramDir => EK::InvalidConfig,
156
            E::VariableInterpolationNotSupported(_) | E::HomeDirInterpolationNotSupported(_) => {
157
                EK::FeatureDisabled
158
            }
159
        }
160
    }
161
}
162

            
163
/// A variable resolver for paths in a configuration file.
164
///
165
/// Typically there should be one resolver per application, and the application should share the
166
/// resolver throughout the application to have consistent path variable expansions. Typically the
167
/// application would create its own resolver with its application-specific variables, but note that
168
/// `TorClientConfig` is an exception which does not accept a resolver from the application and
169
/// instead generates its own. This is done for backwards compatibility reasons.
170
///
171
/// Once constructed, they are used during calls to [`CfgPath::path`] to expand variables in the
172
/// path.
173
#[derive(Clone, Debug, Default)]
174
pub struct CfgPathResolver {
175
    /// The variables and their values. The values can be an `Err` if the variable is expected but
176
    /// can't be expanded.
177
    vars: HashMap<String, Result<Cow<'static, Path>, CfgPathError>>,
178
}
179

            
180
impl CfgPathResolver {
181
    /// Get the value for a given variable name.
182
    #[cfg(feature = "expand-paths")]
183
6733
    fn get_var(&self, var: &str) -> Result<Cow<'static, Path>, CfgPathError> {
184
6733
        match self.vars.get(var) {
185
6674
            Some(val) => val.clone(),
186
59
            None => Err(CfgPathError::UnknownVar(var.to_owned())),
187
        }
188
6733
    }
189

            
190
    /// Set a variable `var` that will be replaced with `val` when a [`CfgPath`] is expanded.
191
    ///
192
    /// Setting an `Err` is useful when a variable is supported, but for whatever reason it can't be
193
    /// expanded, and you'd like to return a more-specific error. An example might be a `USER_HOME`
194
    /// variable for a user that doesn't have a `HOME` environment variable set.
195
    ///
196
    /// ```
197
    /// use std::path::Path;
198
    /// use tor_config_path::{CfgPath, CfgPathResolver};
199
    ///
200
    /// let mut path_resolver = CfgPathResolver::default();
201
    /// path_resolver.set_var("FOO", Ok(Path::new("/foo").to_owned().into()));
202
    ///
203
    /// let path = CfgPath::new("${FOO}/bar".into());
204
    ///
205
    /// #[cfg(feature = "expand-paths")]
206
    /// assert_eq!(path.path(&path_resolver).unwrap(), Path::new("/foo/bar"));
207
    /// #[cfg(not(feature = "expand-paths"))]
208
    /// assert!(path.path(&path_resolver).is_err());
209
    /// ```
210
66770
    pub fn set_var(
211
66770
        &mut self,
212
66770
        var: impl Into<String>,
213
66770
        val: Result<Cow<'static, Path>, CfgPathError>,
214
66770
    ) {
215
66770
        self.vars.insert(var.into(), val);
216
66770
    }
217

            
218
    /// Helper to create a `CfgPathResolver` from str `(name, value)` pairs.
219
    #[cfg(all(test, feature = "expand-paths"))]
220
12
    fn from_pairs<K, V>(vars: impl IntoIterator<Item = (K, V)>) -> CfgPathResolver
221
12
    where
222
12
        K: Into<String>,
223
12
        V: AsRef<OsStr>,
224
    {
225
12
        let mut path_resolver = CfgPathResolver::default();
226
12
        for (name, val) in vars.into_iter() {
227
12
            let val = Path::new(val.as_ref()).to_owned();
228
12
            path_resolver.set_var(name, Ok(val.into()));
229
        }
230
12
        path_resolver
231
12
    }
232
}
233

            
234
impl CfgPath {
235
    /// Create a new configuration path
236
25111
    pub fn new(s: String) -> Self {
237
25111
        CfgPath(PathInner::Shell(s))
238
25111
    }
239

            
240
    /// Construct a new `CfgPath` designating a literal not-to-be-expanded `PathBuf`
241
1527
    pub fn new_literal<P: Into<PathBuf>>(path: P) -> Self {
242
1527
        CfgPath(PathInner::Literal(LiteralPath {
243
1527
            literal: path.into(),
244
1527
        }))
245
1527
    }
246

            
247
    /// Return the path on disk designated by this `CfgPath`.
248
    ///
249
    /// Variables may or may not be resolved using `path_resolver`, depending on whether the
250
    /// `expand-paths` feature is enabled or not.
251
12510
    pub fn path(&self, path_resolver: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
252
12510
        match &self.0 {
253
9482
            PathInner::Shell(s) => expand(s, path_resolver),
254
3028
            PathInner::Literal(LiteralPath { literal }) => Ok(literal.clone()),
255
        }
256
12510
    }
257

            
258
    /// If the `CfgPath` is a string that should be expanded, return the (unexpanded) string,
259
    ///
260
    /// Before use, this string would have be to expanded.  So if you want a path to actually use,
261
    /// call `path` instead.
262
    ///
263
    /// Returns `None` if the `CfgPath` is a literal `PathBuf` not intended for expansion.
264
6
    pub fn as_unexpanded_str(&self) -> Option<&str> {
265
6
        match &self.0 {
266
3
            PathInner::Shell(s) => Some(s),
267
3
            PathInner::Literal(_) => None,
268
        }
269
6
    }
270

            
271
    /// If the `CfgPath` designates a literal not-to-be-expanded `Path`, return a reference to it
272
    ///
273
    /// Returns `None` if the `CfgPath` is a string which should be expanded, which is the
274
    /// usual case.
275
6
    pub fn as_literal_path(&self) -> Option<&Path> {
276
6
        match &self.0 {
277
3
            PathInner::Shell(_) => None,
278
3
            PathInner::Literal(LiteralPath { literal }) => Some(literal),
279
        }
280
6
    }
281
}
282

            
283
impl std::fmt::Display for CfgPath {
284
292
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
285
292
        match &self.0 {
286
1
            PathInner::Literal(LiteralPath { literal }) => write!(fmt, "{:?} [exactly]", literal),
287
291
            PathInner::Shell(s) => s.fmt(fmt),
288
        }
289
292
    }
290
}
291

            
292
/// Return the user's home directory used when expanding paths.
293
// This is public so that applications which want to support for example a `USER_HOME` variable can
294
// use the same home directory expansion that we use in this crate for `~` expansion.
295
#[cfg(feature = "expand-paths")]
296
11205
pub fn home() -> Result<&'static Path, CfgPathError> {
297
    /// Lazy lock holding the home directory.
298
    static HOME_DIR: LazyLock<Option<PathBuf>> =
299
3305
        LazyLock::new(|| Some(BaseDirs::new()?.home_dir().to_owned()));
300
11205
    HOME_DIR
301
11205
        .as_ref()
302
11205
        .map(PathBuf::as_path)
303
11205
        .ok_or(CfgPathError::NoBaseDirs)
304
11205
}
305

            
306
/// Helper: expand a directory given as a string.
307
#[cfg(feature = "expand-paths")]
308
9482
fn expand(s: &str, path_resolver: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
309
9482
    let path = shellexpand::path::full_with_context(
310
9482
        s,
311
1
        || home().ok(),
312
6733
        |x| path_resolver.get_var(x).map(Some),
313
    );
314
9482
    Ok(path.map_err(|e| e.cause)?.into_owned())
315
9482
}
316

            
317
/// Helper: convert a string to a path without expansion.
318
#[cfg(not(feature = "expand-paths"))]
319
fn expand(input: &str, _: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
320
    // We must still de-duplicate `$` and reject `~/`,, so that the behaviour is a superset
321
    if input.starts_with('~') {
322
        return Err(CfgPathError::HomeDirInterpolationNotSupported(input.into()));
323
    }
324

            
325
    let mut out = String::with_capacity(input.len());
326
    let mut s = input;
327
    while let Some((lhs, rhs)) = s.split_once('$') {
328
        if let Some(rhs) = rhs.strip_prefix('$') {
329
            // deduplicate the $
330
            out += lhs;
331
            out += "$";
332
            s = rhs;
333
        } else {
334
            return Err(CfgPathError::VariableInterpolationNotSupported(
335
                input.into(),
336
            ));
337
        }
338
    }
339
    out += s;
340
    Ok(out.into())
341
}
342

            
343
#[cfg(all(test, feature = "expand-paths"))]
344
mod test {
345
    #![allow(clippy::unwrap_used)]
346
    use super::*;
347

            
348
    #[test]
349
    fn expand_no_op() {
350
        let r = CfgPathResolver::from_pairs([("FOO", "foo")]);
351

            
352
        let p = CfgPath::new("Hello/world".to_string());
353
        assert_eq!(p.to_string(), "Hello/world".to_string());
354
        assert_eq!(p.path(&r).unwrap().to_str(), Some("Hello/world"));
355

            
356
        let p = CfgPath::new("/usr/local/foo".to_string());
357
        assert_eq!(p.to_string(), "/usr/local/foo".to_string());
358
        assert_eq!(p.path(&r).unwrap().to_str(), Some("/usr/local/foo"));
359
    }
360

            
361
    #[cfg(not(target_family = "windows"))]
362
    #[test]
363
    fn expand_home() {
364
        let r = CfgPathResolver::from_pairs([("USER_HOME", home().unwrap())]);
365

            
366
        let p = CfgPath::new("~/.arti/config".to_string());
367
        assert_eq!(p.to_string(), "~/.arti/config".to_string());
368

            
369
        let expected = dirs::home_dir().unwrap().join(".arti/config");
370
        assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
371

            
372
        let p = CfgPath::new("${USER_HOME}/.arti/config".to_string());
373
        assert_eq!(p.to_string(), "${USER_HOME}/.arti/config".to_string());
374
        assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
375
    }
376

            
377
    #[cfg(target_family = "windows")]
378
    #[test]
379
    fn expand_home() {
380
        let r = CfgPathResolver::from_pairs([("USER_HOME", home().unwrap())]);
381

            
382
        let p = CfgPath::new("~\\.arti\\config".to_string());
383
        assert_eq!(p.to_string(), "~\\.arti\\config".to_string());
384

            
385
        let expected = dirs::home_dir().unwrap().join(".arti\\config");
386
        assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
387

            
388
        let p = CfgPath::new("${USER_HOME}\\.arti\\config".to_string());
389
        assert_eq!(p.to_string(), "${USER_HOME}\\.arti\\config".to_string());
390
        assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
391
    }
392

            
393
    #[test]
394
    fn expand_bogus() {
395
        let r = CfgPathResolver::from_pairs([("FOO", "foo")]);
396

            
397
        let p = CfgPath::new("${ARTI_WOMBAT}/example".to_string());
398
        assert_eq!(p.to_string(), "${ARTI_WOMBAT}/example".to_string());
399

            
400
        assert!(matches!(p.path(&r), Err(CfgPathError::UnknownVar(_))));
401
        assert_eq!(
402
            &p.path(&r).unwrap_err().to_string(),
403
            "Unrecognized variable ARTI_WOMBAT in path"
404
        );
405
    }
406

            
407
    #[test]
408
    fn literal() {
409
        let r = CfgPathResolver::from_pairs([("ARTI_CACHE", "foo")]);
410

            
411
        let p = CfgPath::new_literal(PathBuf::from("${ARTI_CACHE}/literally"));
412
        // This doesn't get expanded, since we're using a literal path.
413
        assert_eq!(
414
            p.path(&r).unwrap().to_str().unwrap(),
415
            "${ARTI_CACHE}/literally"
416
        );
417
        assert_eq!(p.to_string(), "\"${ARTI_CACHE}/literally\" [exactly]");
418
    }
419

            
420
    #[test]
421
    #[cfg(feature = "expand-paths")]
422
    fn program_dir() {
423
        let current_exe = std::env::current_exe().unwrap();
424
        let r = CfgPathResolver::from_pairs([("PROGRAM_DIR", current_exe.parent().unwrap())]);
425

            
426
        let p = CfgPath::new("${PROGRAM_DIR}/foo".to_string());
427

            
428
        let mut this_binary = current_exe;
429
        this_binary.pop();
430
        this_binary.push("foo");
431
        let expanded = p.path(&r).unwrap();
432
        assert_eq!(expanded, this_binary);
433
    }
434

            
435
    #[test]
436
    #[cfg(not(feature = "expand-paths"))]
437
    fn rejections() {
438
        let r = CfgPathResolver::from_pairs([("PROGRAM_DIR", std::env::current_exe().unwrap())]);
439

            
440
        let chk_err = |s: &str, mke: &dyn Fn(String) -> CfgPathError| {
441
            let p = CfgPath::new(s.to_string());
442
            assert_eq!(p.path(&r).unwrap_err(), mke(s.to_string()));
443
        };
444

            
445
        let chk_ok = |s: &str, exp| {
446
            let p = CfgPath::new(s.to_string());
447
            assert_eq!(p.path(&r), Ok(PathBuf::from(exp)));
448
        };
449

            
450
        chk_err(
451
            "some/${PROGRAM_DIR}/foo",
452
            &CfgPathError::VariableInterpolationNotSupported,
453
        );
454
        chk_err("~some", &CfgPathError::HomeDirInterpolationNotSupported);
455

            
456
        chk_ok("some$$foo$$bar", "some$foo$bar");
457
        chk_ok("no dollars", "no dollars");
458
    }
459
}
460

            
461
#[cfg(test)]
462
mod test_serde {
463
    // @@ begin test lint list maintained by maint/add_warning @@
464
    #![allow(clippy::bool_assert_comparison)]
465
    #![allow(clippy::clone_on_copy)]
466
    #![allow(clippy::dbg_macro)]
467
    #![allow(clippy::mixed_attributes_style)]
468
    #![allow(clippy::print_stderr)]
469
    #![allow(clippy::print_stdout)]
470
    #![allow(clippy::single_char_pattern)]
471
    #![allow(clippy::unwrap_used)]
472
    #![allow(clippy::unchecked_time_subtraction)]
473
    #![allow(clippy::useless_vec)]
474
    #![allow(clippy::needless_pass_by_value)]
475
    #![allow(clippy::string_slice)] // See arti#2571
476
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
477

            
478
    use super::*;
479

            
480
    use std::ffi::OsString;
481
    use std::fmt::Debug;
482

            
483
    use derive_deftly::Deftly;
484
    use tor_config::load::TopLevel;
485

            
486
    #[derive(Serialize, Deserialize, Deftly, Eq, PartialEq, Debug)]
487
    #[derive_deftly(tor_config::derive::TorConfig)]
488
    #[deftly(tor_config(no_default_trait))]
489
    struct TestConfigFile {
490
        #[deftly(tor_config(no_default))]
491
        p: CfgPath,
492
    }
493

            
494
    impl TopLevel for TestConfigFile {
495
        type Builder = TestConfigFileBuilder;
496
    }
497

            
498
    fn deser_json(json: &str) -> CfgPath {
499
        dbg!(json);
500
        let TestConfigFile { p } = serde_json::from_str(json).expect("deser json failed");
501
        p
502
    }
503
    fn deser_toml(toml: &str) -> CfgPath {
504
        dbg!(toml);
505
        let TestConfigFile { p } = toml::from_str(toml).expect("deser toml failed");
506
        p
507
    }
508
    fn deser_toml_cfg(toml: &str) -> CfgPath {
509
        dbg!(toml);
510
        let mut sources = tor_config::ConfigurationSources::new_empty();
511
        sources.push_source(
512
            tor_config::ConfigurationSource::from_verbatim(toml.to_string()),
513
            tor_config::sources::MustRead::MustRead,
514
        );
515
        let cfg = sources.load().unwrap();
516

            
517
        dbg!(&cfg);
518
        let TestConfigFile { p } = tor_config::load::resolve(&cfg).expect("cfg resolution failed");
519
        p
520
    }
521

            
522
    #[test]
523
    fn test_parse() {
524
        fn desers(toml: &str, json: &str) -> Vec<CfgPath> {
525
            vec![deser_toml(toml), deser_toml_cfg(toml), deser_json(json)]
526
        }
527

            
528
        for cp in desers(r#"p = "string""#, r#"{ "p": "string" }"#) {
529
            assert_eq!(cp.as_unexpanded_str(), Some("string"));
530
            assert_eq!(cp.as_literal_path(), None);
531
        }
532

            
533
        for cp in desers(
534
            r#"p = { literal = "lit" }"#,
535
            r#"{ "p": {"literal": "lit"} }"#,
536
        ) {
537
            assert_eq!(cp.as_unexpanded_str(), None);
538
            assert_eq!(cp.as_literal_path(), Some(&*PathBuf::from("lit")));
539
        }
540
    }
541

            
542
    fn non_string_path() -> PathBuf {
543
        #[cfg(target_family = "unix")]
544
        {
545
            use std::os::unix::ffi::OsStringExt;
546
            return PathBuf::from(OsString::from_vec(vec![0x80_u8]));
547
        }
548

            
549
        #[cfg(target_family = "windows")]
550
        {
551
            use std::os::windows::ffi::OsStringExt;
552
            return PathBuf::from(OsString::from_wide(&[0xD800_u16]));
553
        }
554

            
555
        #[allow(unreachable_code)]
556
        // Cannot test non-Stringy Paths on this platform
557
        PathBuf::default()
558
    }
559

            
560
    fn test_roundtrip_cases<SER, S, DESER, E, F>(ser: SER, deser: DESER)
561
    where
562
        SER: Fn(&TestConfigFile) -> Result<S, E>,
563
        DESER: Fn(&S) -> Result<TestConfigFile, F>,
564
        S: Debug,
565
        E: Debug,
566
        F: Debug,
567
    {
568
        let case = |easy, p| {
569
            let input = TestConfigFile { p };
570
            let s = match ser(&input) {
571
                Ok(s) => s,
572
                Err(e) if easy => panic!("ser failed {:?} e={:?}", input, e),
573
                Err(_) => return,
574
            };
575
            dbg!(&input, &s);
576
            let output = deser(&s).expect("deser failed");
577
            assert_eq!(&input, &output, "s={:?}", s);
578
        };
579

            
580
        case(true, CfgPath::new("string".into()));
581
        case(true, CfgPath::new_literal(PathBuf::from("nice path")));
582
        case(true, CfgPath::new_literal(PathBuf::from("path with ✓")));
583

            
584
        // Non-UTF-8 paths are really hard to serialize.  We allow the serializsaton
585
        // to fail, and if it does, we skip the rest of the round trip test.
586
        // But, if they did serialise, we want to make sure that we can deserialize.
587
        // Hence this test case.
588
        case(false, CfgPath::new_literal(non_string_path()));
589
    }
590

            
591
    #[test]
592
    fn roundtrip_json() {
593
        test_roundtrip_cases(
594
            |input| serde_json::to_string(&input),
595
            |json| serde_json::from_str(json),
596
        );
597
    }
598

            
599
    #[test]
600
    fn roundtrip_toml() {
601
        test_roundtrip_cases(|input| toml::to_string(&input), |toml| toml::from_str(toml));
602
    }
603

            
604
    #[test]
605
    fn roundtrip_mpack() {
606
        test_roundtrip_cases(
607
            |input| rmp_serde::to_vec(&input),
608
            |mpack| rmp_serde::from_slice(mpack),
609
        );
610
    }
611
}