Skip to content
This repository has been archived by the owner on Aug 9, 2024. It is now read-only.

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mpyw committed Aug 7, 2024
0 parents commit 8a6dd8c
Show file tree
Hide file tree
Showing 6 changed files with 288 additions and 0 deletions.
40 changes: 40 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: "Test"

on: [push]

jobs:
rust-test:
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Rust stable toolchain
uses: dtolnay/rust-toolchain@nightly
with:
components: rustfmt
- name: Restore cache
uses: Swatinem/rust-cache@v2
- name: Check test
run: cargo +nightly test

rust-lint:
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Rust stable toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: clippy
- name: Install cargo-sort
run: cargo install cargo-sort
- name: Setup nightly cargo fmt
run: rustup toolchain install nightly --component rustfmt
- name: Restore cache
uses: Swatinem/rust-cache@v2
- name: Check format
run: cargo +nightly fmt --all -- --check
- name: Check clippy
run: cargo clippy -- -D warnings
- name: Check sort
run: cargo sort -w -c
21 changes: 21 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Generated by Cargo
# will have compiled files and executables
debug/
target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk

# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb

# RustRover
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
17 changes: 17 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "and_then_map_err"
version = "0.1.0"
authors = ["mpyw <[email protected]>"]
edition = "2021"
rust-version = "1.80.0"
description = "Provides traits for chaining Result operations with different error types WITHOUT the need for intermediate map_err calls."
repository = "https://github.com/yumemi-inc/and-then-map-err"
license = "MIT"
include = ["/src", "LICENSE"]
keywords = ["map_err", "result", "error", "error-conversion", "error-handling"]
categories = ["rust-patterns"]

[dependencies]

[dev-dependencies]
thiserror = "1"
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 YUMEMI Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# and-then-map-err

Provides traits for chaining `Result` operations with different error types **WITHOUT** the need for intermediate `map_err` calls.

