1
#![cfg_attr(docsrs, feature(doc_auto_cfg, 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
#![warn(clippy::cognitive_complexity)]
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
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_duration_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
46

            
47
use std::collections::HashMap;
48
use std::path::{Path, PathBuf};
49

            
50
use serde::{Deserialize, Serialize};
51
use std::borrow::Cow;
52
#[cfg(feature = "expand-paths")]
53
use {directories::BaseDirs, std::sync::LazyLock};
54

            
55
use tor_error::{ErrorKind, HasKind};
56

            
57
#[cfg(all(test, feature = "expand-paths"))]
58
use std::ffi::OsStr;
59

            
60
#[cfg(feature = "address")]
61
pub mod addr;
62

            
63
#[cfg(feature = "arti-client")]
64
mod arti_client_paths;
65

            
66
#[cfg(feature = "arti-client")]
67
#[cfg_attr(docsrs, doc(cfg(feature = "arti-client")))]
68
pub use arti_client_paths::arti_client_base_resolver;
69

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

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

            
94
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
95
/// Inner implementation of PathInner:Literal
96
///
97
/// `LiteralPath` exists to arrange that `PathInner::Literal`'s (de)serialization
98
/// does not overlap with `PathInner::Shell`'s.
99
struct LiteralPath {
100
    /// The underlying `PathBuf`.
101
    literal: PathBuf,
102
}
103

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

            
141
impl HasKind for CfgPathError {
142
    fn kind(&self) -> ErrorKind {
143
        use CfgPathError as E;
144
        use ErrorKind as EK;
145
        match self {
146
            E::UnknownVar(_) | E::InvalidString(_) => EK::InvalidConfig,
147
            E::NoProjectDirs | E::NoBaseDirs => EK::NoHomeDirectory,
148
            E::NoProgramPath | E::NoProgramDir => EK::InvalidConfig,
149
            E::VariableInterpolationNotSupported(_) | E::HomeDirInterpolationNotSupported(_) => {
150
                EK::FeatureDisabled
151
            }
152
        }
153
    }
154
}
155

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

            
173
impl CfgPathResolver {
174
    /// Get the value for a given variable name.
175
    #[cfg(feature = "expand-paths")]
176
2321
    fn get_var(&self, var: &str) -> Result<Cow<'static, Path>, CfgPathError> {
177
2321
        match self.vars.get(var) {
178
2264
            Some(val) => val.clone(),
179
57
            None => Err(CfgPathError::UnknownVar(var.to_owned())),
180
        }
181
2321
    }
182

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

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

            
227
impl CfgPath {
228
    /// Create a new configuration path
229
10399
    pub fn new(s: String) -> Self {
230
10399
        CfgPath(PathInner::Shell(s))
231
10399
    }
232

            
233
    /// Construct a new `CfgPath` designating a literal not-to-be-expanded `PathBuf`
234
999
    pub fn new_literal<P: Into<PathBuf>>(path: P) -> Self {
235
999
        CfgPath(PathInner::Literal(LiteralPath {
236
999
            literal: path.into(),
237
999
        }))
238
999
    }
239

            
240
    /// Return the path on disk designated by this `CfgPath`.
241
    ///
242
    /// Variables may or may not be resolved using `path_resolver`, depending on whether the
243
    /// `expand-paths` feature is enabled or not.
244
4685
    pub fn path(&self, path_resolver: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
245
4685
        match &self.0 {
246
2892
            PathInner::Shell(s) => expand(s, path_resolver),
247
1793
            PathInner::Literal(LiteralPath { literal }) => Ok(literal.clone()),
248
        }
249
4685
    }
250

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

            
264
    /// If the `CfgPath` designates a literal not-to-be-expanded `Path`, return a reference to it
265
    ///
266
    /// Returns `None` if the `CfgPath` is a string which should be expanded, which is the
267
    /// usual case.
268
12
    pub fn as_literal_path(&self) -> Option<&Path> {
269
12
        match &self.0 {
270
6
            PathInner::Shell(_) => None,
271
6
            PathInner::Literal(LiteralPath { literal }) => Some(literal),
272
        }
273
12
    }
274
}
275

            
276
impl std::fmt::Display for CfgPath {
277
330
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278
330
        match &self.0 {
279
2
            PathInner::Literal(LiteralPath { literal }) => write!(fmt, "{:?} [exactly]", literal),
280
328
            PathInner::Shell(s) => s.fmt(fmt),
281
        }
282
330
    }
283
}
284

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

            
299
/// Helper: expand a directory given as a string.
300
#[cfg(feature = "expand-paths")]
301
2892
fn expand(s: &str, path_resolver: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
302
2892
    let path = shellexpand::path::full_with_context(
303
2892
        s,
304
2893
        || home().ok(),
305
2950
        |x| path_resolver.get_var(x).map(Some),
306
2892
    );
307
2896
    Ok(path.map_err(|e| e.cause)?.into_owned())
308
2892
}
309

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

            
318
    let mut out = String::with_capacity(input.len());
