1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
// Copyright © 2019–2021 Trevor Spiteri // This library is free software: you can redistribute it and/or // modify it under the terms of either // // * the Apache License, Version 2.0 or // * the MIT License // // at your option. // // You should have recieved copies of the Apache License and the MIT // License along with the library. If not, see // <https://www.apache.org/licenses/LICENSE-2.0> and // <https://opensource.org/licenses/MIT>. /*! # Numeric casts This crate provides casts and checked casts. ## Quick examples ```rust use az::{Az, OverflowingAs, WrappingAs}; use core::num::Wrapping; // Panics on overflow with `debug_assertions`, otherwise wraps assert_eq!(12i32.az::<u32>(), 12u32); // Always wraps let wrapped = 1u32.wrapping_neg(); assert_eq!((-1).wrapping_as::<u32>(), wrapped); assert_eq!((-1).overflowing_as::<u32>(), (wrapped, true)); // Wrapping can also be obtained using `Wrapping` assert_eq!((-1).az::<Wrapping<u32>>().0, wrapped); ``` Conversions from floating-point to integers are also supported. Numbers are rounded towards zero, but the [`Round`] wrapper can be used to convert floating-point numbers to integers with rounding to the nearest, with ties rounded to even. ```rust use az::{Az, CheckedAs, Round, SaturatingAs}; use core::f32; assert_eq!(15.7.az::<i32>(), 15); assert_eq!(Round(15.5).az::<i32>(), 16); assert_eq!(1.5e20.saturating_as::<i32>(), i32::max_value()); assert_eq!(f32::NAN.checked_as::<i32>(), None); ``` ## Implementing casts for other types To provide casts for another type, you should implement the [`Cast`] trait and if necessary the [`CheckedCast`], [`SaturatingCast`], [`WrappingCast`], [`OverflowingCast`] and [`UnwrappedCast`] traits. The [`Az`], [`CheckedAs`], [`SaturatingAs`], [`WrappingAs`], [`OverflowingAs`] and [`UnwrappedAs`] traits are already implemented for all types using blanket implementations that make use of the former traits. The cast traits can also be implemented for references. This can be useful for expensive types that are not [`Copy`]. For example if you have your own integer type that does not implement [`Copy`], you could implement casts like in the following example. (The type `I` could be an expensive type, for example a bignum integer, but for the example it is only a wrapped [`i32`].) ```rust use az::{Az, Cast}; use core::borrow::Borrow; struct I(i32); impl Cast<i64> for &'_ I { fn cast(self) -> i64 { self.0.cast() } } let owned = I(12); assert_eq!((&owned).az::<i64>(), 12); // borrow can be used if chaining is required assert_eq!(owned.borrow().az::<i64>(), 12); ``` ## Using the *az* crate The *az* crate is available on [crates.io][*az* crate]. To use it in your crate, add it as a dependency inside [*Cargo.toml*]: ```toml [dependencies] az = "1.1" ``` The crate requires rustc version 1.31.0 or later. ## License This crate is free software: you can redistribute it and/or modify it under the terms of either * the [Apache License, Version 2.0][LICENSE-APACHE] or * the [MIT License][LICENSE-MIT] at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache License, Version 2.0, shall be dual licensed as above, without any additional terms or conditions. [*Cargo.toml*]: https://doc.rust-lang.org/cargo/guide/dependencies.html [*az* crate]: https://crates.io/crates/az [LICENSE-APACHE]: https://www.apache.org/licenses/LICENSE-2.0 [LICENSE-MIT]: https://opensource.org/licenses/MIT [`Az`]: trait.Az.html [`Cast`]: trait.Cast.html [`CheckedAs`]: trait.CheckedAs.html [`CheckedCast`]: trait.CheckedCast.html [`Copy`]: https://doc.rust-lang.org/nightly/core/marker/trait.Copy.html [`OverflowingAs`]: trait.OverflowingAs.html [`OverflowingCast`]: trait.OverflowingCast.html [`Round`]: struct.Round.html [`SaturatingAs`]: trait.SaturatingAs.html [`SaturatingCast`]: trait.SaturatingCast.html [`UnwrappedAs`]: trait.UnwrappedAs.html [`UnwrappedCast`]: trait.UnwrappedCast.html [`WrappingAs`]: trait.WrappingAs.html [`WrappingCast`]: trait.WrappingCast.html [`i32`]: https://doc.rust-lang.org/nightly/std/primitive.i32.html */ #![no_std] #![warn(missing_docs)] #![doc(html_root_url = "https://docs.rs/az/~1.1")] #![doc(test(attr(deny(warnings))))] #![cfg_attr(feature = "fail-on-warnings", deny(warnings))] #[cfg(test)] extern crate std; mod float; mod int; #[cfg(test)] mod tests; /** Used to cast values. It is normally easier to use the [`Az`] trait instead of this trait. # Panics When debug assertions are enabled, this trait’s method panics if the value does not fit in the destination. When debug assertions are *not* enabled (usual in release mode), the wrapped value can be returned, but it is not considered a breaking change if in the future it panics; if wrapping is required use [`WrappingCast`] instead. This trait’s method also panics with no debug assertions if the value does not fit and cannot be wrapped, for example when trying to cast floating-point ∞ into an integer type. # Examples ```rust use az::Cast; let a: u32 = 5i32.cast(); assert_eq!(a, 5); assert_eq!(Cast::<u8>::cast(17.1f32), 17); ``` [`Az`]: trait.Az.html [`WrappingCast`]: trait.WrappingCast.html */ pub trait Cast<Dst> { /// Casts the value. fn cast(self) -> Dst; } /** Used for checked casts. This trait’s method returns [`None`] if the value does not fit. It is normally easier to use the [`CheckedAs`] trait instead of this trait. # Examples ```rust use az::CheckedCast; use core::f32; let a: Option<u32> = 5i32.checked_cast(); assert_eq!(a, Some(5)); assert_eq!(CheckedCast::<u32>::checked_cast(-5i32), None); assert_eq!(CheckedCast::<u8>::checked_cast(17.1f32), Some(17)); let b: Option<u8> = f32::NAN.checked_cast(); assert_eq!(b, None); ``` [`CheckedAs`]: trait.CheckedAs.html [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None */ pub trait CheckedCast<Dst> { /// Casts the value. fn checked_cast(self) -> Option<Dst>; } /** Used to cast into the destination type, saturating if the value does not fit. It is normally easier to use the [`SaturatingAs`] trait instead of this trait. # Panics This trait’s method panics if the value does not fit and saturation does not make sense, for example when trying to cast floating-point NaN into an integer type. # Examples ```rust use az::SaturatingCast; let a: u32 = (-1).saturating_cast(); assert_eq!(a, 0); assert_eq!(SaturatingCast::<u8>::saturating_cast(17.0 + 256.0), 255); ``` [`SaturatingAs`]: trait.SaturatingAs.html */ pub trait SaturatingCast<Dst> { /// Casts the value. fn saturating_cast(self) -> Dst; } /** Wrapping cast. It is normally easier to use the [`WrappingAs`] trait instead of this trait. # Panics This trait’s method panics if the value does not fit and cannot be wrapped, for example when trying to cast floating-point ∞ into an integer type. # Examples ```rust use az::WrappingCast; let a: u32 = (-1).wrapping_cast(); assert_eq!(a, u32::max_value()); assert_eq!(WrappingCast::<u8>::wrapping_cast(17.0 + 256.0), 17); ``` [`WrappingAs`]: trait.WrappingAs.html */ pub trait WrappingCast<Dst> { /// Casts the value. fn wrapping_cast(self) -> Dst; } /** Used for overflowing casts. This trait’s method returns a [tuple] of the value and a [`bool`], indicating whether an overflow has occurred. On overflow, the wrapped value is returned. It is normally easier to use the [`OverflowingAs`] trait instead of this trait. # Examples ```rust use az::OverflowingCast; let a: (u8, bool) = 17i32.overflowing_cast(); assert_eq!(a, (17, false)); assert_eq!(OverflowingCast::<u32>::overflowing_cast(-1), (u32::max_value(), true)); assert_eq!(OverflowingCast::<u8>::overflowing_cast(17.0 + 256.0), (17, true)); ``` # Panics This trait’s method panics if the value does not fit and cannot be wrapped, for example when trying to cast floating-point ∞ into an integer type. [`OverflowingAs`]: trait.OverflowingAs.html [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html */ pub trait OverflowingCast<Dst> { /// Casts the value. fn overflowing_cast(self) -> (Dst, bool); } /** Used to cast values, panicking if the value does not fit. It is normally easier to use the [`UnwrappedAs`] trait instead of this trait. # Panics This trait’s method panics if the value does not fit in the destination, even when debug assertions are not enabled. # Examples ```rust use az::UnwrappedCast; let a: u32 = 5i32.unwrapped_cast(); assert_eq!(a, 5); assert_eq!(UnwrappedCast::<u8>::unwrapped_cast(17.1f32), 17); ``` The following panics because of overflow. ```rust,should_panic use az::UnwrappedCast; let _overflow: u32 = (-5i32).unwrapped_cast(); ``` */ pub trait UnwrappedCast<Dst> { /// Casts the value. fn unwrapped_cast(self) -> Dst; } /** Used to cast values. This is a convenience trait to enable writing <code>src.[az][`az`]::<Dst>()</code>. This would not work with the <code>[Cast][`Cast`]::[cast][`Cast::cast`]</code> method because the [`Cast`] trait is generic while its [`cast`][`Cast::cast`] method is not generic. This trait’s method is suitable for chaining. If there is an implementation of <code>[Cast][`Cast`]<Dst></code> for `&Src` but not for `Src`, and the variable `src` is of type `Src`, then <code>src.[az][`az`]::<Dst>()</code> would not work and <code>(&src).[az][`az`]::<Dst>()</code> is not easy to use with chaining, but <code>src.[borrow][`borrow`]().[az][`az`]::<Dst>()</code> works. # Panics When debug assertions are enabled, this trait’s method panics if the value does not fit in the destination. When debug assertions are *not* enabled (usual in release mode), the wrapped value can be returned, but it is not considered a breaking change if in the future it panics; if wrapping is required use [`WrappingAs`] instead. This trait’s method also panics with no debug assertions if the value does not fit and cannot be wrapped, for example when trying to cast floating-point ∞ into an integer type. # Examples ```rust use az::Az; assert_eq!(5i32.az::<u32>(), 5); assert_eq!(17.1f32.az::<u8>(), 17); ``` The following example shows how this trait can be used when [`Cast`] is implemented for a reference type. ```rust use az::{Az, Cast}; use core::borrow::Borrow; struct I(i32); impl Cast<i64> for &'_ I { fn cast(self) -> i64 { self.0.cast() } } let r = &I(-5); assert_eq!(r.az::<i64>(), -5); let owned = I(12); assert_eq!(owned.borrow().az::<i64>(), 12); ``` [`Cast`]: trait.Cast.html [`WrappingAs`]: trait.WrappingAs.html [`az`]: #tymethod.az [`borrow`]: https://doc.rust-lang.org/core/borrow/trait.Borrow.html#tymethod.borrow [`Cast::cast`]: trait.Cast.html#tymethod.cast */ pub trait Az { /// Casts the value. fn az<Dst>(self) -> Dst where Self: Cast<Dst>; } impl<T> Az for T { #[inline] fn az<Dst>(self) -> Dst where Self: Cast<Dst>, { self.cast() } } /** Used for checked casts. This trait’s method returns [`None`] if the value does not fit. This is a convenience trait to enable writing <code>src.[checked\_as][`checked_as`]::<Dst>()</code>. This would not work with the <code>[CheckedCast][`CheckedCast`]::[checked\_cast][`checked_cast`]</code> method because the [`CheckedCast`] trait is generic while its [`checked_cast`] method is not generic. This trait’s method is suitable for chaining. If there is an implementation of <code>[CheckedCast][`CheckedCast`]<Dst></code> for `&Src` but not for `Src`, and the variable `src` is of type `Src`, then <code>src.[checked\_as][`checked_as`]::<Dst>()</code> would not work and <code>(&src).[checked\_as][`checked_as`]::<Dst>()</code> is not easy to use with chaining, but <code>src.[borrow][`borrow`]().[checked\_as][`checked_as`]::<Dst>()</code> works. # Examples ```rust use az::CheckedAs; use core::f32; assert_eq!(5i32.checked_as::<u32>(), Some(5)); assert_eq!((-5i32).checked_as::<u32>(), None); assert_eq!(17.1f32.checked_as::<u8>(), Some(17)); assert_eq!(f32::NAN.checked_as::<u8>(), None); ``` The following example shows how this trait can be used when [`CheckedCast`] is implemented for a reference type. ```rust use az::{CheckedAs, CheckedCast}; use core::borrow::Borrow; struct I(i32); impl CheckedCast<u32> for &'_ I { fn checked_cast(self) -> Option<u32> { self.0.checked_cast() } } let r = &I(-5); assert_eq!(r.checked_as::<u32>(), None); let owned = I(12); assert_eq!(owned.borrow().checked_as::<u32>(), Some(12)); ``` [`CheckedCast`]: trait.CheckedCast.html [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None [`borrow`]: https://doc.rust-lang.org/core/borrow/trait.Borrow.html#tymethod.borrow [`checked_as`]: #tymethod.checked_as [`checked_cast`]: trait.CheckedCast.html#tymethod.checked_cast */ pub trait CheckedAs { /// Casts the value. fn checked_as<Dst>(self) -> Option<Dst> where Self: CheckedCast<Dst>; } impl<T> CheckedAs for T { #[inline] fn checked_as<Dst>(self) -> Option<Dst> where Self: CheckedCast<Dst>, { self.checked_cast() } } /** Used to cast into the destination type, saturating if the value does not fit. This is a convenience trait to enable writing <code>src.[saturating\_as][`saturating_as`]::<Dst>()</code>. This would not work with the <code>[SaturatingCast][`SaturatingCast`]::[saturating\_cast][`saturating_cast`]</code> method because the [`SaturatingCast`] trait is generic while its [`saturating_cast`] method is not generic. This trait’s method is suitable for chaining. If there is an implementation of <code>[SaturatingCast][`SaturatingCast`]<Dst></code> for `&Src` but not for `Src`, and the variable `src` is of type `Src`, then <code>src.[saturating\_as][`saturating_as`]::<Dst>()</code> would not work and <code>(&src).[saturating\_as][`saturating_as`]::<Dst>()</code> is not easy to use with chaining, but <code>src.[borrow][`borrow`]().[saturating\_as][`saturating_as`]::<Dst>()</code> works. # Panics This trait’s method panics if the value does not fit and saturation does not make sense, for example when trying to cast floating-point NaN into an integer type. # Examples ```rust use az::SaturatingAs; assert_eq!((-1).saturating_as::<u32>(), 0); assert_eq!((17.0 + 256.0).saturating_as::<u8>(), 255); ``` The following example shows how this trait can be used when [`SaturatingCast`] is implemented for a reference type. ```rust use az::{SaturatingAs, SaturatingCast}; use core::borrow::Borrow; struct I(i32); impl SaturatingCast<u32> for &'_ I { fn saturating_cast(self) -> u32 { self.0.saturating_cast() } } let r = &I(-5); assert_eq!(r.saturating_as::<u32>(), 0); let owned = I(12); assert_eq!(owned.borrow().saturating_as::<u32>(), 12); ``` [`SaturatingCast`]: trait.SaturatingCast.html [`borrow`]: https://doc.rust-lang.org/core/borrow/trait.Borrow.html#tymethod.borrow [`saturating_as`]: #tymethod.saturating_as [`saturating_cast`]: trait.SaturatingCast.html#tymethod.saturating_cast */ pub trait SaturatingAs { /// Casts the value. fn saturating_as<Dst>(self) -> Dst where Self: SaturatingCast<Dst>; } impl<T> SaturatingAs for T { #[inline] fn saturating_as<Dst>(self) -> Dst where Self: SaturatingCast<Dst>, { self.saturating_cast() } } /** Wrapping cast. This is a convenience trait to enable writing <code>src.[wrapping\_as][`wrapping_as`]::<Dst>()</code>. This would not work with the <code>[WrappingCast][`WrappingCast`]::[wrapping\_cast][`wrapping_cast`]</code> method because the [`WrappingCast`] trait is generic while its [`wrapping_cast`] method is not generic. This trait’s method is suitable for chaining. If there is an implementation of <code>[WrappingCast][`WrappingCast`]<Dst></code> for `&Src` but not for `Src`, and the variable `src` is of type `Src`, then <code>src.[wrapping\_as][`wrapping_as`]::<Dst>()</code> would not work and <code>(&src).[wrapping\_as][`wrapping_as`]::<Dst>()</code> is not easy to use with chaining, but <code>src.[borrow][`borrow`]().[wrapping\_as][`wrapping_as`]::<Dst>()</code> works. # Panics This trait’s method panics if the value does not fit and cannot be wrapped, for example when trying to cast floating-point ∞ into an integer type. # Examples ```rust use az::WrappingAs; assert_eq!((-1).wrapping_as::<u32>(), u32::max_value()); assert_eq!((17.0 + 256.0).wrapping_as::<u8>(), 17); ``` The following example shows how this trait can be used when [`WrappingCast`] is implemented for a reference type. ```rust use az::{WrappingAs, WrappingCast}; use core::borrow::Borrow; struct I(i32); impl WrappingCast<u32> for &'_ I { fn wrapping_cast(self) -> u32 { self.0.wrapping_cast() } } let r = &I(-5); assert_eq!(r.wrapping_as::<u32>(), 5u32.wrapping_neg()); let owned = I(12); assert_eq!(owned.borrow().wrapping_as::<u32>(), 12); ``` [`WrappingCast`]: trait.WrappingCast.html [`borrow`]: https://doc.rust-lang.org/core/borrow/trait.Borrow.html#tymethod.borrow [`wrapping_as`]: #tymethod.wrapping_as [`wrapping_cast`]: trait.WrappingCast.html#tymethod.wrapping_cast */ pub trait WrappingAs { /// Casts the value. fn wrapping_as<Dst>(self) -> Dst where Self: WrappingCast<Dst>; } impl<T> WrappingAs for T { #[inline] fn wrapping_as<Dst>(self) -> Dst where Self: WrappingCast<Dst>, { self.wrapping_cast() } } /** Used for overflowing casts. This trait’s method returns a [tuple] of the value and a [`bool`], indicating whether an overflow has occurred. On overflow, the wrapped value is returned. This is a convenience trait to enable writing <code>src.[overflowing\_as][`overflowing_as`]::<Dst>()</code>. This would not work with the <code>[OverflowingCast][`OverflowingCast`]::[overflowing\_cast][`overflowing_cast`]</code> method because the [`OverflowingCast`] trait is generic while its [`overflowing_cast`] method is not generic. This trait’s method is suitable for chaining. If there is an implementation of <code>[OverflowingCast][`OverflowingCast`]<Dst></code> for `&Src` but not for `Src`, and the variable `src` is of type `Src`, then <code>src.[overflowing\_as][`overflowing_as`]::<Dst>()</code> would not work and <code>(&src).[overflowing\_as][`overflowing_as`]::<Dst>()</code> is not easy to use with chaining, but <code>src.[borrow][`borrow`]().[overflowing\_as][`overflowing_as`]::<Dst>()</code> works. # Panics This trait’s method panics if the value does not fit and cannot be wrapped, for example when trying to cast floating-point ∞ into an integer type. # Examples ```rust use az::OverflowingAs; assert_eq!(17i32.overflowing_as::<u8>(), (17, false)); assert_eq!((-1).overflowing_as::<u32>(), (u32::max_value(), true)); assert_eq!((17.0 + 256.0).overflowing_as::<u8>(), (17, true)); ``` The following example shows how this trait can be used when [`OverflowingCast`] is implemented for a reference type. ```rust use az::{OverflowingAs, OverflowingCast}; use core::borrow::Borrow; struct I(i32); impl OverflowingCast<u32> for &'_ I { fn overflowing_cast(self) -> (u32, bool) { self.0.overflowing_cast() } } let r = &I(-5); assert_eq!(r.overflowing_as::<u32>(), (5u32.wrapping_neg(), true)); let owned = I(12); assert_eq!(owned.borrow().overflowing_as::<u32>(), (12, false)); ``` [`OverflowingCast`]: trait.OverflowingCast.html [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html [`borrow`]: https://doc.rust-lang.org/core/borrow/trait.Borrow.html#tymethod.borrow [`overflowing_as`]: #tymethod.overflowing_as [`overflowing_cast`]: trait.OverflowingCast.html#tymethod.overflowing_cast [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html */ pub trait OverflowingAs { /// Casts the value. fn overflowing_as<Dst>(self) -> (Dst, bool) where Self: OverflowingCast<Dst>; } impl<T> OverflowingAs for T { #[inline] fn overflowing_as<Dst>(self) -> (Dst, bool) where Self: OverflowingCast<Dst>, { self.overflowing_cast() } } /** Used to cast values, panicking if the value does not fit. This is a convenience trait to enable writing <code>src.[unwrapped\_as][`unwrapped_as`]::<Dst>()</code>. This would not work with the <code>[UnwrappedCast][`UnwrappedCast`]::[unwrapped\_cast][`unwrapped_cast`]</code> method because the [`UnwrappedCast`] trait is generic while its [`unwrapped_cast`] method is not generic. This trait’s method is suitable for chaining. If there is an implementation of <code>[UnwrappedCast][`UnwrappedCast`]<Dst></code> for `&Src` but not for `Src`, and the variable `src` is of type `Src`, then <code>src.[unwrapped\_as][`unwrapped_as`]::<Dst>()</code> would not work and <code>(&src).[unwrapped\_as][`unwrapped_as`]::<Dst>()</code> is not easy to use with chaining, but <code>src.[borrow][`borrow`]().[unwrapped\_as][`unwrapped_as`]::<Dst>()</code> works. # Panics This trait’s method panics if the value does not fit in the destination, even when debug assertions are not enabled. # Examples ```rust use az::UnwrappedAs; assert_eq!(5i32.unwrapped_as::<u32>(), 5); assert_eq!(17.1f32.unwrapped_as::<u8>(), 17); ``` The following panics because of overflow. ```rust,should_panic use az::UnwrappedAs; let _overflow = (-5i32).unwrapped_as::<u32>(); ``` The following example shows how this trait can be used when [`UnwrappedCast`] is implemented for a reference type. ```rust use az::{UnwrappedAs, UnwrappedCast}; use core::borrow::Borrow; struct I(i32); impl UnwrappedCast<i64> for &'_ I { fn unwrapped_cast(self) -> i64 { self.0.unwrapped_cast() } } let r = &I(-5); assert_eq!(r.unwrapped_as::<i64>(), -5); let owned = I(12); assert_eq!(owned.borrow().unwrapped_as::<i64>(), 12); ``` [`UnwrappedCast`]: trait.UnwrappedCast.html [`borrow`]: https://doc.rust-lang.org/core/borrow/trait.Borrow.html#tymethod.borrow [`unwrapped_as`]: #tymethod.unwrapped_as [`unwrapped_cast`]: trait.UnwrappedCast.html#tymethod.unwrapped_cast */ pub trait UnwrappedAs { /// Casts the value. fn unwrapped_as<Dst>(self) -> Dst where Self: UnwrappedCast<Dst>; } impl<T> UnwrappedAs for T { #[inline] fn unwrapped_as<Dst>(self) -> Dst where Self: UnwrappedCast<Dst>, { self.unwrapped_cast() } } /// Casts the value. /// /// # Panics /// /// When debug assertions are enabled, panics if the value does not /// fit in the destination. When debug assertions are *not* enabled /// (usual in release mode), the wrapped value can be returned, but it /// is not considered a breaking change if in the future it panics; if /// wrapping is required use [`wrapping_cast`] instead. /// /// This function also panics with no debug assertions if the value /// does not fit and cannot be wrapped, for example when trying to /// cast floating-point ∞ into an integer type. /// /// [`wrapping_cast`]: fn.wrapping_cast.html /// /// # Examples /// /// ```rust /// assert_eq!(az::cast::<i32, u32>(5), 5); /// assert_eq!(az::cast::<f32, u8>(17.1), 17); /// ``` #[inline] pub fn cast<Src: Cast<Dst>, Dst>(src: Src) -> Dst { src.cast() } /// Casts the value, returning [`None`] if the value does not fit. /// /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None /// /// # Examples /// /// ```rust /// use core::f32; /// /// assert_eq!(az::checked_cast::<i32, u32>(5), Some(5)); /// assert_eq!(az::checked_cast::<i32, u32>(-5), None); /// assert_eq!(az::checked_cast::<f32, u8>(17.1), Some(17)); /// assert_eq!(az::checked_cast::<f32, u8>(f32::NAN), None); /// ``` #[inline] pub fn checked_cast<Src: CheckedCast<Dst>, Dst>(src: Src) -> Option<Dst> { src.checked_cast() } /// Casts the value, saturating if the value does not fit. /// /// # Panics /// /// Panics if the value does not fit and saturation does not make /// sense, for example when trying to cast floating-point NaN into an /// integer type. /// /// # Examples /// /// ```rust /// assert_eq!(az::saturating_cast::<i32, u32>(-1), 0); /// assert_eq!(az::saturating_cast::<f32, u8>(17.0 + 256.0), 255); /// ``` #[inline] pub fn saturating_cast<Src: SaturatingCast<Dst>, Dst>(src: Src) -> Dst { src.saturating_cast() } /// Casts the value, wrapping on overflow. /// /// # Panics /// /// Panics if the value does not fit and cannot be wrapped, for /// example when trying to cast floating-point ∞ into an integer type. /// /// # Examples /// /// ```rust /// assert_eq!(az::wrapping_cast::<i32, u32>(-1), u32::max_value()); /// assert_eq!(az::wrapping_cast::<f32, u8>(17.0 + 256.0), 17); /// ``` #[inline] pub fn wrapping_cast<Src: WrappingCast<Dst>, Dst>(src: Src) -> Dst { src.wrapping_cast() } /// Overflowing cast. /// /// Returns a [tuple] of the value and a [`bool`], indicating whether /// an overflow has occurred. On overflow, the wrapped value is /// returned. /// /// # Panics /// /// Panics if the value does not fit and cannot be wrapped, for /// example when trying to cast floating-point ∞ into an integer type. /// /// # Examples /// /// ```rust /// assert_eq!(az::overflowing_cast::<i32, u32>(-1), (u32::max_value(), true)); /// assert_eq!(az::overflowing_cast::<f32, u8>(17.0 + 256.0), (17, true)); /// ``` /// /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html #[inline] pub fn overflowing_cast<Src: OverflowingCast<Dst>, Dst>(src: Src) -> (Dst, bool) { src.overflowing_cast() } /// Casts the value, panicking if the value does not fit. /// /// # Panics /// /// Panics if the value does not fit in the destination, even when /// debug assertions are not enabled. /// /// # Examples /// /// ```rust /// assert_eq!(az::unwrapped_cast::<i32, u32>(5), 5); /// assert_eq!(az::unwrapped_cast::<f32, u8>(17.1), 17); /// ``` /// /// The following panics because of overflow. /// /// ```rust,should_panic /// let _overflow = az::unwrapped_cast::<i32, u32>(-5); /// ``` #[inline] pub fn unwrapped_cast<Src: UnwrappedCast<Dst>, Dst>(src: Src) -> Dst { src.unwrapped_cast() } /// Used to convert floating-point numbers to integers with rounding /// to the nearest, with ties rounded to even. /// /// The underlying value can be retrieved through the `.0` index. /// /// # Examples /// /// ```rust /// use az::Round; /// assert_eq!(az::cast::<_, i32>(Round(0.4)), 0); /// assert_eq!(az::cast::<_, i32>(Round(0.6)), 1); /// // ties rounded to even /// assert_eq!(az::cast::<_, i32>(Round(-0.5)), 0); /// assert_eq!(az::cast::<_, i32>(Round(-1.5)), -2); /// ``` #[repr(transparent)] #[derive(Clone, Copy, Default, Debug, PartialEq, PartialOrd)] pub struct Round<T>(pub T);