|
1 | 1 | //! Definitions of integer that is known not to equal zero.
|
2 | 2 |
|
3 | 3 | use crate::fmt;
|
4 |
| -use crate::ops::{BitOr, BitOrAssign, Div, Rem}; |
| 4 | +use crate::ops::{BitOr, BitOrAssign, Div, Neg, Rem}; |
5 | 5 | use crate::str::FromStr;
|
6 | 6 |
|
7 | 7 | use super::from_str_radix;
|
@@ -513,6 +513,41 @@ nonzero_unsigned_operations! {
|
513 | 513 | macro_rules! nonzero_signed_operations {
|
514 | 514 | ( $( $Ty: ident($Int: ty) -> $Uty: ident($Uint: ty); )+ ) => {
|
515 | 515 | $(
|
| 516 | + #[stable(feature = "nonzero_checked_ops", since = "1.63.0")] |
| 517 | + impl Neg for $Ty { |
| 518 | + type Output = Self; |
| 519 | + /// Negate the non-zero value. |
| 520 | + /// The overflow behaviour of |
| 521 | + #[doc = concat!("[`", stringify!($Ty), "::neg`]")] |
| 522 | + /// is the same as |
| 523 | + #[doc = concat!("[`", stringify!($Int), "::neg`].")] |
| 524 | + /// In particular, overflowing to a zero value |
| 525 | + #[doc = concat!("with [`", stringify!($Ty), "::neg`]")] |
| 526 | + /// remains impossible. |
| 527 | + /// |
| 528 | + /// |
| 529 | + /// # Example |
| 530 | + /// |
| 531 | + /// ``` |
| 532 | + #[doc = concat!("# use std::num::", stringify!($Ty), ";")] |
| 533 | + /// |
| 534 | + /// # fn main() { test().unwrap(); } |
| 535 | + /// # fn test() -> Option<()> { |
| 536 | + #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")] |
| 537 | + #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")] |
| 538 | + /// |
| 539 | + /// assert_eq!(-pos, neg); |
| 540 | + /// assert_eq!(-neg, pos); |
| 541 | + /// # Some(()) |
| 542 | + /// # } |
| 543 | + /// ``` |
| 544 | + #[inline] |
| 545 | + fn neg(self) -> Self { |
| 546 | + // SAFETY: input is nonzero and result cannot overflow to zero. |
| 547 | + unsafe { $Ty::new_unchecked(self.get().neg()) } |
| 548 | + } |
| 549 | + } |
| 550 | + |
516 | 551 | impl $Ty {
|
517 | 552 | /// Computes the absolute value of self.
|
518 | 553 | #[doc = concat!("See [`", stringify!($Int), "::abs`]")]
|
|
0 commit comments