option-operations-0.5.0/.cargo_vcs_info.json0000644000000001360000000000100145270ustar { "git": { "sha1": "8f7198b685b923a1764fd59cc28b9e66bc5026c2" }, "path_in_vcs": "" }option-operations-0.5.0/.github/workflows/CI.yml000064400000000000000000000017100072674642500177610ustar 00000000000000name: CI on: push: branches: [ main ] pull_request: workflow_dispatch: env: CARGO_TERM_COLOR: always jobs: hygiene: name: Hygiene runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: fmt run: cargo fmt -- --check - name: clippy run: cargo clippy --tests build: name: "Build & Test" runs-on: ubuntu-latest strategy: matrix: rust: - stable - beta - nightly - "1.53.0" steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} override: true - name: Test default features run: cargo test --verbose - name: Test no default features run: cargo test --verbose --no-default-features doc: name: "Doc" runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Check doc generation run: cargo doc --verbose option-operations-0.5.0/.gitignore000064400000000000000000000000230072674642500153320ustar 00000000000000/target Cargo.lock option-operations-0.5.0/CHANGELOG.md000064400000000000000000000027750072674642500151730ustar 00000000000000# Change Log ## [Unreleased] - ## [0.5.0] -- 2022-08-15 ### Fixed - Fix `prelude` not exporting `OptionEq`. ## [0.4.1] -- 2022-06-29 ### Added - Fix repository link in `Cargo.toml`. - Specify Minimum Supported Rust Version. ### Fixed - Error: fix a typo in Display impl. ### Changed - Add `forbid(unsafe_code)` constraint. ## [0.4.0] -- 2021-10-24 ### Fixed - Fix auto implementations for OptionOp and OptionOpAssign. In previous version all the implementations required that Op & OpAssign be implemented, which was not consistent with documentation and other Option* traits. Now, the user can implement OptionOp and OptionOpAssign on the inner type and automatically benefit from the implementations on the other variations. ### Changed - Factorize code in macros. ## [0.3.0] -- 2021-10-18 ### Changed - **Breaking**: don't export internal macros. ## [0.2.0] -- 2021-10-15 ### Added - #[must_use] attributes where applicable. - Documentation for the associated types. ## [0.1.0] -- 2021-10-07 - First version with the most common operations. [Unreleased]: https://github.com/fengalin/option-operations/ [0.5.0]: https://github.com/fengalin/option-operations/tree/0.5.0 [0.4.1]: https://github.com/fengalin/option-operations/tree/0.4.1 [0.4.0]: https://github.com/fengalin/option-operations/tree/0.4.0 [0.3.0]: https://github.com/fengalin/option-operations/tree/0.3.0 [0.2.0]: https://github.com/fengalin/option-operations/tree/0.2.0 [0.1.0]: https://github.com/fengalin/option-operations/tree/0.1.0option-operations-0.5.0/Cargo.toml0000644000000021520000000000100125250ustar # 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 = "2018" rust-version = "1.53" name = "option-operations" version = "0.5.0" authors = ["François Laignel "] description = "Traits and auto-implementations to improve arithmetic operations usability when dealing with `Option`s." documentation = "https://docs.rs/option-operations" readme = "README.md" keywords = [ "option", "arithmetic", "operations", "ord", "cmp", ] categories = [ "rust-patterns", "no-std", "mathematics", ] license = "MIT/Apache-2.0" repository = "https://github.com/fengalin/option-operations" [dependencies.paste] version = "1.0.6" [features] default = ["std"] std = [] option-operations-0.5.0/Cargo.toml.orig000064400000000000000000000014260072674642500162410ustar 00000000000000[package] name = "option-operations" version = "0.5.0" authors = ["François Laignel "] categories = ["rust-patterns", "no-std", "mathematics"] description = "Traits and auto-implementations to improve arithmetic operations usability when dealing with `Option`s." documentation = "https://docs.rs/option-operations" keywords = ["option", "arithmetic", "operations", "ord", "cmp"] license = "MIT/Apache-2.0" readme = "README.md" repository = "https://github.com/fengalin/option-operations" edition = "2018" rust-version = "1.53" [features] default = ["std"] # Provide impls for common standard library types like # std::time::Instant and impl std traits like Display & Error. # Requires a dependency on the Rust standard library. std = [] [dependencies] paste = "1.0.6" option-operations-0.5.0/LICENSE-APACHE000064400000000000000000000251370072674642500153030ustar 00000000000000 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. option-operations-0.5.0/LICENSE-MIT000064400000000000000000000017770072674642500150170ustar 00000000000000Permission 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. option-operations-0.5.0/README.md000064400000000000000000000045710072674642500146350ustar 00000000000000# option-operations [![crates.io][Crate Logo]][Crate] [![Documentation][Doc Logo]][Doc] [![Build Status][CI Logo]][CI] [![MSRV][rustc Logo]][Crate] `option-operations` provides traits and auto-implementations to improve arithmetic operations usability when dealing with `Option`s. ## Example Dealing with two `Option`s, can lead to verbose expressions: ``` rust let lhs = Some(1u64); let rhs = Some(u64::MAX); assert_eq!( lhs.zip(rhs).map(|(lhs, rhs)| lhs.saturating_add(rhs)), Some(u64::MAX), ); ``` Thanks to the trait `OptionSaturatingAdd` we can write: ``` rust assert_eq!( lhs.opt_saturating_add(rhs), Some(u64::MAX), ); ``` The trait can also be used with the inner type: ``` rust assert_eq!( lhs.opt_saturating_add(u64::MAX), Some(u64::MAX), ); assert_eq!( 1.opt_saturating_add(rhs), Some(u64::MAX), ); ``` ## Alternative to `PartialOrd` for `Option` Another purpose is to workaround the `PartiaOrd` implementation for `Option`, which uses the declaration order of the variants for `Option`. `None` appearing before `Some(_)`, it results in the following behavior: ``` rust let some_0 = Some(0); let none: Option = None; assert_eq!(none.partial_cmp(&some_0), Some(Ordering::Less)); assert_eq!(some_0.partial_cmp(&none), Some(Ordering::Greater)); ``` In some cases, we might consider that `None` reflects a value which is not defined and thus can not be compared with `Some(_)`. ``` rust assert_eq!(none.opt_cmp(&some_0), None); assert_eq!(some_0.opt_cmp(&none), None); ``` Of course, this is consistent with other usual comparisons: ``` rust assert_eq!(none.opt_lt(&some_0), None); assert_eq!(none.opt_min(&some_0), None); ``` ## LICENSE This crate is licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. [Crate]: https://crates.io/crates/option-operations [Crate Logo]: https://img.shields.io/crates/v/option-operations.svg [Doc]: https://docs.rs/option-operations [Doc Logo]: https://docs.rs/option-operations/badge.svg [CI]: https://github.com/fengalin/option-operations/actions/workflows/CI.yml [CI Logo]: https://github.com/fengalin/option-operations/workflows/CI/badge.svg [rustc Logo]: https://img.shields.io/badge/rust-1.53.0%2B-blue.svg?maxAge=3600 option-operations-0.5.0/src/add.rs000064400000000000000000000242620072674642500152420ustar 00000000000000//! Traits for the addition [`OptionOperations`]. use core::ops::{Add, AddAssign}; use crate::{Error, OptionOperations}; common_option_op!(Add, add, addition); impl_for_ints!(OptionOverflowingAdd, { type Output = Self; fn opt_overflowing_add(self, rhs: Self) -> Option<(Self::Output, bool)> { Some(self.overflowing_add(rhs)) } }); impl_for_ints!(OptionWrappingAdd, { type Output = Self; fn opt_wrapping_add(self, rhs: Self) -> Option { Some(self.wrapping_add(rhs)) } }); option_op_checked!(Add, add, addition); impl_for_ints_and_duration!(OptionCheckedAdd, { type Output = Self; fn opt_checked_add(self, rhs: Self) -> Result, Error> { self.checked_add(rhs).ok_or(Error::Overflow).map(Some) } }); #[cfg(feature = "std")] impl OptionCheckedAdd for std::time::Instant { type Output = Self; fn opt_checked_add(self, rhs: std::time::Duration) -> Result, Error> { self.checked_add(rhs).ok_or(Error::Overflow).map(Some) } } #[cfg(feature = "std")] impl OptionCheckedAdd for std::time::SystemTime { type Output = Self; fn opt_checked_add(self, rhs: std::time::Duration) -> Result, Error> { self.checked_add(rhs).ok_or(Error::Overflow).map(Some) } } option_op_saturating!(Add, add, addition); impl_for_ints_and_duration!(OptionSaturatingAdd, { type Output = Self; fn opt_saturating_add(self, rhs: Self) -> Option { Some(self.saturating_add(rhs)) } }); #[cfg(test)] mod test { use super::*; use crate::OptionOperations; use core::ops::{Add, AddAssign}; #[derive(Copy, Clone, Debug, PartialEq, PartialOrd)] struct MyInt(u64); impl OptionOperations for MyInt {} impl Add for MyInt { type Output = MyInt; fn add(self, rhs: MyInt) -> MyInt { MyInt(self.0.add(rhs.0)) } } impl Add for MyInt { type Output = MyInt; fn add(self, rhs: u64) -> MyInt { MyInt(self.0.add(rhs)) } } impl AddAssign for MyInt { fn add_assign(&mut self, rhs: MyInt) { self.0.add_assign(rhs.0) } } impl AddAssign for MyInt { fn add_assign(&mut self, rhs: u64) { self.0.add_assign(rhs) } } const MY_0: MyInt = MyInt(0); const MY_1: MyInt = MyInt(1); const MY_2: MyInt = MyInt(2); const MY_MAX: MyInt = MyInt(u64::MAX); const SOME_0: Option = Some(MY_0); const SOME_1: Option = Some(MY_1); const SOME_2: Option = Some(MY_2); const SOME_MAX: Option = Some(MY_MAX); const NONE: Option = None; #[test] fn add_my() { assert_eq!(MY_1.opt_add(MY_1), SOME_2); assert_eq!(SOME_1.opt_add(MY_1), SOME_2); assert_eq!(MY_1.opt_add(SOME_1), SOME_2); assert_eq!(MY_1.opt_add(&SOME_1), SOME_2); assert_eq!(MY_1.opt_add(NONE), NONE); assert_eq!(NONE.opt_add(MY_1), NONE); } #[test] fn add_u64() { assert_eq!(MY_1.opt_add(1), SOME_2); assert_eq!(MY_1.opt_add(Some(1)), SOME_2); assert_eq!(SOME_1.opt_add(1), SOME_2); assert_eq!(SOME_1.opt_add(Some(1)), SOME_2); assert_eq!(SOME_1.opt_add(&Some(1)), SOME_2); assert_eq!(MY_1.opt_add(Option::::None), NONE); assert_eq!(Option::::None.opt_add(MY_0), NONE); } #[test] fn add_assign_my() { let mut my = MY_1; my.opt_add_assign(MY_1); assert_eq!(my, MY_2); let mut some = SOME_1; some.opt_add_assign(MY_1); assert_eq!(some, SOME_2); let mut my = MY_1; my.opt_add_assign(SOME_1); assert_eq!(my, MY_2); let mut my = MY_1; my.opt_add_assign(&SOME_1); assert_eq!(my, MY_2); let mut my = MY_1; my.opt_add_assign(NONE); assert_eq!(my, MY_1); let mut some = SOME_1; some.opt_add_assign(SOME_1); assert_eq!(some, SOME_2); let mut some = SOME_1; some.opt_add_assign(&SOME_1); assert_eq!(some, SOME_2); let mut some = SOME_1; some.opt_add_assign(NONE); assert_eq!(some, SOME_1); let mut none = NONE; none.opt_add_assign(SOME_1); assert_eq!(none, NONE); let mut none = NONE; none.opt_add_assign(NONE); assert_eq!(none, NONE); } #[test] fn add_assign_u64() { let mut my = MY_1; my.opt_add_assign(1); assert_eq!(my, MY_2); let mut some = SOME_1; some.opt_add_assign(1); assert_eq!(some, SOME_2); let mut my = MY_1; my.opt_add_assign(Some(1)); assert_eq!(my, MY_2); let mut my = MY_1; my.opt_add_assign(&Some(1)); assert_eq!(my, MY_2); let mut some = SOME_1; some.opt_add_assign(Some(1)); assert_eq!(some, SOME_2); let mut some = SOME_1; some.opt_add_assign(&Some(1)); assert_eq!(some, SOME_2); let mut none = NONE; none.opt_add_assign(Some(1)); assert_eq!(none, NONE); } #[test] fn checked_add() { impl OptionCheckedAdd for MyInt { type Output = MyInt; fn opt_checked_add(self, rhs: MyInt) -> Result, Error> { self.0.opt_checked_add(rhs.0).map(|ok| ok.map(MyInt)) } } impl OptionCheckedAdd for MyInt { type Output = MyInt; fn opt_checked_add(self, rhs: u64) -> Result, Error> { self.0.opt_checked_add(rhs).map(|ok| ok.map(MyInt)) } } assert_eq!(MY_1.opt_checked_add(MY_1), Ok(SOME_2)); assert_eq!(MY_1.opt_checked_add(SOME_1), Ok(SOME_2)); assert_eq!(MY_1.opt_checked_add(&SOME_1), Ok(SOME_2)); assert_eq!(MY_MAX.opt_checked_add(MY_1), Err(Error::Overflow)); assert_eq!(SOME_1.opt_checked_add(MY_1), Ok(SOME_2)); assert_eq!(SOME_1.opt_checked_add(SOME_1), Ok(SOME_2)); assert_eq!(SOME_1.opt_checked_add(&SOME_1), Ok(SOME_2)); assert_eq!(SOME_MAX.opt_checked_add(MY_1), Err(Error::Overflow)); assert_eq!(SOME_MAX.opt_checked_add(1), Err(Error::Overflow)); assert_eq!(SOME_MAX.opt_checked_add(Some(1)), Err(Error::Overflow)); assert_eq!(MY_1.opt_checked_add(SOME_MAX), Err(Error::Overflow)); assert_eq!(MY_MAX.opt_checked_add(NONE), Ok(None)); assert_eq!(NONE.opt_checked_add(SOME_MAX), Ok(None)); } #[test] fn saturating_add() { impl OptionSaturatingAdd for MyInt { type Output = MyInt; fn opt_saturating_add(self, rhs: MyInt) -> Option { self.0.opt_saturating_add(rhs.0).map(MyInt) } } impl OptionSaturatingAdd for MyInt { type Output = MyInt; fn opt_saturating_add(self, rhs: u64) -> Option { self.0.opt_saturating_add(rhs).map(MyInt) } } assert_eq!(MY_1.opt_saturating_add(MY_1), SOME_2); assert_eq!(MY_MAX.opt_saturating_add(MY_1), SOME_MAX); assert_eq!(SOME_MAX.opt_saturating_add(MY_1), SOME_MAX); assert_eq!(SOME_MAX.opt_saturating_add(1), SOME_MAX); assert_eq!(SOME_MAX.opt_saturating_add(Some(1)), SOME_MAX); assert_eq!(SOME_MAX.opt_saturating_add(&Some(1)), SOME_MAX); assert_eq!(MY_1.opt_saturating_add(SOME_MAX), SOME_MAX); assert_eq!(MY_1.opt_saturating_add(&SOME_MAX), SOME_MAX); assert_eq!(MY_MAX.opt_saturating_add(NONE), NONE); assert_eq!(NONE.opt_saturating_add(SOME_MAX), NONE); } #[test] fn overflowing_add() { impl OptionOverflowingAdd for MyInt { type Output = MyInt; fn opt_overflowing_add(self, rhs: MyInt) -> Option<(Self::Output, bool)> { self.0 .opt_overflowing_add(rhs.0) .map(|(val, flag)| (MyInt(val), flag)) } } impl OptionOverflowingAdd for MyInt { type Output = MyInt; fn opt_overflowing_add(self, rhs: u64) -> Option<(Self::Output, bool)> { self.0 .opt_overflowing_add(rhs) .map(|(val, flag)| (MyInt(val), flag)) } } assert_eq!(MY_1.opt_overflowing_add(MY_1), Some((MY_2, false))); assert_eq!(MY_MAX.opt_overflowing_add(MY_1), Some((MY_0, true))); assert_eq!(SOME_MAX.opt_overflowing_add(MY_1), Some((MY_0, true))); assert_eq!(SOME_MAX.opt_overflowing_add(1), Some((MY_0, true))); assert_eq!(SOME_MAX.opt_overflowing_add(Some(1)), Some((MY_0, true))); assert_eq!(SOME_MAX.opt_overflowing_add(&Some(1)), Some((MY_0, true))); assert_eq!(MY_1.opt_overflowing_add(SOME_MAX), Some((MY_0, true))); assert_eq!(MY_1.opt_overflowing_add(&SOME_MAX), Some((MY_0, true))); assert_eq!(MY_MAX.opt_overflowing_add(NONE), None); assert_eq!(NONE.opt_overflowing_add(SOME_MAX), None); } #[test] fn wrapping_add() { impl OptionWrappingAdd for MyInt { type Output = MyInt; fn opt_wrapping_add(self, rhs: MyInt) -> Option { self.0.opt_wrapping_add(rhs.0).map(MyInt) } } impl OptionWrappingAdd for MyInt { type Output = MyInt; fn opt_wrapping_add(self, rhs: u64) -> Option { self.0.opt_wrapping_add(rhs).map(MyInt) } } assert_eq!(MY_1.opt_wrapping_add(MY_1), SOME_2); assert_eq!(MY_MAX.opt_wrapping_add(MY_1), SOME_0); assert_eq!(SOME_MAX.opt_wrapping_add(MY_1), SOME_0); assert_eq!(SOME_MAX.opt_wrapping_add(1), SOME_0); assert_eq!(SOME_MAX.opt_wrapping_add(Some(1)), SOME_0); assert_eq!(SOME_MAX.opt_wrapping_add(&Some(1)), SOME_0); assert_eq!(MY_1.opt_wrapping_add(SOME_MAX), SOME_0); assert_eq!(MY_1.opt_wrapping_add(&SOME_MAX), SOME_0); assert_eq!(MY_MAX.opt_wrapping_add(NONE), NONE); assert_eq!(NONE.opt_wrapping_add(SOME_MAX), NONE); } } option-operations-0.5.0/src/div.rs000064400000000000000000000256340072674642500153000ustar 00000000000000//! Traits for the division [`OptionOperations`]. use core::ops::{Div, DivAssign}; use crate::{Error, OptionOperations}; common_option_op!( Div, div, division, " # Panics Most implementations will panic if `rhs` is zero. ", ); impl_for_ints!(OptionOverflowingDiv, { type Output = Self; fn opt_overflowing_div(self, rhs: Self) -> Option<(Self::Output, bool)> { Some(self.overflowing_div(rhs)) } }); impl_for_ints!(OptionWrappingDiv, { type Output = Self; fn opt_wrapping_div(self, rhs: Self) -> Option { Some(self.wrapping_div(rhs)) } }); option_op_checked!( Div, div, division, "- Returns `Err(Error::DivisionByZero)` if `rhs` is zero.", ); impl_for_ints!(OptionCheckedDiv, { type Output = Self; fn opt_checked_div(self, rhs: Self) -> Result, Error> { if rhs == 0 { return Err(Error::DivisionByZero); } self.checked_div(rhs).ok_or(Error::Overflow).map(Some) } }); impl OptionCheckedDiv for core::time::Duration { type Output = Self; fn opt_checked_div(self, rhs: u32) -> Result, Error> { if rhs == 0 { return Err(Error::DivisionByZero); } self.checked_div(rhs).ok_or(Error::Overflow).map(Some) } } #[cfg(test)] mod test { use super::*; use crate::OptionOperations; use core::ops::{Div, DivAssign}; #[derive(Copy, Clone, Debug, PartialEq, PartialOrd)] struct MyInt(i64); impl OptionOperations for MyInt {} impl Div for MyInt { type Output = MyInt; fn div(self, rhs: MyInt) -> MyInt { MyInt(self.0.div(rhs.0)) } } impl Div for MyInt { type Output = MyInt; fn div(self, rhs: i64) -> MyInt { MyInt(self.0.div(rhs)) } } impl DivAssign for MyInt { fn div_assign(&mut self, rhs: MyInt) { self.0.div_assign(rhs.0) } } impl DivAssign for MyInt { fn div_assign(&mut self, rhs: i64) { self.0.div_assign(rhs) } } const MY_MINUS_1: MyInt = MyInt(-1); const MY_0: MyInt = MyInt(0); const MY_1: MyInt = MyInt(1); const MY_2: MyInt = MyInt(2); const MY_5: MyInt = MyInt(5); const MY_10: MyInt = MyInt(10); const MY_MIN: MyInt = MyInt(i64::MIN); const MY_HALF_MAX: MyInt = MyInt(i64::MAX / 2); const MY_MAX: MyInt = MyInt(i64::MAX); const SOME_MINUS_1: Option = Some(MY_MINUS_1); const SOME_0: Option = Some(MY_0); const SOME_1: Option = Some(MY_1); const SOME_2: Option = Some(MY_2); const SOME_5: Option = Some(MY_5); const SOME_10: Option = Some(MY_10); const SOME_MIN: Option = Some(MY_MIN); const SOME_HALF_MAX: Option = Some(MY_HALF_MAX); const SOME_MAX: Option = Some(MY_MAX); const NONE: Option = None; #[test] fn div_my() { assert_eq!(MY_5.opt_div(MY_1), SOME_5); assert_eq!(SOME_10.opt_div(MY_2), SOME_5); assert_eq!(MY_0.opt_div(SOME_1), SOME_0); assert_eq!(MY_MAX.opt_div(&SOME_2), SOME_HALF_MAX); assert_eq!(MY_1.opt_div(NONE), NONE); assert_eq!(NONE.opt_div(MY_1), NONE); } #[test] #[should_panic] fn div_by_zero_my() { let _ = SOME_10.opt_div(SOME_0); } #[test] fn div_i64() { assert_eq!(MY_5.opt_div(5), SOME_1); assert_eq!(SOME_10.opt_div(MY_2), SOME_5); assert_eq!(MY_0.opt_div(Some(1)), SOME_0); assert_eq!(MY_MAX.opt_div(Some(2)), SOME_HALF_MAX); assert_eq!(MY_1.opt_div(Option::::None), NONE); assert_eq!(Option::::None.opt_div(MY_1), NONE); } #[test] #[should_panic] fn div_by_zero_i64() { let _ = SOME_10.opt_div(Some(0)); } #[test] fn div_assign_my() { let mut my = MY_5; my.opt_div_assign(MY_1); assert_eq!(my, MY_5); let mut some = SOME_10; some.opt_div_assign(MY_5); assert_eq!(some, SOME_2); let mut my = MY_0; my.opt_div_assign(SOME_1); assert_eq!(my, MY_0); let mut my = MY_MAX; my.opt_div_assign(&SOME_2); assert_eq!(my, MY_HALF_MAX); let mut my = MY_1; my.opt_div_assign(NONE); assert_eq!(my, MY_1); let mut some = SOME_2; some.opt_div_assign(SOME_1); assert_eq!(some, SOME_2); let mut some = SOME_10; some.opt_div_assign(&SOME_2); assert_eq!(some, SOME_5); let mut some = SOME_1; some.opt_div_assign(NONE); assert_eq!(some, SOME_1); let mut none = NONE; none.opt_div_assign(SOME_1); assert_eq!(none, NONE); let mut none = NONE; none.opt_div_assign(NONE); assert_eq!(none, NONE); } #[test] #[should_panic] fn div_assign_by_zero_my() { let mut some = SOME_10; some.opt_div_assign(SOME_0); } #[test] fn div_assign_i64() { let mut my = MY_5; my.opt_div_assign(1); assert_eq!(my, MY_5); let mut some = SOME_10; some.opt_div_assign(5); assert_eq!(some, SOME_2); let mut my = MY_0; my.opt_div_assign(1); assert_eq!(my, MY_0); let mut my = MY_MAX; my.opt_div_assign(2); assert_eq!(my, MY_HALF_MAX); let mut my = MY_1; my.opt_div_assign(Option::::None); assert_eq!(my, MY_1); let mut some = SOME_2; some.opt_div_assign(1); assert_eq!(some, SOME_2); let mut some = SOME_1; some.opt_div_assign(Option::::None); assert_eq!(some, SOME_1); let mut none = NONE; none.opt_div_assign(1); assert_eq!(none, NONE); let mut none = NONE; none.opt_div_assign(Option::::None); assert_eq!(none, NONE); } #[test] #[should_panic] fn div_assign_by_zero_i64() { let mut some = SOME_10; some.opt_div_assign(Some(0)); } #[test] fn checked_div() { impl OptionCheckedDiv for MyInt { type Output = MyInt; fn opt_checked_div(self, rhs: MyInt) -> Result, Error> { self.0.opt_checked_div(rhs.0).map(|ok| ok.map(MyInt)) } } impl OptionCheckedDiv for MyInt { type Output = MyInt; fn opt_checked_div(self, rhs: i64) -> Result, Error> { self.0.opt_checked_div(rhs).map(|ok| ok.map(MyInt)) } } assert_eq!(MY_2.opt_checked_div(MY_1), Ok(SOME_2)); assert_eq!(MY_10.opt_checked_div(SOME_5), Ok(SOME_2)); assert_eq!(MY_0.opt_checked_div(&SOME_1), Ok(SOME_0)); assert_eq!(MY_MAX.opt_checked_div(MY_2), Ok(SOME_HALF_MAX)); assert_eq!(MY_MAX.opt_checked_div(MY_0), Err(Error::DivisionByZero)); assert_eq!(MY_MIN.opt_checked_div(MY_MINUS_1), Err(Error::Overflow)); assert_eq!(SOME_2.opt_checked_div(MY_1), Ok(SOME_2)); assert_eq!(SOME_10.opt_checked_div(SOME_2), Ok(SOME_5)); assert_eq!(SOME_0.opt_checked_div(&SOME_1), Ok(SOME_0)); assert_eq!(SOME_MAX.opt_checked_div(MY_2), Ok(SOME_HALF_MAX)); assert_eq!(SOME_MAX.opt_checked_div(MY_0), Err(Error::DivisionByZero)); assert_eq!(SOME_MIN.opt_checked_div(MY_MINUS_1), Err(Error::Overflow)); assert_eq!(SOME_MAX.opt_checked_div(0), Err(Error::DivisionByZero)); assert_eq!(SOME_MIN.opt_checked_div(-1), Err(Error::Overflow)); assert_eq!( SOME_MAX.opt_checked_div(Some(0)), Err(Error::DivisionByZero) ); assert_eq!(SOME_MIN.opt_checked_div(Some(-1)), Err(Error::Overflow)); assert_eq!(SOME_MAX.opt_checked_div(SOME_0), Err(Error::DivisionByZero)); assert_eq!(SOME_MIN.opt_checked_div(SOME_MINUS_1), Err(Error::Overflow)); assert_eq!(MY_MIN.opt_checked_div(NONE), Ok(None)); assert_eq!(NONE.opt_checked_div(SOME_MIN), Ok(None)); } #[test] fn overflowing_div() { impl OptionOverflowingDiv for MyInt { type Output = MyInt; fn opt_overflowing_div(self, rhs: MyInt) -> Option<(Self::Output, bool)> { self.0 .opt_overflowing_div(rhs.0) .map(|(val, flag)| (MyInt(val), flag)) } } impl OptionOverflowingDiv for MyInt { type Output = MyInt; fn opt_overflowing_div(self, rhs: i64) -> Option<(Self::Output, bool)> { self.0 .opt_overflowing_div(rhs) .map(|(val, flag)| (MyInt(val), flag)) } } assert_eq!(MY_2.opt_overflowing_div(MY_1), Some((MY_2, false))); assert_eq!(MY_0.opt_overflowing_div(MY_1), Some((MY_0, false))); assert_eq!(MY_MAX.opt_overflowing_div(MY_2), Some((MY_HALF_MAX, false))); assert_eq!(MY_MIN.opt_overflowing_div(MY_MINUS_1), Some((MY_MIN, true))); assert_eq!( SOME_MIN.opt_overflowing_div(MY_MINUS_1), Some((MY_MIN, true)) ); assert_eq!(SOME_MIN.opt_overflowing_div(-1), Some((MY_MIN, true))); assert_eq!(SOME_MIN.opt_overflowing_div(Some(-1)), Some((MY_MIN, true))); assert_eq!( SOME_MIN.opt_overflowing_div(&Some(-1)), Some((MY_MIN, true)) ); assert_eq!( MY_MIN.opt_overflowing_div(SOME_MINUS_1), Some((MY_MIN, true)) ); assert_eq!( MY_MIN.opt_overflowing_div(&SOME_MINUS_1), Some((MY_MIN, true)) ); assert_eq!(MY_MIN.opt_overflowing_div(NONE), None); assert_eq!(NONE.opt_overflowing_div(MY_MIN), None); } #[test] fn wrapping_div() { impl OptionWrappingDiv for MyInt { type Output = MyInt; fn opt_wrapping_div(self, rhs: MyInt) -> Option { self.0.opt_wrapping_div(rhs.0).map(MyInt) } } impl OptionWrappingDiv for MyInt { type Output = MyInt; fn opt_wrapping_div(self, rhs: i64) -> Option { self.0.opt_wrapping_div(rhs).map(MyInt) } } assert_eq!(MY_2.opt_wrapping_div(MY_1), SOME_2); assert_eq!(MY_0.opt_wrapping_div(MY_1), SOME_0); assert_eq!(MY_MIN.opt_wrapping_div(MY_MINUS_1), SOME_MIN); assert_eq!(SOME_MIN.opt_wrapping_div(MY_MINUS_1), SOME_MIN); assert_eq!(SOME_MIN.opt_wrapping_div(-1), SOME_MIN); assert_eq!(SOME_MIN.opt_wrapping_div(Some(-1)), SOME_MIN); assert_eq!(SOME_MIN.opt_wrapping_div(&Some(-1)), SOME_MIN); assert_eq!(MY_MIN.opt_wrapping_div(SOME_MINUS_1), SOME_MIN); assert_eq!(MY_MIN.opt_wrapping_div(&SOME_MINUS_1), SOME_MIN); assert_eq!(MY_MIN.opt_wrapping_div(NONE), None); assert_eq!(NONE.opt_wrapping_div(MY_MIN), None); } } option-operations-0.5.0/src/eq.rs000064400000000000000000000110300072674642500151040ustar 00000000000000//! Trait for the equality [`OptionOperations`]. use crate::OptionOperations; /// Trait for the equality [`OptionOperations`]. pub trait OptionEq { /// Tests whether `self` is equal to `other`. /// /// Returns `None` if they can't be compared, e.g. if /// at most one argument is `None`. #[must_use] fn opt_eq(&self, other: Rhs) -> Option; /// Tests whether `self` is not equal to `other`. /// /// Returns `None` if they can't be compared, e.g. if /// at most one argument is `None`. #[must_use] fn opt_ne(&self, other: Rhs) -> Option { self.opt_eq(other).map(|res| !res) } } impl OptionEq<&Rhs, Rhs> for T where T: OptionOperations + PartialEq, { fn opt_eq(&self, rhs: &Rhs) -> Option { Some(self.eq(rhs)) } } impl OptionEq for T where T: OptionOperations + for<'a> OptionEq<&'a Rhs, Rhs>, { fn opt_eq(&self, rhs: Rhs) -> Option { self.opt_eq(&rhs) } } impl OptionEq<&Option, InnerRhs> for T where T: OptionOperations + for<'a> OptionEq<&'a InnerRhs, InnerRhs>, { fn opt_eq(&self, rhs: &Option) -> Option { rhs.as_ref().and_then(|inner_rhs| self.opt_eq(inner_rhs)) } } impl OptionEq, InnerRhs> for T where T: OptionOperations + for<'a> OptionEq<&'a InnerRhs, InnerRhs>, { fn opt_eq(&self, rhs: Option) -> Option { rhs.as_ref().and_then(|inner_rhs| self.opt_eq(inner_rhs)) } } impl OptionEq<&Rhs, Rhs> for Option where T: OptionOperations + for<'a> OptionEq<&'a Rhs, Rhs>, { fn opt_eq(&self, rhs: &Rhs) -> Option { self.as_ref().and_then(|inner_self| inner_self.opt_eq(rhs)) } } impl OptionEq for Option where T: OptionOperations + for<'a> OptionEq<&'a Rhs, Rhs>, { fn opt_eq(&self, rhs: Rhs) -> Option { self.opt_eq(&rhs) } } impl OptionEq<&Option, InnerRhs> for Option where T: OptionOperations + for<'a> OptionEq<&'a InnerRhs, InnerRhs>, { fn opt_eq(&self, rhs: &Option) -> Option { match (self, rhs) { (Some(inner_self), Some(inner_rhs)) => inner_self.opt_eq(inner_rhs), (None, None) => Some(true), _ => None, } } } impl OptionEq, InnerRhs> for Option where T: OptionOperations + for<'a> OptionEq<&'a InnerRhs, InnerRhs>, { fn opt_eq(&self, rhs: Option) -> Option { match (self, rhs.as_ref()) { (Some(inner_self), Some(inner_rhs)) => inner_self.opt_eq(inner_rhs), (None, None) => Some(true), _ => None, } } } #[cfg(test)] mod test { use super::OptionEq; use crate::OptionOperations; #[derive(Copy, Clone, Debug, PartialEq, PartialOrd)] struct MyInt(u64); impl OptionOperations for MyInt {} const MY_1: MyInt = MyInt(1); const MY_2: MyInt = MyInt(2); const SOME_1: Option = Some(MY_1); const SOME_2: Option = Some(MY_2); const NONE: Option = None; #[test] fn opt_eq() { assert_eq!(MY_1.opt_eq(MY_1), Some(true)); assert_eq!(MY_1.opt_eq(SOME_1), Some(true)); assert_eq!(SOME_1.opt_eq(MY_1), Some(true)); assert_eq!(SOME_1.opt_eq(SOME_1), Some(true)); assert_eq!(MY_1.opt_eq(MY_2), Some(false)); assert_eq!(MY_1.opt_eq(SOME_2), Some(false)); assert_eq!(SOME_1.opt_eq(MY_2), Some(false)); assert_eq!(SOME_1.opt_eq(SOME_2), Some(false)); assert_eq!(MY_1.opt_eq(NONE), None); assert_eq!(NONE.opt_eq(SOME_2), None); assert_eq!(SOME_1.opt_eq(NONE), None); assert_eq!(NONE.opt_eq(SOME_2), None); assert_eq!(NONE.opt_eq(NONE), Some(true)); } #[test] fn opt_ne() { assert_eq!(MY_1.opt_ne(MY_1), Some(false)); assert_eq!(MY_1.opt_ne(SOME_1), Some(false)); assert_eq!(SOME_1.opt_ne(MY_1), Some(false)); assert_eq!(SOME_1.opt_ne(SOME_1), Some(false)); assert_eq!(MY_1.opt_ne(MY_2), Some(true)); assert_eq!(MY_1.opt_ne(SOME_2), Some(true)); assert_eq!(SOME_1.opt_ne(MY_2), Some(true)); assert_eq!(SOME_1.opt_ne(SOME_2), Some(true)); assert_eq!(MY_1.opt_ne(NONE), None); assert_eq!(NONE.opt_ne(SOME_2), None); assert_eq!(SOME_1.opt_ne(NONE), None); assert_eq!(NONE.opt_ne(SOME_2), None); assert_eq!(NONE.opt_ne(NONE), Some(false)); } } option-operations-0.5.0/src/error.rs000064400000000000000000000023320072674642500156350ustar 00000000000000//! Error type which can be returned by some [`OptionOperations`]. #[cfg(feature = "std")] use std::{error, fmt}; // Required for doc #[allow(unused)] use crate::OptionOperations; /// Error type which can be returned by some [`OptionOperations`]. #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum Error { /// Division by zero attempted with an [`OptionOperations`]. DivisionByZero, /// An [`OptionOperations`] overflowed. Overflow, } impl Error { /// Returns `true` if this [`Error`] results from a division by zero. #[must_use] pub fn is_division_by_zero(&self) -> bool { matches!(self, Error::DivisionByZero) } /// Returns `true` if this [`Error`] results from an overflow. #[must_use] pub fn is_overflow(&self) -> bool { matches!(self, Error::Overflow) } } #[cfg(feature = "std")] impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::DivisionByZero => f.write_str("An Option Operation overflowed"), Error::Overflow => f.write_str("Division by zero attempted with an Option Operation"), } } } #[cfg(feature = "std")] impl error::Error for Error {} option-operations-0.5.0/src/lib.rs000064400000000000000000000107550072674642500152620ustar 00000000000000//! `option-operations` provides traits and auto-implementations to //! improve arithmetic operations usability when dealing with `Option`s. //! //! # Example //! //! Dealing with two `Option`s, can lead to verbose expressions: //! //! ``` //! let lhs = Some(1u64); //! let rhs = Some(u64::MAX); //! //! assert_eq!( //! lhs.zip(rhs).map(|(lhs, rhs)| lhs.saturating_add(rhs)), //! Some(u64::MAX), //! ); //! ``` //! //! Thanks to the trait [`OptionSaturatingAdd`] we can write: //! //! ``` //! # use option_operations::{Error, OptionSaturatingAdd}; //! # let lhs = Some(1u64); //! # let rhs = Some(u64::MAX); //! assert_eq!( //! lhs.opt_saturating_add(rhs), //! Some(u64::MAX), //! ); //! ``` //! //! The trait can also be used with the inner type: //! //! ``` //! # use option_operations::{Error, OptionSaturatingAdd}; //! # let lhs = Some(1u64); //! # let rhs = Some(u64::MAX); //! assert_eq!( //! lhs.opt_saturating_add(u64::MAX), //! Some(u64::MAX), //! ); //! //! assert_eq!( //! 1.opt_saturating_add(rhs), //! Some(u64::MAX), //! ); //! ``` //! //! # Alternative to `PartialOrd` for `Option` //! //! Another purpose is to workaround the `PartiaOrd` implementation //! for `Option`, which uses the declaration order of the variants //! for `Option`. `None` appearing before `Some(_)`, it results in //! the following behavior: //! //! ``` //! # use core::cmp::Ordering; //! let some_0 = Some(0); //! let none: Option = None; //! //! assert_eq!(none.partial_cmp(&some_0), Some(Ordering::Less)); //! assert_eq!(some_0.partial_cmp(&none), Some(Ordering::Greater)); //! ``` //! //! In some cases, we might consider that `None` reflects a value which //! is not defined and thus can not be compared with `Some(_)`. //! //! ``` //! # use option_operations::{OptionOperations, OptionOrd}; //! # let some_0 = Some(0); //! # let none: Option = None; //! assert_eq!(none.opt_cmp(&some_0), None); //! assert_eq!(some_0.opt_cmp(&none), None); //! ``` //! //! Of course, this is consistent with other usual comparisons: //! //! ``` rust //! # use option_operations::{OptionOperations, OptionOrd, OptionMinMax}; //! # let some_0 = Some(0); //! # let none: Option = None; //! assert_eq!(none.opt_lt(&some_0), None); //! assert_eq!(none.opt_min(some_0), None); //! ``` #![forbid(unsafe_code)] #![cfg_attr(not(feature = "std"), no_std)] /// Trait for inner types participating in `option-operations`. /// /// The purpose of this trait is twofold: /// /// - Auto-implement various `Option*` traits such as `OptionOrd`. /// - Prevent some conflicting auto-implementation of traits on /// `Option`. pub trait OptionOperations {} impl OptionOperations for &T {} impl OptionOperations for &mut T {} #[macro_use] mod macros; impl_for_all!(OptionOperations); pub mod add; pub use add::{ OptionAdd, OptionAddAssign, OptionCheckedAdd, OptionOverflowingAdd, OptionSaturatingAdd, OptionWrappingAdd, }; pub mod error; pub use error::Error; pub mod div; pub use div::{ OptionCheckedDiv, OptionDiv, OptionDivAssign, OptionOverflowingDiv, OptionWrappingDiv, }; pub mod eq; pub use eq::OptionEq; pub mod min_max; pub use min_max::OptionMinMax; pub mod mul; pub use mul::{ OptionCheckedMul, OptionMul, OptionMulAssign, OptionOverflowingMul, OptionSaturatingMul, OptionWrappingMul, }; pub mod ord; pub use ord::OptionOrd; pub mod rem; pub use rem::{ OptionCheckedRem, OptionOverflowingRem, OptionRem, OptionRemAssign, OptionWrappingRem, }; pub mod sub; pub use sub::{ OptionCheckedSub, OptionOverflowingSub, OptionSaturatingSub, OptionSub, OptionSubAssign, OptionWrappingSub, }; pub mod prelude { pub use crate::add::{ OptionAdd, OptionAddAssign, OptionCheckedAdd, OptionOverflowingAdd, OptionSaturatingAdd, OptionWrappingAdd, }; pub use crate::div::{ OptionCheckedDiv, OptionDiv, OptionDivAssign, OptionOverflowingDiv, OptionWrappingDiv, }; pub use crate::eq::OptionEq; pub use crate::min_max::OptionMinMax; pub use crate::mul::{ OptionCheckedMul, OptionMul, OptionMulAssign, OptionOverflowingMul, OptionSaturatingMul, OptionWrappingMul, }; pub use crate::ord::OptionOrd; pub use crate::rem::{ OptionCheckedRem, OptionOverflowingRem, OptionRem, OptionRemAssign, OptionWrappingRem, }; pub use crate::sub::{ OptionCheckedSub, OptionOverflowingSub, OptionSaturatingSub, OptionSub, OptionSubAssign, OptionWrappingSub, }; pub use crate::OptionOperations; } option-operations-0.5.0/src/macros/impl_for.rs000064400000000000000000000031410072674642500175760ustar 00000000000000macro_rules! impl_for { ($trait:ident, $typ_:ty, $block:tt) => { impl $trait for $typ_ $block }; } macro_rules! impl_for_ints { ($trait:ident, $block:tt) => { impl_for!($trait, i8, $block); impl_for!($trait, i16, $block); impl_for!($trait, i32, $block); impl_for!($trait, i64, $block); impl_for!($trait, i128, $block); impl_for!($trait, u8, $block); impl_for!($trait, u16, $block); impl_for!($trait, u32, $block); impl_for!($trait, u64, $block); impl_for!($trait, u128, $block); }; } macro_rules! impl_for_floats { ($trait:ident, $block:tt) => { impl_for!($trait, f32, $block); impl_for!($trait, f64, $block); }; } macro_rules! impl_for_numerics { ($trait:ident, $block:tt) => { impl_for_ints!($trait, $block); impl_for_floats!($trait, $block); }; } macro_rules! impl_for_time_types { ($trait:ident, $block:tt) => { impl_for!($trait, core::time::Duration, $block); #[cfg(feature = "std")] impl_for!($trait, std::time::Instant, $block); #[cfg(feature = "std")] impl_for!($trait, std::time::SystemTime, $block); }; } macro_rules! impl_for_ints_and_duration { ($trait:ident, $block:tt) => { impl_for_ints!($trait, $block); impl_for!($trait, core::time::Duration, $block); }; } macro_rules! impl_for_all { ($trait:ident, $block:tt) => { impl_for_numerics!($trait, $block); impl_for_time_types!($trait, $block); }; ($trait:ident) => { impl_for_all!($trait, {}); }; } option-operations-0.5.0/src/macros/mod.rs000064400000000000000000000017460072674642500165570ustar 00000000000000#[macro_use] mod impl_for; #[macro_use] mod option_op; #[macro_use] mod option_op_assign; #[macro_use] mod option_op_checked; #[macro_use] mod option_op_overflowing; #[macro_use] mod option_op_saturating; #[macro_use] mod option_op_wrapping; macro_rules! common_option_op { ($trait:ident, $op:ident, $op_name:ident $(, $extra_doc:expr)? $(,)?) => { paste::paste! { option_op!( $trait, $op, $op_name, $($extra_doc)? ); option_op_assign!( $trait, $op, $op_name, $($extra_doc)? ); option_op_overflowing!( $trait, $op, $op_name, $($extra_doc)? ); option_op_wrapping!( $trait, $op, $op_name, $($extra_doc)? ); } }; } option-operations-0.5.0/src/macros/option_op.rs000064400000000000000000000100000072674642500177650ustar 00000000000000macro_rules! option_op { ($op_trait:ident, $op:ident, $op_name:ident $(, $extra_doc:expr)? $(,)?) => { paste::paste! { #[doc = "Trait for values and `Option`s " $op_name "."] /// /// Implementing this trait leads to the following auto-implementations: /// #[doc = "- `" [