diff options
| author | mo khan <mo@mokhan.ca> | 2025-07-15 16:37:08 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2025-07-17 16:30:22 -0600 |
| commit | 45df4d0d9b577fecee798d672695fe24ff57fb1b (patch) | |
| tree | 1b99bf645035b58e0d6db08c7a83521f41f7a75b /vendor/either | |
| parent | f94f79608393d4ab127db63cc41668445ef6b243 (diff) | |
feat: migrate from Cedar to SpiceDB authorization system
This is a major architectural change that replaces the Cedar policy-based
authorization system with SpiceDB's relation-based authorization.
Key changes:
- Migrate from Rust to Go implementation
- Replace Cedar policies with SpiceDB schema and relationships
- Switch from envoy `ext_authz` with Cedar to SpiceDB permission checks
- Update build system and dependencies for Go ecosystem
- Maintain Envoy integration for external authorization
This change enables more flexible permission modeling through SpiceDB's
Google Zanzibar inspired relation-based system, supporting complex
hierarchical permissions that were difficult to express in Cedar.
Breaking change: Existing Cedar policies and Rust-based configuration
will no longer work and need to be migrated to SpiceDB schema.
Diffstat (limited to 'vendor/either')
| -rw-r--r-- | vendor/either/.cargo-checksum.json | 1 | ||||
| -rw-r--r-- | vendor/either/Cargo.lock | 96 | ||||
| -rw-r--r-- | vendor/either/Cargo.toml | 70 | ||||
| -rw-r--r-- | vendor/either/LICENSE-APACHE | 201 | ||||
| -rw-r--r-- | vendor/either/LICENSE-MIT | 25 | ||||
| -rw-r--r-- | vendor/either/README-crates.io.md | 10 | ||||
| -rw-r--r-- | vendor/either/README.rst | 204 | ||||
| -rw-r--r-- | vendor/either/src/into_either.rs | 64 | ||||
| -rw-r--r-- | vendor/either/src/iterator.rs | 315 | ||||
| -rw-r--r-- | vendor/either/src/lib.rs | 1561 | ||||
| -rw-r--r-- | vendor/either/src/serde_untagged.rs | 69 | ||||
| -rw-r--r-- | vendor/either/src/serde_untagged_optional.rs | 74 |
12 files changed, 0 insertions, 2690 deletions
diff --git a/vendor/either/.cargo-checksum.json b/vendor/either/.cargo-checksum.json deleted file mode 100644 index d06d97c3..00000000 --- a/vendor/either/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.lock":"fa51302ea4d0f21da8621d0376bc26e2ffc28754fef88a80fa8d48897cbef662","Cargo.toml":"e88e6acce3b0cbf6734ab7c41cbc01a6b368843eb29d57f06e3b917ec9af03e0","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"7576269ea71f767b99297934c0b2367532690f8c4badc695edf8e04ab6a1e545","README-crates.io.md":"b775991a01ab4a0a8de6169f597775319d9ce8178f5c74ccdc634f13a286b20c","README.rst":"fb08fabe5268b1f350bf8772c240c93190f7b88ae856dd09e77248e65881eebf","src/into_either.rs":"0477f226bbba78ef017de08b87d421d3cd99fbc95b90ba4e6e3e803e3d15254e","src/iterator.rs":"eef042c8fa7d2d2cb002ed81dedf8c124ec36252ae8bd0368039c788f686edd8","src/lib.rs":"430b3125aa77ab51bca768e6be8d4a2cbdb9932338f9e5d90803a0a2fe99b371","src/serde_untagged.rs":"e826ee0ab31616e49c3e3f3711c8441001ee424b3e7a8c4c466cfcc4f8a7701a","src/serde_untagged_optional.rs":"86265f09d0795428bb2ce013b070d1badf1e2210217844a9ff3f04b2795868ab"},"package":"48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"}
\ No newline at end of file diff --git a/vendor/either/Cargo.lock b/vendor/either/Cargo.lock deleted file mode 100644 index 3c336a9a..00000000 --- a/vendor/either/Cargo.lock +++ /dev/null @@ -1,96 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "either" -version = "1.15.0" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "itoa" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" - -[[package]] -name = "memchr" -version = "2.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" - -[[package]] -name = "proc-macro2" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.39" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1f1914ce909e1658d9907913b4b91947430c7d9be598b15a1912935b8c04801" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "ryu" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" - -[[package]] -name = "serde" -version = "1.0.218" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8dfc9d19bdbf6d17e22319da49161d5d0108e4188e8b680aef6299eed22df60" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.218" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f09503e191f4e797cb8aac08e9a4a4695c5edf6a2e70e376d961ddd5c969f82b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.140" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" -dependencies = [ - "itoa", - "memchr", - "ryu", - "serde", -] - -[[package]] -name = "syn" -version = "2.0.99" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e02e925281e18ffd9d640e234264753c43edc62d64b2d4cf898f1bc5e75f3fc2" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "unicode-ident" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" diff --git a/vendor/either/Cargo.toml b/vendor/either/Cargo.toml deleted file mode 100644 index 68b38fd8..00000000 --- a/vendor/either/Cargo.toml +++ /dev/null @@ -1,70 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies. -# -# If you are reading this file be aware that the original Cargo.toml -# will likely look very different (and much more reasonable). -# See Cargo.toml.orig for the original contents. - -[package] -edition = "2021" -rust-version = "1.63.0" -name = "either" -version = "1.15.0" -authors = ["bluss"] -build = false -autolib = false -autobins = false -autoexamples = false -autotests = false -autobenches = false -description = """ -The enum `Either` with variants `Left` and `Right` is a general purpose sum type with two cases. -""" -documentation = "https://docs.rs/either/1/" -readme = "README-crates.io.md" -keywords = [ - "data-structure", - "no_std", -] -categories = [ - "data-structures", - "no-std", -] -license = "MIT OR Apache-2.0" -repository = "https://github.com/rayon-rs/either" - -[package.metadata.docs.rs] -features = ["serde"] - -[package.metadata.playground] -features = ["serde"] - -[package.metadata.release] -allow-branch = ["main"] -sign-tag = true -tag-name = "{{version}}" - -[features] -default = ["std"] -std = [] -use_std = ["std"] - -[lib] -name = "either" -path = "src/lib.rs" - -[dependencies.serde] -version = "1.0.95" -features = [ - "alloc", - "derive", -] -optional = true -default-features = false - -[dev-dependencies.serde_json] -version = "1.0.0" diff --git a/vendor/either/LICENSE-APACHE b/vendor/either/LICENSE-APACHE deleted file mode 100644 index 16fe87b0..00000000 --- a/vendor/either/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/either/LICENSE-MIT b/vendor/either/LICENSE-MIT deleted file mode 100644 index 9203baa0..00000000 --- a/vendor/either/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2015 - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/vendor/either/README-crates.io.md b/vendor/either/README-crates.io.md deleted file mode 100644 index d3689027..00000000 --- a/vendor/either/README-crates.io.md +++ /dev/null @@ -1,10 +0,0 @@ -The enum `Either` with variants `Left` and `Right` is a general purpose -sum type with two cases. - -Either has methods that are similar to Option and Result, and it also implements -traits like `Iterator`. - -Includes macros `try_left!()` and `try_right!()` to use for -short-circuiting logic, similar to how the `?` operator is used with `Result`. -Note that `Either` is general purpose. For describing success or error, use the -regular `Result`. diff --git a/vendor/either/README.rst b/vendor/either/README.rst deleted file mode 100644 index 7665f1ff..00000000 --- a/vendor/either/README.rst +++ /dev/null @@ -1,204 +0,0 @@ - -Either -====== - -The enum ``Either`` with variants ``Left`` and ``Right`` and trait -implementations including Iterator, Read, Write. - -Either has methods that are similar to Option and Result. - -Includes convenience macros ``try_left!()`` and ``try_right!()`` to use for -short-circuiting logic. - -Please read the `API documentation here`__ - -__ https://docs.rs/either/ - -|build_status|_ |crates|_ - -.. |build_status| image:: https://github.com/rayon-rs/either/workflows/CI/badge.svg?branch=main -.. _build_status: https://github.com/rayon-rs/either/actions - -.. |crates| image:: https://img.shields.io/crates/v/either.svg -.. _crates: https://crates.io/crates/either - -How to use with cargo:: - - [dependencies] - either = "1" - - -Recent Changes --------------- - -- 1.15.0 - - - Fix ``serde`` support when building without ``std``, by @klkvr (#119) - - - Use a more common ``std`` feature for default enablement, deprecating - the ``use_std`` feature as a mere alias of the new name. - -- 1.14.0 - - - **MSRV**: ``either`` now requires Rust 1.63 or later. - - - Implement ``fmt::Write`` for ``Either``, by @yotamofek (#113) - - - Replace ``Into<Result> for Either`` with ``From<Either> for Result``, by @cuviper (#118) - -- 1.13.0 - - - Add new methods ``.cloned()`` and ``.copied()``, by @ColonelThirtyTwo (#107) - -- 1.12.0 - - - **MSRV**: ``either`` now requires Rust 1.37 or later. - - - Specialize ``nth_back`` for ``Either`` and ``IterEither``, by @cuviper (#106) - -- 1.11.0 - - - Add new trait ``IntoEither`` that is useful to convert to ``Either`` in method chains, - by @SFM61319 (#101) - -- 1.10.0 - - - Add new methods ``.factor_iter()``, ``.factor_iter_mut()``, and ``.factor_into_iter()`` - that return ``Either`` items, plus ``.iter()`` and ``.iter_mut()`` to convert to direct - reference iterators; by @aj-bagwell and @cuviper (#91) - -- 1.9.0 - - - Add new methods ``.map_either()`` and ``.map_either_with()``, by @nasadorian (#82) - -- 1.8.1 - - - Clarified that the multiple licenses are combined with OR. - -- 1.8.0 - - - **MSRV**: ``either`` now requires Rust 1.36 or later. - - - Add new methods ``.as_pin_ref()`` and ``.as_pin_mut()`` to project a - pinned ``Either`` as inner ``Pin`` variants, by @cuviper (#77) - - - Implement the ``Future`` trait, by @cuviper (#77) - - - Specialize more methods of the ``io`` traits, by @Kixunil and @cuviper (#75) - -- 1.7.0 - - - **MSRV**: ``either`` now requires Rust 1.31 or later. - - - Export the macro ``for_both!``, by @thomaseizinger (#58) - - - Implement the ``io::Seek`` trait, by @Kerollmops (#60) - - - Add new method ``.either_into()`` for ``Into`` conversion, by @TonalidadeHidrica (#63) - - - Add new methods ``.factor_ok()``, ``.factor_err()``, and ``.factor_none()``, - by @zachs18 (#67) - - - Specialize ``source`` in the ``Error`` implementation, by @thomaseizinger (#69) - - - Specialize more iterator methods and implement the ``FusedIterator`` trait, - by @Ten0 (#66) and @cuviper (#71) - - - Specialize ``Clone::clone_from``, by @cuviper (#72) - -- 1.6.1 - - - Add new methods ``.expect_left()``, ``.unwrap_left()``, - and equivalents on the right, by @spenserblack (#51) - -- 1.6.0 - - - Add new modules ``serde_untagged`` and ``serde_untagged_optional`` to customize - how ``Either`` fields are serialized in other types, by @MikailBag (#49) - -- 1.5.3 - - - Add new method ``.map()`` for ``Either<T, T>`` by @nvzqz (#40). - -- 1.5.2 - - - Add new methods ``.left_or()``, ``.left_or_default()``, ``.left_or_else()``, - and equivalents on the right, by @DCjanus (#36) - -- 1.5.1 - - - Add ``AsRef`` and ``AsMut`` implementations for common unsized types: - ``str``, ``[T]``, ``CStr``, ``OsStr``, and ``Path``, by @mexus (#29) - -- 1.5.0 - - - Add new methods ``.factor_first()``, ``.factor_second()`` and ``.into_inner()`` - by @mathstuf (#19) - -- 1.4.0 - - - Add inherent method ``.into_iter()`` by @cuviper (#12) - -- 1.3.0 - - - Add opt-in serde support by @hcpl - -- 1.2.0 - - - Add method ``.either_with()`` by @Twey (#13) - -- 1.1.0 - - - Add methods ``left_and_then``, ``right_and_then`` by @rampantmonkey - - Include license files in the repository and released crate - -- 1.0.3 - - - Add crate categories - -- 1.0.2 - - - Forward more ``Iterator`` methods - - Implement ``Extend`` for ``Either<L, R>`` if ``L, R`` do. - -- 1.0.1 - - - Fix ``Iterator`` impl for ``Either`` to forward ``.fold()``. - -- 1.0.0 - - - Add default crate feature ``use_std`` so that you can opt out of linking to - std. - -- 0.1.7 - - - Add methods ``.map_left()``, ``.map_right()`` and ``.either()``. - - Add more documentation - -- 0.1.3 - - - Implement Display, Error - -- 0.1.2 - - - Add macros ``try_left!`` and ``try_right!``. - -- 0.1.1 - - - Implement Deref, DerefMut - -- 0.1.0 - - - Initial release - - Support Iterator, Read, Write - -License -------- - -Dual-licensed to be compatible with the Rust project. - -Licensed under the Apache License, Version 2.0 -https://www.apache.org/licenses/LICENSE-2.0 or the MIT license -https://opensource.org/licenses/MIT, at your -option. This file may not be copied, modified, or distributed -except according to those terms. diff --git a/vendor/either/src/into_either.rs b/vendor/either/src/into_either.rs deleted file mode 100644 index 73746c80..00000000 --- a/vendor/either/src/into_either.rs +++ /dev/null @@ -1,64 +0,0 @@ -//! The trait [`IntoEither`] provides methods for converting a type `Self`, whose -//! size is constant and known at compile-time, into an [`Either`] variant. - -use super::{Either, Left, Right}; - -/// Provides methods for converting a type `Self` into either a [`Left`] or [`Right`] -/// variant of [`Either<Self, Self>`](Either). -/// -/// The [`into_either`](IntoEither::into_either) method takes a [`bool`] to determine -/// whether to convert to [`Left`] or [`Right`]. -/// -/// The [`into_either_with`](IntoEither::into_either_with) method takes a -/// [predicate function](FnOnce) to determine whether to convert to [`Left`] or [`Right`]. -pub trait IntoEither: Sized { - /// Converts `self` into a [`Left`] variant of [`Either<Self, Self>`](Either) - /// if `into_left` is `true`. - /// Converts `self` into a [`Right`] variant of [`Either<Self, Self>`](Either) - /// otherwise. - /// - /// # Examples - /// - /// ``` - /// use either::{IntoEither, Left, Right}; - /// - /// let x = 0; - /// assert_eq!(x.into_either(true), Left(x)); - /// assert_eq!(x.into_either(false), Right(x)); - /// ``` - fn into_either(self, into_left: bool) -> Either<Self, Self> { - if into_left { - Left(self) - } else { - Right(self) - } - } - - /// Converts `self` into a [`Left`] variant of [`Either<Self, Self>`](Either) - /// if `into_left(&self)` returns `true`. - /// Converts `self` into a [`Right`] variant of [`Either<Self, Self>`](Either) - /// otherwise. - /// - /// # Examples - /// - /// ``` - /// use either::{IntoEither, Left, Right}; - /// - /// fn is_even(x: &u8) -> bool { - /// x % 2 == 0 - /// } - /// - /// let x = 0; - /// assert_eq!(x.into_either_with(is_even), Left(x)); - /// assert_eq!(x.into_either_with(|x| !is_even(x)), Right(x)); - /// ``` - fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> - where - F: FnOnce(&Self) -> bool, - { - let into_left = into_left(&self); - self.into_either(into_left) - } -} - -impl<T> IntoEither for T {} diff --git a/vendor/either/src/iterator.rs b/vendor/either/src/iterator.rs deleted file mode 100644 index d54fab79..00000000 --- a/vendor/either/src/iterator.rs +++ /dev/null @@ -1,315 +0,0 @@ -use super::{for_both, Either, Left, Right}; -use core::iter; - -macro_rules! wrap_either { - ($value:expr => $( $tail:tt )*) => { - match $value { - Left(inner) => inner.map(Left) $($tail)*, - Right(inner) => inner.map(Right) $($tail)*, - } - }; -} - -/// Iterator that maps left or right iterators to corresponding `Either`-wrapped items. -/// -/// This struct is created by the [`Either::factor_into_iter`], -/// [`factor_iter`][Either::factor_iter], -/// and [`factor_iter_mut`][Either::factor_iter_mut] methods. -#[derive(Clone, Debug)] -pub struct IterEither<L, R> { - inner: Either<L, R>, -} - -impl<L, R> IterEither<L, R> { - pub(crate) fn new(inner: Either<L, R>) -> Self { - IterEither { inner } - } -} - -impl<L, R, A> Extend<A> for Either<L, R> -where - L: Extend<A>, - R: Extend<A>, -{ - fn extend<T>(&mut self, iter: T) - where - T: IntoIterator<Item = A>, - { - for_both!(self, inner => inner.extend(iter)) - } -} - -/// `Either<L, R>` is an iterator if both `L` and `R` are iterators. -impl<L, R> Iterator for Either<L, R> -where - L: Iterator, - R: Iterator<Item = L::Item>, -{ - type Item = L::Item; - - fn next(&mut self) -> Option<Self::Item> { - for_both!(self, inner => inner.next()) - } - - fn size_hint(&self) -> (usize, Option<usize>) { - for_both!(self, inner => inner.size_hint()) - } - - fn fold<Acc, G>(self, init: Acc, f: G) -> Acc - where - G: FnMut(Acc, Self::Item) -> Acc, - { - for_both!(self, inner => inner.fold(init, f)) - } - - fn for_each<F>(self, f: F) - where - F: FnMut(Self::Item), - { - for_both!(self, inner => inner.for_each(f)) - } - - fn count(self) -> usize { - for_both!(self, inner => inner.count()) - } - - fn last(self) -> Option<Self::Item> { - for_both!(self, inner => inner.last()) - } - - fn nth(&mut self, n: usize) -> Option<Self::Item> { - for_both!(self, inner => inner.nth(n)) - } - - fn collect<B>(self) -> B - where - B: iter::FromIterator<Self::Item>, - { - for_both!(self, inner => inner.collect()) - } - - fn partition<B, F>(self, f: F) -> (B, B) - where - B: Default + Extend<Self::Item>, - F: FnMut(&Self::Item) -> bool, - { - for_both!(self, inner => inner.partition(f)) - } - - fn all<F>(&mut self, f: F) -> bool - where - F: FnMut(Self::Item) -> bool, - { - for_both!(self, inner => inner.all(f)) - } - - fn any<F>(&mut self, f: F) -> bool - where - F: FnMut(Self::Item) -> bool, - { - for_both!(self, inner => inner.any(f)) - } - - fn find<P>(&mut self, predicate: P) -> Option<Self::Item> - where - P: FnMut(&Self::Item) -> bool, - { - for_both!(self, inner => inner.find(predicate)) - } - - fn find_map<B, F>(&mut self, f: F) -> Option<B> - where - F: FnMut(Self::Item) -> Option<B>, - { - for_both!(self, inner => inner.find_map(f)) - } - - fn position<P>(&mut self, predicate: P) -> Option<usize> - where - P: FnMut(Self::Item) -> bool, - { - for_both!(self, inner => inner.position(predicate)) - } -} - -impl<L, R> DoubleEndedIterator for Either<L, R> -where - L: DoubleEndedIterator, - R: DoubleEndedIterator<Item = L::Item>, -{ - fn next_back(&mut self) -> Option<Self::Item> { - for_both!(self, inner => inner.next_back()) - } - - fn nth_back(&mut self, n: usize) -> Option<Self::Item> { - for_both!(self, inner => inner.nth_back(n)) - } - - fn rfold<Acc, G>(self, init: Acc, f: G) -> Acc - where - G: FnMut(Acc, Self::Item) -> Acc, - { - for_both!(self, inner => inner.rfold(init, f)) - } - - fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> - where - P: FnMut(&Self::Item) -> bool, - { - for_both!(self, inner => inner.rfind(predicate)) - } -} - -impl<L, R> ExactSizeIterator for Either<L, R> -where - L: ExactSizeIterator, - R: ExactSizeIterator<Item = L::Item>, -{ - fn len(&self) -> usize { - for_both!(self, inner => inner.len()) - } -} - -impl<L, R> iter::FusedIterator for Either<L, R> -where - L: iter::FusedIterator, - R: iter::FusedIterator<Item = L::Item>, -{ -} - -impl<L, R> Iterator for IterEither<L, R> -where - L: Iterator, - R: Iterator, -{ - type Item = Either<L::Item, R::Item>; - - fn next(&mut self) -> Option<Self::Item> { - Some(map_either!(self.inner, ref mut inner => inner.next()?)) - } - - fn size_hint(&self) -> (usize, Option<usize>) { - for_both!(self.inner, ref inner => inner.size_hint()) - } - - fn fold<Acc, G>(self, init: Acc, f: G) -> Acc - where - G: FnMut(Acc, Self::Item) -> Acc, - { - wrap_either!(self.inner => .fold(init, f)) - } - - fn for_each<F>(self, f: F) - where - F: FnMut(Self::Item), - { - wrap_either!(self.inner => .for_each(f)) - } - - fn count(self) -> usize { - for_both!(self.inner, inner => inner.count()) - } - - fn last(self) -> Option<Self::Item> { - Some(map_either!(self.inner, inner => inner.last()?)) - } - - fn nth(&mut self, n: usize) -> Option<Self::Item> { - Some(map_either!(self.inner, ref mut inner => inner.nth(n)?)) - } - - fn collect<B>(self) -> B - where - B: iter::FromIterator<Self::Item>, - { - wrap_either!(self.inner => .collect()) - } - - fn partition<B, F>(self, f: F) -> (B, B) - where - B: Default + Extend<Self::Item>, - F: FnMut(&Self::Item) -> bool, - { - wrap_either!(self.inner => .partition(f)) - } - - fn all<F>(&mut self, f: F) -> bool - where - F: FnMut(Self::Item) -> bool, - { - wrap_either!(&mut self.inner => .all(f)) - } - - fn any<F>(&mut self, f: F) -> bool - where - F: FnMut(Self::Item) -> bool, - { - wrap_either!(&mut self.inner => .any(f)) - } - - fn find<P>(&mut self, predicate: P) -> Option<Self::Item> - where - P: FnMut(&Self::Item) -> bool, - { - wrap_either!(&mut self.inner => .find(predicate)) - } - - fn find_map<B, F>(&mut self, f: F) -> Option<B> - where - F: FnMut(Self::Item) -> Option<B>, - { - wrap_either!(&mut self.inner => .find_map(f)) - } - - fn position<P>(&mut self, predicate: P) -> Option<usize> - where - P: FnMut(Self::Item) -> bool, - { - wrap_either!(&mut self.inner => .position(predicate)) - } -} - -impl<L, R> DoubleEndedIterator for IterEither<L, R> -where - L: DoubleEndedIterator, - R: DoubleEndedIterator, -{ - fn next_back(&mut self) -> Option<Self::Item> { - Some(map_either!(self.inner, ref mut inner => inner.next_back()?)) - } - - fn nth_back(&mut self, n: usize) -> Option<Self::Item> { - Some(map_either!(self.inner, ref mut inner => inner.nth_back(n)?)) - } - - fn rfold<Acc, G>(self, init: Acc, f: G) -> Acc - where - G: FnMut(Acc, Self::Item) -> Acc, - { - wrap_either!(self.inner => .rfold(init, f)) - } - - fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> - where - P: FnMut(&Self::Item) -> bool, - { - wrap_either!(&mut self.inner => .rfind(predicate)) - } -} - -impl<L, R> ExactSizeIterator for IterEither<L, R> -where - L: ExactSizeIterator, - R: ExactSizeIterator, -{ - fn len(&self) -> usize { - for_both!(self.inner, ref inner => inner.len()) - } -} - -impl<L, R> iter::FusedIterator for IterEither<L, R> -where - L: iter::FusedIterator, - R: iter::FusedIterator, -{ -} diff --git a/vendor/either/src/lib.rs b/vendor/either/src/lib.rs deleted file mode 100644 index e2265eb7..00000000 --- a/vendor/either/src/lib.rs +++ /dev/null @@ -1,1561 +0,0 @@ -//! The enum [`Either`] with variants `Left` and `Right` is a general purpose -//! sum type with two cases. -//! -//! [`Either`]: enum.Either.html -//! -//! **Crate features:** -//! -//! * `"std"` -//! Enabled by default. Disable to make the library `#![no_std]`. -//! -//! * `"serde"` -//! Disabled by default. Enable to `#[derive(Serialize, Deserialize)]` for `Either` -//! - -#![doc(html_root_url = "https://docs.rs/either/1/")] -#![no_std] - -#[cfg(any(test, feature = "std"))] -extern crate std; - -#[cfg(feature = "serde")] -pub mod serde_untagged; - -#[cfg(feature = "serde")] -pub mod serde_untagged_optional; - -use core::convert::{AsMut, AsRef}; -use core::fmt; -use core::future::Future; -use core::ops::Deref; -use core::ops::DerefMut; -use core::pin::Pin; - -#[cfg(any(test, feature = "std"))] -use std::error::Error; -#[cfg(any(test, feature = "std"))] -use std::io::{self, BufRead, Read, Seek, SeekFrom, Write}; - -pub use crate::Either::{Left, Right}; - -/// The enum `Either` with variants `Left` and `Right` is a general purpose -/// sum type with two cases. -/// -/// The `Either` type is symmetric and treats its variants the same way, without -/// preference. -/// (For representing success or error, use the regular `Result` enum instead.) -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -pub enum Either<L, R> { - /// A value of type `L`. - Left(L), - /// A value of type `R`. - Right(R), -} - -/// Evaluate the provided expression for both [`Either::Left`] and [`Either::Right`]. -/// -/// This macro is useful in cases where both sides of [`Either`] can be interacted with -/// in the same way even though the don't share the same type. -/// -/// Syntax: `either::for_both!(` *expression* `,` *pattern* `=>` *expression* `)` -/// -/// # Example -/// -/// ``` -/// use either::Either; -/// -/// fn length(owned_or_borrowed: Either<String, &'static str>) -> usize { -/// either::for_both!(owned_or_borrowed, s => s.len()) -/// } -/// -/// fn main() { -/// let borrowed = Either::Right("Hello world!"); -/// let owned = Either::Left("Hello world!".to_owned()); -/// -/// assert_eq!(length(borrowed), 12); -/// assert_eq!(length(owned), 12); -/// } -/// ``` -#[macro_export] -macro_rules! for_both { - ($value:expr, $pattern:pat => $result:expr) => { - match $value { - $crate::Either::Left($pattern) => $result, - $crate::Either::Right($pattern) => $result, - } - }; -} - -/// Macro for unwrapping the left side of an [`Either`], which fails early -/// with the opposite side. Can only be used in functions that return -/// `Either` because of the early return of `Right` that it provides. -/// -/// See also [`try_right!`] for its dual, which applies the same just to the -/// right side. -/// -/// # Example -/// -/// ``` -/// use either::{Either, Left, Right}; -/// -/// fn twice(wrapper: Either<u32, &str>) -> Either<u32, &str> { -/// let value = either::try_left!(wrapper); -/// Left(value * 2) -/// } -/// -/// fn main() { -/// assert_eq!(twice(Left(2)), Left(4)); -/// assert_eq!(twice(Right("ups")), Right("ups")); -/// } -/// ``` -#[macro_export] -macro_rules! try_left { - ($expr:expr) => { - match $expr { - $crate::Left(val) => val, - $crate::Right(err) => return $crate::Right(::core::convert::From::from(err)), - } - }; -} - -/// Dual to [`try_left!`], see its documentation for more information. -#[macro_export] -macro_rules! try_right { - ($expr:expr) => { - match $expr { - $crate::Left(err) => return $crate::Left(::core::convert::From::from(err)), - $crate::Right(val) => val, - } - }; -} - -macro_rules! map_either { - ($value:expr, $pattern:pat => $result:expr) => { - match $value { - Left($pattern) => Left($result), - Right($pattern) => Right($result), - } - }; -} - -mod iterator; -pub use self::iterator::IterEither; - -mod into_either; -pub use self::into_either::IntoEither; - -impl<L: Clone, R: Clone> Clone for Either<L, R> { - fn clone(&self) -> Self { - match self { - Left(inner) => Left(inner.clone()), - Right(inner) => Right(inner.clone()), - } - } - - fn clone_from(&mut self, source: &Self) { - match (self, source) { - (Left(dest), Left(source)) => dest.clone_from(source), - (Right(dest), Right(source)) => dest.clone_from(source), - (dest, source) => *dest = source.clone(), - } - } -} - -impl<L, R> Either<L, R> { - /// Return true if the value is the `Left` variant. - /// - /// ``` - /// use either::*; - /// - /// let values = [Left(1), Right("the right value")]; - /// assert_eq!(values[0].is_left(), true); - /// assert_eq!(values[1].is_left(), false); - /// ``` - pub fn is_left(&self) -> bool { - match self { - Left(_) => true, - Right(_) => false, - } - } - - /// Return true if the value is the `Right` variant. - /// - /// ``` - /// use either::*; - /// - /// let values = [Left(1), Right("the right value")]; - /// assert_eq!(values[0].is_right(), false); - /// assert_eq!(values[1].is_right(), true); - /// ``` - pub fn is_right(&self) -> bool { - !self.is_left() - } - - /// Convert the left side of `Either<L, R>` to an `Option<L>`. - /// - /// ``` - /// use either::*; - /// - /// let left: Either<_, ()> = Left("some value"); - /// assert_eq!(left.left(), Some("some value")); - /// - /// let right: Either<(), _> = Right(321); - /// assert_eq!(right.left(), None); - /// ``` - pub fn left(self) -> Option<L> { - match self { - Left(l) => Some(l), - Right(_) => None, - } - } - - /// Convert the right side of `Either<L, R>` to an `Option<R>`. - /// - /// ``` - /// use either::*; - /// - /// let left: Either<_, ()> = Left("some value"); - /// assert_eq!(left.right(), None); - /// - /// let right: Either<(), _> = Right(321); - /// assert_eq!(right.right(), Some(321)); - /// ``` - pub fn right(self) -> Option<R> { - match self { - Left(_) => None, - Right(r) => Some(r), - } - } - - /// Convert `&Either<L, R>` to `Either<&L, &R>`. - /// - /// ``` - /// use either::*; - /// - /// let left: Either<_, ()> = Left("some value"); - /// assert_eq!(left.as_ref(), Left(&"some value")); - /// - /// let right: Either<(), _> = Right("some value"); - /// assert_eq!(right.as_ref(), Right(&"some value")); - /// ``` - pub fn as_ref(&self) -> Either<&L, &R> { - map_either!(self, inner => inner) - } - - /// Convert `&mut Either<L, R>` to `Either<&mut L, &mut R>`. - /// - /// ``` - /// use either::*; - /// - /// fn mutate_left(value: &mut Either<u32, u32>) { - /// if let Some(l) = value.as_mut().left() { - /// *l = 999; - /// } - /// } - /// - /// let mut left = Left(123); - /// let mut right = Right(123); - /// mutate_left(&mut left); - /// mutate_left(&mut right); - /// assert_eq!(left, Left(999)); - /// assert_eq!(right, Right(123)); - /// ``` - pub fn as_mut(&mut self) -> Either<&mut L, &mut R> { - map_either!(self, inner => inner) - } - - /// Convert `Pin<&Either<L, R>>` to `Either<Pin<&L>, Pin<&R>>`, - /// pinned projections of the inner variants. - pub fn as_pin_ref(self: Pin<&Self>) -> Either<Pin<&L>, Pin<&R>> { - // SAFETY: We can use `new_unchecked` because the `inner` parts are - // guaranteed to be pinned, as they come from `self` which is pinned. - unsafe { map_either!(Pin::get_ref(self), inner => Pin::new_unchecked(inner)) } - } - - /// Convert `Pin<&mut Either<L, R>>` to `Either<Pin<&mut L>, Pin<&mut R>>`, - /// pinned projections of the inner variants. - pub fn as_pin_mut(self: Pin<&mut Self>) -> Either<Pin<&mut L>, Pin<&mut R>> { - // SAFETY: `get_unchecked_mut` is fine because we don't move anything. - // We can use `new_unchecked` because the `inner` parts are guaranteed - // to be pinned, as they come from `self` which is pinned, and we never - // offer an unpinned `&mut L` or `&mut R` through `Pin<&mut Self>`. We - // also don't have an implementation of `Drop`, nor manual `Unpin`. - unsafe { map_either!(Pin::get_unchecked_mut(self), inner => Pin::new_unchecked(inner)) } - } - - /// Convert `Either<L, R>` to `Either<R, L>`. - /// - /// ``` - /// use either::*; - /// - /// let left: Either<_, ()> = Left(123); - /// assert_eq!(left.flip(), Right(123)); - /// - /// let right: Either<(), _> = Right("some value"); - /// assert_eq!(right.flip(), Left("some value")); - /// ``` - pub fn flip(self) -> Either<R, L> { - match self { - Left(l) => Right(l), - Right(r) => Left(r), - } - } - - /// Apply the function `f` on the value in the `Left` variant if it is present rewrapping the - /// result in `Left`. - /// - /// ``` - /// use either::*; - /// - /// let left: Either<_, u32> = Left(123); - /// assert_eq!(left.map_left(|x| x * 2), Left(246)); - /// - /// let right: Either<u32, _> = Right(123); - /// assert_eq!(right.map_left(|x| x * 2), Right(123)); - /// ``` - pub fn map_left<F, M>(self, f: F) -> Either<M, R> - where - F: FnOnce(L) -> M, - { - match self { - Left(l) => Left(f(l)), - Right(r) => Right(r), - } - } - - /// Apply the function `f` on the value in the `Right` variant if it is present rewrapping the - /// result in `Right`. - /// - /// ``` - /// use either::*; - /// - /// let left: Either<_, u32> = Left(123); - /// assert_eq!(left.map_right(|x| x * 2), Left(123)); - /// - /// let right: Either<u32, _> = Right(123); - /// assert_eq!(right.map_right(|x| x * 2), Right(246)); - /// ``` - pub fn map_right<F, S>(self, f: F) -> Either<L, S> - where - F: FnOnce(R) -> S, - { - match self { - Left(l) => Left(l), - Right(r) => Right(f(r)), - } - } - - /// Apply the functions `f` and `g` to the `Left` and `Right` variants - /// respectively. This is equivalent to - /// [bimap](https://hackage.haskell.org/package/bifunctors-5/docs/Data-Bifunctor.html) - /// in functional programming. - /// - /// ``` - /// use either::*; - /// - /// let f = |s: String| s.len(); - /// let g = |u: u8| u.to_string(); - /// - /// let left: Either<String, u8> = Left("loopy".into()); - /// assert_eq!(left.map_either(f, g), Left(5)); - /// - /// let right: Either<String, u8> = Right(42); - /// assert_eq!(right.map_either(f, g), Right("42".into())); - /// ``` - pub fn map_either<F, G, M, S>(self, f: F, g: G) -> Either<M, S> - where - F: FnOnce(L) -> M, - G: FnOnce(R) -> S, - { - match self { - Left(l) => Left(f(l)), - Right(r) => Right(g(r)), - } - } - - /// Similar to [`map_either`][Self::map_either], with an added context `ctx` accessible to - /// both functions. - /// - /// ``` - /// use either::*; - /// - /// let mut sum = 0; - /// - /// // Both closures want to update the same value, so pass it as context. - /// let mut f = |sum: &mut usize, s: String| { *sum += s.len(); s.to_uppercase() }; - /// let mut g = |sum: &mut usize, u: usize| { *sum += u; u.to_string() }; - /// - /// let left: Either<String, usize> = Left("loopy".into()); - /// assert_eq!(left.map_either_with(&mut sum, &mut f, &mut g), Left("LOOPY".into())); - /// - /// let right: Either<String, usize> = Right(42); - /// assert_eq!(right.map_either_with(&mut sum, &mut f, &mut g), Right("42".into())); - /// - /// assert_eq!(sum, 47); - /// ``` - pub fn map_either_with<Ctx, F, G, M, S>(self, ctx: Ctx, f: F, g: G) -> Either<M, S> - where - F: FnOnce(Ctx, L) -> M, - G: FnOnce(Ctx, R) -> S, - { - match self { - Left(l) => Left(f(ctx, l)), - Right(r) => Right(g(ctx, r)), - } - } - - /// Apply one of two functions depending on contents, unifying their result. If the value is - /// `Left(L)` then the first function `f` is applied; if it is `Right(R)` then the second - /// function `g` is applied. - /// - /// ``` - /// use either::*; - /// - /// fn square(n: u32) -> i32 { (n * n) as i32 } - /// fn negate(n: i32) -> i32 { -n } - /// - /// let left: Either<u32, i32> = Left(4); - /// assert_eq!(left.either(square, negate), 16); - /// - /// let right: Either<u32, i32> = Right(-4); - /// assert_eq!(right.either(square, negate), 4); - /// ``` - pub fn either<F, G, T>(self, f: F, g: G) -> T - where - F: FnOnce(L) -> T, - G: FnOnce(R) -> T, - { - match self { - Left(l) => f(l), - Right(r) => g(r), - } - } - - /// Like [`either`][Self::either], but provide some context to whichever of the - /// functions ends up being called. - /// - /// ``` - /// // In this example, the context is a mutable reference - /// use either::*; - /// - /// let mut result = Vec::new(); - /// - /// let values = vec![Left(2), Right(2.7)]; - /// - /// for value in values { - /// value.either_with(&mut result, - /// |ctx, integer| ctx.push(integer), - /// |ctx, real| ctx.push(f64::round(real) as i32)); - /// } - /// - /// assert_eq!(result, vec![2, 3]); - /// ``` - pub fn either_with<Ctx, F, G, T>(self, ctx: Ctx, f: F, g: G) -> T - where - F: FnOnce(Ctx, L) -> T, - G: FnOnce(Ctx, R) -> T, - { - match self { - Left(l) => f(ctx, l), - Right(r) => g(ctx, r), - } - } - - /// Apply the function `f` on the value in the `Left` variant if it is present. - /// - /// ``` - /// use either::*; - /// - /// let left: Either<_, u32> = Left(123); - /// assert_eq!(left.left_and_then::<_,()>(|x| Right(x * 2)), Right(246)); - /// - /// let right: Either<u32, _> = Right(123); - /// assert_eq!(right.left_and_then(|x| Right::<(), _>(x * 2)), Right(123)); - /// ``` - pub fn left_and_then<F, S>(self, f: F) -> Either<S, R> - where - F: FnOnce(L) -> Either<S, R>, - { - match self { - Left(l) => f(l), - Right(r) => Right(r), - } - } - - /// Apply the function `f` on the value in the `Right` variant if it is present. - /// - /// ``` - /// use either::*; - /// - /// let left: Either<_, u32> = Left(123); - /// assert_eq!(left.right_and_then(|x| Right(x * 2)), Left(123)); - /// - /// let right: Either<u32, _> = Right(123); - /// assert_eq!(right.right_and_then(|x| Right(x * 2)), Right(246)); - /// ``` - pub fn right_and_then<F, S>(self, f: F) -> Either<L, S> - where - F: FnOnce(R) -> Either<L, S>, - { - match self { - Left(l) => Left(l), - Right(r) => f(r), - } - } - - /// Convert the inner value to an iterator. - /// - /// This requires the `Left` and `Right` iterators to have the same item type. - /// See [`factor_into_iter`][Either::factor_into_iter] to iterate different types. - /// - /// ``` - /// use either::*; - /// - /// let left: Either<_, Vec<u32>> = Left(vec![1, 2, 3, 4, 5]); - /// let mut right: Either<Vec<u32>, _> = Right(vec![]); - /// right.extend(left.into_iter()); - /// assert_eq!(right, Right(vec![1, 2, 3, 4, 5])); - /// ``` - #[allow(clippy::should_implement_trait)] - pub fn into_iter(self) -> Either<L::IntoIter, R::IntoIter> - where - L: IntoIterator, - R: IntoIterator<Item = L::Item>, - { - map_either!(self, inner => inner.into_iter()) - } - - /// Borrow the inner value as an iterator. - /// - /// This requires the `Left` and `Right` iterators to have the same item type. - /// See [`factor_iter`][Either::factor_iter] to iterate different types. - /// - /// ``` - /// use either::*; - /// - /// let left: Either<_, &[u32]> = Left(vec![2, 3]); - /// let mut right: Either<Vec<u32>, _> = Right(&[4, 5][..]); - /// let mut all = vec![1]; - /// all.extend(left.iter()); - /// all.extend(right.iter()); - /// assert_eq!(all, vec![1, 2, 3, 4, 5]); - /// ``` - pub fn iter(&self) -> Either<<&L as IntoIterator>::IntoIter, <&R as IntoIterator>::IntoIter> - where - for<'a> &'a L: IntoIterator, - for<'a> &'a R: IntoIterator<Item = <&'a L as IntoIterator>::Item>, - { - map_either!(self, inner => inner.into_iter()) - } - - /// Mutably borrow the inner value as an iterator. - /// - /// This requires the `Left` and `Right` iterators to have the same item type. - /// See [`factor_iter_mut`][Either::factor_iter_mut] to iterate different types. - /// - /// ``` - /// use either::*; - /// - /// let mut left: Either<_, &mut [u32]> = Left(vec![2, 3]); - /// for l in left.iter_mut() { - /// *l *= *l - /// } - /// assert_eq!(left, Left(vec![4, 9])); - /// - /// let mut inner = [4, 5]; - /// let mut right: Either<Vec<u32>, _> = Right(&mut inner[..]); - /// for r in right.iter_mut() { - /// *r *= *r - /// } - /// assert_eq!(inner, [16, 25]); - /// ``` - pub fn iter_mut( - &mut self, - ) -> Either<<&mut L as IntoIterator>::IntoIter, <&mut R as IntoIterator>::IntoIter> - where - for<'a> &'a mut L: IntoIterator, - for<'a> &'a mut R: IntoIterator<Item = <&'a mut L as IntoIterator>::Item>, - { - map_either!(self, inner => inner.into_iter()) - } - - /// Converts an `Either` of `Iterator`s to be an `Iterator` of `Either`s - /// - /// Unlike [`into_iter`][Either::into_iter], this does not require the - /// `Left` and `Right` iterators to have the same item type. - /// - /// ``` - /// use either::*; - /// let left: Either<_, Vec<u8>> = Left(&["hello"]); - /// assert_eq!(left.factor_into_iter().next(), Some(Left(&"hello"))); - /// - /// let right: Either<&[&str], _> = Right(vec![0, 1]); - /// assert_eq!(right.factor_into_iter().collect::<Vec<_>>(), vec![Right(0), Right(1)]); - /// - /// ``` - // TODO(MSRV): doc(alias) was stabilized in Rust 1.48 - // #[doc(alias = "transpose")] - pub fn factor_into_iter(self) -> IterEither<L::IntoIter, R::IntoIter> - where - L: IntoIterator, - R: IntoIterator, - { - IterEither::new(map_either!(self, inner => inner.into_iter())) - } - - /// Borrows an `Either` of `Iterator`s to be an `Iterator` of `Either`s - /// - /// Unlike [`iter`][Either::iter], this does not require the - /// `Left` and `Right` iterators to have the same item type. - /// - /// ``` - /// use either::*; - /// let left: Either<_, Vec<u8>> = Left(["hello"]); - /// assert_eq!(left.factor_iter().next(), Some(Left(&"hello"))); - /// - /// let right: Either<[&str; 2], _> = Right(vec![0, 1]); - /// assert_eq!(right.factor_iter().collect::<Vec<_>>(), vec![Right(&0), Right(&1)]); - /// - /// ``` - pub fn factor_iter( - &self, - ) -> IterEither<<&L as IntoIterator>::IntoIter, <&R as IntoIterator>::IntoIter> - where - for<'a> &'a L: IntoIterator, - for<'a> &'a R: IntoIterator, - { - IterEither::new(map_either!(self, inner => inner.into_iter())) - } - - /// Mutably borrows an `Either` of `Iterator`s to be an `Iterator` of `Either`s - /// - /// Unlike [`iter_mut`][Either::iter_mut], this does not require the - /// `Left` and `Right` iterators to have the same item type. - /// - /// ``` - /// use either::*; - /// let mut left: Either<_, Vec<u8>> = Left(["hello"]); - /// left.factor_iter_mut().for_each(|x| *x.unwrap_left() = "goodbye"); - /// assert_eq!(left, Left(["goodbye"])); - /// - /// let mut right: Either<[&str; 2], _> = Right(vec![0, 1, 2]); - /// right.factor_iter_mut().for_each(|x| if let Right(r) = x { *r = -*r; }); - /// assert_eq!(right, Right(vec![0, -1, -2])); - /// - /// ``` - pub fn factor_iter_mut( - &mut self, - ) -> IterEither<<&mut L as IntoIterator>::IntoIter, <&mut R as IntoIterator>::IntoIter> - where - for<'a> &'a mut L: IntoIterator, - for<'a> &'a mut R: IntoIterator, - { - IterEither::new(map_either!(self, inner => inner.into_iter())) - } - - /// Return left value or given value - /// - /// Arguments passed to `left_or` are eagerly evaluated; if you are passing - /// the result of a function call, it is recommended to use - /// [`left_or_else`][Self::left_or_else], which is lazily evaluated. - /// - /// # Examples - /// - /// ``` - /// # use either::*; - /// let left: Either<&str, &str> = Left("left"); - /// assert_eq!(left.left_or("foo"), "left"); - /// - /// let right: Either<&str, &str> = Right("right"); - /// assert_eq!(right.left_or("left"), "left"); - /// ``` - pub fn left_or(self, other: L) -> L { - match self { - Either::Left(l) => l, - Either::Right(_) => other, - } - } - - /// Return left or a default - /// - /// # Examples - /// - /// ``` - /// # use either::*; - /// let left: Either<String, u32> = Left("left".to_string()); - /// assert_eq!(left.left_or_default(), "left"); - /// - /// let right: Either<String, u32> = Right(42); - /// assert_eq!(right.left_or_default(), String::default()); - /// ``` - pub fn left_or_default(self) -> L - where - L: Default, - { - match self { - Either::Left(l) => l, - Either::Right(_) => L::default(), - } - } - - /// Returns left value or computes it from a closure - /// - /// # Examples - /// - /// ``` - /// # use either::*; - /// let left: Either<String, u32> = Left("3".to_string()); - /// assert_eq!(left.left_or_else(|_| unreachable!()), "3"); - /// - /// let right: Either<String, u32> = Right(3); - /// assert_eq!(right.left_or_else(|x| x.to_string()), "3"); - /// ``` - pub fn left_or_else<F>(self, f: F) -> L - where - F: FnOnce(R) -> L, - { - match self { - Either::Left(l) => l, - Either::Right(r) => f(r), - } - } - - /// Return right value or given value - /// - /// Arguments passed to `right_or` are eagerly evaluated; if you are passing - /// the result of a function call, it is recommended to use - /// [`right_or_else`][Self::right_or_else], which is lazily evaluated. - /// - /// # Examples - /// - /// ``` - /// # use either::*; - /// let right: Either<&str, &str> = Right("right"); - /// assert_eq!(right.right_or("foo"), "right"); - /// - /// let left: Either<&str, &str> = Left("left"); - /// assert_eq!(left.right_or("right"), "right"); - /// ``` - pub fn right_or(self, other: R) -> R { - match self { - Either::Left(_) => other, - Either::Right(r) => r, - } - } - - /// Return right or a default - /// - /// # Examples - /// - /// ``` - /// # use either::*; - /// let left: Either<String, u32> = Left("left".to_string()); - /// assert_eq!(left.right_or_default(), u32::default()); - /// - /// let right: Either<String, u32> = Right(42); - /// assert_eq!(right.right_or_default(), 42); - /// ``` - pub fn right_or_default(self) -> R - where - R: Default, - { - match self { - Either::Left(_) => R::default(), - Either::Right(r) => r, - } - } - - /// Returns right value or computes it from a closure - /// - /// # Examples - /// - /// ``` - /// # use either::*; - /// let left: Either<String, u32> = Left("3".to_string()); - /// assert_eq!(left.right_or_else(|x| x.parse().unwrap()), 3); - /// - /// let right: Either<String, u32> = Right(3); - /// assert_eq!(right.right_or_else(|_| unreachable!()), 3); - /// ``` - pub fn right_or_else<F>(self, f: F) -> R - where - F: FnOnce(L) -> R, - { - match self { - Either::Left(l) => f(l), - Either::Right(r) => r, - } - } - - /// Returns the left value - /// - /// # Examples - /// - /// ``` - /// # use either::*; - /// let left: Either<_, ()> = Left(3); - /// assert_eq!(left.unwrap_left(), 3); - /// ``` - /// - /// # Panics - /// - /// When `Either` is a `Right` value - /// - /// ```should_panic - /// # use either::*; - /// let right: Either<(), _> = Right(3); - /// right.unwrap_left(); - /// ``` - pub fn unwrap_left(self) -> L - where - R: core::fmt::Debug, - { - match self { - Either::Left(l) => l, - Either::Right(r) => { - panic!("called `Either::unwrap_left()` on a `Right` value: {:?}", r) - } - } - } - - /// Returns the right value - /// - /// # Examples - /// - /// ``` - /// # use either::*; - /// let right: Either<(), _> = Right(3); - /// assert_eq!(right.unwrap_right(), 3); - /// ``` - /// - /// # Panics - /// - /// When `Either` is a `Left` value - /// - /// ```should_panic - /// # use either::*; - /// let left: Either<_, ()> = Left(3); - /// left.unwrap_right(); - /// ``` - pub fn unwrap_right(self) -> R - where - L: core::fmt::Debug, - { - match self { - Either::Right(r) => r, - Either::Left(l) => panic!("called `Either::unwrap_right()` on a `Left` value: {:?}", l), - } - } - - /// Returns the left value - /// - /// # Examples - /// - /// ``` - /// # use either::*; - /// let left: Either<_, ()> = Left(3); - /// assert_eq!(left.expect_left("value was Right"), 3); - /// ``` - /// - /// # Panics - /// - /// When `Either` is a `Right` value - /// - /// ```should_panic - /// # use either::*; - /// let right: Either<(), _> = Right(3); - /// right.expect_left("value was Right"); - /// ``` - pub fn expect_left(self, msg: &str) -> L - where - R: core::fmt::Debug, - { - match self { - Either::Left(l) => l, - Either::Right(r) => panic!("{}: {:?}", msg, r), - } - } - - /// Returns the right value - /// - /// # Examples - /// - /// ``` - /// # use either::*; - /// let right: Either<(), _> = Right(3); - /// assert_eq!(right.expect_right("value was Left"), 3); - /// ``` - /// - /// # Panics - /// - /// When `Either` is a `Left` value - /// - /// ```should_panic - /// # use either::*; - /// let left: Either<_, ()> = Left(3); - /// left.expect_right("value was Right"); - /// ``` - pub fn expect_right(self, msg: &str) -> R - where - L: core::fmt::Debug, - { - match self { - Either::Right(r) => r, - Either::Left(l) => panic!("{}: {:?}", msg, l), - } - } - - /// Convert the contained value into `T` - /// - /// # Examples - /// - /// ``` - /// # use either::*; - /// // Both u16 and u32 can be converted to u64. - /// let left: Either<u16, u32> = Left(3u16); - /// assert_eq!(left.either_into::<u64>(), 3u64); - /// let right: Either<u16, u32> = Right(7u32); - /// assert_eq!(right.either_into::<u64>(), 7u64); - /// ``` - pub fn either_into<T>(self) -> T - where - L: Into<T>, - R: Into<T>, - { - for_both!(self, inner => inner.into()) - } -} - -impl<L, R> Either<Option<L>, Option<R>> { - /// Factors out `None` from an `Either` of [`Option`]. - /// - /// ``` - /// use either::*; - /// let left: Either<_, Option<String>> = Left(Some(vec![0])); - /// assert_eq!(left.factor_none(), Some(Left(vec![0]))); - /// - /// let right: Either<Option<Vec<u8>>, _> = Right(Some(String::new())); - /// assert_eq!(right.factor_none(), Some(Right(String::new()))); - /// ``` - // TODO(MSRV): doc(alias) was stabilized in Rust 1.48 - // #[doc(alias = "transpose")] - pub fn factor_none(self) -> Option<Either<L, R>> { - match self { - Left(l) => l.map(Either::Left), - Right(r) => r.map(Either::Right), - } - } -} - -impl<L, R, E> Either<Result<L, E>, Result<R, E>> { - /// Factors out a homogenous type from an `Either` of [`Result`]. - /// - /// Here, the homogeneous type is the `Err` type of the [`Result`]. - /// - /// ``` - /// use either::*; - /// let left: Either<_, Result<String, u32>> = Left(Ok(vec![0])); - /// assert_eq!(left.factor_err(), Ok(Left(vec![0]))); - /// - /// let right: Either<Result<Vec<u8>, u32>, _> = Right(Ok(String::new())); - /// assert_eq!(right.factor_err(), Ok(Right(String::new()))); - /// ``` - // TODO(MSRV): doc(alias) was stabilized in Rust 1.48 - // #[doc(alias = "transpose")] - pub fn factor_err(self) -> Result<Either<L, R>, E> { - match self { - Left(l) => l.map(Either::Left), - Right(r) => r.map(Either::Right), - } - } -} - -impl<T, L, R> Either<Result<T, L>, Result<T, R>> { - /// Factors out a homogenous type from an `Either` of [`Result`]. - /// - /// Here, the homogeneous type is the `Ok` type of the [`Result`]. - /// - /// ``` - /// use either::*; - /// let left: Either<_, Result<u32, String>> = Left(Err(vec![0])); - /// assert_eq!(left.factor_ok(), Err(Left(vec![0]))); - /// - /// let right: Either<Result<u32, Vec<u8>>, _> = Right(Err(String::new())); - /// assert_eq!(right.factor_ok(), Err(Right(String::new()))); - /// ``` - // TODO(MSRV): doc(alias) was stabilized in Rust 1.48 - // #[doc(alias = "transpose")] - pub fn factor_ok(self) -> Result<T, Either<L, R>> { - match self { - Left(l) => l.map_err(Either::Left), - Right(r) => r.map_err(Either::Right), - } - } -} - -impl<T, L, R> Either<(T, L), (T, R)> { - /// Factor out a homogeneous type from an either of pairs. - /// - /// Here, the homogeneous type is the first element of the pairs. - /// - /// ``` - /// use either::*; - /// let left: Either<_, (u32, String)> = Left((123, vec![0])); - /// assert_eq!(left.factor_first().0, 123); - /// - /// let right: Either<(u32, Vec<u8>), _> = Right((123, String::new())); - /// assert_eq!(right.factor_first().0, 123); - /// ``` - pub fn factor_first(self) -> (T, Either<L, R>) { - match self { - Left((t, l)) => (t, Left(l)), - Right((t, r)) => (t, Right(r)), - } - } -} - -impl<T, L, R> Either<(L, T), (R, T)> { - /// Factor out a homogeneous type from an either of pairs. - /// - /// Here, the homogeneous type is the second element of the pairs. - /// - /// ``` - /// use either::*; - /// let left: Either<_, (String, u32)> = Left((vec![0], 123)); - /// assert_eq!(left.factor_second().1, 123); - /// - /// let right: Either<(Vec<u8>, u32), _> = Right((String::new(), 123)); - /// assert_eq!(right.factor_second().1, 123); - /// ``` - pub fn factor_second(self) -> (Either<L, R>, T) { - match self { - Left((l, t)) => (Left(l), t), - Right((r, t)) => (Right(r), t), - } - } -} - -impl<T> Either<T, T> { - /// Extract the value of an either over two equivalent types. - /// - /// ``` - /// use either::*; - /// - /// let left: Either<_, u32> = Left(123); - /// assert_eq!(left.into_inner(), 123); - /// - /// let right: Either<u32, _> = Right(123); - /// assert_eq!(right.into_inner(), 123); - /// ``` - pub fn into_inner(self) -> T { - for_both!(self, inner => inner) - } - - /// Map `f` over the contained value and return the result in the - /// corresponding variant. - /// - /// ``` - /// use either::*; - /// - /// let value: Either<_, i32> = Right(42); - /// - /// let other = value.map(|x| x * 2); - /// assert_eq!(other, Right(84)); - /// ``` - pub fn map<F, M>(self, f: F) -> Either<M, M> - where - F: FnOnce(T) -> M, - { - match self { - Left(l) => Left(f(l)), - Right(r) => Right(f(r)), - } - } -} - -impl<L, R> Either<&L, &R> { - /// Maps an `Either<&L, &R>` to an `Either<L, R>` by cloning the contents of - /// either branch. - pub fn cloned(self) -> Either<L, R> - where - L: Clone, - R: Clone, - { - map_either!(self, inner => inner.clone()) - } - - /// Maps an `Either<&L, &R>` to an `Either<L, R>` by copying the contents of - /// either branch. - pub fn copied(self) -> Either<L, R> - where - L: Copy, - R: Copy, - { - map_either!(self, inner => *inner) - } -} - -impl<L, R> Either<&mut L, &mut R> { - /// Maps an `Either<&mut L, &mut R>` to an `Either<L, R>` by cloning the contents of - /// either branch. - pub fn cloned(self) -> Either<L, R> - where - L: Clone, - R: Clone, - { - map_either!(self, inner => inner.clone()) - } - - /// Maps an `Either<&mut L, &mut R>` to an `Either<L, R>` by copying the contents of - /// either branch. - pub fn copied(self) -> Either<L, R> - where - L: Copy, - R: Copy, - { - map_either!(self, inner => *inner) - } -} - -/// Convert from `Result` to `Either` with `Ok => Right` and `Err => Left`. -impl<L, R> From<Result<R, L>> for Either<L, R> { - fn from(r: Result<R, L>) -> Self { - match r { - Err(e) => Left(e), - Ok(o) => Right(o), - } - } -} - -/// Convert from `Either` to `Result` with `Right => Ok` and `Left => Err`. -impl<L, R> From<Either<L, R>> for Result<R, L> { - fn from(val: Either<L, R>) -> Self { - match val { - Left(l) => Err(l), - Right(r) => Ok(r), - } - } -} - -/// `Either<L, R>` is a future if both `L` and `R` are futures. -impl<L, R> Future for Either<L, R> -where - L: Future, - R: Future<Output = L::Output>, -{ - type Output = L::Output; - - fn poll( - self: Pin<&mut Self>, - cx: &mut core::task::Context<'_>, - ) -> core::task::Poll<Self::Output> { - for_both!(self.as_pin_mut(), inner => inner.poll(cx)) - } -} - -#[cfg(any(test, feature = "std"))] -/// `Either<L, R>` implements `Read` if both `L` and `R` do. -/// -/// Requires crate feature `"std"` -impl<L, R> Read for Either<L, R> -where - L: Read, - R: Read, -{ - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - for_both!(self, inner => inner.read(buf)) - } - - fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { - for_both!(self, inner => inner.read_exact(buf)) - } - - fn read_to_end(&mut self, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> { - for_both!(self, inner => inner.read_to_end(buf)) - } - - fn read_to_string(&mut self, buf: &mut std::string::String) -> io::Result<usize> { - for_both!(self, inner => inner.read_to_string(buf)) - } -} - -#[cfg(any(test, feature = "std"))] -/// `Either<L, R>` implements `Seek` if both `L` and `R` do. -/// -/// Requires crate feature `"std"` -impl<L, R> Seek for Either<L, R> -where - L: Seek, - R: Seek, -{ - fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { - for_both!(self, inner => inner.seek(pos)) - } -} - -#[cfg(any(test, feature = "std"))] -/// Requires crate feature `"std"` -impl<L, R> BufRead for Either<L, R> -where - L: BufRead, - R: BufRead, -{ - fn fill_buf(&mut self) -> io::Result<&[u8]> { - for_both!(self, inner => inner.fill_buf()) - } - - fn consume(&mut self, amt: usize) { - for_both!(self, inner => inner.consume(amt)) - } - - fn read_until(&mut self, byte: u8, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> { - for_both!(self, inner => inner.read_until(byte, buf)) - } - - fn read_line(&mut self, buf: &mut std::string::String) -> io::Result<usize> { - for_both!(self, inner => inner.read_line(buf)) - } -} - -#[cfg(any(test, feature = "std"))] -/// `Either<L, R>` implements `Write` if both `L` and `R` do. -/// -/// Requires crate feature `"std"` -impl<L, R> Write for Either<L, R> -where - L: Write, - R: Write, -{ - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - for_both!(self, inner => inner.write(buf)) - } - - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - for_both!(self, inner => inner.write_all(buf)) - } - - fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { - for_both!(self, inner => inner.write_fmt(fmt)) - } - - fn flush(&mut self) -> io::Result<()> { - for_both!(self, inner => inner.flush()) - } -} - -impl<L, R, Target> AsRef<Target> for Either<L, R> -where - L: AsRef<Target>, - R: AsRef<Target>, -{ - fn as_ref(&self) -> &Target { - for_both!(self, inner => inner.as_ref()) - } -} - -macro_rules! impl_specific_ref_and_mut { - ($t:ty, $($attr:meta),* ) => { - $(#[$attr])* - impl<L, R> AsRef<$t> for Either<L, R> - where L: AsRef<$t>, R: AsRef<$t> - { - fn as_ref(&self) -> &$t { - for_both!(self, inner => inner.as_ref()) - } - } - - $(#[$attr])* - impl<L, R> AsMut<$t> for Either<L, R> - where L: AsMut<$t>, R: AsMut<$t> - { - fn as_mut(&mut self) -> &mut $t { - for_both!(self, inner => inner.as_mut()) - } - } - }; -} - -impl_specific_ref_and_mut!(str,); -impl_specific_ref_and_mut!( - ::std::path::Path, - cfg(feature = "std"), - doc = "Requires crate feature `std`." -); -impl_specific_ref_and_mut!( - ::std::ffi::OsStr, - cfg(feature = "std"), - doc = "Requires crate feature `std`." -); -impl_specific_ref_and_mut!( - ::std::ffi::CStr, - cfg(feature = "std"), - doc = "Requires crate feature `std`." -); - -impl<L, R, Target> AsRef<[Target]> for Either<L, R> -where - L: AsRef<[Target]>, - R: AsRef<[Target]>, -{ - fn as_ref(&self) -> &[Target] { - for_both!(self, inner => inner.as_ref()) - } -} - -impl<L, R, Target> AsMut<Target> for Either<L, R> -where - L: AsMut<Target>, - R: AsMut<Target>, -{ - fn as_mut(&mut self) -> &mut Target { - for_both!(self, inner => inner.as_mut()) - } -} - -impl<L, R, Target> AsMut<[Target]> for Either<L, R> -where - L: AsMut<[Target]>, - R: AsMut<[Target]>, -{ - fn as_mut(&mut self) -> &mut [Target] { - for_both!(self, inner => inner.as_mut()) - } -} - -impl<L, R> Deref for Either<L, R> -where - L: Deref, - R: Deref<Target = L::Target>, -{ - type Target = L::Target; - - fn deref(&self) -> &Self::Target { - for_both!(self, inner => &**inner) - } -} - -impl<L, R> DerefMut for Either<L, R> -where - L: DerefMut, - R: DerefMut<Target = L::Target>, -{ - fn deref_mut(&mut self) -> &mut Self::Target { - for_both!(self, inner => &mut *inner) - } -} - -#[cfg(any(test, feature = "std"))] -/// `Either` implements `Error` if *both* `L` and `R` implement it. -/// -/// Requires crate feature `"std"` -impl<L, R> Error for Either<L, R> -where - L: Error, - R: Error, -{ - fn source(&self) -> Option<&(dyn Error + 'static)> { - for_both!(self, inner => inner.source()) - } - - #[allow(deprecated)] - fn description(&self) -> &str { - for_both!(self, inner => inner.description()) - } - - #[allow(deprecated)] - fn cause(&self) -> Option<&dyn Error> { - for_both!(self, inner => inner.cause()) - } -} - -impl<L, R> fmt::Display for Either<L, R> -where - L: fmt::Display, - R: fmt::Display, -{ - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - for_both!(self, inner => inner.fmt(f)) - } -} - -impl<L, R> fmt::Write for Either<L, R> -where - L: fmt::Write, - R: fmt::Write, -{ - fn write_str(&mut self, s: &str) -> fmt::Result { - for_both!(self, inner => inner.write_str(s)) - } - - fn write_char(&mut self, c: char) -> fmt::Result { - for_both!(self, inner => inner.write_char(c)) - } - - fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result { - for_both!(self, inner => inner.write_fmt(args)) - } -} - -#[test] -fn basic() { - let mut e = Left(2); - let r = Right(2); - assert_eq!(e, Left(2)); - e = r; - assert_eq!(e, Right(2)); - assert_eq!(e.left(), None); - assert_eq!(e.right(), Some(2)); - assert_eq!(e.as_ref().right(), Some(&2)); - assert_eq!(e.as_mut().right(), Some(&mut 2)); -} - -#[test] -fn macros() { - use std::string::String; - - fn a() -> Either<u32, u32> { - let x: u32 = try_left!(Right(1337u32)); - Left(x * 2) - } - assert_eq!(a(), Right(1337)); - - fn b() -> Either<String, &'static str> { - Right(try_right!(Left("foo bar"))) - } - assert_eq!(b(), Left(String::from("foo bar"))); -} - -#[test] -fn deref() { - use std::string::String; - - fn is_str(_: &str) {} - let value: Either<String, &str> = Left(String::from("test")); - is_str(&value); -} - -#[test] -fn iter() { - let x = 3; - let mut iter = match x { - 3 => Left(0..10), - _ => Right(17..), - }; - - assert_eq!(iter.next(), Some(0)); - assert_eq!(iter.count(), 9); -} - -#[test] -fn seek() { - use std::io; - - let use_empty = false; - let mut mockdata = [0x00; 256]; - for (i, data) in mockdata.iter_mut().enumerate() { - *data = i as u8; - } - - let mut reader = if use_empty { - // Empty didn't impl Seek until Rust 1.51 - Left(io::Cursor::new([])) - } else { - Right(io::Cursor::new(&mockdata[..])) - }; - - let mut buf = [0u8; 16]; - assert_eq!(reader.read(&mut buf).unwrap(), buf.len()); - assert_eq!(buf, mockdata[..buf.len()]); - - // the first read should advance the cursor and return the next 16 bytes thus the `ne` - assert_eq!(reader.read(&mut buf).unwrap(), buf.len()); - assert_ne!(buf, mockdata[..buf.len()]); - - // if the seek operation fails it should read 16..31 instead of 0..15 - reader.seek(io::SeekFrom::Start(0)).unwrap(); - assert_eq!(reader.read(&mut buf).unwrap(), buf.len()); - assert_eq!(buf, mockdata[..buf.len()]); -} - -#[test] -fn read_write() { - use std::io; - - let use_stdio = false; - let mockdata = [0xff; 256]; - - let mut reader = if use_stdio { - Left(io::stdin()) - } else { - Right(&mockdata[..]) - }; - - let mut buf = [0u8; 16]; - assert_eq!(reader.read(&mut buf).unwrap(), buf.len()); - assert_eq!(&buf, &mockdata[..buf.len()]); - - let mut mockbuf = [0u8; 256]; - let mut writer = if use_stdio { - Left(io::stdout()) - } else { - Right(&mut mockbuf[..]) - }; - - let buf = [1u8; 16]; - assert_eq!(writer.write(&buf).unwrap(), buf.len()); -} - -#[test] -fn error() { - let invalid_utf8 = b"\xff"; - #[allow(invalid_from_utf8)] - let res = if let Err(error) = ::std::str::from_utf8(invalid_utf8) { - Err(Left(error)) - } else if let Err(error) = "x".parse::<i32>() { - Err(Right(error)) - } else { - Ok(()) - }; - assert!(res.is_err()); - #[allow(deprecated)] - res.unwrap_err().description(); // make sure this can be called -} - -/// A helper macro to check if AsRef and AsMut are implemented for a given type. -macro_rules! check_t { - ($t:ty) => {{ - fn check_ref<T: AsRef<$t>>() {} - fn propagate_ref<T1: AsRef<$t>, T2: AsRef<$t>>() { - check_ref::<Either<T1, T2>>() - } - fn check_mut<T: AsMut<$t>>() {} - fn propagate_mut<T1: AsMut<$t>, T2: AsMut<$t>>() { - check_mut::<Either<T1, T2>>() - } - }}; -} - -// This "unused" method is here to ensure that compilation doesn't fail on given types. -fn _unsized_ref_propagation() { - check_t!(str); - - fn check_array_ref<T: AsRef<[Item]>, Item>() {} - fn check_array_mut<T: AsMut<[Item]>, Item>() {} - - fn propagate_array_ref<T1: AsRef<[Item]>, T2: AsRef<[Item]>, Item>() { - check_array_ref::<Either<T1, T2>, _>() - } - - fn propagate_array_mut<T1: AsMut<[Item]>, T2: AsMut<[Item]>, Item>() { - check_array_mut::<Either<T1, T2>, _>() - } -} - -// This "unused" method is here to ensure that compilation doesn't fail on given types. -#[cfg(feature = "std")] -fn _unsized_std_propagation() { - check_t!(::std::path::Path); - check_t!(::std::ffi::OsStr); - check_t!(::std::ffi::CStr); -} diff --git a/vendor/either/src/serde_untagged.rs b/vendor/either/src/serde_untagged.rs deleted file mode 100644 index 72078c3e..00000000 --- a/vendor/either/src/serde_untagged.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! Untagged serialization/deserialization support for Either<L, R>. -//! -//! `Either` uses default, externally-tagged representation. -//! However, sometimes it is useful to support several alternative types. -//! For example, we may have a field which is generally Map<String, i32> -//! but in typical cases Vec<String> would suffice, too. -//! -//! ```rust -//! # fn main() -> Result<(), Box<dyn std::error::Error>> { -//! use either::Either; -//! use std::collections::HashMap; -//! -//! #[derive(serde::Serialize, serde::Deserialize, Debug)] -//! #[serde(transparent)] -//! struct IntOrString { -//! #[serde(with = "either::serde_untagged")] -//! inner: Either<Vec<String>, HashMap<String, i32>> -//! }; -//! -//! // serialization -//! let data = IntOrString { -//! inner: Either::Left(vec!["Hello".to_string()]) -//! }; -//! // notice: no tags are emitted. -//! assert_eq!(serde_json::to_string(&data)?, r#"["Hello"]"#); -//! -//! // deserialization -//! let data: IntOrString = serde_json::from_str( -//! r#"{"a": 0, "b": 14}"# -//! )?; -//! println!("found {:?}", data); -//! # Ok(()) -//! # } -//! ``` - -use serde::{Deserialize, Deserializer, Serialize, Serializer}; - -#[derive(serde::Serialize, serde::Deserialize)] -#[serde(untagged)] -enum Either<L, R> { - Left(L), - Right(R), -} - -pub fn serialize<L, R, S>(this: &super::Either<L, R>, serializer: S) -> Result<S::Ok, S::Error> -where - S: Serializer, - L: Serialize, - R: Serialize, -{ - let untagged = match this { - super::Either::Left(left) => Either::Left(left), - super::Either::Right(right) => Either::Right(right), - }; - untagged.serialize(serializer) -} - -pub fn deserialize<'de, L, R, D>(deserializer: D) -> Result<super::Either<L, R>, D::Error> -where - D: Deserializer<'de>, - L: Deserialize<'de>, - R: Deserialize<'de>, -{ - match Either::deserialize(deserializer) { - Ok(Either::Left(left)) => Ok(super::Either::Left(left)), - Ok(Either::Right(right)) => Ok(super::Either::Right(right)), - Err(error) => Err(error), - } -} diff --git a/vendor/either/src/serde_untagged_optional.rs b/vendor/either/src/serde_untagged_optional.rs deleted file mode 100644 index fb3239ac..00000000 --- a/vendor/either/src/serde_untagged_optional.rs +++ /dev/null @@ -1,74 +0,0 @@ -//! Untagged serialization/deserialization support for Option<Either<L, R>>. -//! -//! `Either` uses default, externally-tagged representation. -//! However, sometimes it is useful to support several alternative types. -//! For example, we may have a field which is generally Map<String, i32> -//! but in typical cases Vec<String> would suffice, too. -//! -//! ```rust -//! # fn main() -> Result<(), Box<dyn std::error::Error>> { -//! use either::Either; -//! use std::collections::HashMap; -//! -//! #[derive(serde::Serialize, serde::Deserialize, Debug)] -//! #[serde(transparent)] -//! struct IntOrString { -//! #[serde(with = "either::serde_untagged_optional")] -//! inner: Option<Either<Vec<String>, HashMap<String, i32>>> -//! }; -//! -//! // serialization -//! let data = IntOrString { -//! inner: Some(Either::Left(vec!["Hello".to_string()])) -//! }; -//! // notice: no tags are emitted. -//! assert_eq!(serde_json::to_string(&data)?, r#"["Hello"]"#); -//! -//! // deserialization -//! let data: IntOrString = serde_json::from_str( -//! r#"{"a": 0, "b": 14}"# -//! )?; -//! println!("found {:?}", data); -//! # Ok(()) -//! # } -//! ``` - -use serde::{Deserialize, Deserializer, Serialize, Serializer}; - -#[derive(Serialize, Deserialize)] -#[serde(untagged)] -enum Either<L, R> { - Left(L), - Right(R), -} - -pub fn serialize<L, R, S>( - this: &Option<super::Either<L, R>>, - serializer: S, -) -> Result<S::Ok, S::Error> -where - S: Serializer, - L: Serialize, - R: Serialize, -{ - let untagged = match this { - Some(super::Either::Left(left)) => Some(Either::Left(left)), - Some(super::Either::Right(right)) => Some(Either::Right(right)), - None => None, - }; - untagged.serialize(serializer) -} - -pub fn deserialize<'de, L, R, D>(deserializer: D) -> Result<Option<super::Either<L, R>>, D::Error> -where - D: Deserializer<'de>, - L: Deserialize<'de>, - R: Deserialize<'de>, -{ - match Option::deserialize(deserializer) { - Ok(Some(Either::Left(left))) => Ok(Some(super::Either::Left(left))), - Ok(Some(Either::Right(right))) => Ok(Some(super::Either::Right(right))), - Ok(None) => Ok(None), - Err(error) => Err(error), - } -} |
