condtype-1.3.0/.cargo_vcs_info.json0000644000000001360000000000100126620ustar { "git": { "sha1": "a4850f4f8e9eef4fc93f9b9050bc0c85fac1182a" }, "path_in_vcs": "" }condtype-1.3.0/.gitignore000064400000000000000000000030011046102023000134340ustar 00000000000000### Linux ### *~ # temporary files which can be created if a process still has a handle open of a deleted file .fuse_hidden* # KDE directory preferences .directory # Linux trash folder which might appear on any partition or disk .Trash-* # .nfs files are created when an open file is removed but is still being accessed .nfs* ### macOS ### # General .DS_Store .AppleDouble .LSOverride # Icon must end with two \r Icon # Thumbnails ._* # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk ### macOS Patch ### # iCloud generated files *.icloud ### Rust ### # Generated by Cargo # will have compiled files and executables debug/ target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk # MSVC Windows builds of rustc generate these, which store debugging information *.pdb ### Windows ### # Windows thumbnail cache files Thumbs.db Thumbs.db:encryptable ehthumbs.db ehthumbs_vista.db # Dump file *.stackdump # Folder config file [Dd]esktop.ini # Recycle Bin used on file shares $RECYCLE.BIN/ # Windows Installer files *.cab *.msi *.msix *.msm *.msp # Windows shortcuts *.lnk condtype-1.3.0/CHANGELOG.md000064400000000000000000000025451046102023000132710ustar 00000000000000# Changelog [![crates.io][crate-badge]][crate] All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog] and this project adheres to [Semantic Versioning]. ## [Unreleased] ## [1.3.0] - 2023-08-20 ### Added - `num` module containing conditional aliases to numeric types. ## [1.2.0] - 2023-05-09 ### Added - `if let` pattern matching in [`condval!`]. ## [1.1.0] - 2023-04-25 ### Added - [`condval!`] macro to construct [conditionally-typed][CondType] values. ## 1.0.0 - 2023-04-18 ### Added - [`CondType`][CondType] type alias that is determined by a boolean condition, just like [`std::conditional_t` in C++](https://en.cppreference.com/w/cpp/types/conditional). [crate]: https://crates.io/crates/condtype [crate-badge]: https://img.shields.io/crates/v/condtype.svg [Keep a Changelog]: http://keepachangelog.com/en/1.0.0/ [Semantic Versioning]: http://semver.org/spec/v2.0.0.html [Unreleased]: https://github.com/nvzqz/condtype/compare/v1.3.0...HEAD [1.3.0]: https://github.com/nvzqz/condtype/compare/v1.2.0...v1.3.0 [1.2.0]: https://github.com/nvzqz/condtype/compare/v1.1.0...v1.2.0 [1.1.0]: https://github.com/nvzqz/condtype/compare/v1.0.0...v1.1.0 [CondType]: https://docs.rs/condtype/latest/condtype/type.CondType.html [`condval!`]: https://docs.rs/condtype/latest/condtype/macro.condval.html condtype-1.3.0/Cargo.toml0000644000000020520000000000100106570ustar # 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.59.0" name = "condtype" version = "1.3.0" authors = ["Nikolai Vazquez"] description = "Choose types at compile-time via boolean constants." homepage = "https://github.com/nvzqz/condtype" documentation = "https://docs.rs/condtype" readme = "README.md" keywords = [ "boolean", "condition", "const", "depend", "type", ] categories = [ "no-std", "rust-patterns", ] license = "MIT OR Apache-2.0" repository = "https://github.com/nvzqz/condtype" [dev-dependencies.cfg-if] version = "1" [dev-dependencies.libc] version = "0.2.141" condtype-1.3.0/Cargo.toml.orig000064400000000000000000000011011046102023000143320ustar 00000000000000[package] name = "condtype" version = "1.3.0" edition = "2021" authors = ["Nikolai Vazquez"] license = "MIT OR Apache-2.0" description = "Choose types at compile-time via boolean constants." repository = "https://github.com/nvzqz/condtype" homepage = "https://github.com/nvzqz/condtype" documentation = "https://docs.rs/condtype" categories = ["no-std", "rust-patterns"] keywords = ["boolean", "condition", "const", "depend", "type"] readme = "README.md" # Const generics ordered before type generics. rust-version = "1.59.0" [dev-dependencies] libc = "0.2.141" cfg-if = "1" condtype-1.3.0/LICENSE-APACHE000064400000000000000000000261361046102023000134060ustar 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. condtype-1.3.0/LICENSE-MIT000064400000000000000000000020601046102023000131040ustar 00000000000000MIT License Copyright (c) 2023 Nikolai Vazquez 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. condtype-1.3.0/README.md000064400000000000000000000136551046102023000127430ustar 00000000000000# `condtype` [![docs.rs](https://img.shields.io/crates/v/condtype.svg?style=flat-square&label=docs&color=blue&logo=rust)](https://docs.rs/condtype) [![crates.io](https://img.shields.io/crates/d/condtype.svg?style=flat-square)](https://crates.io/crates/condtype) [![github](https://img.shields.io/github/stars/nvzqz/condtype.svg?style=flat-square&color=black)][github] Choose Rust types at compile-time via boolean constants, brought to you by [Nikolai Vazquez](https://hachyderm.io/@nikolai). If you find this library useful, consider [starring it][github] as well as [sponsoring](https://github.com/sponsors/nvzqz) or [donating once](https://paypal.me/nvzqz). 💖 [github]: https://github.com/nvzqz/condtype ## Conditional Typing The [`CondType`] type and [`condval!`] macro choose types at compile-time using [`bool`] constants, just like [`std::conditional_t` in C++](https://en.cppreference.com/w/cpp/types/conditional). Unlike the [`Either`] type, the type chosen by [`CondType`]/[`condval!`] is directly used, rather than wrapped with an [`enum`] type. This may be considered a form of [dependent typing](https://en.wikipedia.org/wiki/Dependent_type), but it is limited in ability and is restricted to compile-time constants rather than runtime values. ## `CondType` In the following example, [`CondType`] aliases either [`&str`] or [`i32`], depending on the boolean [generic constant][const-generics]: ```rust use condtype::CondType; let str: CondType = "hello"; let int: CondType = 42; // Unsized types are also supported: let str: &CondType = "world"; ``` ## `condval!` [`condval!`] enables choosing differently-typed values without specifying types. In the following example, `val` is inferred to be either [`&str`] or [`i32`], depending on `COND`. ```rust use condtype::condval; const COND: bool = true; let val = condval!(if COND { "hello" } else { 42 }); assert_eq!(val, "hello"); ``` `if let` pattern matching is also supported: ```rust use condtype::condval; const STR: Option<&str> = Some("hello"); let val = condval!(if let Some(str) = STR { str.to_uppercase() } else { 42 }); assert_eq!(val, "HELLO"); ``` ### Platform-Specific Types This library can make code for some platforms more efficient by using smaller-sized types, depending on platform-specific constants. In the following example, the `RlimOption` type can be either [Option]\<[rlim_t][resource.h]> or [`rlim_t`][resource.h] itself, where [`rlim_t::MAX`] can be treated as a sentinel value for [`Option::None`][None] if it is not equal to [`RLIM_INFINITY`][resource.h]. ```rust use condtype::{condval, CondType}; use libc::{rlim_t, RLIM_INFINITY}; const RLIM_INFINITY_IS_MAX: bool = RLIM_INFINITY == rlim_t::MAX; type RlimOption = CondType, rlim_t>; const RLIM_NONE: RlimOption = condval!(if RLIM_INFINITY_IS_MAX { None:: } else { rlim_t::MAX }); // Convert from either `RlimOption` type to `Option` via the `Into` trait: let rlim_none: Option = RLIM_NONE.into(); ``` Without this library, one could otherwise use [`cfg_if!`] to achieve the same goal. However, using [`#[cfg]`][cfg] requires maintaining a list of platforms and being more fine-grained if [`RLIM_INFINITY`][resource.h] is dependent on CPU architecture. ```rust use cfg_if::cfg_if; use libc::rlim_t; cfg_if! { // Platforms where `RLIM_INFINITY != rlim_t::MAX`: if #[cfg(any( target_os = "macos", target_os = "freebsd", target_os = "solaris", // ad nauseam... ))] { type RlimOption = rlim_t; const RLIM_NONE: RlimOption = rlim_t::MAX; } else { type RlimOption = Option; const RLIM_NONE: RlimOption = None; } } ``` ## Limitations It is currently not possible to use [`CondType`] or [`condval!`] with a [generic constant][const-generics] because [Rust does not yet consider trait implementations based on booleans to be exhaustive](https://github.com/rust-lang/project-const-generics/issues/26). Once that issue is resolved, all versions of this library should _just work_ with generic constants. ```rust,ignore fn generic() { let val: CondType = condval!(if B { "hello" } else { 42 }); } ``` ## Install This library is [available on crates.io](https://crates.io/crates/condtype) and can be used by running the following `cargo` command in your project directory: ```sh cargo add condtype ``` or by manually adding the following to your project's [`Cargo.toml`](https://doc.rust-lang.org/cargo/reference/manifest.html): ```toml [dependencies] condtype = "1.3.0" ``` ## License Like the Rust project, this library may be used under either the [MIT License](https://github.com/nvzqz/condtype/blob/main/LICENSE-MIT) or [Apache License (Version 2.0)](https://github.com/nvzqz/condtype/blob/main/LICENSE-APACHE). [`CondType`]: https://docs.rs/condtype/latest/condtype/type.CondType.html [`condval!`]: https://docs.rs/condtype/latest/condtype/macro.condval.html [`Either`]: https://docs.rs/either/latest/either/enum.Either.html [`cfg_if!`]: https://docs.rs/cfg-if/latest/cfg_if/macro.cfg_if.html [`const`]: https://doc.rust-lang.org/std/keyword.const.html [`enum`]: https://doc.rust-lang.org/std/keyword.enum.html [`bool`]: https://doc.rust-lang.org/std/primitive.bool.html [`i32`]: https://doc.rust-lang.org/std/primitive.i32.html [`&str`]: https://doc.rust-lang.org/std/primitive.str.html [Option]: https://doc.rust-lang.org/std/option/enum.Option.html [None]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None [cfg]: https://doc.rust-lang.org/rust-by-example/attribute/cfg.html [`rlim_t::MAX`]: https://doc.rust-lang.org/std/primitive.u64.html#associatedconstant.MAX [const-generics]: https://doc.rust-lang.org/reference/items/generics.html#const-generics [resource.h]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_resource.h.html condtype-1.3.0/src/lib.rs000064400000000000000000000224451046102023000133640ustar 00000000000000//! [`CondType`]: CondType //! [`condval!`]: condval //! [`bool`]: bool //! [`i32`]: i32 //! [`&str`]: str //! [`rlim_t::MAX`]: u64::MAX //! [Option]: Option //! [None]: None #![doc = include_str!("../README.md")] #![cfg_attr(not(doc), no_std)] #![warn(missing_docs)] pub mod num; /// [Conditionally aliases a type](crate#conditional-typing) using a [`bool`] /// constant. /// /// This is the Rust equivalent of [`std::conditional_t` in C++](https://en.cppreference.com/w/cpp/types/conditional). /// Unlike the [`Either`] type, the type chosen by `CondType` is aliased, rather /// than wrapped with an [`enum`] type. This may be considered a form of [dependent typing](https://en.wikipedia.org/wiki/Dependent_type), /// but it is limited in ability and is restricted to compile-time constants /// rather than runtime values. /// /// [`enum`]: https://doc.rust-lang.org/std/keyword.enum.html /// [`Either`]: https://docs.rs/either/latest/either/enum.Either.html /// /// # Examples /// /// In the following example, `CondType` aliases [`&str`](str) or [`i32`]: /// /// ``` /// use condtype::CondType; /// /// let str: CondType = "hello"; /// let int: CondType = 42; /// ``` /// /// This can also alias \![Sized] types: /// /// ``` /// # use condtype::CondType; /// type T = CondType; /// /// let val: &T = "world"; /// ``` /// /// Rather than assign a value by knowing the condition, this can be used with /// [`condval!`] to choose a value based on the same condition: /// /// ``` /// # use condtype::*; /// const COND: bool = // ... /// # true; /// /// let val: CondType = condval!(if COND { /// "hello" /// } else { /// 42 /// }); /// ``` pub type CondType = as imp::AssocType>::Type; /// Instantiates a [conditionally-typed](crate#conditional-typing) value. /// /// Attempting to return different types from [`if`]/[`else`] is not normally /// possible since both branches must produce the same type: /// /// ```compile_fail /// let val = if true { "hello" } else { 42 }; /// ``` /// /// This macro enables returning different types by making the type be /// conditional on a [`const`] [`bool`]: /// /// ``` /// use condtype::condval; /// /// let val: &str = condval!(if true { "hello" } else { 42 }); /// let val: i32 = condval!(if false { "hello" } else { 42 }); /// ``` /// /// # Performance /// /// This macro uses a pattern called ["TT munching"](https://veykril.github.io/tlborm/decl-macros/patterns/tt-muncher.html) /// to parse the [`if`] condition expression. Compile times for TT munchers are /// quadratic relative to the input length, so an expression like `!!!!!!!COND` /// will compile slightly slower than `!COND` because it recurses 6 more times. /// /// This can be mitigated by: /// - Moving all logic in the [`if`] condition to a separate [`const`]. /// - Wrapping the logic in a block, e.g. `{ !true && !false }`. /// /// # Examples /// /// Given two conditions, the following code will construct either a /// [`&str`](str), [`i32`], or [`Vec`]: /// /// ``` /// # use condtype::condval; /// const COND1: bool = // ... /// # true; /// const COND2: bool = // ... /// # true; /// /// let str = "hello"; /// let int = 42; /// let vec = vec![1, 2, 3]; /// /// let val = condval!(if COND1 { /// str /// } else if COND2 { /// int /// } else { /// vec /// }); /// ``` /// /// `if let` pattern matching is also supported: /// /// ``` /// # use condtype::*; /// const STR: Option<&str> = // ... /// # None; /// /// let val = condval!(if let Some(str) = STR { /// str.to_uppercase() /// } else { /// 42 /// }); /// ``` /// /// This macro can be used with [`CondType`] to construct [`const`] values: /// /// ``` /// use condtype::{condval, CondType}; /// /// const COND: bool = // ... /// # true; /// /// const VAL: CondType = condval!(if COND { /// "hello" /// } else { /// 42 /// }); /// ``` /// /// Each branch is lazily evaluated, so there are no effects from unvisited /// branches: /// /// ``` /// # use condtype::*; /// let x; /// /// let val = condval!(if true { /// x = 10; /// "hello" /// } else { /// x = 50; /// 42 /// }); /// /// assert_eq!(x, 10); /// assert_eq!(val, "hello"); /// ``` /// /// Branch conditions can be any [`bool`] expression. However, see /// [performance advice](#performance). /// /// ``` /// # use condtype::*; /// let val = condval!(if !true && !false { /// "hello" /// } else { /// 42 /// }); /// /// assert_eq!(val, 42); /// ``` /// /// Assigning an incorrect type will cause a compile failure: /// /// ```compile_fail /// # use condtype::*; /// let val: bool = condval!(if true { /// "hello" /// } else { /// 42 /// }); /// ``` /// /// Attempting to reuse a non-[`Copy`] value from either branch will cause a /// compile failure, because it has been moved into that branch and can thus no /// longer be used in the outer context: /// /// ```compile_fail /// # use condtype::*; /// let int = 42; /// let vec = vec![1, 2, 3]; /// /// let val = condval!(if true { /// int /// } else { /// vec /// }); /// /// println!("{:?}", vec); /// ``` /// /// [`const`]: https://doc.rust-lang.org/std/keyword.const.html /// [`else`]: https://doc.rust-lang.org/std/keyword.else.html /// [`if`]: https://doc.rust-lang.org/std/keyword.if.html #[macro_export] macro_rules! condval { (if let $pat:pat = $input:block $then:block else $else:block) => { $crate::condval!(if { #[allow(unused_variables)] { ::core::matches!($input, $pat) } } { if let $pat = $input $then else { ::core::unreachable!() } } else $else) }; (if let $pat:pat = $input:block $then:block else $($else:tt)+) => { $crate::condval!(if let $pat = $input $then else { $crate::condval!($($else)+) }) }; (if let $pat:pat = $($rest:tt)*) => { $crate::__condval_let_parser!($pat, [] $($rest)*) }; (if $cond:block $then:block else $else:block) => { match <() as $crate::__private::If<$cond, _, _>>::PROOF { $crate::__private::EitherTypeEq::Left(te) => te.coerce($then), $crate::__private::EitherTypeEq::Right(te) => te.coerce($else), } }; (if $cond:block $then:block else $($else:tt)+) => { $crate::condval!(if $cond $then else { $crate::condval!($($else)+) }) }; (if $($rest:tt)*) => { $crate::__condval_parser!([] $($rest)*) }; } /// Helps `condval!` parse any `if` condition expression by accumulating tokens. #[doc(hidden)] #[macro_export] macro_rules! __condval_parser { ([$($cond:tt)+] $then:block else $($else:tt)+) => { $crate::condval!(if { $($cond)+ } $then else $($else)+) }; ([$($cond:tt)*] $next:tt $($rest:tt)*) => { $crate::__condval_parser!([$($cond)* $next] $($rest)*) }; } /// Helps `condval!` parse any `if let` input expression by accumulating tokens. #[doc(hidden)] #[macro_export] macro_rules! __condval_let_parser { ($pat:pat, [$($input:tt)+] $then:block else $($else:tt)+) => { $crate::condval!(if let $pat = { $($input)+ } $then else $($else)+) }; ($pat:pat, [$($input:tt)*] $next:tt $($rest:tt)*) => { $crate::__condval_let_parser!($pat, [$($input)* $next] $($rest)*) }; } /// Pseudo-public implementation details for `condval!`. #[doc(hidden)] pub mod __private { use crate::imp::TypeEq; pub enum EitherTypeEq { Left(TypeEq), Right(TypeEq), } pub trait If { type Chosen; const PROOF: EitherTypeEq; } impl If for () { type Chosen = T; const PROOF: EitherTypeEq = EitherTypeEq::Left(TypeEq::NEW); } impl If for () { type Chosen = F; const PROOF: EitherTypeEq = EitherTypeEq::Right(TypeEq::NEW); } } /// Public-in-private implementation details. mod imp { use core::{marker::PhantomData, mem::ManuallyDrop}; pub struct CondType( // `CondType` is covariant over `T` and `F`. PhantomData, PhantomData, ); pub trait AssocType { type Type: ?Sized; } impl AssocType for CondType { type Type = F; } impl AssocType for CondType { type Type = T; } #[allow(clippy::type_complexity)] pub struct TypeEq( PhantomData<( // `TypeEq` is invariant over `T` and `U`. fn(T) -> T, fn(U) -> U, )>, ); impl TypeEq { pub const NEW: Self = TypeEq(PhantomData); } impl TypeEq { pub const fn coerce(self, from: T) -> U { #[repr(C)] union Transmuter { from: ManuallyDrop, into: ManuallyDrop, } // SAFETY: `TypeEq` instances can only be constructed if `T` and `U` // are the same type. unsafe { ManuallyDrop::into_inner( Transmuter { from: ManuallyDrop::new(from), } .into, ) } } } } condtype-1.3.0/src/num.rs000064400000000000000000000074201046102023000134110ustar 00000000000000//! Conditional aliases to numeric types. //! //! # Examples //! //! ``` //! use std::fs::File; //! use condtype::num::Usize64; //! //! fn handle_throughput(bytes: Usize64) { //! // ... //! } //! //! // usize //! let s: &str = // ... //! # ""; //! handle_throughput(s.len() as Usize64); //! //! // u64 //! # fn file() -> std::io::Result<()> { //! let f: File = // ... //! # panic!(); //! handle_throughput(f.metadata()?.len() as Usize64); //! # Ok(()) } //! ``` //! //! # Pitfalls //! //! Because these are type aliases, some operations may happen to work for the //! current target but not for other targets. //! //! The following example handles [`Usize32`] explicitly as [`usize`] or [`u32`] //! depending on whether the platform is 64-bit or 32-bit: //! //! ``` //! # use condtype::num::Usize32; //! #[cfg(target_pointer_width = "64")] //! let x: Usize32 = usize::MAX; //! //! #[cfg(target_pointer_width = "32")] //! let x: Usize32 = u32::MAX; //! ``` //! //! Instead, the code should be made portable by using an `as` cast: //! //! ``` //! # use condtype::num::Usize32; //! let x: Usize32 = usize::MAX as Usize32; //! ``` use core::mem::size_of; use crate::CondType; /// Conditional alias to the larger of two types. macro_rules! max_ty { ($a:ty, $b:ty) => { CondType<{ size_of::<$a>() > size_of::<$b>() }, $a, $b> }; } /// A signed integer that is convertible from [`isize`] and [`i8`]–[`i16`]. /// /// The integer is guaranteed to be at least [`isize`] large and [`i16`] small. pub type Isize16 = max_ty!(isize, i16); /// A signed integer that is convertible from [`isize`] and [`i8`]–[`i32`]. /// /// The integer is guaranteed to be at least [`isize`] large and [`i32`] small. pub type Isize32 = max_ty!(isize, i32); /// A signed integer that is convertible from [`isize`] and [`i8`]–[`i64`]. /// /// The integer is guaranteed to be at least [`isize`] large and [`i64`] small. pub type Isize64 = max_ty!(isize, i64); /// A signed integer that is convertible from [`isize`] and [`i8`]–[`i128`]. /// /// The integer is guaranteed to be at least [`isize`] large and [`i128`] small. pub type Isize128 = max_ty!(isize, i128); /// An unsigned integer that is convertible from [`usize`] and [`u8`]–[`u16`]. /// /// The integer is guaranteed to be at least [`usize`] large and [`u16`] small. pub type Usize16 = max_ty!(usize, u16); /// An unsigned integer that is convertible from [`usize`] and [`u8`]–[`u32`]. /// /// The integer is guaranteed to be at least [`usize`] large and [`u32`] small. pub type Usize32 = max_ty!(usize, u32); /// An unsigned integer that is convertible from [`usize`] and [`u8`]–[`u64`]. /// /// The integer is guaranteed to be at least [`usize`] large and [`u64`] small. pub type Usize64 = max_ty!(usize, u64); /// An unsigned integer that is convertible from [`usize`] and [`u8`]–[`u128`]. /// /// The integer is guaranteed to be at least [`usize`] large and [`u128`] small. pub type Usize128 = max_ty!(usize, u128); #[cfg(test)] mod tests { use core::any::{type_name, TypeId}; use super::*; #[test] fn expected_type() { macro_rules! assert_eq_ty { ($a:ty, $b:ty) => { assert_eq!( TypeId::of::<$a>(), TypeId::of::<$b>(), "{} != {}", type_name::<$a>(), type_name::<$b>() ); }; } #[cfg(target_pointer_width = "32")] assert_eq_ty!(Usize32, u32); #[cfg(target_pointer_width = "64")] assert_eq_ty!(Usize32, usize); #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] assert_eq_ty!(Usize64, u64); #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] assert_eq_ty!(Usize128, u128); } } condtype-1.3.0/tests/condval.rs000064400000000000000000000061611046102023000146140ustar 00000000000000#![forbid(unsafe_code)] use condtype::*; #[test] fn condval_true() { let x = condval!(if true { "a" } else { 1 }); assert_eq!(x, "a"); } #[test] fn condval_false() { let x = condval!(if false { "a" } else { 1 }); assert_eq!(x, 1); } #[test] fn condval_const() { pub const COND: bool = false; let x = condval!(if COND { "a" } else { 1 }); assert_eq!(x, 1); } #[test] fn condval_path() { mod cond { pub const COND: bool = false; } let x = condval!(if cond::COND { "a" } else { 1 }); assert_eq!(x, 1); } #[test] fn condval_not_true() { let x = condval!(if !true { "a" } else { 1 }); assert_eq!(x, 1); } #[test] fn condval_and() { let x = condval!(if true && false { "a" } else { 1 }); assert_eq!(x, 1); } #[test] fn condval_paren() { #[allow(unused_parens)] let x = condval!(if (true && false) { "a" } else { 1 }); assert_eq!(x, 1); } #[test] fn condval_struct_method() { struct Foo {} impl Foo { const fn foo(self) -> bool { false } } // Although this expression isn't allowed in normal `if`, we opt to parse // any condition expressions. let x = condval!(if Foo {}.foo() { "a" } else { 1 }); assert_eq!(x, 1); } #[test] fn condval_hygiene() { // "te" is used by the `match` in `condval!`. let te = 1; let x = condval!(if false { "a" } else { te }); assert_eq!(x, 1); } #[test] fn condval_empty() { let _: () = condval!(if true { } else { 1 }); let _: () = condval!(if false { "a" } else { }); let _: () = condval!(if false { "a" } else if false { 1 } else { }); } #[test] fn condval_else_if1() { let x = condval!(if true { "a" } else if false { 1 } else { 42.0 }); assert_eq!(x, "a"); } #[test] fn condval_else_if2() { let x = condval!(if false { "a" } else if false { 1 } else { 42.0 }); assert_eq!(x, 42.0); } #[test] fn condval_else_if3() { let x = condval!(if false { "a" } else if false { 1 } else if true { 42.0 } else { [1, 2, 3] }); assert_eq!(x, 42.0); } #[test] fn condval_else_if4() { let x = condval!(if false { "a" } else if false { 1 } else if false { 42.0 } else { [1, 2, 3] }); assert_eq!(x, [1, 2, 3]); } #[test] fn condval_let1() { const VAL: Option<&str> = Some("a"); let x = condval!(if let Some(val) = VAL { val } else { 1 }); assert_eq!(x, "a"); } #[test] fn condval_let2() { const VAL1: Option = None; const VAL2: Option<&str> = Some("a"); let x = condval!(if let Some(val1) = VAL1 { val1 } else if let Some(val2) = VAL2 { val2 } else { 42.0 }); assert_eq!(x, "a"); } #[test] fn condval_let3() { const VAL1: Option = None; const VAL2: Option<&str> = None; let x = condval!(if let Some(val1) = VAL1 { val1 } else if let Some(val2) = VAL2 { val2 } else { 42.0 }); assert_eq!(x, 42.0); }