easy-cast-0.4.4/.cargo_vcs_info.json0000644000000001120000000000000127230ustar { "git": { "sha1": "051c50ff749ba16b80b4d9d48d378c412ed154d8" } } easy-cast-0.4.4/.github/workflows/test.yml000064400000000000000000000022570000000000000166040ustar 00000000000000name: Tests on: push: branches: [ master ] pull_request: branches: [ master ] jobs: fmt-and-test: name: Test and check formatting runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: beta override: true components: rustfmt - name: Rustfmt check uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check - name: Test run: | cargo test cargo test --all-features cargo test --no-default-features cargo test --no-default-features --features libm test: name: Test MSRV runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: "1.32.0" override: true - name: Test run: | cargo test cargo test --all-features cargo test --no-default-features cargo test --no-default-features --features libm easy-cast-0.4.4/.gitignore000064400000000000000000000000230000000000000134620ustar 00000000000000/target Cargo.lock easy-cast-0.4.4/CHANGELOG.md000064400000000000000000000017430000000000000133150ustar 00000000000000Changelog ========= ## [0.4.4] — 2021-04-12 - Fix negative int to float digits check (#18) ## [0.4.3] — 2021-04-12 - Unify some macros via `impl_int_generic` (#16) - Improve error messages in asserts (#17) ## [0.4.2] — 2021-04-03 - Fix `i16::conv(1usize)` (#15) - Update README (#15) ## [0.4.1] — 2021-04-01 - Fix `conv(0)` from int to float (#14) ## [0.4.0] — 2021-04-01 - Add `try_conv` and `try_cast` methods (#12) - Add `try_conv_nearest` etc. (#12) - Removed `Conv for f32` (#12) - Replaced `assert_range` and `assert_non_neg` with `assert_int` (#12) - MSRV is 1.32.0 (#12) ## [0.3.0] — 2021-03-29 - Add `conv_trunc` / `cast_trunc` (#11) - Explicitly support Rust 1.36.0 (and potentially older; #10) - Support `no_std` (#10) - Fix rounding for `floor` on negative values (#10) ## [0.2.0] — 2021-03-20 - Add feature flags controlling assert behaviour - Remove restrictions on isize/usize (#6) - Fix bad revert checks (#6) easy-cast-0.4.4/COPYRIGHT000064400000000000000000000002640000000000000127740ustar 00000000000000This work, the KAS project including the kas and kas-macros libraries, is copyrighted by the following contributors: Diggory Hardy This list may be incomplete. easy-cast-0.4.4/Cargo.toml0000644000000020470000000000000107320ustar # 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "easy-cast" version = "0.4.4" authors = ["Diggory Hardy "] description = "Type conversions which are expected to succeed" documentation = "https://docs.rs/easy-cast/" readme = "README.md" keywords = ["cast", "into", "from", "conversion"] license = "Apache-2.0" repository = "https://github.com/kas-gui/easy-cast" [dependencies.libm] version = "0.2.1" optional = true [features] always_assert = ["assert_float", "assert_int"] assert_float = [] assert_int = [] default = ["std"] std = [] easy-cast-0.4.4/Cargo.toml.orig000064400000000000000000000016020000000000000143650ustar 00000000000000[package] name = "easy-cast" version = "0.4.4" authors = ["Diggory Hardy "] edition = "2018" license = "Apache-2.0" description = "Type conversions which are expected to succeed" readme = "README.md" documentation = "https://docs.rs/easy-cast/" keywords = ["cast", "into", "from", "conversion"] repository = "https://github.com/kas-gui/easy-cast" [features] default = ["std"] # Without std, float conversions are disabled (unless libm is used) std = [] # Note: assertions are always used in debug builds; these only affect release builds: # Always use all assertions always_assert = ["assert_float", "assert_int"] # Always assert when converting from floating-point types assert_float = [] # Always assert when converting from integer types assert_int = [] [dependencies.libm] # libm may be used instead of std to provide float conversions version = "0.2.1" optional = true easy-cast-0.4.4/LICENSE000064400000000000000000000251370000000000000125140ustar 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. easy-cast-0.4.4/README.md000064400000000000000000000076030000000000000127640ustar 00000000000000Easy-cast ========= [![Test Status](https://github.com/kas-gui/easy-cast/workflows/Tests/badge.svg?event=push)](https://github.com/kas-gui/easy-cast/actions) [![Docs](https://docs.rs/easy-cast/badge.svg)](https://docs.rs/easy-cast) Type conversion, success expected This library is written to make numeric type conversions easy. Such conversions usually fall into one of the following cases: - the conversion must preserve values exactly (use [`From`] or [`Into`] or [`Conv`] or [`Cast`]) - the conversion is expected to preserve values exactly, though this is not ensured by the types in question (use [`Conv`] or [`Cast`]) - the conversion could fail and must be checked at run-time (use [`TryFrom`] or [`TryInto`] or [`Conv::try_conv`] or [`Cast::try_cast`]) - the conversion is from floating point values to integers and should round to the "nearest" integer (use [`ConvFloat`] or [`CastFloat`]) - the conversion is from `f32` to `f64` or vice-versa; in this case use of `as f32` / `as f64` is likely acceptable since `f32` has special representations for non-finite values and conversion to `f64` is exact - truncating conversion (modular arithmetic) is desired; in this case `as` probably does exactly what you want - saturating conversion is desired (less common; not supported here) If you are wondering "why not just use `as`", there are a few reasons: - integer conversions may silently truncate - integer conversions to/from signed types silently reinterpret - prior to Rust 1.45.0 float-to-int conversions were not fully defined; since this version they use saturating conversion (NaN converts to 0) - you want some assurance (at least in debug builds) that the conversion will preserve values correctly without having to proof-read code When should you *not* use this library? - Only numeric conversions are supported - Conversions from floats do not provide fine control of rounding modes - This library has not been thoroughly tested correctness [`From`]: https://doc.rust-lang.org/stable/std/convert/trait.From.html [`Into`]: https://doc.rust-lang.org/stable/std/convert/trait.Into.html [`TryFrom`]: https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html [`TryInto`]: https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html [`Conv`]: https://docs.rs/easy-cast/latest/easy_cast/trait.Conv.html [`Cast`]: https://docs.rs/easy-cast/latest/easy_cast/trait.Cast.html [`Conv::try_conv`]: https://docs.rs/easy-cast/latest/easy_cast/trait.Conv.html#tymethod.try_conv [`Conv::try_cast`]: https://docs.rs/easy-cast/latest/easy_cast/trait.Conv.html#tymethod.try_cast [`ConvFloat`]: https://docs.rs/easy-cast/latest/easy_cast/trait.ConvFloat.html [`CastFloat`]: https://docs.rs/easy-cast/latest/easy_cast/trait.CastFloat.html ## Assertions All type conversions which are potentially fallible assert on failure in debug builds. In release builds assertions may be omitted, thus making incorrect conversions possible. If the `always_assert` feature flag is set, assertions will be turned on in all builds. Some additional feature flags are available for finer-grained control (see [Cargo.toml](Cargo.toml)). ## MSRV and no_std The Minumum Supported Rust Version is 1.32.0 (first release of Edition 2018). By default, `std` support is required. With default features disabled `no_std` is supported, but the `ConvFloat` and `CastFloat` traits are unavailable. Enabling the `libm` feature will re-enable these traits. Copyright and Licence ------- The [COPYRIGHT](COPYRIGHT) file includes a list of contributors who claim copyright on this project. This list may be incomplete; new contributors may optionally add themselves to this list. The easy-cast library is published under the terms of the Apache License, Version 2.0. You may obtain a copy of this licence from the [LICENSE](LICENSE) file or on the following webpage: easy-cast-0.4.4/src/lib.rs000064400000000000000000000742750000000000000134210ustar 00000000000000// 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 in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! Type conversion, success expected //! //! This library is written to make numeric type conversions easy. Such //! conversions usually fall into one of the following cases: //! //! - the conversion must preserve values exactly (use [`From`] or [`Into`] //! or [`Conv`] or [`Cast`]) //! - the conversion is expected to preserve values exactly, though this is //! not ensured by the types in question (use [`Conv`] or [`Cast`]) //! - the conversion could fail and must be checked at run-time (use //! [`TryFrom`] or [`TryInto`] or [`Conv::try_conv`] or [`Cast::try_cast`]) //! - the conversion is from floating point values to integers and should //! round to the "nearest" integer (use [`ConvFloat`] or [`CastFloat`]) //! - the conversion is from `f32` to `f64` or vice-versa; in this case use of //! `as f32` / `as f64` is likely acceptable since `f32` has special //! representations for non-finite values and conversion to `f64` is exact //! - truncating conversion (modular arithmetic) is desired; in this case `as` //! probably does exactly what you want //! - saturating conversion is desired (less common; not supported here) //! //! If you are wondering "why not just use `as`", there are a few reasons: //! //! - integer conversions may silently truncate //! - integer conversions to/from signed types silently reinterpret //! - prior to Rust 1.45.0 float-to-int conversions were not fully defined; //! since this version they use saturating conversion (NaN converts to 0) //! - you want some assurance (at least in debug builds) that the conversion //! will preserve values correctly without having to proof-read code //! //! When should you *not* use this library? //! //! - Only numeric conversions are supported //! - Conversions from floats do not provide fine control of rounding modes //! - This library has not been thoroughly tested correctness //! //! ## Assertions //! //! All type conversions which are potentially fallible assert on failure in //! debug builds. In release builds assertions may be omitted, thus making //! incorrect conversions possible. //! //! If the `always_assert` feature flag is set, assertions will be turned on in //! all builds. Some additional feature flags are available for finer-grained //! control (see `Cargo.toml`). //! //! ## no_std support //! //! When the crate's default features are disabled (and `std` is not enabled) //! then the library supports `no_std`. In this case, [`ConvFloat`] and //! [`CastFloat`] are only available if the `libm` optional dependency is //! enabled. //! //! [`TryFrom`]: core::convert::TryFrom //! [`TryInto`]: core::convert::TryInto #![deny(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(doc_cfg, feature(doc_cfg))] use core::mem::size_of; /// Error types for conversions #[derive(Clone, Debug, PartialEq, Eq)] pub enum Error { /// Source value lies outside of target type's range Range, /// Loss of precision and/or outside of target type's range Inexact, } #[cfg(feature = "std")] impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "cast conversion: {}", match self { Error::Range => "source value not in target range", Error::Inexact => "loss of precision or range error", } ) } } #[cfg(feature = "std")] impl std::error::Error for Error {} /// Like [`From`], but supporting potentially-fallible conversions /// /// This trait is intended to replace *many* uses of the `as` keyword for /// numeric conversions, though not all. /// Conversions from floating-point types are excluded since it is very easy to /// (accidentally) produce non-integer values; instead use [`ConvFloat`]. /// /// Two methods are provided: /// /// - [`Conv::conv`] is for "success expected" conversions. In debug builds /// and when using the `always_assert` feature flag, inexact conversions /// will panic. In other cases, conversions may produce incorrect values /// (according to the behaviour of `as`). This is similar to the behviour of /// Rust's overflow checks on integer arithmetic, and intended for usage /// when the user is "reasonably sure" that conversion will succeed. /// - [`Conv::try_conv`] is for fallible conversions, and always produces an /// error if the conversion would be inexact. pub trait Conv: Sized { /// Convert from `T` to `Self` fn conv(v: T) -> Self; /// Try converting from `T` to `Self` fn try_conv(v: T) -> Result; } impl Conv for T { #[inline] fn conv(v: T) -> Self { v } #[inline] fn try_conv(v: T) -> Result { Ok(v) } } macro_rules! impl_via_from { ($x:ty: $y:ty) => { impl Conv<$x> for $y { #[inline] fn conv(x: $x) -> $y { <$y>::from(x) } #[inline] fn try_conv(x: $x) -> Result { Ok(<$y>::from(x)) } } }; ($x:ty: $y:ty, $($yy:ty),+) => { impl_via_from!($x: $y); impl_via_from!($x: $($yy),+); }; } impl_via_from!(f32: f64); impl_via_from!(i8: f32, f64, i16, i32, i64, i128); impl_via_from!(i16: f32, f64, i32, i64, i128); impl_via_from!(i32: f64, i64, i128); impl_via_from!(i64: i128); impl_via_from!(u8: f32, f64, i16, i32, i64, i128); impl_via_from!(u8: u16, u32, u64, u128); impl_via_from!(u16: f32, f64, i32, i64, i128, u32, u64, u128); impl_via_from!(u32: f64, i64, i128, u64, u128); impl_via_from!(u64: i128, u128); macro_rules! impl_via_as_neg_check { ($x:ty: $y:ty) => { impl Conv<$x> for $y { #[inline] fn conv(x: $x) -> $y { #[cfg(any(debug_assertions, feature = "assert_int"))] assert!( x >= 0, "cast x: {} to {}: expected x >= 0, found x = {}", stringify!($x), stringify!($y), x ); x as $y } #[inline] fn try_conv(x: $x) -> Result { if x >= 0 { Ok(x as $y) } else { Err(Error::Range) } } } }; ($x:ty: $y:ty, $($yy:ty),+) => { impl_via_as_neg_check!($x: $y); impl_via_as_neg_check!($x: $($yy),+); }; } impl_via_as_neg_check!(i8: u8, u16, u32, u64, u128); impl_via_as_neg_check!(i16: u16, u32, u64, u128); impl_via_as_neg_check!(i32: u32, u64, u128); impl_via_as_neg_check!(i64: u64, u128); impl_via_as_neg_check!(i128: u128); // Assumption: $y::MAX is representable as $x macro_rules! impl_via_as_max_check { ($x:ty: $y:tt) => { impl Conv<$x> for $y { #[inline] fn conv(x: $x) -> $y { #[cfg(any(debug_assertions, feature = "assert_int"))] assert!( x <= core::$y::MAX as $x, "cast x: {} to {}: expected x <= {}, found x = {}", stringify!($x), stringify!($y), core::$y::MAX, x ); x as $y } #[inline] fn try_conv(x: $x) -> Result { if x <= core::$y::MAX as $x { Ok(x as $y) } else { Err(Error::Range) } } } }; ($x:ty: $y:tt, $($yy:tt),+) => { impl_via_as_max_check!($x: $y); impl_via_as_max_check!($x: $($yy),+); }; } impl_via_as_max_check!(u8: i8); impl_via_as_max_check!(u16: i8, i16, u8); impl_via_as_max_check!(u32: i8, i16, i32, u8, u16); impl_via_as_max_check!(u64: i8, i16, i32, i64, u8, u16, u32); impl_via_as_max_check!(u128: i8, i16, i32, i64, i128); impl_via_as_max_check!(u128: u8, u16, u32, u64); // Assumption: $y::MAX and $y::MIN are representable as $x macro_rules! impl_via_as_range_check { ($x:ty: $y:tt) => { impl Conv<$x> for $y { #[inline] fn conv(x: $x) -> $y { #[cfg(any(debug_assertions, feature = "assert_int"))] assert!( core::$y::MIN as $x <= x && x <= core::$y::MAX as $x, "cast x: {} to {}: expected {} <= x <= {}, found x = {}", stringify!($x), stringify!($y), core::$y::MIN, core::$y::MAX, x ); x as $y } #[inline] fn try_conv(x: $x) -> Result { if core::$y::MIN as $x <= x && x <= core::$y::MAX as $x { Ok(x as $y) } else { Err(Error::Range) } } } }; ($x:ty: $y:tt, $($yy:tt),+) => { impl_via_as_range_check!($x: $y); impl_via_as_range_check!($x: $($yy),+); }; } impl_via_as_range_check!(i16: i8, u8); impl_via_as_range_check!(i32: i8, i16, u8, u16); impl_via_as_range_check!(i64: i8, i16, i32, u8, u16, u32); impl_via_as_range_check!(i128: i8, i16, i32, i64, u8, u16, u32, u64); macro_rules! impl_int_generic { ($x:tt: $y:tt) => { impl Conv<$x> for $y { #[allow(unused_comparisons)] #[inline] fn conv(x: $x) -> $y { let src_is_signed = core::$x::MIN != 0; let dst_is_signed = core::$y::MIN != 0; if size_of::<$x>() < size_of::<$y>() { if !dst_is_signed { #[cfg(any(debug_assertions, feature = "assert_int"))] assert!( x >= 0, "cast x: {} to {}: expected x >= 0, found x = {}", stringify!($x), stringify!($y), x ); } } else if size_of::<$x>() == size_of::<$y>() { if dst_is_signed { #[cfg(any(debug_assertions, feature = "assert_int"))] assert!( x <= core::$y::MAX as $x, "cast x: {} to {}: expected x <= {}, found x = {}", stringify!($x), stringify!($y), core::$y::MAX, x ); } else if src_is_signed { #[cfg(any(debug_assertions, feature = "assert_int"))] assert!( x >= 0, "cast x: {} to {}: expected x >= 0, found x = {}", stringify!($x), stringify!($y), x ); } } else { // src size > dst size if src_is_signed { #[cfg(any(debug_assertions, feature = "assert_int"))] assert!( core::$y::MIN as $x <= x && x <= core::$y::MAX as $x, "cast x: {} to {}: expected {} <= x <= {}, found x = {}", stringify!($x), stringify!($y), core::$y::MIN, core::$y::MAX, x ); } else { #[cfg(any(debug_assertions, feature = "assert_int"))] assert!( x <= core::$y::MAX as $x, "cast x: {} to {}: expected x <= {}, found x = {}", stringify!($x), stringify!($y), core::$y::MAX, x ); } } x as $y } #[allow(unused_comparisons)] #[inline] fn try_conv(x: $x) -> Result { let src_is_signed = core::$x::MIN != 0; let dst_is_signed = core::$y::MIN != 0; if size_of::<$x>() < size_of::<$y>() { if dst_is_signed || x >= 0 { return Ok(x as $y); } } else if size_of::<$x>() == size_of::<$y>() { if dst_is_signed { if x <= core::$y::MAX as $x { return Ok(x as $y); } } else if src_is_signed { if x >= 0 { return Ok(x as $y); } } else { // types are identical (e.g. usize == u64) return Ok(x as $y); } } else { // src size > dst size if src_is_signed { if core::$y::MIN as $x <= x && x <= core::$y::MAX as $x { return Ok(x as $y); } } else { if x <= core::$y::MAX as $x { return Ok(x as $y); } } } Err(Error::Range) } } }; ($x:tt: $y:tt, $($yy:tt),+) => { impl_int_generic!($x: $y); impl_int_generic!($x: $($yy),+); }; } impl_int_generic!(i8: isize, usize); impl_int_generic!(i16: isize, usize); impl_int_generic!(i32: isize, usize); impl_int_generic!(i64: isize, usize); impl_int_generic!(i128: isize, usize); impl_int_generic!(u8: isize, usize); impl_int_generic!(u16: isize, usize); impl_int_generic!(u32: isize, usize); impl_int_generic!(u64: isize, usize); impl_int_generic!(u128: isize, usize); impl_int_generic!(isize: i8, i16, i32, i64, i128); impl_int_generic!(usize: i8, i16, i32, i64, i128, isize); impl_int_generic!(isize: u8, u16, u32, u64, u128, usize); impl_int_generic!(usize: u8, u16, u32, u64, u128); macro_rules! impl_via_digits_check { ($x:ty: $y:tt) => { impl Conv<$x> for $y { #[inline] fn conv(x: $x) -> Self { if cfg!(any(debug_assertions, feature = "assert_digits")) { Self::try_conv(x).unwrap_or_else(|_| { panic!( "cast x: {} to {}: inexact for x = {}", stringify!($x), stringify!($y), x ) }) } else { x as $y } } #[inline] fn try_conv(x: $x) -> Result { let src_ty_bits = (size_of::<$x>() * 8) as u32; let src_digits = src_ty_bits.saturating_sub(x.leading_zeros() + x.trailing_zeros()); let dst_digits = core::$y::MANTISSA_DIGITS; if src_digits <= dst_digits { Ok(x as $y) } else { Err(Error::Inexact) } } } }; ($x:ty: $y:tt, $($yy:tt),+) => { impl_via_digits_check!($x: $y); impl_via_digits_check!($x: $($yy),+); }; } macro_rules! impl_via_digits_check_signed { ($x:ty: $y:tt) => { impl Conv<$x> for $y { #[inline] fn conv(x: $x) -> Self { if cfg!(any(debug_assertions, feature = "assert_digits")) { Self::try_conv(x).unwrap_or_else(|_| { panic!( "cast x: {} to {}: inexact for x = {}", stringify!($x), stringify!($y), x ) }) } else { x as $y } } #[inline] fn try_conv(x: $x) -> Result { let src_ty_bits = (size_of::<$x>() * 8) as u32; let src_digits = x.checked_abs() .map(|y| src_ty_bits.saturating_sub(y.leading_zeros() + y.trailing_zeros())) .unwrap_or(1 /*MIN has one binary digit in float repr*/); let dst_digits = core::$y::MANTISSA_DIGITS; if src_digits <= dst_digits { Ok(x as $y) } else { Err(Error::Inexact) } } } }; ($x:ty: $y:tt, $($yy:tt),+) => { impl_via_digits_check_signed!($x: $y); impl_via_digits_check_signed!($x: $($yy),+); }; } impl_via_digits_check!(u32: f32); impl_via_digits_check!(u64: f32, f64); impl_via_digits_check!(u128: f32, f64); impl_via_digits_check!(usize: f32, f64); impl_via_digits_check_signed!(i32: f32); impl_via_digits_check_signed!(i64: f32, f64); impl_via_digits_check_signed!(i128: f32, f64); impl_via_digits_check_signed!(isize: f32, f64); #[cfg(all(not(feature = "std"), feature = "libm"))] trait FloatRound { fn round(self) -> Self; fn floor(self) -> Self; fn ceil(self) -> Self; } #[cfg(all(not(feature = "std"), feature = "libm"))] impl FloatRound for f32 { fn round(self) -> Self { libm::roundf(self) } fn floor(self) -> Self { libm::floorf(self) } fn ceil(self) -> Self { libm::ceilf(self) } } #[cfg(all(not(feature = "std"), feature = "libm"))] impl FloatRound for f64 { fn round(self) -> Self { libm::round(self) } fn floor(self) -> Self { libm::floor(self) } fn ceil(self) -> Self { libm::ceil(self) } } /// Nearest / floor / ceil conversions from floating point types /// /// This trait is explicitly for conversions from floating-point values to /// integers, supporting four rounding modes for fallible and for /// "success expected" conversions. /// /// Two sets of methods are provided: /// /// - `conv_*` methods are for "success expected" conversions. In debug builds /// and when using the `always_assert` or the `assert_float` feature flag, /// out-of-range conversions will panic. In other cases, conversions may /// produce incorrect values (according to the behaviour of as, which is /// saturating cast since Rust 1.45.0 and undefined for older compilers). /// Non-finite source values (`inf` and `NaN`) are considered out-of-range. /// - `try_conv_*` methods are for fallible conversions and always produce an /// error if the conversion would be out of range. /// /// For `f64` to `f32` where loss-of-precision is allowable, it is probably /// acceptable to use `as` (and if need be, check that the result is finite /// with `x.is_finite()`). The reverse, `f32` to `f64`, is always exact. #[cfg(any(feature = "std", feature = "libm"))] #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "libm"))))] pub trait ConvFloat: Sized { /// Convert to integer with truncatation /// /// Rounds towards zero (same as `as`). fn conv_trunc(x: T) -> Self; /// Convert to the nearest integer /// /// Half-way cases are rounded away from `0`. fn conv_nearest(x: T) -> Self; /// Convert the floor to an integer /// /// Returns the largest integer less than or equal to `x`. fn conv_floor(x: T) -> Self; /// Convert the ceiling to an integer /// /// Returns the smallest integer greater than or equal to `x`. fn conv_ceil(x: T) -> Self; /// Try converting to integer with truncation /// /// Rounds towards zero (same as `as`). fn try_conv_trunc(x: T) -> Result; /// Try converting to the nearest integer /// /// Half-way cases are rounded away from `0`. fn try_conv_nearest(x: T) -> Result; /// Try converting the floor to an integer /// /// Returns the largest integer less than or equal to `x`. fn try_conv_floor(x: T) -> Result; /// Try convert the ceiling to an integer /// /// Returns the smallest integer greater than or equal to `x`. fn try_conv_ceil(x: T) -> Result; } #[cfg(any(feature = "std", feature = "libm"))] #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "libm"))))] macro_rules! impl_float { ($x:ty: $y:tt) => { impl ConvFloat<$x> for $y { #[inline] fn conv_trunc(x: $x) -> $y { if cfg!(any(debug_assertions, feature = "assert_float")) { Self::try_conv_trunc(x).unwrap_or_else(|_| { panic!( "cast x: {} to {} (trunc): range error for x = {}", stringify!($x), stringify!($y), x ) }) } else { x as $y } } #[inline] fn conv_nearest(x: $x) -> $y { if cfg!(any(debug_assertions, feature = "assert_float")) { Self::try_conv_nearest(x).unwrap_or_else(|_| { panic!( "cast x: {} to {} (nearest): range error for x = {}", stringify!($x), stringify!($y), x ) }) } else { x.round() as $y } } #[inline] fn conv_floor(x: $x) -> $y { if cfg!(any(debug_assertions, feature = "assert_float")) { Self::try_conv_floor(x).unwrap_or_else(|_| { panic!( "cast x: {} to {} (floor): range error for x = {}", stringify!($x), stringify!($y), x ) }) } else { x.floor() as $y } } #[inline] fn conv_ceil(x: $x) -> $y { if cfg!(any(debug_assertions, feature = "assert_float")) { Self::try_conv_ceil(x).unwrap_or_else(|_| { panic!( "cast x: {} to {} (ceil): range error for x = {}", stringify!($x), stringify!($y), x ) }) } else { x.ceil() as $y } } #[inline] fn try_conv_trunc(x: $x) -> Result { // Tested: these limits work for $x=f32 and all $y except u128 const LBOUND: $x = core::$y::MIN as $x - 1.0; const UBOUND: $x = core::$y::MAX as $x + 1.0; if x > LBOUND && x < UBOUND { Ok(x as $y) } else { Err(Error::Range) } } #[inline] fn try_conv_nearest(x: $x) -> Result { // Tested: these limits work for $x=f32 and all $y except u128 const LBOUND: $x = core::$y::MIN as $x; const UBOUND: $x = core::$y::MAX as $x + 1.0; let x = x.round(); if x >= LBOUND && x < UBOUND { Ok(x as $y) } else { Err(Error::Range) } } #[inline] fn try_conv_floor(x: $x) -> Result { // Tested: these limits work for $x=f32 and all $y except u128 const LBOUND: $x = core::$y::MIN as $x; const UBOUND: $x = core::$y::MAX as $x + 1.0; let x = x.floor(); if x >= LBOUND && x < UBOUND { Ok(x as $y) } else { Err(Error::Range) } } #[inline] fn try_conv_ceil(x: $x) -> Result { // Tested: these limits work for $x=f32 and all $y except u128 const LBOUND: $x = core::$y::MIN as $x; const UBOUND: $x = core::$y::MAX as $x + 1.0; let x = x.ceil(); if x >= LBOUND && x < UBOUND { Ok(x as $y) } else { Err(Error::Range) } } } }; ($x:ty: $y:tt, $($yy:tt),+) => { impl_float!($x: $y); impl_float!($x: $($yy),+); }; } // Assumption: usize < 128-bit #[cfg(any(feature = "std", feature = "libm"))] impl_float!(f32: i8, i16, i32, i64, i128, isize); #[cfg(any(feature = "std", feature = "libm"))] impl_float!(f32: u8, u16, u32, u64, usize); #[cfg(any(feature = "std", feature = "libm"))] impl_float!(f64: i8, i16, i32, i64, i128, isize); #[cfg(any(feature = "std", feature = "libm"))] impl_float!(f64: u8, u16, u32, u64, u128, usize); #[cfg(any(feature = "std", feature = "libm"))] impl ConvFloat for u128 { #[inline] fn conv_trunc(x: f32) -> u128 { if cfg!(any(debug_assertions, feature = "assert_float")) { Self::try_conv_trunc(x).unwrap_or_else(|_| { panic!( "cast x: f32 to u128 (trunc/floor): range error for x = {}", x ) }) } else { x as u128 } } #[inline] fn conv_nearest(x: f32) -> u128 { if cfg!(any(debug_assertions, feature = "assert_float")) { Self::try_conv_nearest(x).unwrap_or_else(|_| { panic!("cast x: f32 to u128 (nearest): range error for x = {}", x) }) } else { x.round() as u128 } } #[inline] fn conv_floor(x: f32) -> u128 { ConvFloat::conv_trunc(x) } #[inline] fn conv_ceil(x: f32) -> u128 { if cfg!(any(debug_assertions, feature = "assert_float")) { Self::try_conv_ceil(x) .unwrap_or_else(|_| panic!("cast x: f32 to u128 (ceil): range error for x = {}", x)) } else { x.ceil() as u128 } } #[inline] fn try_conv_trunc(x: f32) -> Result { // Note: f32::MAX < u128::MAX if x >= 0.0 && x.is_finite() { Ok(x as u128) } else { Err(Error::Range) } } #[inline] fn try_conv_nearest(x: f32) -> Result { let x = x.round(); if x >= 0.0 && x.is_finite() { Ok(x as u128) } else { Err(Error::Range) } } #[inline] fn try_conv_floor(x: f32) -> Result { Self::try_conv_trunc(x) } #[inline] fn try_conv_ceil(x: f32) -> Result { let x = x.ceil(); if x >= 0.0 && x.is_finite() { Ok(x as u128) } else { Err(Error::Range) } } } /// Like [`Into`], but for [`Conv`] /// /// Two methods are provided: /// /// - [`Cast::cast`] is for "success expected" conversions. In debug builds /// and when using the `always_assert` feature flag, inexact conversions /// will panic. In other cases, conversions may produce incorrect values /// (according to the behaviour of `as`). This is similar to the behviour of /// Rust's overflow checks on integer arithmetic, and intended for usage /// when the user is "reasonably sure" that conversion will succeed. /// - [`Cast::try_cast`] is for fallible conversions, and always produces an /// error if the conversion would be inexact. pub trait Cast { /// Cast from `Self` to `T` fn cast(self) -> T; /// Try converting from `Self` to `T` fn try_cast(self) -> Result; } impl> Cast for S { #[inline] fn cast(self) -> T { T::conv(self) } #[inline] fn try_cast(self) -> Result { T::try_conv(self) } } /// Like [`Into`], but for [`ConvFloat`] /// /// Two sets of methods are provided: /// /// - `cast_*` methods are for "success expected" conversions. In debug builds /// and when using the `always_assert` or the `assert_float` feature flag, /// out-of-range conversions will panic. In other cases, conversions may /// produce incorrect values (according to the behaviour of as, which is /// saturating cast since Rust 1.45.0 and undefined for older compilers). /// Non-finite source values (`inf` and `NaN`) are considered out-of-range. /// - `try_cast_*` methods are for fallible conversions and always produce an /// error if the conversion would be out of range. #[cfg(any(feature = "std", feature = "libm"))] #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "libm"))))] pub trait CastFloat { /// Cast to integer, truncating /// /// Rounds towards zero (same as `as`). fn cast_trunc(self) -> T; /// Cast to the nearest integer /// /// Half-way cases are rounded away from `0`. fn cast_nearest(self) -> T; /// Cast the floor to an integer /// /// Returns the largest integer less than or equal to `self`. fn cast_floor(self) -> T; /// Cast the ceiling to an integer /// /// Returns the smallest integer greater than or equal to `self`. fn cast_ceil(self) -> T; /// Try converting to integer with truncation /// /// Rounds towards zero (same as `as`). fn try_cast_trunc(self) -> Result; /// Try converting to the nearest integer /// /// Half-way cases are rounded away from `0`. fn try_cast_nearest(self) -> Result; /// Try converting the floor to an integer /// /// Returns the largest integer less than or equal to `x`. fn try_cast_floor(self) -> Result; /// Try convert the ceiling to an integer /// /// Returns the smallest integer greater than or equal to `x`. fn try_cast_ceil(self) -> Result; } #[cfg(any(feature = "std", feature = "libm"))] impl> CastFloat for S { #[inline] fn cast_trunc(self) -> T { T::conv_trunc(self) } #[inline] fn cast_nearest(self) -> T { T::conv_nearest(self) } #[inline] fn cast_floor(self) -> T { T::conv_floor(self) } #[inline] fn cast_ceil(self) -> T { T::conv_ceil(self) } #[inline] fn try_cast_trunc(self) -> Result { T::try_conv_trunc(self) } #[inline] fn try_cast_nearest(self) -> Result { T::try_conv_nearest(self) } #[inline] fn try_cast_floor(self) -> Result { T::try_conv_floor(self) } #[inline] fn try_cast_ceil(self) -> Result { T::try_conv_ceil(self) } } easy-cast-0.4.4/tests/tests.rs000064400000000000000000000030330000000000000143500ustar 00000000000000use easy_cast::*; #[test] fn int_casts() { let a: i32 = 213; let b: u128 = a.cast(); let c = u8::conv(b); let d = c.cast(); assert_eq!(a, d); } #[test] fn signed_to_unsigned() { u32::conv(0i32); u32::conv(1i32); u32::conv(core::i32::MAX); } #[test] #[should_panic] fn signed_to_unsigned_n1() { u32::conv(-1i32); } #[test] fn unsigned_to_signed() { i32::conv(0u32); i32::conv(1u32); i16::conv(1usize); } #[test] #[should_panic] fn unsigned_to_signed_large() { i32::conv(0x8000_0000u32); } #[test] fn int_to_float() { f32::conv(0); f32::conv(0x00FF_FFFF); f32::conv(-64i32); } #[test] #[should_panic] fn int_to_float_inexact() { f32::conv(0x01FF_FFFF); } #[test] #[cfg(any(feature = "std", feature = "libm"))] fn float_casts() { assert_eq!(u64::conv_nearest(13.2f32), 13); let x: i128 = 13.5f32.cast_nearest(); assert_eq!(x, 14); assert_eq!(u8::conv_floor(13.8f64), 13); assert_eq!(u32::conv_ceil(13.1f32), 14); assert_eq!(i64::conv_floor(-3168565.13), -3168566); } #[test] #[cfg(any(feature = "std", feature = "libm"))] fn float_trunc() { let xx = [-32768.0f32, -32768.99, -0.99, 0.99, 32767.99]; let yy = [-32768i16, -32768, 0, 0, 32767]; for (x, y) in xx[..].iter().zip(yy[..].iter()) { assert_eq!(i16::conv_trunc(*x), *y); } } #[test] #[should_panic] #[cfg(any(feature = "std", feature = "libm"))] fn float_trunc_fail1() { i16::conv_trunc(32768.0f32); } #[test] #[should_panic] fn u32_max_f32() { f32::conv(core::u32::MAX); }