from_path/
lib.rs

1//! Loading values from paths.
2//!
3//! This crate provides the [`FromPath`] trait for types that can have values loaded from paths.
4//!
5//! There is also the [`from_path`] convenience function for when the types can be inferred.
6//!
7//! # Example
8//!
9//! Assuming there is some file named `hello-world` with the content `Hello, world!`,
10//! we first implement the trait and then load the content from the file:
11//!
12//! ```rust
13//! use std::{fs::read_to_string, io::Error, path::Path};
14//!
15//! use from_path::{FromPath, from_path};
16//!
17//! struct Content {
18//!     pub string: String,
19//! }
20//!
21//! impl Content {
22//!     pub fn new(string: String) -> Self {
23//!         Self { string }
24//!     }
25//! }
26//!
27//! impl FromPath for Content {
28//!     type Error = Error;
29//!
30//!     fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, Self::Error> {
31//!         read_to_string(path).map(Content::new)
32//!     }
33//! }
34//!
35//! let content: Content = from_path("hello-world").unwrap();
36//!
37//! assert_eq!(content.string.trim(), "Hello, world!");
38//! ```
39
40#![forbid(unsafe_code)]
41#![deny(missing_docs)]
42
43use std::path::Path;
44
45/// Loading values from paths.
46pub trait FromPath: Sized {
47    /// The associated error type returned from [`from_path`] on failure.
48    ///
49    /// [`from_path`]: Self::from_path
50    type Error;
51
52    /// Loads the value of this type from the given path.
53    ///
54    /// # Errors
55    ///
56    /// Returns [`Error`] when loading fails.
57    ///
58    /// [`Error`]: Self::Error
59    fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, Self::Error>;
60}
61
62/// Loads the value of the given type from the given path.
63///
64/// # Errors
65///
66/// Returns [`Error`] when loading fails.
67///
68/// [`Error`]: FromPath::Error
69pub fn from_path<F: FromPath, P: AsRef<Path>>(path: P) -> Result<F, F::Error> {
70    F::from_path(path)
71}