319
    let mut s = input;
320
    while let Some((lhs, rhs)) = s.split_once('$') {
321
        if let Some(rhs) = rhs.strip_prefix('$') {
322
            // deduplicate the $
323
            out += lhs;
324
            out += "$";
325
            s = rhs;
326
        } else {
327
            return Err(CfgPathError::VariableInterpolationNotSupported(
328
                input.into(),
329
            ));
330
        }
331
    }
332
    out += s;
333
    Ok(out.into())
334
}
335

            
336
#[cfg(all(test, feature = "expand-paths"))]
337
mod test {
338
    #![allow(clippy::unwrap_used)]
339
    use super::*;
340

            
341
    #[test]
342
    fn expand_no_op() {
343
        let r = CfgPathResolver::from_pairs([("FOO", "foo")]);
344

            
345
        let p = CfgPath::new("Hello/world".to_string());
346
        assert_eq!(p.to_string(), "Hello/world".to_string());
347
        assert_eq!(p.path(&r).unwrap().to_str(), Some("Hello/world"));
348

            
349
        let p = CfgPath::new("/usr/local/foo".to_string());
350
        assert_eq!(p.to_string(), "/usr/local/foo".to_string());
351
        assert_eq!(p.path(&r).unwrap().to_str(), Some("/usr/local/foo"));
352
    }
353

            
354
    #[cfg(not(target_family = "windows"))]
355
    #[test]
356
    fn expand_home() {
357
        let r = CfgPathResolver::from_pairs([("USER_HOME", home().unwrap())]);
358

            
359
        let p = CfgPath::new("~/.arti/config".to_string());
360
        assert_eq!(p.to_string(), "~/.arti/config".to_string());
361

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

            
365
        let p = CfgPath::new("${USER_HOME}/.arti/config".to_string());
366
        assert_eq!(p.to_string(), "${USER_HOME}/.arti/config".to_string());
367
        assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
368
    }
369

            
370
    #[cfg(target_family = "windows")]
371
    #[test]
372
    fn expand_home() {
373
        let r = CfgPathResolver::from_pairs([("USER_HOME", home().unwrap())]);
374

            
375
        let p = CfgPath::new("~\\.arti\\config".to_string());
376
        assert_eq!(p.to_string(), "~\\.arti\\config".to_string());
377

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

            
381
        let p = CfgPath::new("${USER_HOME}\\.arti\\config".to_string());
382
        assert_eq!(p.to_string(), "${USER_HOME}\\.arti\\config".to_string());
383
        assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
384
    }
385

            
386
    #[test]
387
    fn expand_bogus() {
388
        let r = CfgPathResolver::from_pairs([("FOO", "foo")]);
389

            
390
        let p = CfgPath::new("${ARTI_WOMBAT}/example".to_string());
391
        assert_eq!(p.to_string(), "${ARTI_WOMBAT}/example".to_string());
392

            
393
        assert!(matches!(p.path(&r), Err(CfgPathError::UnknownVar(_))));
394
        assert_eq!(
395
            &p.path(&r).unwrap_err().to_string(),
396
            "Unrecognized variable ARTI_WOMBAT in path"
397
        );
398
    }
399

            
400
    #[test]
401
    fn literal() {
402
        let r = CfgPathResolver::from_pairs([("ARTI_CACHE", "foo")]);
403

            
404
        let p = CfgPath::new_literal(PathBuf::from("${ARTI_CACHE}/literally"));
405
        // This doesn't get expanded, since we're using a literal path.
406
        assert_eq!(
407
            p.path(&r).unwrap().to_str().unwrap(),
408
            "${ARTI_CACHE}/literally"
409
        );
410
        assert_eq!(p.to_string(), "\"${ARTI_CACHE}/literally\" [exactly]");
411
    }
412

            
413
    #[test]
414
    #[cfg(feature = "expand-paths")]
415
    fn program_dir() {
416
        let current_exe = std::env::current_exe().unwrap();
417
        let r = CfgPathResolver::from_pairs([("PROGRAM_DIR", current_exe.parent().unwrap())]);
418

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

            
421
        let mut this_binary = current_exe;
422
        this_binary.pop();
423
        this_binary.push("foo");
424
        let expanded = p.path(&r).unwrap();
425
        assert_eq!(expanded, this_binary);
426
    }
427

            
428
    #[test]
429
    #[cfg(not(feature = "expand-paths"))]
430
    fn rejections() {
431
        let r = CfgPathResolver::from_pairs([("PROGRAM_DIR", std::env::current_exe().unwrap())]);
432

            
433
        let chk_err = |s: &str, mke: &dyn Fn(String) -> CfgPathError| {
434
            let p = CfgPath::new(s.to_string());
435
            assert_eq!(p.path(&r).unwrap_err(), mke(s.to_string()));
436
        };
437

            
438
        let chk_ok = |s: &str, exp| {
439
            let p = CfgPath::new(s.to_string());
440
            assert_eq!(p.path(&r), Ok(PathBuf::from(exp)));
441
        };
442

            
443
        chk_err(
444
            "some/${PROGRAM_DIR}/foo",
445
            &CfgPathError::VariableInterpolationNotSupported,
446
        );
447
        chk_err("~some", &CfgPathError::HomeDirInterpolationNotSupported);
448

            
449
        chk_ok("some$$foo$$bar", "some$foo$bar");
450
        chk_ok("no dollars", "no dollars");
451
    }
452
}
453

            
454
#[cfg(test)]
455
mod test_serde {
456
    // @@ begin test lint list maintained by maint/add_warning @@
457
    #![allow(clippy::bool_assert_comparison)]
458
    #![allow(clippy::clone_on_copy)]
459
    #![allow(clippy::dbg_macro)]
460
    #![allow(clippy::mixed_attributes_style)]
461
    #![allow(clippy::print_stderr)]
462
    #![allow(clippy::print_stdout)]
463
    #![allow(clippy::single_char_pattern)]
464
    #![allow(clippy::unwrap_used)]
465
    #![allow(clippy::unchecked_duration_subtraction)]
466
    #![allow(clippy::useless_vec)]
467
    #![allow(clippy::needless_pass_by_value)]
468
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
469

            
470
    use super::*;
471

            
472
    use std::ffi::OsString;
473
    use std::fmt::Debug;
474

            
475
    use derive_builder::Builder;
476
    use tor_config::load::TopLevel;
477
    use tor_config::{ConfigBuildError, impl_standard_builder};
478

            
479
    #[derive(Serialize, Deserialize, Builder, Eq, PartialEq, Debug)]
480
    #[builder(derive(Serialize, Deserialize, Debug))]
481
    #[builder(build_fn(error = "ConfigBuildError"))]
482
    struct TestConfigFile {
483
        p: CfgPath,
484
    }
485

            
486
    impl_standard_builder! { TestConfigFile: !Default }
487

            
488
    impl TopLevel for TestConfigFile {
489
        type Builder = TestConfigFileBuilder;
490
    }
491

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

            
511
        dbg!(&cfg);
512
        let TestConfigFile { p } = tor_config::load::resolve(cfg).expect("cfg resolution failed");
513
        p
514
    }
