result_extensions/lib.rs
1//! # Result Extensions
2//!
3//! A simple library that functionally creates Result<T, E> values from arbitrary types.
4//!
5//! Usage:
6//! ```
7//! mod some_mod {
8//! use result_extensions::ResultExtensions;
9//! fn is_greater_than_ten(input: i64) -> Result<bool, String> {
10//! match input {
11//! i64::MIN..=0 => {
12//! "this function does not accept values less than or equal to zero for some reason"
13//! .to_string()
14//! .to_err()
15//! }
16//! 1..=9 => false.to_ok(),
17//! _ => true.to_ok(),
18//! }
19//! }
20//! }
21
22/// Allows any Sized type to be functionally moved into a Result<T, E>.
23pub trait ResultExtensions
24where
25 Self: Sized,
26{
27 /// Converts the caller into an Ok (left-hand-side) Result.
28 fn to_ok<E>(self) -> Result<Self, E> {
29 Ok(self)
30 }
31
32 /// Converts the caller into an Err (right-hand-side) Result.
33 fn to_err<T>(self) -> Result<T, Self> {
34 Err(self)
35 }
36}
37impl<T> ResultExtensions for T {}
38
39#[cfg(test)]
40mod tests {
41 use crate::ResultExtensions;
42
43 #[test]
44 fn test_to_ok() {
45 let result = get_ok("ok");
46 if let Ok(ok_text) = result {
47 assert_eq!("ok", ok_text, "unexpected Ok text",);
48 } else {
49 panic!("expected result to be an Ok variant, but got: {:?}", result);
50 }
51 }
52
53 #[test]
54 fn test_to_err() {
55 let result = get_err("error");
56 if let Err(err_text) = result {
57 assert_eq!("error", err_text, "unexpected Err text",);
58 } else {
59 panic!(
60 "expected result to be an Err variant, but got: {:?}",
61 result
62 );
63 }
64 }
65
66 fn get_ok<S: Into<String>>(ok_value: S) -> Result<String, String> {
67 ok_value.into().to_ok()
68 }
69
70 fn get_err<S: Into<String>>(err_value: S) -> Result<String, String> {
71 err_value.into().to_err()
72 }
73}