Skip to content

Commit 3af148a

Browse files
committed
Implement infra-stable Neg for NonZeroI*.
1 parent 855fc02 commit 3af148a

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

library/core/src/num/nonzero.rs

+36-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Definitions of integer that is known not to equal zero.
22
33
use crate::fmt;
4-
use crate::ops::{BitOr, BitOrAssign, Div, Rem};
4+
use crate::ops::{BitOr, BitOrAssign, Div, Neg, Rem};
55
use crate::str::FromStr;
66

77
use super::from_str_radix;
@@ -513,6 +513,41 @@ nonzero_unsigned_operations! {
513513
macro_rules! nonzero_signed_operations {
514514
( $( $Ty: ident($Int: ty) -> $Uty: ident($Uint: ty); )+ ) => {
515515
$(
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+
516551
impl $Ty {
517552
/// Computes the absolute value of self.
518553
#[doc = concat!("See [`", stringify!($Int), "::abs`]")]

0 commit comments

Comments
 (0)