515

            
516
    #[test]
517
    fn test_parse() {
518
        fn desers(toml: &str, json: &str) -> Vec<CfgPath> {
519
            vec![deser_toml(toml), deser_toml_cfg(toml), deser_json(json)]
520
        }
521

            
522
        for cp in desers(r#"p = "string""#, r#"{ "p": "string" }"#) {
523
            assert_eq!(cp.as_unexpanded_str(), Some("string"));
524
            assert_eq!(cp.as_literal_path(), None);
525
        }
526

            
527
        for cp in desers(
528
            r#"p = { literal = "lit" }"#,
529
            r#"{ "p": {"literal": "lit"} }"#,
530
        ) {
531
            assert_eq!(cp.as_unexpanded_str(), None);
532
            assert_eq!(cp.as_literal_path(), Some(&*PathBuf::from("lit")));
533
        }
534
    }
535

            
536
    fn non_string_path() -> PathBuf {
537
        #[cfg(target_family = "unix")]
538
        {
539
            use std::os::unix::ffi::OsStringExt;
540
            return PathBuf::from(OsString::from_vec(vec![0x80_u8]));
541
        }
542

            
543
        #[cfg(target_family = "windows")]
544
        {
545
            use std::os::windows::ffi::OsStringExt;
546
            return PathBuf::from(OsString::from_wide(&[0xD800_u16]));
547
        }
548

            
549
        #[allow(unreachable_code)]
550
        // Cannot test non-Stringy Paths on this platform
551
        PathBuf::default()
552
    }
553

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

            
574
        case(true, CfgPath::new("string".into()));
575
        case(true, CfgPath::new_literal(PathBuf::from("nice path")));
576
        case(true, CfgPath::new_literal(PathBuf::from("path with ✓")));
577

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

            
585
    #[test]
586
    fn roundtrip_json() {
587
        test_roundtrip_cases(
588
            |input| serde_json::to_string(&input),
589
            |json| serde_json::from_str(json),
590
        );
591
    }
592

            
593
    #[test]
594
    fn roundtrip_toml() {
595
        test_roundtrip_cases(|input| toml::to_string(&input), |toml| toml::from_str(toml));
596
    }
597

            
598
    #[test]
599
    fn roundtrip_mpack() {
600
        test_roundtrip_cases(
601
            |input| rmp_serde::to_vec(&input),
602
            |mpack| rmp_serde::from_slice(mpack),
603
        );
604
    }
605
}