├── .github └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README-crates.io.md ├── README.rst └── src ├── into_either.rs ├── iterator.rs ├── lib.rs ├── serde_untagged.rs └── serde_untagged_optional.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: [ main ] 4 | pull_request: 5 | merge_group: 6 | 7 | name: CI 8 | 9 | jobs: 10 | ci: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | fail-fast: false 14 | matrix: 15 | rust: 16 | - 1.63.0 # MSRV 17 | - stable 18 | - beta 19 | - nightly 20 | features: 21 | - "" 22 | - "serde" 23 | 24 | steps: 25 | - name: Checkout 26 | uses: actions/checkout@v4 27 | 28 | - name: Cache the registry 29 | uses: actions/cache@v4 30 | if: startsWith(matrix.rust, '1') 31 | with: 32 | path: ~/.cargo/registry/index 33 | key: cargo-${{ matrix.rust }}-git-index 34 | 35 | - name: Set up Rust 36 | uses: dtolnay/rust-toolchain@master 37 | with: 38 | toolchain: ${{ matrix.rust }} 39 | 40 | - name: Build (no_std) 41 | run: cargo build --no-default-features --features "${{ matrix.features }}" 42 | 43 | - name: Build 44 | run: cargo build --features "${{ matrix.features }}" 45 | 46 | - name: Test 47 | run: cargo test --features "${{ matrix.features }}" 48 | 49 | - name: Doc 50 | run: cargo doc --features "${{ matrix.features }}" 51 | 52 | clippy: 53 | name: Rustfmt and Clippy 54 | runs-on: ubuntu-latest 55 | steps: 56 | - name: Checkout 57 | uses: actions/checkout@v4 58 | 59 | - name: Set up nightly Rust 60 | uses: dtolnay/rust-toolchain@nightly 61 | with: 62 | components: rustfmt, clippy 63 | 64 | - name: Rustfmt 65 | run: cargo fmt --all -- --check 66 | 67 | - name: Clippy 68 | run: cargo clippy # -- -D warnings 69 | 70 | # One job that "summarizes" the success state of this pipeline. This can then be added to branch 71 | # protection, rather than having to add each job separately. 72 | success: 73 | name: Success 74 | runs-on: ubuntu-latest 75 | needs: [ci, clippy] 76 | # Github branch protection is exceedingly silly and treats "jobs skipped because a dependency 77 | # failed" as success. So we have to do some contortions to ensure the job fails if any of its 78 | # dependencies fails. 79 | if: always() # make sure this is never "skipped" 80 | steps: 81 | # Manually check the status of all dependencies. `if: failure()` does not work. 82 | - name: check if any dependency failed 83 | run: jq --exit-status 'all(.result == "success")' <<< '${{ toJson(needs) }}' 84 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "either" 3 | version = "1.15.0" 4 | authors = ["bluss"] 5 | edition = "2021" 6 | rust-version = "1.63.0" 7 | 8 | license = "MIT OR Apache-2.0" 9 | repository = "https://github.com/rayon-rs/either" 10 | documentation = "https://docs.rs/either/1/" 11 | readme = "README-crates.io.md" 12 | 13 | description = """ 14 | The enum `Either` with variants `Left` and `Right` is a general purpose sum type with two cases. 15 | """ 16 | 17 | keywords = ["data-structure", "no_std"] 18 | categories = ["data-structures", "no-std"] 19 | 20 | [dependencies] 21 | serde = { version = "1.0.95", optional = true, default-features = false, features = ["alloc", "derive"] } 22 | 23 | [features] 24 | default = ["std"] 25 | std = [] 26 | use_std = ["std"] # deprecated alias 27 | 28 | [dev-dependencies] 29 | serde_json = "1.0.0" 30 | 31 | [package.metadata.release] 32 | allow-branch = ["main"] 33 | sign-tag = true 34 | tag-name = "{{version}}" 35 | 36 | [package.metadata.docs.rs] 37 | features = ["serde"] 38 | 39 | [package.metadata.playground] 40 | features = ["serde"] 41 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 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 [yyyy] [name of copyright owner] 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: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README-crates.io.md: -------------------------------------------------------------------------------- 1 | The enum `Either` with variants `Left` and `Right` is a general purpose 2 | sum type with two cases. 3 | 4 | Either has methods that are similar to Option and Result, and it also implements 5 | traits like `Iterator`. 6 | 7 | Includes macros `try_left!()` and `try_right!()` to use for 8 | short-circuiting logic, similar to how the `?` operator is used with `Result`. 9 | Note that `Either` is general purpose. For describing success or error, use the 10 | regular `Result`. 11 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | 2 | Either 3 | ====== 4 | 5 | The enum ``Either`` with variants ``Left`` and ``Right`` and trait 6 | implementations including Iterator, Read, Write. 7 | 8 | Either has methods that are similar to Option and Result. 9 | 10 | Includes convenience macros ``try_left!()`` and ``try_right!()`` to use for 11 | short-circuiting logic. 12 | 13 | Please read the `API documentation here`__ 14 | 15 | __ https://docs.rs/either/ 16 | 17 | |build_status|_ |crates|_ 18 | 19 | .. |build_status| image:: https://github.com/rayon-rs/either/workflows/CI/badge.svg?branch=main 20 | .. _build_status: https://github.com/rayon-rs/either/actions 21 | 22 | .. |crates| image:: https://img.shields.io/crates/v/either.svg 23 | .. _crates: https://crates.io/crates/either 24 | 25 | How to use with cargo:: 26 | 27 | [dependencies] 28 | either = "1" 29 | 30 | 31 | Recent Changes 32 | -------------- 33 | 34 | - 1.15.0 35 | 36 | - Fix ``serde`` support when building without ``std``, by @klkvr (#119) 37 | 38 | - Use a more common ``std`` feature for default enablement, deprecating 39 | the ``use_std`` feature as a mere alias of the new name. 40 | 41 | - 1.14.0 42 | 43 | - **MSRV**: ``either`` now requires Rust 1.63 or later. 44 | 45 | - Implement ``fmt::Write`` for ``Either``, by @yotamofek (#113) 46 | 47 | - Replace ``Into for Either`` with ``From for Result``, by @cuviper (#118) 48 | 49 | - 1.13.0 50 | 51 | - Add new methods ``.cloned()`` and ``.copied()``, by @ColonelThirtyTwo (#107) 52 | 53 | - 1.12.0 54 | 55 | - **MSRV**: ``either`` now requires Rust 1.37 or later. 56 | 57 | - Specialize ``nth_back`` for ``Either`` and ``IterEither``, by @cuviper (#106) 58 | 59 | - 1.11.0 60 | 61 | - Add new trait ``IntoEither`` that is useful to convert to ``Either`` in method chains, 62 | by @SFM61319 (#101) 63 | 64 | - 1.10.0 65 | 66 | - Add new methods ``.factor_iter()``, ``.factor_iter_mut()``, and ``.factor_into_iter()`` 67 | that return ``Either`` items, plus ``.iter()`` and ``.iter_mut()`` to convert to direct 68 | reference iterators; by @aj-bagwell and @cuviper (#91) 69 | 70 | - 1.9.0 71 | 72 | - Add new methods ``.map_either()`` and ``.map_either_with()``, by @nasadorian (#82) 73 | 74 | - 1.8.1 75 | 76 | - Clarified that the multiple licenses are combined with OR. 77 | 78 | - 1.8.0 79 | 80 | - **MSRV**: ``either`` now requires Rust 1.36 or later. 81 | 82 | - Add new methods ``.as_pin_ref()`` and ``.as_pin_mut()`` to project a 83 | pinned ``Either`` as inner ``Pin`` variants, by @cuviper (#77) 84 | 85 | - Implement the ``Future`` trait, by @cuviper (#77) 86 | 87 | - Specialize more methods of the ``io`` traits, by @Kixunil and @cuviper (#75) 88 | 89 | - 1.7.0 90 | 91 | - **MSRV**: ``either`` now requires Rust 1.31 or later. 92 | 93 | - Export the macro ``for_both!``, by @thomaseizinger (#58) 94 | 95 | - Implement the ``io::Seek`` trait, by @Kerollmops (#60) 96 | 97 | - Add new method ``.either_into()`` for ``Into`` conversion, by @TonalidadeHidrica (#63) 98 | 99 | - Add new methods ``.factor_ok()``, ``.factor_err()``, and ``.factor_none()``, 100 | by @zachs18 (#67) 101 | 102 | - Specialize ``source`` in the ``Error`` implementation, by @thomaseizinger (#69) 103 | 104 | - Specialize more iterator methods and implement the ``FusedIterator`` trait, 105 | by @Ten0 (#66) and @cuviper (#71) 106 | 107 | - Specialize ``Clone::clone_from``, by @cuviper (#72) 108 | 109 | - 1.6.1 110 | 111 | - Add new methods ``.expect_left()``, ``.unwrap_left()``, 112 | and equivalents on the right, by @spenserblack (#51) 113 | 114 | - 1.6.0 115 | 116 | - Add new modules ``serde_untagged`` and ``serde_untagged_optional`` to customize 117 | how ``Either`` fields are serialized in other types, by @MikailBag (#49) 118 | 119 | - 1.5.3 120 | 121 | - Add new method ``.map()`` for ``Either`` by @nvzqz (#40). 122 | 123 | - 1.5.2 124 | 125 | - Add new methods ``.left_or()``, ``.left_or_default()``, ``.left_or_else()``, 126 | and equivalents on the right, by @DCjanus (#36) 127 | 128 | - 1.5.1 129 | 130 | - Add ``AsRef`` and ``AsMut`` implementations for common unsized types: 131 | ``str``, ``[T]``, ``CStr``, ``OsStr``, and ``Path``, by @mexus (#29) 132 | 133 | - 1.5.0 134 | 135 | - Add new methods ``.factor_first()``, ``.factor_second()`` and ``.into_inner()`` 136 | by @mathstuf (#19) 137 | 138 | - 1.4.0 139 | 140 | - Add inherent method ``.into_iter()`` by @cuviper (#12) 141 | 142 | - 1.3.0 143 | 144 | - Add opt-in serde support by @hcpl 145 | 146 | - 1.2.0 147 | 148 | - Add method ``.either_with()`` by @Twey (#13) 149 | 150 | - 1.1.0 151 | 152 | - Add methods ``left_and_then``, ``right_and_then`` by @rampantmonkey 153 | - Include license files in the repository and released crate 154 | 155 | - 1.0.3 156 | 157 | - Add crate categories 158 | 159 | - 1.0.2 160 | 161 | - Forward more ``Iterator`` methods 162 | - Implement ``Extend`` for ``Either`` if ``L, R`` do. 163 | 164 | - 1.0.1 165 | 166 | - Fix ``Iterator`` impl for ``Either`` to forward ``.fold()``. 167 | 168 | - 1.0.0 169 | 170 | - Add default crate feature ``use_std`` so that you can opt out of linking to 171 | std. 172 | 173 | - 0.1.7 174 | 175 | - Add methods ``.map_left()``, ``.map_right()`` and ``.either()``. 176 | - Add more documentation 177 | 178 | - 0.1.3 179 | 180 | - Implement Display, Error 181 | 182 | - 0.1.2 183 | 184 | - Add macros ``try_left!`` and ``try_right!``. 185 | 186 | - 0.1.1 187 | 188 | - Implement Deref, DerefMut 189 | 190 | - 0.1.0 191 | 192 | - Initial release 193 | - Support Iterator, Read, Write 194 | 195 | License 196 | ------- 197 | 198 | Dual-licensed to be compatible with the Rust project. 199 | 200 | Licensed under the Apache License, Version 2.0 201 | https://www.apache.org/licenses/LICENSE-2.0 or the MIT license 202 | https://opensource.org/licenses/MIT, at your 203 | option. This file may not be copied, modified, or distributed 204 | except according to those terms. 205 | -------------------------------------------------------------------------------- /src/into_either.rs: -------------------------------------------------------------------------------- 1 | //! The trait [`IntoEither`] provides methods for converting a type `Self`, whose 2 | //! size is constant and known at compile-time, into an [`Either`] variant. 3 | 4 | use super::{Either, Left, Right}; 5 | 6 | /// Provides methods for converting a type `Self` into either a [`Left`] or [`Right`] 7 | /// variant of [`Either`](Either). 8 | /// 9 | /// The [`into_either`](IntoEither::into_either) method takes a [`bool`] to determine 10 | /// whether to convert to [`Left`] or [`Right`]. 11 | /// 12 | /// The [`into_either_with`](IntoEither::into_either_with) method takes a 13 | /// [predicate function](FnOnce) to determine whether to convert to [`Left`] or [`Right`]. 14 | pub trait IntoEither: Sized { 15 | /// Converts `self` into a [`Left`] variant of [`Either`](Either) 16 | /// if `into_left` is `true`. 17 | /// Converts `self` into a [`Right`] variant of [`Either`](Either) 18 | /// otherwise. 19 | /// 20 | /// # Examples 21 | /// 22 | /// ``` 23 | /// use either::{IntoEither, Left, Right}; 24 | /// 25 | /// let x = 0; 26 | /// assert_eq!(x.into_either(true), Left(x)); 27 | /// assert_eq!(x.into_either(false), Right(x)); 28 | /// ``` 29 | fn into_either(self, into_left: bool) -> Either { 30 | if into_left { 31 | Left(self) 32 | } else { 33 | Right(self) 34 | } 35 | } 36 | 37 | /// Converts `self` into a [`Left`] variant of [`Either`](Either) 38 | /// if `into_left(&self)` returns `true`. 39 | /// Converts `self` into a [`Right`] variant of [`Either`](Either) 40 | /// otherwise. 41 | /// 42 | /// # Examples 43 | /// 44 | /// ``` 45 | /// use either::{IntoEither, Left, Right}; 46 | /// 47 | /// fn is_even(x: &u8) -> bool { 48 | /// x % 2 == 0 49 | /// } 50 | /// 51 | /// let x = 0; 52 | /// assert_eq!(x.into_either_with(is_even), Left(x)); 53 | /// assert_eq!(x.into_either_with(|x| !is_even(x)), Right(x)); 54 | /// ``` 55 | fn into_either_with(self, into_left: F) -> Either 56 | where 57 | F: FnOnce(&Self) -> bool, 58 | { 59 | let into_left = into_left(&self); 60 | self.into_either(into_left) 61 | } 62 | } 63 | 64 | impl IntoEither for T {} 65 | -------------------------------------------------------------------------------- /src/iterator.rs: -------------------------------------------------------------------------------- 1 | use super::{for_both, Either, Left, Right}; 2 | use core::iter; 3 | 4 | macro_rules! wrap_either { 5 | ($value:expr => $( $tail:tt )*) => { 6 | match $value { 7 | Left(inner) => inner.map(Left) $($tail)*, 8 | Right(inner) => inner.map(Right) $($tail)*, 9 | } 10 | }; 11 | } 12 | 13 | /// Iterator that maps left or right iterators to corresponding `Either`-wrapped items. 14 | /// 15 | /// This struct is created by the [`Either::factor_into_iter`], 16 | /// [`factor_iter`][Either::factor_iter], 17 | /// and [`factor_iter_mut`][Either::factor_iter_mut] methods. 18 | #[derive(Clone, Debug)] 19 | pub struct IterEither { 20 | inner: Either, 21 | } 22 | 23 | impl IterEither { 24 | pub(crate) fn new(inner: Either) -> Self { 25 | IterEither { inner } 26 | } 27 | } 28 | 29 | impl Extend for Either 30 | where 31 | L: Extend, 32 | R: Extend, 33 | { 34 | fn extend(&mut self, iter: T) 35 | where 36 | T: IntoIterator, 37 | { 38 | for_both!(self, inner => inner.extend(iter)) 39 | } 40 | } 41 | 42 | /// `Either` is an iterator if both `L` and `R` are iterators. 43 | impl Iterator for Either 44 | where 45 | L: Iterator, 46 | R: Iterator, 47 | { 48 | type Item = L::Item; 49 | 50 | fn next(&mut self) -> Option { 51 | for_both!(self, inner => inner.next()) 52 | } 53 | 54 | fn size_hint(&self) -> (usize, Option) { 55 | for_both!(self, inner => inner.size_hint()) 56 | } 57 | 58 | fn fold(self, init: Acc, f: G) -> Acc 59 | where 60 | G: FnMut(Acc, Self::Item) -> Acc, 61 | { 62 | for_both!(self, inner => inner.fold(init, f)) 63 | } 64 | 65 | fn for_each(self, f: F) 66 | where 67 | F: FnMut(Self::Item), 68 | { 69 | for_both!(self, inner => inner.for_each(f)) 70 | } 71 | 72 | fn count(self) -> usize { 73 | for_both!(self, inner => inner.count()) 74 | } 75 | 76 | fn last(self) -> Option { 77 | for_both!(self, inner => inner.last()) 78 | } 79 | 80 | fn nth(&mut self, n: usize) -> Option { 81 | for_both!(self, inner => inner.nth(n)) 82 | } 83 | 84 | fn collect(self) -> B 85 | where 86 | B: iter::FromIterator, 87 | { 88 | for_both!(self, inner => inner.collect()) 89 | } 90 | 91 | fn partition(self, f: F) -> (B, B) 92 | where 93 | B: Default + Extend, 94 | F: FnMut(&Self::Item) -> bool, 95 | { 96 | for_both!(self, inner => inner.partition(f)) 97 | } 98 | 99 | fn all(&mut self, f: F) -> bool 100 | where 101 | F: FnMut(Self::Item) -> bool, 102 | { 103 | for_both!(self, inner => inner.all(f)) 104 | } 105 | 106 | fn any(&mut self, f: F) -> bool 107 | where 108 | F: FnMut(Self::Item) -> bool, 109 | { 110 | for_both!(self, inner => inner.any(f)) 111 | } 112 | 113 | fn find