- Documentation: [and_then_map_err - Rust](https://docs.rs/and-then-map-err/latest/and_then_map_err/)
- Inspired by [rust - Is there a way to use and_then with different error types without map_err? - Stack Overflow](https://stackoverflow.com/questions/43772092/is-there-a-way-to-use-and-then-with-different-error-types-without-map-err)
183 changes: 183 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
//! # `and_then_map_err`
//!
//! `and_then_map_err` provides traits for chaining `Result` operations
//! with different error types without needing intermediate `map_err` calls.
//! This allows more flexible error handling by converting error types
//! between chained operations.
//!
//! ## Features
//!
//! - `AndThenMapErr` trait: Enables chaining `Result` operations where the error type can be converted.
//! - `MapErrAndThen` trait: Enables mapping the error type of initial `Result` before chaining another operation.
//!
//! ## Examples
//!
//! ```rust
//! use thiserror::Error;
//! use and_then_map_err::{AndThenMapErr, MapErrAndThen};
//!
//! #[derive(Error, Debug, Eq, PartialEq)]
//! pub enum ParentError {
//! #[error("parent error: {0}")]
//! Parent(String),
//! #[error("parent error from child error: {0}")]
//! FromChild(#[from] ChildError),
//! }
//!
//! #[derive(Error, Debug, Eq, PartialEq)]
//! pub enum ChildError {
//! #[error("child error: {0}")]
//! Child(String),
//! }
//!
//! let result_or_parent_err: Result<(), ParentError> = Ok(());
//! let new_result_or_parent_err: Result<(), ParentError> = result_or_parent_err.and_then_map_err(|x| {
//! Err(ChildError::Child("error occurred afterwards".to_string()))
//! });
//! assert_eq!(new_result_or_parent_err, Err(ParentError::FromChild(ChildError::Child("error occurred afterwards".to_string()))));
//!
//! let result_or_child_err: Result<(), ChildError> = Err(ChildError::Child("initial error".to_string()));
//! let new_result_or_parent_err: Result<(), ParentError> = result_or_child_err.map_err_and_then(|x| {
//! Ok(x)
//! });
//! assert_eq!(new_result_or_parent_err, Err(ParentError::FromChild(ChildError::Child("initial error".to_string()))));
//! ```

/// The `and_then_map_err` trait allows for error mapping on `Result` types.
/// This trait converts an error in the result of the operation `Result<U, E2>`
/// to a different error type `E1` if the initial operation fails.
///
/// # Examples
///
/// ```
/// use thiserror::Error;
/// use and_then_map_err::AndThenMapErr;
///
/// #[derive(Error, Debug, Eq, PartialEq)]
/// pub enum ParentError {
/// #[error("parent error: {0}")]
/// Parent(String),
/// #[error("parent error from child error: {0}")]
/// FromChild(#[from] ChildError),
/// }
///
/// #[derive(Error, Debug, Eq, PartialEq)]
/// pub enum ChildError {
/// #[error("child error: {0}")]
/// Child(String),
/// }
///
/// // Case 1: The original result is Ok and the operation succeeds.
/// let result: Result<(), ParentError> = Ok(());
/// let new_result: Result<(), ParentError> = result.and_then_map_err(|x| -> Result<(), ChildError> {
/// Ok(x)
/// });
/// assert_eq!(new_result, Ok(()));
///
/// // Case 2: The original result is an Err of type ParentError.
/// let result: Result<(), ParentError> = Err(ParentError::Parent("initial error".to_string()));
/// let new_result: Result<(), ParentError> = result.and_then_map_err(|x| -> Result<(), ChildError> {
/// Ok(x)
/// });
/// assert_eq!(new_result, Err(ParentError::Parent("initial error".to_string())));
/// assert_eq!(new_result.unwrap_err().to_string(), "parent error: initial error");
///
/// // Case 3: The original result is Ok but the operation returns an Err of type ChildError.
/// let result: Result<(), ParentError> = Ok(());
/// let new_result: Result<(), ParentError> = result.and_then_map_err(|x| {
/// Err(ChildError::Child("error occurred afterwards".to_string()))
/// });
/// assert_eq!(new_result, Err(ParentError::FromChild(ChildError::Child("error occurred afterwards".to_string()))));
/// ```
pub trait AndThenMapErr<T, E1> {
fn and_then_map_err<U, E2, F>(self, op: F) -> Result<U, E1>
where
E1: From<E2>,
F: FnOnce(T) -> Result<U, E2>;
}

impl<T, E1> AndThenMapErr<T, E1> for Result<T, E1> {
fn and_then_map_err<U, E2, F>(self, op: F) -> Result<U, E1>
where
E1: From<E2>,
F: FnOnce(T) -> Result<U, E2>,
{
match self {
Ok(t) => match op(t) {
Ok(u) => Ok(u),
Err(e2) => Err(E1::from(e2)),
},
Err(e1) => Err(e1),
}
}
}

/// The `map_err_and_then` trait allows for error mapping on `Result` types.
/// This trait converts an error in the initial `Result<T, E1>` to a different error type `E2`
/// if the operation fails.
///
/// # Examples
///
/// ```
/// use thiserror::Error;
/// use and_then_map_err::MapErrAndThen;
///
/// #[derive(Error, Debug, Eq, PartialEq)]
/// pub enum ParentError {
/// #[error("parent error: {0}")]
/// Parent(String),
/// #[error("parent error from child error: {0}")]
/// FromChild(#[from] ChildError),
/// }
///
/// #[derive(Error, Debug, Eq, PartialEq)]
/// pub enum ChildError {
/// #[error("child error: {0}")]
/// Child(String),
/// }
///
/// // Case 1: The original result is Ok and the operation succeeds.
/// let result: Result<(), ChildError> = Ok(());
/// let new_result: Result<(), ParentError> = result.map_err_and_then(|x| {
/// Ok(x)
/// });
/// assert_eq!(new_result, Ok(()));
///
/// // Case 2: The original result is an Err of type ChildError.
/// let result: Result<(), ChildError> = Err(ChildError::Child("initial error".to_string()));
/// let new_result: Result<(), ParentError> = result.map_err_and_then(|x| {
/// Ok(x)
/// });
/// assert_eq!(new_result, Err(ParentError::FromChild(ChildError::Child("initial error".to_string()))));
/// assert_eq!(new_result.unwrap_err().to_string(), "parent error from child error: child error: initial error");
///
/// // Case 3: The original result is Ok but the operation returns an Err of type ParentError.
/// let result: Result<(), ChildError> = Ok(());
/// let new_result: Result<(), ParentError> = result.map_err_and_then(|x| {
/// Err(ParentError::Parent("error occurred afterwards".to_string()))
/// });
/// assert_eq!(new_result, Err(ParentError::Parent("error occurred afterwards".to_string())));
/// assert_eq!(new_result.unwrap_err().to_string(), "parent error: error occurred afterwards");
/// ```
pub trait MapErrAndThen<T, E1> {
fn map_err_and_then<U, E2, F>(self, op: F) -> Result<U, E2>
where
E2: From<E1>,
F: FnOnce(T) -> Result<U, E2>;
}

impl<T, E1> MapErrAndThen<T, E1> for Result<T, E1> {
fn map_err_and_then<U, E2, F>(self, op: F) -> Result<U, E2>
where
E2: From<E1>,
F: FnOnce(T) -> Result<U, E2>,
{
match self {
Ok(t) => match op(t) {
Ok(u) => Ok(u),
Err(e2) => Err(e2),
},
Err(e1) => Err(E2::from(e1)),
}
}
}

0 comments on commit 8a6dd8c

Please sign in to comment.