ref_map/lib.rs
1/*
2 * lib.rs
3 *
4 * ref-map - Convenience methods for references of Option and Result.
5 * Copyright (c) 2020-2021 Ammon Smith
6 *
7 * ref-map is available free of charge under the terms of the MIT
8 * License. You are free to redistribute and/or modify it under those
9 * terms. It is distributed in the hopes that it will be useful, but
10 * WITHOUT ANY WARRANTY. See the LICENSE file for more details.
11 *
12 */
13
14#![deny(missing_debug_implementations, missing_docs)]
15#![forbid(unsafe_code)]
16
17//! Convenience methods when dealing with references of [`Option`]s and [`Result`]s.
18//!
19//! It introduces two traits, [`OptionRefMap`] and [`ResultRefMap`], which add methods
20//! to their respective standard library enums to avoid needing to add `.as_ref()`
21//! before any `.map()` methods on their value.
22//!
23//! This is useful when you want to borrow from an `Option` or `Result` but want
24//! to avoid the boilerplate of first getting the references to the values contained inside.
25//!
26//! ```
27//! use ref_map::*;
28//!
29//! let string: Option<String> = Some("hello world\n".into());
30//!
31//! // Without ref-map:
32//! // the .as_ref() is necessary because otherwise it tries to consume the String
33//! let message: Option<&str> = string.as_ref().map(|s| s.trim());
34//!
35//! // With ref-map:
36//! let message: Option<&str> = string.ref_map(|s| s.trim());
37//! ```
38//!
39//! Similarly, `.ref_map()` and `.ref_map_err()` are available for `Result`s to mimic
40//! their `.map()` and `.map_err()` methods:
41//!
42//! ```
43//! # use ref_map::*;
44//! # use std::path::{Path, PathBuf};
45//! let answer: Result<PathBuf, String> = Ok(PathBuf::from("/test"));
46//!
47//! // Mapping borrowed Ok(_) to another type
48//! let path: Result<&Path, &String> = answer.ref_map(|p| p.as_path());
49//!
50//! // Mapping borrower Err(_)
51//! let error: Result<&PathBuf, &str> = answer.ref_map_err(|e| e.as_str());
52//! ```
53//!
54//! [`Option`]: https://doc.rust-lang.org/std/option/enum.Option.html
55//! [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
56//! [`OptionRefMap`]: ./trait.OptionRefMap.html
57//! [`ResultRefMap`]: ./trait.ResultRefMap.html
58
59mod option;
60mod result;
61
62#[cfg(test)]
63mod test;
64
65/// Extension trait for `Option`.
66pub use self::option::OptionRefMap;
67
68/// Extension trait for `Result`.
69pub use self::result::ResultRefMap;