(&mut self, predicate: P) -> Option 114 | where 115 | P: FnMut(&Self::Item) -> bool, 116 | { 117 | for_both!(self, inner => inner.find(predicate)) 118 | } 119 | 120 | fn find_map(&mut self, f: F) -> Option 121 | where 122 | F: FnMut(Self::Item) -> Option, 123 | { 124 | for_both!(self, inner => inner.find_map(f)) 125 | } 126 | 127 | fn position

(&mut self, predicate: P) -> Option 128 | where 129 | P: FnMut(Self::Item) -> bool, 130 | { 131 | for_both!(self, inner => inner.position(predicate)) 132 | } 133 | } 134 | 135 | impl DoubleEndedIterator for Either 136 | where 137 | L: DoubleEndedIterator, 138 | R: DoubleEndedIterator, 139 | { 140 | fn next_back(&mut self) -> Option { 141 | for_both!(self, inner => inner.next_back()) 142 | } 143 | 144 | fn nth_back(&mut self, n: usize) -> Option { 145 | for_both!(self, inner => inner.nth_back(n)) 146 | } 147 | 148 | fn rfold(self, init: Acc, f: G) -> Acc 149 | where 150 | G: FnMut(Acc, Self::Item) -> Acc, 151 | { 152 | for_both!(self, inner => inner.rfold(init, f)) 153 | } 154 | 155 | fn rfind

(&mut self, predicate: P) -> Option 156 | where 157 | P: FnMut(&Self::Item) -> bool, 158 | { 159 | for_both!(self, inner => inner.rfind(predicate)) 160 | } 161 | } 162 | 163 | impl ExactSizeIterator for Either 164 | where 165 | L: ExactSizeIterator, 166 | R: ExactSizeIterator, 167 | { 168 | fn len(&self) -> usize { 169 | for_both!(self, inner => inner.len()) 170 | } 171 | } 172 | 173 | impl iter::FusedIterator for Either 174 | where 175 | L: iter::FusedIterator, 176 | R: iter::FusedIterator, 177 | { 178 | } 179 | 180 | impl Iterator for IterEither 181 | where 182 | L: Iterator, 183 | R: Iterator, 184 | { 185 | type Item = Either; 186 | 187 | fn next(&mut self) -> Option { 188 | Some(map_either!(self.inner, ref mut inner => inner.next()?)) 189 | } 190 | 191 | fn size_hint(&self) -> (usize, Option) { 192 | for_both!(self.inner, ref inner => inner.size_hint()) 193 | } 194 | 195 | fn fold(self, init: Acc, f: G) -> Acc 196 | where 197 | G: FnMut(Acc, Self::Item) -> Acc, 198 | { 199 | wrap_either!(self.inner => .fold(init, f)) 200 | } 201 | 202 | fn for_each(self, f: F) 203 | where 204 | F: FnMut(Self::Item), 205 | { 206 | wrap_either!(self.inner => .for_each(f)) 207 | } 208 | 209 | fn count(self) -> usize { 210 | for_both!(self.inner, inner => inner.count()) 211 | } 212 | 213 | fn last(self) -> Option { 214 | Some(map_either!(self.inner, inner => inner.last()?)) 215 | } 216 | 217 | fn nth(&mut self, n: usize) -> Option { 218 | Some(map_either!(self.inner, ref mut inner => inner.nth(n)?)) 219 | } 220 | 221 | fn collect(self) -> B 222 | where 223 | B: iter::FromIterator, 224 | { 225 | wrap_either!(self.inner => .collect()) 226 | } 227 | 228 | fn partition(self, f: F) -> (B, B) 229 | where 230 | B: Default + Extend, 231 | F: FnMut(&Self::Item) -> bool, 232 | { 233 | wrap_either!(self.inner => .partition(f)) 234 | } 235 | 236 | fn all(&mut self, f: F) -> bool 237 | where 238 | F: FnMut(Self::Item) -> bool, 239 | { 240 | wrap_either!(&mut self.inner => .all(f)) 241 | } 242 | 243 | fn any(&mut self, f: F) -> bool 244 | where 245 | F: FnMut(Self::Item) -> bool, 246 | { 247 | wrap_either!(&mut self.inner => .any(f)) 248 | } 249 | 250 | fn find

(&mut self, predicate: P) -> Option 251 | where 252 | P: FnMut(&Self::Item) -> bool, 253 | { 254 | wrap_either!(&mut self.inner => .find(predicate)) 255 | } 256 | 257 | fn find_map(&mut self, f: F) -> Option 258 | where 259 | F: FnMut(Self::Item) -> Option, 260 | { 261 | wrap_either!(&mut self.inner => .find_map(f)) 262 | } 263 | 264 | fn position

(&mut self, predicate: P) -> Option 265 | where 266 | P: FnMut(Self::Item) -> bool, 267 | { 268 | wrap_either!(&mut self.inner => .position(predicate)) 269 | } 270 | } 271 | 272 | impl DoubleEndedIterator for IterEither 273 | where 274 | L: DoubleEndedIterator, 275 | R: DoubleEndedIterator, 276 | { 277 | fn next_back(&mut self) -> Option { 278 | Some(map_either!(self.inner, ref mut inner => inner.next_back()?)) 279 | } 280 | 281 | fn nth_back(&mut self, n: usize) -> Option { 282 | Some(map_either!(self.inner, ref mut inner => inner.nth_back(n)?)) 283 | } 284 | 285 | fn rfold(self, init: Acc, f: G) -> Acc 286 | where 287 | G: FnMut(Acc, Self::Item) -> Acc, 288 | { 289 | wrap_either!(self.inner => .rfold(init, f)) 290 | } 291 | 292 | fn rfind

(&mut self, predicate: P) -> Option 293 | where 294 | P: FnMut(&Self::Item) -> bool, 295 | { 296 | wrap_either!(&mut self.inner => .rfind(predicate)) 297 | } 298 | } 299 | 300 | impl ExactSizeIterator for IterEither 301 | where 302 | L: ExactSizeIterator, 303 | R: ExactSizeIterator, 304 | { 305 | fn len(&self) -> usize { 306 | for_both!(self.inner, ref inner => inner.len()) 307 | } 308 | } 309 | 310 | impl iter::FusedIterator for IterEither 311 | where 312 | L: iter::FusedIterator, 313 | R: iter::FusedIterator, 314 | { 315 | } 316 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! The enum [`Either`] with variants `Left` and `Right` is a general purpose 2 | //! sum type with two cases. 3 | //! 4 | //! [`Either`]: enum.Either.html 5 | //! 6 | //! **Crate features:** 7 | //! 8 | //! * `"std"` 9 | //! Enabled by default. Disable to make the library `#![no_std]`. 10 | //! 11 | //! * `"serde"` 12 | //! Disabled by default. Enable to `#[derive(Serialize, Deserialize)]` for `Either` 13 | //! 14 | 15 | #![doc(html_root_url = "https://docs.rs/either/1/")] 16 | #![no_std] 17 | 18 | #[cfg(any(test, feature = "std"))] 19 | extern crate std; 20 | 21 | #[cfg(feature = "serde")] 22 | pub mod serde_untagged; 23 | 24 | #[cfg(feature = "serde")] 25 | pub mod serde_untagged_optional; 26 | 27 | use core::convert::{AsMut, AsRef}; 28 | use core::fmt; 29 | use core::future::Future; 30 | use core::ops::Deref; 31 | use core::ops::DerefMut; 32 | use core::pin::Pin; 33 | 34 | #[cfg(any(test, feature = "std"))] 35 | use std::error::Error; 36 | #[cfg(any(test, feature = "std"))] 37 | use std::io::{self, BufRead, Read, Seek, SeekFrom, Write}; 38 | 39 | pub use crate::Either::{Left, Right}; 40 | 41 | /// The enum `Either` with variants `Left` and `Right` is a general purpose 42 | /// sum type with two cases. 43 | /// 44 | /// The `Either` type is symmetric and treats its variants the same way, without 45 | /// preference. 46 | /// (For representing success or error, use the regular `Result` enum instead.) 47 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 48 | #[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 49 | pub enum Either { 50 | /// A value of type `L`. 51 | Left(L), 52 | /// A value of type `R`. 53 | Right(R), 54 | } 55 | 56 | /// Evaluate the provided expression for both [`Either::Left`] and [`Either::Right`]. 57 | /// 58 | /// This macro is useful in cases where both sides of [`Either`] can be interacted with 59 | /// in the same way even though the don't share the same type. 60 | /// 61 | /// Syntax: `either::for_both!(` *expression* `,` *pattern* `=>` *expression* `)` 62 | /// 63 | /// # Example 64 | /// 65 | /// ``` 66 | /// use either::Either; 67 | /// 68 | /// fn length(owned_or_borrowed: Either) -> usize { 69 | /// either::for_both!(owned_or_borrowed, s => s.len()) 70 | /// } 71 | /// 72 | /// fn main() { 73 | /// let borrowed = Either::Right("Hello world!"); 74 | /// let owned = Either::Left("Hello world!".to_owned()); 75 | /// 76 | /// assert_eq!(length(borrowed), 12); 77 | /// assert_eq!(length(owned), 12); 78 | /// } 79 | /// ``` 80 | #[macro_export] 81 | macro_rules! for_both { 82 | ($value:expr, $pattern:pat => $result:expr) => { 83 | match $value { 84 | $crate::Either::Left($pattern) => $result, 85 | $crate::Either::Right($pattern) => $result, 86 | } 87 | }; 88 | } 89 | 90 | /// Macro for unwrapping the left side of an [`Either`], which fails early 91 | /// with the opposite side. Can only be used in functions that return 92 | /// `Either` because of the early return of `Right` that it provides. 93 | /// 94 | /// See also [`try_right!`] for its dual, which applies the same just to the 95 | /// right side. 96 | /// 97 | /// # Example 98 | /// 99 | /// ``` 100 | /// use either::{Either, Left, Right}; 101 | /// 102 | /// fn twice(wrapper: Either) -> Either { 103 | /// let value = either::try_left!(wrapper); 104 | /// Left(value * 2) 105 | /// } 106 | /// 107 | /// fn main() { 108 | /// assert_eq!(twice(Left(2)), Left(4)); 109 | /// assert_eq!(twice(Right("ups")), Right("ups")); 110 | /// } 111 | /// ``` 112 | #[macro_export] 113 | macro_rules! try_left { 114 | ($expr:expr) => { 115 | match $expr { 116 | $crate::Left(val) => val, 117 | $crate::Right(err) => return $crate::Right(::core::convert::From::from(err)), 118 | } 119 | }; 120 | } 121 | 122 | /// Dual to [`try_left!`], see its documentation for more information. 123 | #[macro_export] 124 | macro_rules! try_right { 125 | ($expr:expr) => { 126 | match $expr { 127 | $crate::Left(err) => return $crate::Left(::core::convert::From::from(err)), 128 | $crate::Right(val) => val, 129 | } 130 | }; 131 | } 132 | 133 | macro_rules! map_either { 134 | ($value:expr, $pattern:pat => $result:expr) => { 135 | match $value { 136 | Left($pattern) => Left($result), 137 | Right($pattern) => Right($result), 138 | } 139 | }; 140 | } 141 | 142 | mod iterator; 143 | pub use self::iterator::IterEither; 144 | 145 | mod into_either; 146 | pub use self::into_either::IntoEither; 147 | 148 | impl Clone for Either { 149 | fn clone(&self) -> Self { 150 | match self { 151 | Left(inner) => Left(inner.clone()), 152 | Right(inner) => Right(inner.clone()), 153 | } 154 | } 155 | 156 | fn clone_from(&mut self, source: &Self) { 157 | match (self, source) { 158 | (Left(dest), Left(source)) => dest.clone_from(source), 159 | (Right(dest), Right(source)) => dest.clone_from(source), 160 | (dest, source) => *dest = source.clone(), 161 | } 162 | } 163 | } 164 | 165 | impl Either { 166 | /// Return true if the value is the `Left` variant. 167 | /// 168 | /// ``` 169 | /// use either::*; 170 | /// 171 | /// let values = [Left(1), Right("the right value")]; 172 | /// assert_eq!(values[0].is_left(), true); 173 | /// assert_eq!(values[1].is_left(), false); 174 | /// ``` 175 | pub fn is_left(&self) -> bool { 176 | match self { 177 | Left(_) => true, 178 | Right(_) => false, 179 | } 180 | } 181 | 182 | /// Return true if the value is the `Right` variant. 183 | /// 184 | /// ``` 185 | /// use either::*; 186 | /// 187 | /// let values = [Left(1), Right("the right value")]; 188 | /// assert_eq!(values[0].is_right(), false); 189 | /// assert_eq!(values[1].is_right(), true); 190 | /// ``` 191 | pub fn is_right(&self) -> bool { 192 | !self.is_left() 193 | } 194 | 195 | /// Convert the left side of `Either` to an `Option`. 196 | /// 197 | /// ``` 198 | /// use either::*; 199 | /// 200 | /// let left: Either<_, ()> = Left("some value"); 201 | /// assert_eq!(left.left(), Some("some value")); 202 | /// 203 | /// let right: Either<(), _> = Right(321); 204 | /// assert_eq!(right.left(), None); 205 | /// ``` 206 | pub fn left(self) -> Option { 207 | match self { 208 | Left(l) => Some(l), 209 | Right(_) => None, 210 | } 211 | } 212 | 213 | /// Convert the right side of `Either` to an `Option`. 214 | /// 215 | /// ``` 216 | /// use either::*; 217 | /// 218 | /// let left: Either<_, ()> = Left("some value"); 219 | /// assert_eq!(left.right(), None); 220 | /// 221 | /// let right: Either<(), _> = Right(321); 222 | /// assert_eq!(right.right(), Some(321)); 223 | /// ``` 224 | pub fn right(self) -> Option { 225 | match self { 226 | Left(_) => None, 227 | Right(r) => Some(r), 228 | } 229 | } 230 | 231 | /// Convert `&Either` to `Either<&L, &R>`. 232 | /// 233 | /// ``` 234 | /// use either::*; 235 | /// 236 | /// let left: Either<_, ()> = Left("some value"); 237 | /// assert_eq!(left.as_ref(), Left(&"some value")); 238 | /// 239 | /// let right: Either<(), _> = Right("some value"); 240 | /// assert_eq!(right.as_ref(), Right(&"some value")); 241 | /// ``` 242 | pub fn as_ref(&self) -> Either<&L, &R> { 243 | map_either!(self, inner => inner) 244 | } 245 | 246 | /// Convert `&mut Either` to `Either<&mut L, &mut R>`. 247 | /// 248 | /// ``` 249 | /// use either::*; 250 | /// 251 | /// fn mutate_left(value: &mut Either) { 252 | /// if let Some(l) = value.as_mut().left() { 253 | /// *l = 999; 254 | /// } 255 | /// } 256 | /// 257 | /// let mut left = Left(123); 258 | /// let mut right = Right(123); 259 | /// mutate_left(&mut left); 260 | /// mutate_left(&mut right); 261 | /// assert_eq!(left, Left(999)); 262 | /// assert_eq!(right, Right(123)); 263 | /// ``` 264 | pub fn as_mut(&mut self) -> Either<&mut L, &mut R> { 265 | map_either!(self, inner => inner) 266 | } 267 | 268 | /// Convert `Pin<&Either>` to `Either, Pin<&R>>`, 269 | /// pinned projections of the inner variants. 270 | pub fn as_pin_ref(self: Pin<&Self>) -> Either, Pin<&R>> { 271 | // SAFETY: We can use `new_unchecked` because the `inner` parts are 272 | // guaranteed to be pinned, as they come from `self` which is pinned. 273 | unsafe { map_either!(Pin::get_ref(self), inner => Pin::new_unchecked(inner)) } 274 | } 275 | 276 | /// Convert `Pin<&mut Either>` to `Either, Pin<&mut R>>`, 277 | /// pinned projections of the inner variants. 278 | pub fn as_pin_mut(self: Pin<&mut Self>) -> Either, Pin<&mut R>> { 279 | // SAFETY: `get_unchecked_mut` is fine because we don't move anything. 280 | // We can use `new_unchecked` because the `inner` parts are guaranteed 281 | // to be pinned, as they come from `self` which is pinned, and we never 282 | // offer an unpinned `&mut L` or `&mut R` through `Pin<&mut Self>`. We 283 | // also don't have an implementation of `Drop`, nor manual `Unpin`. 284 | unsafe { map_either!(Pin::get_unchecked_mut(self), inner => Pin::new_unchecked(inner)) } 285 | } 286 | 287 | /// Convert `Either` to `Either`. 288 | /// 289 | /// ``` 290 | /// use either::*; 291 | /// 292 | /// let left: Either<_, ()> = Left(123); 293 | /// assert_eq!(left.flip(), Right(123)); 294 | /// 295 | /// let right: Either<(), _> = Right("some value"); 296 | /// assert_eq!(right.flip(), Left("some value")); 297 | /// ``` 298 | pub fn flip(self) -> Either { 299 | match self { 300 | Left(l) => Right(l), 301 | Right(r) => Left(r), 302 | } 303 | } 304 | 305 | /// Apply the function `f` on the value in the `Left` variant if it is present rewrapping the 306 | /// result in `Left`. 307 | /// 308 | /// ``` 309 | /// use either::*; 310 | /// 311 | /// let left: Either<_, u32> = Left(123); 312 | /// assert_eq!(left.map_left(|x| x * 2), Left(246)); 313 | /// 314 | /// let right: Either = Right(123); 315 | /// assert_eq!(right.map_left(|x| x * 2), Right(123)); 316 | /// ``` 317 | pub fn map_left(self, f: F) -> Either 318 | where 319 | F: FnOnce(L) -> M, 320 | { 321 | match self { 322 | Left(l) => Left(f(l)), 323 | Right(r) => Right(r), 324 | } 325 | } 326 | 327 | /// Apply the function `f` on the value in the `Right` variant if it is present rewrapping the 328 | /// result in `Right`. 329 | /// 330 | /// ``` 331 | /// use either::*; 332 | /// 333 | /// let left: Either<_, u32> = Left(123); 334 | /// assert_eq!(left.map_right(|x| x * 2), Left(123)); 335 | /// 336 | /// let right: Either = Right(123); 337 | /// assert_eq!(right.map_right(|x| x * 2), Right(246)); 338 | /// ``` 339 | pub fn map_right(self, f: F) -> Either 340 | where 341 | F: FnOnce(R) -> S, 342 | { 343 | match self { 344 | Left(l) => Left(l), 345 | Right(r) => Right(f(r)), 346 | } 347 | } 348 | 349 | /// Apply the functions `f` and `g` to the `Left` and `Right` variants 350 | /// respectively. This is equivalent to 351 | /// [bimap](https://hackage.haskell.org/package/bifunctors-5/docs/Data-Bifunctor.html) 352 | /// in functional programming. 353 | /// 354 | /// ``` 355 | /// use either::*; 356 | /// 357 | /// let f = |s: String| s.len(); 358 | /// let g = |u: u8| u.to_string(); 359 | /// 360 | /// let left: Either = Left("loopy".into()); 361 | /// assert_eq!(left.map_either(f, g), Left(5)); 362 | /// 363 | /// let right: Either = Right(42); 364 | /// assert_eq!(right.map_either(f, g), Right("42".into())); 365 | /// ``` 366 | pub fn map_either(self, f: F, g: G) -> Either 367 | where 368 | F: FnOnce(L) -> M, 369 | G: FnOnce(R) -> S, 370 | { 371 | match self { 372 | Left(l) => Left(f(l)), 373 | Right(r) => Right(g(r)), 374 | } 375 | } 376 | 377 | /// Similar to [`map_either`][Self::map_either], with an added context `ctx` accessible to 378 | /// both functions. 379 | /// 380 | /// ``` 381 | /// use either::*; 382 | /// 383 | /// let mut sum = 0; 384 | /// 385 | /// // Both closures want to update the same value, so pass it as context. 386 | /// let mut f = |sum: &mut usize, s: String| { *sum += s.len(); s.to_uppercase() }; 387 | /// let mut g = |sum: &mut usize, u: usize| { *sum += u; u.to_string() }; 388 | /// 389 | /// let left: Either = Left("loopy".into()); 390 | /// assert_eq!(left.map_either_with(&mut sum, &mut f, &mut g), Left("LOOPY".into())); 391 | /// 392 | /// let right: Either = Right(42); 393 | /// assert_eq!(right.map_either_with(&mut sum, &mut f, &mut g), Right("42".into())); 394 | /// 395 | /// assert_eq!(sum, 47); 396 | /// ``` 397 | pub fn map_either_with(self, ctx: Ctx, f: F, g: G) -> Either 398 | where 399 | F: FnOnce(Ctx, L) -> M, 400 | G: FnOnce(Ctx, R) -> S, 401 | { 402 | match self { 403 | Left(l) => Left(f(ctx, l)), 404 | Right(r) => Right(g(ctx, r)), 405 | } 406 | } 407 | 408 | /// Apply one of two functions depending on contents, unifying their result. If the value is 409 | /// `Left(L)` then the first function `f` is applied; if it is `Right(R)` then the second 410 | /// function `g` is applied. 411 | /// 412 | /// ``` 413 | /// use either::*; 414 | /// 415 | /// fn square(n: u32) -> i32 { (n * n) as i32 } 416 | /// fn negate(n: i32) -> i32 { -n } 417 | /// 418 | /// let left: Either = Left(4); 419 | /// assert_eq!(left.either(square, negate), 16); 420 | /// 421 | /// let right: Either = Right(-4); 422 | /// assert_eq!(right.either(square, negate), 4); 423 | /// ``` 424 | pub fn either(self, f: F, g: G) -> T 425 | where 426 | F: FnOnce(L) -> T, 427 | G: FnOnce(R) -> T, 428 | { 429 | match self { 430 | Left(l) => f(l), 431 | Right(r) => g(r), 432 | } 433 | } 434 | 435 | /// Like [`either`][Self::either], but provide some context to whichever of the 436 | /// functions ends up being called. 437 | /// 438 | /// ``` 439 | /// // In this example, the context is a mutable reference 440 | /// use either::*; 441 | /// 442 | /// let mut result = Vec::new(); 443 | /// 444 | /// let values = vec![Left(2), Right(2.7)]; 445 | /// 446 | /// for value in values { 447 | /// value.either_with(&mut result, 448 | /// |ctx, integer| ctx.push(integer), 449 | /// |ctx, real| ctx.push(f64::round(real) as i32)); 450 | /// } 451 | /// 452 | /// assert_eq!(result, vec![2, 3]); 453 | /// ``` 454 | pub fn either_with(self, ctx: Ctx, f: F, g: G) -> T 455 | where 456 | F: FnOnce(Ctx, L) -> T, 457 | G: FnOnce(Ctx, R) -> T, 458 | { 459 | match self { 460 | Left(l) => f(ctx, l), 461 | Right(r) => g(ctx, r), 462 | } 463 | } 464 | 465 | /// Apply the function `f` on the value in the `Left` variant if it is present. 466 | /// 467 | /// ``` 468 | /// use either::*; 469 | /// 470 | /// let left: Either<_, u32> = Left(123); 471 | /// assert_eq!(left.left_and_then::<_,()>(|x| Right(x * 2)), Right(246)); 472 | /// 473 | /// let right: Either = Right(123); 474 | /// assert_eq!(right.left_and_then(|x| Right::<(), _>(x * 2)), Right(123)); 475 | /// ``` 476 | pub fn left_and_then(self, f: F) -> Either 477 | where 478 | F: FnOnce(L) -> Either, 479 | { 480 | match self { 481 | Left(l) => f(l), 482 | Right(r) => Right(r), 483 | } 484 | } 485 | 486 | /// Apply the function `f` on the value in the `Right` variant if it is present. 487 | /// 488 | /// ``` 489 | /// use either::*; 490 | /// 491 | /// let left: Either<_, u32> = Left(123); 492 | /// assert_eq!(left.right_and_then(|x| Right(x * 2)), Left(123)); 493 | /// 494 | /// let right: Either = Right(123); 495 | /// assert_eq!(right.right_and_then(|x| Right(x * 2)), Right(246)); 496 | /// ``` 497 | pub fn right_and_then(self, f: F) -> Either 498 | where 499 | F: FnOnce(R) -> Either, 500 | { 501 | match self { 502 | Left(l) => Left(l), 503 | Right(r) => f(r), 504 | } 505 | } 506 | 507 | /// Convert the inner value to an iterator. 508 | /// 509 | /// This requires the `Left` and `Right` iterators to have the same item type. 510 | /// See [`factor_into_iter`][Either::factor_into_iter] to iterate different types. 511 | /// 512 | /// ``` 513 | /// use either::*; 514 | /// 515 | /// let left: Either<_, Vec> = Left(vec![1, 2, 3, 4, 5]); 516 | /// let mut right: Either, _> = Right(vec![]); 517 | /// right.extend(left.into_iter()); 518 | /// assert_eq!(right, Right(vec![1, 2, 3, 4, 5])); 519 | /// ``` 520 | #[allow(clippy::should_implement_trait)] 521 | pub fn into_iter(self) -> Either 522 | where 523 | L: IntoIterator, 524 | R: IntoIterator, 525 | { 526 | map_either!(self, inner => inner.into_iter()) 527 | } 528 | 529 | /// Borrow the inner value as an iterator. 530 | /// 531 | /// This requires the `Left` and `Right` iterators to have the same item type. 532 | /// See [`factor_iter`][Either::factor_iter] to iterate different types. 533 | /// 534 | /// ``` 535 | /// use either::*; 536 | /// 537 | /// let left: Either<_, &[u32]> = Left(vec![2, 3]); 538 | /// let mut right: Either, _> = Right(&[4, 5][..]); 539 | /// let mut all = vec![1]; 540 | /// all.extend(left.iter()); 541 | /// all.extend(right.iter()); 542 | /// assert_eq!(all, vec![1, 2, 3, 4, 5]); 543 | /// ``` 544 | pub fn iter(&self) -> Either<<&L as IntoIterator>::IntoIter, <&R as IntoIterator>::IntoIter> 545 | where 546 | for<'a> &'a L: IntoIterator, 547 | for<'a> &'a R: IntoIterator::Item>, 548 | { 549 | map_either!(self, inner => inner.into_iter()) 550 | } 551 | 552 | /// Mutably borrow the inner value as an iterator. 553 | /// 554 | /// This requires the `Left` and `Right` iterators to have the same item type. 555 | /// See [`factor_iter_mut`][Either::factor_iter_mut] to iterate different types. 556 | /// 557 | /// ``` 558 | /// use either::*; 559 | /// 560 | /// let mut left: Either<_, &mut [u32]> = Left(vec![2, 3]); 561 | /// for l in left.iter_mut() { 562 | /// *l *= *l 563 | /// } 564 | /// assert_eq!(left, Left(vec![4, 9])); 565 | /// 566 | /// let mut inner = [4, 5]; 567 | /// let mut right: Either, _> = Right(&mut inner[..]); 568 | /// for r in right.iter_mut() { 569 | /// *r *= *r 570 | /// } 571 | /// assert_eq!(inner, [16, 25]); 572 | /// ``` 573 | pub fn iter_mut( 574 | &mut self, 575 | ) -> Either<<&mut L as IntoIterator>::IntoIter, <&mut R as IntoIterator>::IntoIter> 576 | where 577 | for<'a> &'a mut L: IntoIterator, 578 | for<'a> &'a mut R: IntoIterator::Item>, 579 | { 580 | map_either!(self, inner => inner.into_iter()) 581 | } 582 | 583 | /// Converts an `Either` of `Iterator`s to be an `Iterator` of `Either`s 584 | /// 585 | /// Unlike [`into_iter`][Either::into_iter], this does not require the 586 | /// `Left` and `Right` iterators to have the same item type. 587 | /// 588 | /// ``` 589 | /// use either::*; 590 | /// let left: Either<_, Vec> = Left(&["hello"]); 591 | /// assert_eq!(left.factor_into_iter().next(), Some(Left(&"hello"))); 592 | /// 593 | /// let right: Either<&[&str], _> = Right(vec![0, 1]); 594 | /// assert_eq!(right.factor_into_iter().collect::>(), vec![Right(0), Right(1)]); 595 | /// 596 | /// ``` 597 | // TODO(MSRV): doc(alias) was stabilized in Rust 1.48 598 | // #[doc(alias = "transpose")] 599 | pub fn factor_into_iter(self) -> IterEither 600 | where 601 | L: IntoIterator, 602 | R: IntoIterator, 603 | { 604 | IterEither::new(map_either!(self, inner => inner.into_iter())) 605 | } 606 | 607 | /// Borrows an `Either` of `Iterator`s to be an `Iterator` of `Either`s 608 | /// 609 | /// Unlike [`iter`][Either::iter], this does not require the 610 | /// `Left` and `Right` iterators to have the same item type. 611 | /// 612 | /// ``` 613 | /// use either::*; 614 | /// let left: Either<_, Vec> = Left(["hello"]); 615 | /// assert_eq!(left.factor_iter().next(), Some(Left(&"hello"))); 616 | /// 617 | /// let right: Either<[&str; 2], _> = Right(vec![0, 1]); 618 | /// assert_eq!(right.factor_iter().collect::>(), vec![Right(&0), Right(&1)]); 619 | /// 620 | /// ``` 621 | pub fn factor_iter( 622 | &self, 623 | ) -> IterEither<<&L as IntoIterator>::IntoIter, <&R as IntoIterator>::IntoIter> 624 | where 625 | for<'a> &'a L: IntoIterator, 626 | for<'a> &'a R: IntoIterator, 627 | { 628 | IterEither::new(map_either!(self, inner => inner.into_iter())) 629 | } 630 | 631 | /// Mutably borrows an `Either` of `Iterator`s to be an `Iterator` of `Either`s 632 | /// 633 | /// Unlike [`iter_mut`][Either::iter_mut], this does not require the 634 | /// `Left` and `Right` iterators to have the same item type. 635 | /// 636 | /// ``` 637 | /// use either::*; 638 | /// let mut left: Either<_, Vec> = Left(["hello"]); 639 | /// left.factor_iter_mut().for_each(|x| *x.unwrap_left() = "goodbye"); 640 | /// assert_eq!(left, Left(["goodbye"])); 641 | /// 642 | /// let mut right: Either<[&str; 2], _> = Right(vec![0, 1, 2]); 643 | /// right.factor_iter_mut().for_each(|x| if let Right(r) = x { *r = -*r; }); 644 | /// assert_eq!(right, Right(vec![0, -1, -2])); 645 | /// 646 | /// ``` 647 | pub fn factor_iter_mut( 648 | &mut self, 649 | ) -> IterEither<<&mut L as IntoIterator>::IntoIter, <&mut R as IntoIterator>::IntoIter> 650 | where 651 | for<'a> &'a mut L: IntoIterator, 652 | for<'a> &'a mut R: IntoIterator, 653 | { 654 | IterEither::new(map_either!(self, inner => inner.into_iter())) 655 | } 656 | 657 | /// Return left value or given value 658 | /// 659 | /// Arguments passed to `left_or` are eagerly evaluated; if you are passing 660 | /// the result of a function call, it is recommended to use 661 | /// [`left_or_else`][Self::left_or_else], which is lazily evaluated. 662 | /// 663 | /// # Examples 664 | /// 665 | /// ``` 666 | /// # use either::*; 667 | /// let left: Either<&str, &str> = Left("left"); 668 | /// assert_eq!(left.left_or("foo"), "left"); 669 | /// 670 | /// let right: Either<&str, &str> = Right("right"); 671 | /// assert_eq!(right.left_or("left"), "left"); 672 | /// ``` 673 | pub fn left_or(self, other: L) -> L { 674 | match self { 675 | Either::Left(l) => l, 676 | Either::Right(_) => other, 677 | } 678 | } 679 | 680 | /// Return left or a default 681 | /// 682 | /// # Examples 683 | /// 684 | /// ``` 685 | /// # use either::*; 686 | /// let left: Either = Left("left".to_string()); 687 | /// assert_eq!(left.left_or_default(), "left"); 688 | /// 689 | /// let right: Either = Right(42); 690 | /// assert_eq!(right.left_or_default(), String::default()); 691 | /// ``` 692 | pub fn left_or_default(self) -> L 693 | where 694 | L: Default, 695 | { 696 | match self { 697 | Either::Left(l) => l, 698 | Either::Right(_) => L::default(), 699 | } 700 | } 701 | 702 | /// Returns left value or computes it from a closure 703 | /// 704 | /// # Examples 705 | /// 706 | /// ``` 707 | /// # use either::*; 708 | /// let left: Either = Left("3".to_string()); 709 | /// assert_eq!(left.left_or_else(|_| unreachable!()), "3"); 710 | /// 711 | /// let right: Either = Right(3); 712 | /// assert_eq!(right.left_or_else(|x| x.to_string()), "3"); 713 | /// ``` 714 | pub fn left_or_else(self, f: F) -> L 715 | where 716 | F: FnOnce(R) -> L, 717 | { 718 | match self { 719 | Either::Left(l) => l, 720 | Either::Right(r) => f(r), 721 | } 722 | } 723 | 724 | /// Return right value or given value 725 | /// 726 | /// Arguments passed to `right_or` are eagerly evaluated; if you are passing 727 | /// the result of a function call, it is recommended to use 728 | /// [`right_or_else`][Self::right_or_else], which is lazily evaluated. 729 | /// 730 | /// # Examples 731 | /// 732 | /// ``` 733 | /// # use either::*; 734 | /// let right: Either<&str, &str> = Right("right"); 735 | /// assert_eq!(right.right_or("foo"), "right"); 736 | /// 737 | /// let left: Either<&str, &str> = Left("left"); 738 | /// assert_eq!(left.right_or("right"), "right"); 739 | /// ``` 740 | pub fn right_or(self, other: R) -> R { 741 | match self { 742 | Either::Left(_) => other, 743 | Either::Right(r) => r, 744 | } 745 | } 746 | 747 | /// Return right or a default 748 | /// 749 | /// # Examples 750 | /// 751 | /// ``` 752 | /// # use either::*; 753 | /// let left: Either = Left("left".to_string()); 754 | /// assert_eq!(left.right_or_default(), u32::default()); 755 | /// 756 | /// let right: Either = Right(42); 757 | /// assert_eq!(right.right_or_default(), 42); 758 | /// ``` 759 | pub fn right_or_default(self) -> R 760 | where 761 | R: Default, 762 | { 763 | match self { 764 | Either::Left(_) => R::default(), 765 | Either::Right(r) => r, 766 | } 767 | } 768 | 769 | /// Returns right value or computes it from a closure 770 | /// 771 | /// # Examples 772 | /// 773 | /// ``` 774 | /// # use either::*; 775 | /// let left: Either = Left("3".to_string()); 776 | /// assert_eq!(left.right_or_else(|x| x.parse().unwrap()), 3); 777 | /// 778 | /// let right: Either = Right(3); 779 | /// assert_eq!(right.right_or_else(|_| unreachable!()), 3); 780 | /// ``` 781 | pub fn right_or_else(self, f: F) -> R 782 | where 783 | F: FnOnce(L) -> R, 784 | { 785 | match self { 786 | Either::Left(l) => f(l), 787 | Either::Right(r) => r, 788 | } 789 | } 790 | 791 | /// Returns the left value 792 | /// 793 | /// # Examples 794 | /// 795 | /// ``` 796 | /// # use either::*; 797 | /// let left: Either<_, ()> = Left(3); 798 | /// assert_eq!(left.unwrap_left(), 3); 799 | /// ``` 800 | /// 801 | /// # Panics 802 | /// 803 | /// When `Either` is a `Right` value 804 | /// 805 | /// ```should_panic 806 | /// # use either::*; 807 | /// let right: Either<(), _> = Right(3); 808 | /// right.unwrap_left(); 809 | /// ``` 810 | pub fn unwrap_left(self) -> L 811 | where 812 | R: core::fmt::Debug, 813 | { 814 | match self { 815 | Either::Left(l) => l, 816 | Either::Right(r) => { 817 | panic!("called `Either::unwrap_left()` on a `Right` value: {:?}", r) 818 | } 819 | } 820 | } 821 | 822 | /// Returns the right value 823 | /// 824 | /// # Examples 825 | /// 826 | /// ``` 827 | /// # use either::*; 828 | /// let right: Either<(), _> = Right(3); 829 | /// assert_eq!(right.unwrap_right(), 3); 830 | /// ``` 831 | /// 832 | /// # Panics 833 | /// 834 | /// When `Either` is a `Left` value 835 | /// 836 | /// ```should_panic 837 | /// # use either::*; 838 | /// let left: Either<_, ()> = Left(3); 839 | /// left.unwrap_right(); 840 | /// ``` 841 | pub fn unwrap_right(self) -> R 842 | where 843 | L: core::fmt::Debug, 844 | { 845 | match self { 846 | Either::Right(r) => r, 847 | Either::Left(l) => panic!("called `Either::unwrap_right()` on a `Left` value: {:?}", l), 848 | } 849 | } 850 | 851 | /// Returns the left value 852 | /// 853 | /// # Examples 854 | /// 855 | /// ``` 856 | /// # use either::*; 857 | /// let left: Either<_, ()> = Left(3); 858 | /// assert_eq!(left.expect_left("value was Right"), 3); 859 | /// ``` 860 | /// 861 | /// # Panics 862 | /// 863 | /// When `Either` is a `Right` value 864 | /// 865 | /// ```should_panic 866 | /// # use either::*; 867 | /// let right: Either<(), _> = Right(3); 868 | /// right.expect_left("value was Right"); 869 | /// ``` 870 | pub fn expect_left(self, msg: &str) -> L 871 | where 872 | R: core::fmt::Debug, 873 | { 874 | match self { 875 | Either::Left(l) => l, 876 | Either::Right(r) => panic!("{}: {:?}", msg, r), 877 | } 878 | } 879 | 880 | /// Returns the right value 881 | /// 882 | /// # Examples 883 | /// 884 | /// ``` 885 | /// # use either::*; 886 | /// let right: Either<(), _> = Right(3); 887 | /// assert_eq!(right.expect_right("value was Left"), 3); 888 | /// ``` 889 | /// 890 | /// # Panics 891 | /// 892 | /// When `Either` is a `Left` value 893 | /// 894 | /// ```should_panic 895 | /// # use either::*; 896 | /// let left: Either<_, ()> = Left(3); 897 | /// left.expect_right("value was Right"); 898 | /// ``` 899 | pub fn expect_right(self, msg: &str) -> R 900 | where 901 | L: core::fmt::Debug, 902 | { 903 | match self { 904 | Either::Right(r) => r, 905 | Either::Left(l) => panic!("{}: {:?}", msg, l), 906 | } 907 | } 908 | 909 | /// Convert the contained value into `T` 910 | /// 911 | /// # Examples 912 | /// 913 | /// ``` 914 | /// # use either::*; 915 | /// // Both u16 and u32 can be converted to u64. 916 | /// let left: Either = Left(3u16); 917 | /// assert_eq!(left.either_into::(), 3u64); 918 | /// let right: Either = Right(7u32); 919 | /// assert_eq!(right.either_into::(), 7u64); 920 | /// ``` 921 | pub fn either_into(self) -> T 922 | where 923 | L: Into, 924 | R: Into, 925 | { 926 | for_both!(self, inner => inner.into()) 927 | } 928 | } 929 | 930 | impl Either, Option> { 931 | /// Factors out `None` from an `Either` of [`Option`]. 932 | /// 933 | /// ``` 934 | /// use either::*; 935 | /// let left: Either<_, Option> = Left(Some(vec![0])); 936 | /// assert_eq!(left.factor_none(), Some(Left(vec![0]))); 937 | /// 938 | /// let right: Either>, _> = Right(Some(String::new())); 939 | /// assert_eq!(right.factor_none(), Some(Right(String::new()))); 940 | /// ``` 941 | // TODO(MSRV): doc(alias) was stabilized in Rust 1.48 942 | // #[doc(alias = "transpose")] 943 | pub fn factor_none(self) -> Option> { 944 | match self { 945 | Left(l) => l.map(Either::Left), 946 | Right(r) => r.map(Either::Right), 947 | } 948 | } 949 | } 950 | 951 | impl Either, Result> { 952 | /// Factors out a homogenous type from an `Either` of [`Result`]. 953 | /// 954 | /// Here, the homogeneous type is the `Err` type of the [`Result`]. 955 | /// 956 | /// ``` 957 | /// use either::*; 958 | /// let left: Either<_, Result> = Left(Ok(vec![0])); 959 | /// assert_eq!(left.factor_err(), Ok(Left(vec![0]))); 960 | /// 961 | /// let right: Either, u32>, _> = Right(Ok(String::new())); 962 | /// assert_eq!(right.factor_err(), Ok(Right(String::new()))); 963 | /// ``` 964 | // TODO(MSRV): doc(alias) was stabilized in Rust 1.48 965 | // #[doc(alias = "transpose")] 966 | pub fn factor_err(self) -> Result, E> { 967 | match self { 968 | Left(l) => l.map(Either::Left), 969 | Right(r) => r.map(Either::Right), 970 | } 971 | } 972 | } 973 | 974 | impl Either, Result> { 975 | /// Factors out a homogenous type from an `Either` of [`Result`]. 976 | /// 977 | /// Here, the homogeneous type is the `Ok` type of the [`Result`]. 978 | /// 979 | /// ``` 980 | /// use either::*; 981 | /// let left: Either<_, Result> = Left(Err(vec![0])); 982 | /// assert_eq!(left.factor_ok(), Err(Left(vec![0]))); 983 | /// 984 | /// let right: Either>, _> = Right(Err(String::new())); 985 | /// assert_eq!(right.factor_ok(), Err(Right(String::new()))); 986 | /// ``` 987 | // TODO(MSRV): doc(alias) was stabilized in Rust 1.48 988 | // #[doc(alias = "transpose")] 989 | pub fn factor_ok(self) -> Result> { 990 | match self { 991 | Left(l) => l.map_err(Either::Left), 992 | Right(r) => r.map_err(Either::Right), 993 | } 994 | } 995 | } 996 | 997 | impl Either<(T, L), (T, R)> { 998 | /// Factor out a homogeneous type from an either of pairs. 999 | /// 1000 | /// Here, the homogeneous type is the first element of the pairs. 1001 | /// 1002 | /// ``` 1003 | /// use either::*; 1004 | /// let left: Either<_, (u32, String)> = Left((123, vec![0])); 1005 | /// assert_eq!(left.factor_first().0, 123); 1006 | /// 1007 | /// let right: Either<(u32, Vec), _> = Right((123, String::new())); 1008 | /// assert_eq!(right.factor_first().0, 123); 1009 | /// ``` 1010 | pub fn factor_first(self) -> (T, Either) { 1011 | match self { 1012 | Left((t, l)) => (t, Left(l)), 1013 | Right((t, r)) => (t, Right(r)), 1014 | } 1015 | } 1016 | } 1017 | 1018 | impl Either<(L, T), (R, T)> { 1019 | /// Factor out a homogeneous type from an either of pairs. 1020 | /// 1021 | /// Here, the homogeneous type is the second element of the pairs. 1022 | /// 1023 | /// ``` 1024 | /// use either::*; 1025 | /// let left: Either<_, (String, u32)> = Left((vec![0], 123)); 1026 | /// assert_eq!(left.factor_second().1, 123); 1027 | /// 1028 | /// let right: Either<(Vec, u32), _> = Right((String::new(), 123)); 1029 | /// assert_eq!(right.factor_second().1, 123); 1030 | /// ``` 1031 | pub fn factor_second(self) -> (Either, T) { 1032 | match self { 1033 | Left((l, t)) => (Left(l), t), 1034 | Right((r, t)) => (Right(r), t), 1035 | } 1036 | } 1037 | } 1038 | 1039 | impl Either { 1040 | /// Extract the value of an either over two equivalent types. 1041 | /// 1042 | /// ``` 1043 | /// use either::*; 1044 | /// 1045 | /// let left: Either<_, u32> = Left(123); 1046 | /// assert_eq!(left.into_inner(), 123); 1047 | /// 1048 | /// let right: Either = Right(123); 1049 | /// assert_eq!(right.into_inner(), 123); 1050 | /// ``` 1051 | pub fn into_inner(self) -> T { 1052 | for_both!(self, inner => inner) 1053 | } 1054 | 1055 | /// Map `f` over the contained value and return the result in the 1056 | /// corresponding variant. 1057 | /// 1058 | /// ``` 1059 | /// use either::*; 1060 | /// 1061 | /// let value: Either<_, i32> = Right(42); 1062 | /// 1063 | /// let other = value.map(|x| x * 2); 1064 | /// assert_eq!(other, Right(84)); 1065 | /// ``` 1066 | pub fn map(self, f: F) -> Either 1067 | where 1068 | F: FnOnce(T) -> M, 1069 | { 1070 | match self { 1071 | Left(l) => Left(f(l)), 1072 | Right(r) => Right(f(r)), 1073 | } 1074 | } 1075 | } 1076 | 1077 | impl Either<&L, &R> { 1078 | /// Maps an `Either<&L, &R>` to an `Either` by cloning the contents of 1079 | /// either branch. 1080 | pub fn cloned(self) -> Either 1081 | where 1082 | L: Clone, 1083 | R: Clone, 1084 | { 1085 | map_either!(self, inner => inner.clone()) 1086 | } 1087 | 1088 | /// Maps an `Either<&L, &R>` to an `Either` by copying the contents of 1089 | /// either branch. 1090 | pub fn copied(self) -> Either 1091 | where 1092 | L: Copy, 1093 | R: Copy, 1094 | { 1095 | map_either!(self, inner => *inner) 1096 | } 1097 | } 1098 | 1099 | impl Either<&mut L, &mut R> { 1100 | /// Maps an `Either<&mut L, &mut R>` to an `Either` by cloning the contents of 1101 | /// either branch. 1102 | pub fn cloned(self) -> Either 1103 | where 1104 | L: Clone, 1105 | R: Clone, 1106 | { 1107 | map_either!(self, inner => inner.clone()) 1108 | } 1109 | 1110 | /// Maps an `Either<&mut L, &mut R>` to an `Either` by copying the contents of 1111 | /// either branch. 1112 | pub fn copied(self) -> Either 1113 | where 1114 | L: Copy, 1115 | R: Copy, 1116 | { 1117 | map_either!(self, inner => *inner) 1118 | } 1119 | } 1120 | 1121 | /// Convert from `Result` to `Either` with `Ok => Right` and `Err => Left`. 1122 | impl From> for Either { 1123 | fn from(r: Result) -> Self { 1124 | match r { 1125 | Err(e) => Left(e), 1126 | Ok(o) => Right(o), 1127 | } 1128 | } 1129 | } 1130 | 1131 | /// Convert from `Either` to `Result` with `Right => Ok` and `Left => Err`. 1132 | impl From> for Result { 1133 | fn from(val: Either) -> Self { 1134 | match val { 1135 | Left(l) => Err(l), 1136 | Right(r) => Ok(r), 1137 | } 1138 | } 1139 | } 1140 | 1141 | /// `Either` is a future if both `L` and `R` are futures. 1142 | impl Future for Either 1143 | where 1144 | L: Future, 1145 | R: Future, 1146 | { 1147 | type Output = L::Output; 1148 | 1149 | fn poll( 1150 | self: Pin<&mut Self>, 1151 | cx: &mut core::task::Context<'_>, 1152 | ) -> core::task::Poll { 1153 | for_both!(self.as_pin_mut(), inner => inner.poll(cx)) 1154 | } 1155 | } 1156 | 1157 | #[cfg(any(test, feature = "std"))] 1158 | /// `Either` implements `Read` if both `L` and `R` do. 1159 | /// 1160 | /// Requires crate feature `"std"` 1161 | impl Read for Either 1162 | where 1163 | L: Read, 1164 | R: Read, 1165 | { 1166 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 1167 | for_both!(self, inner => inner.read(buf)) 1168 | } 1169 | 1170 | fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { 1171 | for_both!(self, inner => inner.read_exact(buf)) 1172 | } 1173 | 1174 | fn read_to_end(&mut self, buf: &mut std::vec::Vec) -> io::Result { 1175 | for_both!(self, inner => inner.read_to_end(buf)) 1176 | } 1177 | 1178 | fn read_to_string(&mut self, buf: &mut std::string::String) -> io::Result { 1179 | for_both!(self, inner => inner.read_to_string(buf)) 1180 | } 1181 | } 1182 | 1183 | #[cfg(any(test, feature = "std"))] 1184 | /// `Either` implements `Seek` if both `L` and `R` do. 1185 | /// 1186 | /// Requires crate feature `"std"` 1187 | impl Seek for Either 1188 | where 1189 | L: Seek, 1190 | R: Seek, 1191 | { 1192 | fn seek(&mut self, pos: SeekFrom) -> io::Result { 1193 | for_both!(self, inner => inner.seek(pos)) 1194 | } 1195 | } 1196 | 1197 | #[cfg(any(test, feature = "std"))] 1198 | /// Requires crate feature `"std"` 1199 | impl BufRead for Either 1200 | where 1201 | L: BufRead, 1202 | R: BufRead, 1203 | { 1204 | fn fill_buf(&mut self) -> io::Result<&[u8]> { 1205 | for_both!(self, inner => inner.fill_buf()) 1206 | } 1207 | 1208 | fn consume(&mut self, amt: usize) { 1209 | for_both!(self, inner => inner.consume(amt)) 1210 | } 1211 | 1212 | fn read_until(&mut self, byte: u8, buf: &mut std::vec::Vec) -> io::Result { 1213 | for_both!(self, inner => inner.read_until(byte, buf)) 1214 | } 1215 | 1216 | fn read_line(&mut self, buf: &mut std::string::String) -> io::Result { 1217 | for_both!(self, inner => inner.read_line(buf)) 1218 | } 1219 | } 1220 | 1221 | #[cfg(any(test, feature = "std"))] 1222 | /// `Either` implements `Write` if both `L` and `R` do. 1223 | /// 1224 | /// Requires crate feature `"std"` 1225 | impl Write for Either 1226 | where 1227 | L: Write, 1228 | R: Write, 1229 | { 1230 | fn write(&mut self, buf: &[u8]) -> io::Result { 1231 | for_both!(self, inner => inner.write(buf)) 1232 | } 1233 | 1234 | fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { 1235 | for_both!(self, inner => inner.write_all(buf)) 1236 | } 1237 | 1238 | fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { 1239 | for_both!(self, inner => inner.write_fmt(fmt)) 1240 | } 1241 | 1242 | fn flush(&mut self) -> io::Result<()> { 1243 | for_both!(self, inner => inner.flush()) 1244 | } 1245 | } 1246 | 1247 | impl AsRef for Either 1248 | where 1249 | L: AsRef, 1250 | R: AsRef, 1251 | { 1252 | fn as_ref(&self) -> &Target { 1253 | for_both!(self, inner => inner.as_ref()) 1254 | } 1255 | } 1256 | 1257 | macro_rules! impl_specific_ref_and_mut { 1258 | ($t:ty, $($attr:meta),* ) => { 1259 | $(#[$attr])* 1260 | impl AsRef<$t> for Either 1261 | where L: AsRef<$t>, R: AsRef<$t> 1262 | { 1263 | fn as_ref(&self) -> &$t { 1264 | for_both!(self, inner => inner.as_ref()) 1265 | } 1266 | } 1267 | 1268 | $(#[$attr])* 1269 | impl AsMut<$t> for Either 1270 | where L: AsMut<$t>, R: AsMut<$t> 1271 | { 1272 | fn as_mut(&mut self) -> &mut $t { 1273 | for_both!(self, inner => inner.as_mut()) 1274 | } 1275 | } 1276 | }; 1277 | } 1278 | 1279 | impl_specific_ref_and_mut!(str,); 1280 | impl_specific_ref_and_mut!( 1281 | ::std::path::Path, 1282 | cfg(feature = "std"), 1283 | doc = "Requires crate feature `std`." 1284 | ); 1285 | impl_specific_ref_and_mut!( 1286 | ::std::ffi::OsStr, 1287 | cfg(feature = "std"), 1288 | doc = "Requires crate feature `std`." 1289 | ); 1290 | impl_specific_ref_and_mut!( 1291 | ::std::ffi::CStr, 1292 | cfg(feature = "std"), 1293 | doc = "Requires crate feature `std`." 1294 | ); 1295 | 1296 | impl AsRef<[Target]> for Either 1297 | where 1298 | L: AsRef<[Target]>, 1299 | R: AsRef<[Target]>, 1300 | { 1301 | fn as_ref(&self) -> &[Target] { 1302 | for_both!(self, inner => inner.as_ref()) 1303 | } 1304 | } 1305 | 1306 | impl AsMut for Either 1307 | where 1308 | L: AsMut, 1309 | R: AsMut, 1310 | { 1311 | fn as_mut(&mut self) -> &mut Target { 1312 | for_both!(self, inner => inner.as_mut()) 1313 | } 1314 | } 1315 | 1316 | impl AsMut<[Target]> for Either 1317 | where 1318 | L: AsMut<[Target]>, 1319 | R: AsMut<[Target]>, 1320 | { 1321 | fn as_mut(&mut self) -> &mut [Target] { 1322 | for_both!(self, inner => inner.as_mut()) 1323 | } 1324 | } 1325 | 1326 | impl Deref for Either 1327 | where 1328 | L: Deref, 1329 | R: Deref, 1330 | { 1331 | type Target = L::Target; 1332 | 1333 | fn deref(&self) -> &Self::Target { 1334 | for_both!(self, inner => &**inner) 1335 | } 1336 | } 1337 | 1338 | impl DerefMut for Either 1339 | where 1340 | L: DerefMut, 1341 | R: DerefMut, 1342 | { 1343 | fn deref_mut(&mut self) -> &mut Self::Target { 1344 | for_both!(self, inner => &mut *inner) 1345 | } 1346 | } 1347 | 1348 | #[cfg(any(test, feature = "std"))] 1349 | /// `Either` implements `Error` if *both* `L` and `R` implement it. 1350 | /// 1351 | /// Requires crate feature `"std"` 1352 | impl Error for Either 1353 | where 1354 | L: Error, 1355 | R: Error, 1356 | { 1357 | fn source(&self) -> Option<&(dyn Error + 'static)> { 1358 | for_both!(self, inner => inner.source()) 1359 | } 1360 | 1361 | #[allow(deprecated)] 1362 | fn description(&self) -> &str { 1363 | for_both!(self, inner => inner.description()) 1364 | } 1365 | 1366 | #[allow(deprecated)] 1367 | fn cause(&self) -> Option<&dyn Error> { 1368 | for_both!(self, inner => inner.cause()) 1369 | } 1370 | } 1371 | 1372 | impl fmt::Display for Either 1373 | where 1374 | L: fmt::Display, 1375 | R: fmt::Display, 1376 | { 1377 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 1378 | for_both!(self, inner => inner.fmt(f)) 1379 | } 1380 | } 1381 | 1382 | impl fmt::Write for Either 1383 | where 1384 | L: fmt::Write, 1385 | R: fmt::Write, 1386 | { 1387 | fn write_str(&mut self, s: &str) -> fmt::Result { 1388 | for_both!(self, inner => inner.write_str(s)) 1389 | } 1390 | 1391 | fn write_char(&mut self, c: char) -> fmt::Result { 1392 | for_both!(self, inner => inner.write_char(c)) 1393 | } 1394 | 1395 | fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result { 1396 | for_both!(self, inner => inner.write_fmt(args)) 1397 | } 1398 | } 1399 | 1400 | #[test] 1401 | fn basic() { 1402 | let mut e = Left(2); 1403 | let r = Right(2); 1404 | assert_eq!(e, Left(2)); 1405 | e = r; 1406 | assert_eq!(e, Right(2)); 1407 | assert_eq!(e.left(), None); 1408 | assert_eq!(e.right(), Some(2)); 1409 | assert_eq!(e.as_ref().right(), Some(&2)); 1410 | assert_eq!(e.as_mut().right(), Some(&mut 2)); 1411 | } 1412 | 1413 | #[test] 1414 | fn macros() { 1415 | use std::string::String; 1416 | 1417 | fn a() -> Either { 1418 | let x: u32 = try_left!(Right(1337u32)); 1419 | Left(x * 2) 1420 | } 1421 | assert_eq!(a(), Right(1337)); 1422 | 1423 | fn b() -> Either { 1424 | Right(try_right!(Left("foo bar"))) 1425 | } 1426 | assert_eq!(b(), Left(String::from("foo bar"))); 1427 | } 1428 | 1429 | #[test] 1430 | fn deref() { 1431 | use std::string::String; 1432 | 1433 | fn is_str(_: &str) {} 1434 | let value: Either = Left(String::from("test")); 1435 | is_str(&value); 1436 | } 1437 | 1438 | #[test] 1439 | fn iter() { 1440 | let x = 3; 1441 | let mut iter = match x { 1442 | 3 => Left(0..10), 1443 | _ => Right(17..), 1444 | }; 1445 | 1446 | assert_eq!(iter.next(), Some(0)); 1447 | assert_eq!(iter.count(), 9); 1448 | } 1449 | 1450 | #[test] 1451 | fn seek() { 1452 | use std::io; 1453 | 1454 | let use_empty = false; 1455 | let mut mockdata = [0x00; 256]; 1456 | for (i, data) in mockdata.iter_mut().enumerate() { 1457 | *data = i as u8; 1458 | } 1459 | 1460 | let mut reader = if use_empty { 1461 | // Empty didn't impl Seek until Rust 1.51 1462 | Left(io::Cursor::new([])) 1463 | } else { 1464 | Right(io::Cursor::new(&mockdata[..])) 1465 | }; 1466 | 1467 | let mut buf = [0u8; 16]; 1468 | assert_eq!(reader.read(&mut buf).unwrap(), buf.len()); 1469 | assert_eq!(buf, mockdata[..buf.len()]); 1470 | 1471 | // the first read should advance the cursor and return the next 16 bytes thus the `ne` 1472 | assert_eq!(reader.read(&mut buf).unwrap(), buf.len()); 1473 | assert_ne!(buf, mockdata[..buf.len()]); 1474 | 1475 | // if the seek operation fails it should read 16..31 instead of 0..15 1476 | reader.seek(io::SeekFrom::Start(0)).unwrap(); 1477 | assert_eq!(reader.read(&mut buf).unwrap(), buf.len()); 1478 | assert_eq!(buf, mockdata[..buf.len()]); 1479 | } 1480 | 1481 | #[test] 1482 | fn read_write() { 1483 | use std::io; 1484 | 1485 | let use_stdio = false; 1486 | let mockdata = [0xff; 256]; 1487 | 1488 | let mut reader = if use_stdio { 1489 | Left(io::stdin()) 1490 | } else { 1491 | Right(&mockdata[..]) 1492 | }; 1493 | 1494 | let mut buf = [0u8; 16]; 1495 | assert_eq!(reader.read(&mut buf).unwrap(), buf.len()); 1496 | assert_eq!(&buf, &mockdata[..buf.len()]); 1497 | 1498 | let mut mockbuf = [0u8; 256]; 1499 | let mut writer = if use_stdio { 1500 | Left(io::stdout()) 1501 | } else { 1502 | Right(&mut mockbuf[..]) 1503 | }; 1504 | 1505 | let buf = [1u8; 16]; 1506 | assert_eq!(writer.write(&buf).unwrap(), buf.len()); 1507 | } 1508 | 1509 | #[test] 1510 | fn error() { 1511 | let invalid_utf8 = b"\xff"; 1512 | #[allow(invalid_from_utf8)] 1513 | let res = if let Err(error) = ::std::str::from_utf8(invalid_utf8) { 1514 | Err(Left(error)) 1515 | } else if let Err(error) = "x".parse::() { 1516 | Err(Right(error)) 1517 | } else { 1518 | Ok(()) 1519 | }; 1520 | assert!(res.is_err()); 1521 | #[allow(deprecated)] 1522 | res.unwrap_err().description(); // make sure this can be called 1523 | } 1524 | 1525 | /// A helper macro to check if AsRef and AsMut are implemented for a given type. 1526 | macro_rules! check_t { 1527 | ($t:ty) => {{ 1528 | fn check_ref>() {} 1529 | fn propagate_ref, T2: AsRef<$t>>() { 1530 | check_ref::>() 1531 | } 1532 | fn check_mut>() {} 1533 | fn propagate_mut, T2: AsMut<$t>>() { 1534 | check_mut::>() 1535 | } 1536 | }}; 1537 | } 1538 | 1539 | // This "unused" method is here to ensure that compilation doesn't fail on given types. 1540 | fn _unsized_ref_propagation() { 1541 | check_t!(str); 1542 | 1543 | fn check_array_ref, Item>() {} 1544 | fn check_array_mut, Item>() {} 1545 | 1546 | fn propagate_array_ref, T2: AsRef<[Item]>, Item>() { 1547 | check_array_ref::, _>() 1548 | } 1549 | 1550 | fn propagate_array_mut, T2: AsMut<[Item]>, Item>() { 1551 | check_array_mut::, _>() 1552 | } 1553 | } 1554 | 1555 | // This "unused" method is here to ensure that compilation doesn't fail on given types. 1556 | #[cfg(feature = "std")] 1557 | fn _unsized_std_propagation() { 1558 | check_t!(::std::path::Path); 1559 | check_t!(::std::ffi::OsStr); 1560 | check_t!(::std::ffi::CStr); 1561 | } 1562 | -------------------------------------------------------------------------------- /src/serde_untagged.rs: -------------------------------------------------------------------------------- 1 | //! Untagged serialization/deserialization support for Either. 2 | //! 3 | //! `Either` uses default, externally-tagged representation. 4 | //! However, sometimes it is useful to support several alternative types. 5 | //! For example, we may have a field which is generally Map 6 | //! but in typical cases Vec would suffice, too. 7 | //! 8 | //! ```rust 9 | //! # fn main() -> Result<(), Box> { 10 | //! use either::Either; 11 | //! use std::collections::HashMap; 12 | //! 13 | //! #[derive(serde::Serialize, serde::Deserialize, Debug)] 14 | //! #[serde(transparent)] 15 | //! struct IntOrString { 16 | //! #[serde(with = "either::serde_untagged")] 17 | //! inner: Either, HashMap> 18 | //! }; 19 | //! 20 | //! // serialization 21 | //! let data = IntOrString { 22 | //! inner: Either::Left(vec!["Hello".to_string()]) 23 | //! }; 24 | //! // notice: no tags are emitted. 25 | //! assert_eq!(serde_json::to_string(&data)?, r#"["Hello"]"#); 26 | //! 27 | //! // deserialization 28 | //! let data: IntOrString = serde_json::from_str( 29 | //! r#"{"a": 0, "b": 14}"# 30 | //! )?; 31 | //! println!("found {:?}", data); 32 | //! # Ok(()) 33 | //! # } 34 | //! ``` 35 | 36 | use serde::{Deserialize, Deserializer, Serialize, Serializer}; 37 | 38 | #[derive(serde::Serialize, serde::Deserialize)] 39 | #[serde(untagged)] 40 | enum Either { 41 | Left(L), 42 | Right(R), 43 | } 44 | 45 | pub fn serialize(this: &super::Either, serializer: S) -> Result 46 | where 47 | S: Serializer, 48 | L: Serialize, 49 | R: Serialize, 50 | { 51 | let untagged = match this { 52 | super::Either::Left(left) => Either::Left(left), 53 | super::Either::Right(right) => Either::Right(right), 54 | }; 55 | untagged.serialize(serializer) 56 | } 57 | 58 | pub fn deserialize<'de, L, R, D>(deserializer: D) -> Result, D::Error> 59 | where 60 | D: Deserializer<'de>, 61 | L: Deserialize<'de>, 62 | R: Deserialize<'de>, 63 | { 64 | match Either::deserialize(deserializer) { 65 | Ok(Either::Left(left)) => Ok(super::Either::Left(left)), 66 | Ok(Either::Right(right)) => Ok(super::Either::Right(right)), 67 | Err(error) => Err(error), 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/serde_untagged_optional.rs: -------------------------------------------------------------------------------- 1 | //! Untagged serialization/deserialization support for Option>. 2 | //! 3 | //! `Either` uses default, externally-tagged representation. 4 | //! However, sometimes it is useful to support several alternative types. 5 | //! For example, we may have a field which is generally Map 6 | //! but in typical cases Vec would suffice, too. 7 | //! 8 | //! ```rust 9 | //! # fn main() -> Result<(), Box> { 10 | //! use either::Either; 11 | //! use std::collections::HashMap; 12 | //! 13 | //! #[derive(serde::Serialize, serde::Deserialize, Debug)] 14 | //! #[serde(transparent)] 15 | //! struct IntOrString { 16 | //! #[serde(with = "either::serde_untagged_optional")] 17 | //! inner: Option, HashMap>> 18 | //! }; 19 | //! 20 | //! // serialization 21 | //! let data = IntOrString { 22 | //! inner: Some(Either::Left(vec!["Hello".to_string()])) 23 | //! }; 24 | //! // notice: no tags are emitted. 25 | //! assert_eq!(serde_json::to_string(&data)?, r#"["Hello"]"#); 26 | //! 27 | //! // deserialization 28 | //! let data: IntOrString = serde_json::from_str( 29 | //! r#"{"a": 0, "b": 14}"# 30 | //! )?; 31 | //! println!("found {:?}", data); 32 | //! # Ok(()) 33 | //! # } 34 | //! ``` 35 | 36 | use serde::{Deserialize, Deserializer, Serialize, Serializer}; 37 | 38 | #[derive(Serialize, Deserialize)] 39 | #[serde(untagged)] 40 | enum Either { 41 | Left(L), 42 | Right(R), 43 | } 44 | 45 | pub fn serialize( 46 | this: &Option>, 47 | serializer: S, 48 | ) -> Result 49 | where 50 | S: Serializer, 51 | L: Serialize, 52 | R: Serialize, 53 | { 54 | let untagged = match this { 55 | Some(super::Either::Left(left)) => Some(Either::Left(left)), 56 | Some(super::Either::Right(right)) => Some(Either::Right(right)), 57 | None => None, 58 | }; 59 | untagged.serialize(serializer) 60 | } 61 | 62 | pub fn deserialize<'de, L, R, D>(deserializer: D) -> Result>, D::Error> 63 | where 64 | D: Deserializer<'de>, 65 | L: Deserialize<'de>, 66 | R: Deserialize<'de>, 67 | { 68 | match Option::deserialize(deserializer) { 69 | Ok(Some(Either::Left(left))) => Ok(Some(super::Either::Left(left))), 70 | Ok(Some(Either::Right(right))) => Ok(Some(super::Either::Right(right))), 71 | Ok(None) => Ok(None), 72 | Err(error) => Err(error), 73 | } 74 | } 75 | --------------------------------------------------------------------------------