├── .github └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE.txt ├── LICENSE-MIT.txt ├── README.md ├── rust-toolchain.toml ├── src └── lib.rs └── tests ├── email_validation.rs ├── from_option.rs └── from_result.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: push 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v1 12 | - name: Build 13 | run: cargo build 14 | - name: Test 15 | run: cargo test 16 | - name: Clippy 17 | run: cargo clippy --all-targets --all-features -- -D warnings 18 | - name: Format 19 | run: cargo fmt --all -- --check 20 | 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "multi_try" 3 | version = "0.4.0" 4 | authors = ["Josh Mcguigan"] 5 | edition = "2018" 6 | description = "Safely combine results" 7 | repository = "https://github.com/JoshMcguigan/multi_try" 8 | readme = "README.md" 9 | license = "MIT OR Apache-2.0" 10 | 11 | [dependencies] 12 | -------------------------------------------------------------------------------- /LICENSE-APACHE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Josh Mcguigan 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Josh Mcguigan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # multi_try 2 | [![crates.io badge](https://img.shields.io/crates/v/multi_try.svg)](https://crates.io/crates/multi_try) 3 | [![Docs.rs](https://docs.rs/multi_try/badge.svg)](https://docs.rs/multi_try) 4 | 5 | This crate allows you to combine multiple `Result` types and return either a 6 | tuple containing all of their results, or a `Vec` of any errors which occurred. 7 | It is useful when you want to provide an error message for all errors rather 8 | than simply returning the first error. 9 | 10 | Generics are used to support `Result` for any types of `T` and `E`. The 11 | `Ok` types of the combined results are NOT required to be the same, but all of 12 | the `Err` types must be the same. 13 | 14 | ### [The Documentation](https://docs.rs/multi_try) 15 | 16 | ## Example 17 | 18 | ```rust 19 | use multi_try::MultiTry; 20 | 21 | struct A { 22 | b: Result, 23 | c: Result, 24 | d: Result, 25 | } 26 | 27 | struct ValidatedA { 28 | b: i32, 29 | c: i64, 30 | d: f32, 31 | } 32 | 33 | enum MyErr { 34 | FailedB, 35 | FailedC, 36 | FailedD, 37 | } 38 | 39 | fn validate(a: A) -> Result> { 40 | let (b, c, d) = a.b.and_try(a.c).and_try(a.d)?; 41 | 42 | Ok(ValidatedA { b, c, d }) 43 | } 44 | ``` 45 | 46 | Check the `tests` directory for additional examples. 47 | 48 | ## License 49 | 50 | Licensed under either of 51 | 52 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 53 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 54 | 55 | at your option. 56 | 57 | ### Contribution 58 | 59 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 60 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "1.66.0" 3 | components = [ "rustfmt", "clippy" ] 4 | 5 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate allows you to combine multiple `Result` types and return either a 2 | //! tuple containing all of their results, or a `Vec` of any errors which occurred. 3 | //! It is useful when you want to provide an error message for all errors rather 4 | //! than simply returning the first error. 5 | //! 6 | //! Generics are used to support `Result` for any types of `T` and `E`. The 7 | //! `Ok` types of the combined results are NOT required to be the same, but all of 8 | //! the `Err` types must be the same. 9 | //! 10 | //! See the documentation for the [`MultiTry` trait] for more information and an example. 11 | //! 12 | //! [`MultiTry` trait]: trait.MultiTry.html 13 | 14 | /// Exposes the `and_try` method for combining multiple `Result` types. 15 | /// 16 | /// This is an extension trait designed to add functionality to the `Result` type. That 17 | /// means that to use this trait's methods, you must have it in scope: 18 | /// 19 | /// ```no_run 20 | /// use multi_try::MultiTry; 21 | /// ``` 22 | /// 23 | /// The `Ok` variant of each combined `Result` can have any type. Each value will be combined into 24 | /// a tuple. We support up to 27 items, though we never expect anyone to need anything close to 25 | /// that. The `Err` variant of each `Result` must have the same type. Each error that occurs will 26 | /// be combined into a single `Vec`. 27 | /// 28 | /// The idea is that you can try many different operations, collect any errors that occurred, and 29 | /// then only proceed if every operation was a success. The example below demonstrates that: 30 | /// 31 | /// ```no_run 32 | /// use multi_try::MultiTry; 33 | /// 34 | /// struct A { 35 | /// b: Result, 36 | /// c: Result, 37 | /// d: Result, 38 | /// } 39 | /// 40 | /// struct ValidatedA { 41 | /// b: i32, 42 | /// c: i64, 43 | /// d: f32, 44 | /// } 45 | /// 46 | /// enum MyErr { 47 | /// FailedB, 48 | /// FailedC, 49 | /// FailedD, 50 | /// } 51 | /// 52 | /// fn validate(a: A) -> Result> { 53 | /// // Only continue beyond this point if all the `Result` values were `Ok` 54 | /// let (b, c, d) = a.b.and_try(a.c).and_try(a.d)?; 55 | /// 56 | /// Ok(ValidatedA { b, c, d }) 57 | /// } 58 | /// ``` 59 | pub trait MultiTry { 60 | /// The output of the `and_try` operation 61 | type Output; 62 | 63 | /// Returns the current `Result` combined with the given `Result`. If both are `Ok`, this will 64 | /// return a new tuple that combines the results. If either have failed, this will return a 65 | /// vector containing each error that occurred. 66 | /// 67 | /// ``` 68 | /// use multi_try::MultiTry; 69 | /// # // These functions are used to get around type inference issues 70 | /// # fn Ok(value: T) -> Result { Result::Ok(value) } 71 | /// # fn Err(err: E) -> Result { Result::Err(err) } 72 | /// 73 | /// # fn main() -> Result<(), Vec<&'static str>> { 74 | /// // Combines two results so we get a 2-tuple 75 | /// assert_eq!(Ok(1).and_try(Ok("abc"))?, (1, "abc")); 76 | /// // Combines two results with another result so we get a 3-tuple 77 | /// assert_eq!(Ok(1).and_try(Ok("abc")).and_try(Ok(37.4))?, (1, "abc", 37.4)); 78 | /// // Even if one succeeds, we only return Ok() if they both do 79 | /// assert_eq!(Err("bad!").and_try(Ok(32)).unwrap_err(), vec!["bad!"]); 80 | /// assert_eq!(Ok(1).and_try(Err("very bad!")).unwrap_err(), vec!["very bad!"]); 81 | /// // If both fail, we return both errors 82 | /// assert_eq!(Err("bad!").and_try(Err("very bad!")).unwrap_err(), vec!["bad!", "very bad!"]); 83 | /// # Result::Ok(()) } 84 | /// ``` 85 | fn and_try(self, other: Result) -> Self::Output; 86 | } 87 | 88 | // Allows you to combine Result with Result to get Result<(T, RT), Vec> 89 | impl MultiTry for Result { 90 | type Output = Result<(T, RT), Vec>; 91 | 92 | fn and_try(self, other: Result) -> Self::Output { 93 | match (self, other) { 94 | (Ok(a), Ok(b)) => Ok((a, b)), 95 | (Ok(_), Err(eb)) => Err(vec![eb]), 96 | (Err(ea), Ok(_)) => Err(vec![ea]), 97 | (Err(ea), Err(eb)) => Err(vec![ea, eb]), 98 | } 99 | } 100 | } 101 | 102 | macro_rules! impl_multi_try { 103 | ($($typ:ident),+) => { 104 | impl MultiTry for Result<($($typ),+,), Vec> { 105 | type Output = Result<($($typ),*, RT), Vec>; 106 | 107 | fn and_try(self, other: Result) -> Self::Output { 108 | #[allow(non_snake_case)] // reusing the type parameter identifiers as variables 109 | match (self, other) { 110 | (Ok(($($typ),+,)), Ok(rt)) => Ok(($($typ),+, rt)), 111 | (Ok(_), Err(e)) => Err(vec![e]), 112 | (Err(errs), Ok(_)) => Err(errs), 113 | (Err(mut errs), Err(e)) => Err({ 114 | errs.push(e); 115 | errs 116 | }), 117 | } 118 | } 119 | } 120 | }; 121 | } 122 | 123 | impl_multi_try!(A); 124 | impl_multi_try!(A, B); 125 | impl_multi_try!(A, B, C); 126 | impl_multi_try!(A, B, C, D); 127 | impl_multi_try!(A, B, C, D, E); 128 | impl_multi_try!(A, B, C, D, E, F); 129 | impl_multi_try!(A, B, C, D, E, F, G); 130 | impl_multi_try!(A, B, C, D, E, F, G, H); 131 | impl_multi_try!(A, B, C, D, E, F, G, H, I); 132 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J); 133 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K); 134 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L); 135 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M); 136 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M, N); 137 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O); 138 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P); 139 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q); 140 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R); 141 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S); 142 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T); 143 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U); 144 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V); 145 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W); 146 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X); 147 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y); 148 | impl_multi_try!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z); 149 | -------------------------------------------------------------------------------- /tests/email_validation.rs: -------------------------------------------------------------------------------- 1 | use multi_try::MultiTry; 2 | 3 | #[derive(Debug, PartialEq)] 4 | struct Email<'a> { 5 | to: &'a str, 6 | from: &'a str, 7 | subject: &'a str, 8 | body: &'a str, 9 | } 10 | 11 | #[derive(Debug, PartialEq)] 12 | struct ValidatedEmail<'a> { 13 | to: &'a str, 14 | from: &'a str, 15 | subject: &'a str, 16 | body: &'a str, 17 | } 18 | 19 | #[derive(Debug, PartialEq)] 20 | enum EmailValidationErr { 21 | EmailAddress, 22 | RecipientEmailAddress, 23 | SenderEmailAddress, 24 | Subject, 25 | Body, 26 | } 27 | 28 | fn validate_address(address: &str) -> Result<&str, EmailValidationErr> { 29 | if address.contains('@') { 30 | Ok(address) 31 | } else { 32 | Err(EmailValidationErr::EmailAddress) 33 | } 34 | } 35 | 36 | fn validate_subject(subject: &str) -> Result<&str, EmailValidationErr> { 37 | if subject.len() > 5 { 38 | Ok(subject) 39 | } else { 40 | Err(EmailValidationErr::Subject) 41 | } 42 | } 43 | 44 | fn validate_body(body: &str) -> Result<&str, EmailValidationErr> { 45 | if body.len() > 10 { 46 | Ok(body) 47 | } else { 48 | Err(EmailValidationErr::Body) 49 | } 50 | } 51 | 52 | fn validate_email(email: Email) -> Result> { 53 | let (to, from, subject, body) = validate_address(email.to) 54 | .map_err(|_| EmailValidationErr::RecipientEmailAddress) 55 | .and_try(validate_address(email.from).map_err(|_| EmailValidationErr::SenderEmailAddress)) 56 | .and_try(validate_subject(email.subject)) 57 | .and_try(validate_body(email.body))?; 58 | 59 | Ok(ValidatedEmail { 60 | to, 61 | from, 62 | subject, 63 | body, 64 | }) 65 | } 66 | 67 | #[cfg(test)] 68 | mod tests { 69 | use super::*; 70 | 71 | #[test] 72 | fn all_err() { 73 | let a = Email { 74 | to: "Tom", 75 | from: "Mary", 76 | subject: "s", 77 | body: "b", 78 | }; 79 | 80 | let result = validate_email(a); 81 | let expected = Err(vec![ 82 | EmailValidationErr::RecipientEmailAddress, 83 | EmailValidationErr::SenderEmailAddress, 84 | EmailValidationErr::Subject, 85 | EmailValidationErr::Body, 86 | ]); 87 | 88 | assert_eq!(expected, result); 89 | } 90 | 91 | #[test] 92 | fn body_err() { 93 | let a = Email { 94 | to: "Tom@mail.com", 95 | from: "Mary@mail.com", 96 | subject: "good morning", 97 | body: "b", 98 | }; 99 | 100 | let result = validate_email(a); 101 | let expected = Err(vec![EmailValidationErr::Body]); 102 | 103 | assert_eq!(expected, result); 104 | } 105 | 106 | #[test] 107 | fn all_ok() { 108 | let a = Email { 109 | to: "Tom@mail.com", 110 | from: "Mary@mail.com", 111 | subject: "good morning", 112 | body: "Isn't it a lovely morning?!", 113 | }; 114 | 115 | let result = validate_email(a); 116 | let expected = Ok(ValidatedEmail { 117 | to: "Tom@mail.com", 118 | from: "Mary@mail.com", 119 | subject: "good morning", 120 | body: "Isn't it a lovely morning?!", 121 | }); 122 | 123 | assert_eq!(expected, result); 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /tests/from_option.rs: -------------------------------------------------------------------------------- 1 | use multi_try::MultiTry; 2 | 3 | #[derive(Debug, PartialEq)] 4 | struct A { 5 | b: Option, 6 | c: Option, 7 | d: Option, 8 | e: Option, 9 | } 10 | 11 | #[derive(Debug, PartialEq)] 12 | struct ValidatedA { 13 | b: i32, 14 | c: i32, 15 | d: i32, 16 | e: u32, 17 | } 18 | 19 | #[derive(Debug, PartialEq)] 20 | enum ValidationError { 21 | MissingB, 22 | MissingC, 23 | MissingD, 24 | MissingE, 25 | } 26 | 27 | fn validate(a: A) -> Result> { 28 | let (b, c, d, e) = 29 | a.b.ok_or(ValidationError::MissingB) 30 | .and_try(a.c.ok_or(ValidationError::MissingC)) 31 | .and_try(a.d.ok_or(ValidationError::MissingD)) 32 | .and_try(a.e.ok_or(ValidationError::MissingE))?; 33 | 34 | Ok(ValidatedA { b, c, d, e }) 35 | } 36 | 37 | #[cfg(test)] 38 | mod tests { 39 | use super::*; 40 | 41 | #[test] 42 | fn all_empty() { 43 | let a = A { 44 | b: None, 45 | c: None, 46 | d: None, 47 | e: None, 48 | }; 49 | 50 | let result = validate(a); 51 | let expected = Err(vec![ 52 | ValidationError::MissingB, 53 | ValidationError::MissingC, 54 | ValidationError::MissingD, 55 | ValidationError::MissingE, 56 | ]); 57 | 58 | assert_eq!(expected, result); 59 | } 60 | 61 | #[test] 62 | fn b_empty() { 63 | let a = A { 64 | b: None, 65 | c: Some(1), 66 | d: Some(1), 67 | e: Some(2), 68 | }; 69 | 70 | let result = validate(a); 71 | let expected = Err(vec![ValidationError::MissingB]); 72 | 73 | assert_eq!(expected, result); 74 | } 75 | 76 | #[test] 77 | fn none_empty() { 78 | let a = A { 79 | b: Some(1), 80 | c: Some(2), 81 | d: Some(3), 82 | e: Some(4), 83 | }; 84 | 85 | let result = validate(a); 86 | let expected = Ok(ValidatedA { 87 | b: 1, 88 | c: 2, 89 | d: 3, 90 | e: 4, 91 | }); 92 | 93 | assert_eq!(expected, result); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /tests/from_result.rs: -------------------------------------------------------------------------------- 1 | use multi_try::MultiTry; 2 | 3 | #[derive(Debug, PartialEq)] 4 | struct A { 5 | b: Result, 6 | c: Result, 7 | d: Result, 8 | } 9 | 10 | #[derive(Debug, PartialEq)] 11 | struct ValidatedA { 12 | b: i32, 13 | c: i64, 14 | d: f32, 15 | } 16 | 17 | #[derive(Debug, PartialEq)] 18 | enum MyErr { 19 | FailedB, 20 | FailedC, 21 | FailedD, 22 | } 23 | 24 | fn validate(a: A) -> Result> { 25 | let (b, c, d) = a.b.and_try(a.c).and_try(a.d)?; 26 | 27 | Ok(ValidatedA { b, c, d }) 28 | } 29 | 30 | #[cfg(test)] 31 | mod tests { 32 | use super::*; 33 | 34 | #[test] 35 | fn all_err() { 36 | let a = A { 37 | b: Err(MyErr::FailedB), 38 | c: Err(MyErr::FailedC), 39 | d: Err(MyErr::FailedD), 40 | }; 41 | 42 | let result = validate(a); 43 | let expected = Err(vec![MyErr::FailedB, MyErr::FailedC, MyErr::FailedD]); 44 | 45 | assert_eq!(expected, result); 46 | } 47 | 48 | #[test] 49 | fn c_err() { 50 | let a = A { 51 | b: Ok(1), 52 | c: Err(MyErr::FailedC), 53 | d: Ok(3.0), 54 | }; 55 | 56 | let result = validate(a); 57 | let expected = Err(vec![MyErr::FailedC]); 58 | 59 | assert_eq!(expected, result); 60 | } 61 | 62 | #[test] 63 | fn all_ok() { 64 | let a = A { 65 | b: Ok(1), 66 | c: Ok(2), 67 | d: Ok(3.0), 68 | }; 69 | 70 | let result = validate(a); 71 | let expected = Ok(ValidatedA { b: 1, c: 2, d: 3.0 }); 72 | 73 | assert_eq!(expected, result); 74 | } 75 | } 76 | --------------------------------------------------------------------------------