#
core/ops/
arith.rs

    1/// The addition operator `+`.
    2///
    3/// Note that `Rhs` is `Self` by default, but this is not mandatory. For
    4/// example, [`std::time::SystemTime`] implements `Add<Duration>`, which permits
    5/// operations of the form `SystemTime = SystemTime + Duration`.
    6///
    7/// [`std::time::SystemTime`]: ../../std/time/struct.SystemTime.html
    8///
    9/// # Examples
    10///
    11/// ## `Add`able points
    12///
    13/// ```
    14/// use std::ops::Add;
    15///
    16/// #[derive(Debug, Copy, Clone, PartialEq)]
    17/// struct Point {
    18///     x: i32,
    19///     y: i32,
    20/// }
    21///
    22/// impl Add for Point {
    23///     type Output = Self;
    24///
    25///     fn add(self, other: Self) -> Self {
    26///         Self {
    27///             x: self.x + other.x,
    28///             y: self.y + other.y,
    29///         }
    30///     }
    31/// }
    32///
    33/// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
    34///            Point { x: 3, y: 3 });
    35/// ```
    36///
    37/// ## Implementing `Add` with generics
    38///
    39/// Here is an example of the same `Point` struct implementing the `Add` trait
    40/// using generics.
    41///
    42/// ```
    43/// use std::ops::Add;
    44///
    45/// #[derive(Debug, Copy, Clone, PartialEq)]
    46/// struct Point<T> {
    47///     x: T,
    48///     y: T,
    49/// }
    50///
    51/// // Notice that the implementation uses the associated type `Output`.
    52/// impl<T: Add<Output = T>> Add for Point<T> {
    53///     type Output = Self;
    54///
    55///     fn add(self, other: Self) -> Self::Output {
    56///         Self {
    57///             x: self.x + other.x,
    58///             y: self.y + other.y,
    59///         }
    60///     }
    61/// }
    62///
    63/// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
    64///            Point { x: 3, y: 3 });
    65/// ```
    66#[lang = "add"]
    67#[stable(feature = "rust1", since = "1.0.0")]
    68#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    69#[rustc_on_unimplemented(
    70    on(all(Self = "{integer}", Rhs = "{float}"), message = "cannot add a float to an integer",),
    71    on(all(Self = "{float}", Rhs = "{integer}"), message = "cannot add an integer to a float",),
    72    message = "cannot add `{Rhs}` to `{Self}`",
    73    label = "no implementation for `{Self} + {Rhs}`",
    74    append_const_msg
    75)]
    76#[doc(alias = "+")]
    77#[const_trait]
    78pub trait Add<Rhs = Self> {
    79    /// The resulting type after applying the `+` operator.
    80    #[stable(feature = "rust1", since = "1.0.0")]
    81    type Output;
    82
    83    /// Performs the `+` operation.
    84    ///
    85    /// # Example
    86    ///
    87    /// ```
    88    /// assert_eq!(12 + 1, 13);
    89    /// ```
    90    #[must_use = "this returns the result of the operation, without modifying the original"]
    91    #[rustc_diagnostic_item = "add"]
    92    #[stable(feature = "rust1", since = "1.0.0")]
    93    fn add(self, rhs: Rhs) -> Self::Output;
    94}
    95
    96macro_rules! add_impl {
    97    ($($t:ty)*) => ($(
    98        #[stable(feature = "rust1", since = "1.0.0")]
    99        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    100        impl const Add for $t {
    101            type Output = $t;
    102
    103            #[inline]
    104            #[track_caller]
    105            #[rustc_inherit_overflow_checks]
    106            fn add(self, other: $t) -> $t { self + other }
    107        }
    108
    109        forward_ref_binop! { impl Add, add for $t, $t,
    110        #[stable(feature = "rust1", since = "1.0.0")]
    111        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
    112    )*)
    113}
    114
    115add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
    116
    117/// The subtraction operator `-`.
    118///
    119/// Note that `Rhs` is `Self` by default, but this is not mandatory. For
    120/// example, [`std::time::SystemTime`] implements `Sub<Duration>`, which permits
    121/// operations of the form `SystemTime = SystemTime - Duration`.
    122///
    123/// [`std::time::SystemTime`]: ../../std/time/struct.SystemTime.html
    124///
    125/// # Examples
    126///
    127/// ## `Sub`tractable points
    128///
    129/// ```
    130/// use std::ops::Sub;
    131///
    132/// #[derive(Debug, Copy, Clone, PartialEq)]
    133/// struct Point {
    134///     x: i32,
    135///     y: i32,
    136/// }
    137///
    138/// impl Sub for Point {
    139///     type Output = Self;
    140///
    141///     fn sub(self, other: Self) -> Self::Output {
    142///         Self {
    143///             x: self.x - other.x,
    144///             y: self.y - other.y,
    145///         }
    146///     }
    147/// }
    148///
    149/// assert_eq!(Point { x: 3, y: 3 } - Point { x: 2, y: 3 },
    150///            Point { x: 1, y: 0 });
    151/// ```
    152///
    153/// ## Implementing `Sub` with generics
    154///
    155/// Here is an example of the same `Point` struct implementing the `Sub` trait
    156/// using generics.
    157///
    158/// ```
    159/// use std::ops::Sub;
    160///
    161/// #[derive(Debug, PartialEq)]
    162/// struct Point<T> {
    163///     x: T,
    164///     y: T,
    165/// }
    166///
    167/// // Notice that the implementation uses the associated type `Output`.
    168/// impl<T: Sub<Output = T>> Sub for Point<T> {
    169///     type Output = Self;
    170///
    171///     fn sub(self, other: Self) -> Self::Output {
    172///         Point {
    173///             x: self.x - other.x,
    174///             y: self.y - other.y,
    175///         }
    176///     }
    177/// }
    178///
    179/// assert_eq!(Point { x: 2, y: 3 } - Point { x: 1, y: 0 },
    180///            Point { x: 1, y: 3 });
    181/// ```
    182#[lang = "sub"]
    183#[stable(feature = "rust1", since = "1.0.0")]
    184#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    185#[rustc_on_unimplemented(
    186    message = "cannot subtract `{Rhs}` from `{Self}`",
    187    label = "no implementation for `{Self} - {Rhs}`",
    188    append_const_msg
    189)]
    190#[doc(alias = "-")]
    191#[const_trait]
    192pub trait Sub<Rhs = Self> {
    193    /// The resulting type after applying the `-` operator.
    194    #[stable(feature = "rust1", since = "1.0.0")]
    195    type Output;
    196
    197    /// Performs the `-` operation.
    198    ///
    199    /// # Example
    200    ///
    201    /// ```
    202    /// assert_eq!(12 - 1, 11);
    203    /// ```
    204    #[must_use = "this returns the result of the operation, without modifying the original"]
    205    #[rustc_diagnostic_item = "sub"]
    206    #[stable(feature = "rust1", since = "1.0.0")]
    207    fn sub(self, rhs: Rhs) -> Self::Output;
    208}
    209
    210macro_rules! sub_impl {
    211    ($($t:ty)*) => ($(
    212        #[stable(feature = "rust1", since = "1.0.0")]
    213        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    214        impl const Sub for $t {
    215            type Output = $t;
    216
    217            #[inline]
    218            #[track_caller]
    219            #[rustc_inherit_overflow_checks]
    220            fn sub(self, other: $t) -> $t { self - other }
    221        }
    222
    223        forward_ref_binop! { impl Sub, sub for $t, $t,
    224        #[stable(feature = "rust1", since = "1.0.0")]
    225        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
    226    )*)
    227}
    228
    229sub_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
    230
    231/// The multiplication operator `*`.
    232///
    233/// Note that `Rhs` is `Self` by default, but this is not mandatory.
    234///
    235/// # Examples
    236///
    237/// ## `Mul`tipliable rational numbers
    238///
    239/// ```
    240/// use std::ops::Mul;
    241///
    242/// // By the fundamental theorem of arithmetic, rational numbers in lowest
    243/// // terms are unique. So, by keeping `Rational`s in reduced form, we can
    244/// // derive `Eq` and `PartialEq`.
    245/// #[derive(Debug, Eq, PartialEq)]
    246/// struct Rational {
    247///     numerator: usize,
    248///     denominator: usize,
    249/// }
    250///
    251/// impl Rational {
    252///     fn new(numerator: usize, denominator: usize) -> Self {
    253///         if denominator == 0 {
    254///             panic!("Zero is an invalid denominator!");
    255///         }
    256///
    257///         // Reduce to lowest terms by dividing by the greatest common
    258///         // divisor.
    259///         let gcd = gcd(numerator, denominator);
    260///         Self {
    261///             numerator: numerator / gcd,
    262///             denominator: denominator / gcd,
    263///         }
    264///     }
    265/// }
    266///
    267/// impl Mul for Rational {
    268///     // The multiplication of rational numbers is a closed operation.
    269///     type Output = Self;
    270///
    271///     fn mul(self, rhs: Self) -> Self {
    272///         let numerator = self.numerator * rhs.numerator;
    273///         let denominator = self.denominator * rhs.denominator;
    274///         Self::new(numerator, denominator)
    275///     }
    276/// }
    277///
    278/// // Euclid's two-thousand-year-old algorithm for finding the greatest common
    279/// // divisor.
    280/// fn gcd(x: usize, y: usize) -> usize {
    281///     let mut x = x;
    282///     let mut y = y;
    283///     while y != 0 {
    284///         let t = y;
    285///         y = x % y;
    286///         x = t;
    287///     }
    288///     x
    289/// }
    290///
    291/// assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
    292/// assert_eq!(Rational::new(2, 3) * Rational::new(3, 4),
    293///            Rational::new(1, 2));
    294/// ```
    295///
    296/// ## Multiplying vectors by scalars as in linear algebra
    297///
    298/// ```
    299/// use std::ops::Mul;
    300///
    301/// struct Scalar { value: usize }
    302///
    303/// #[derive(Debug, PartialEq)]
    304/// struct Vector { value: Vec<usize> }
    305///
    306/// impl Mul<Scalar> for Vector {
    307///     type Output = Self;
    308///
    309///     fn mul(self, rhs: Scalar) -> Self::Output {
    310///         Self { value: self.value.iter().map(|v| v * rhs.value).collect() }
    311///     }
    312/// }
    313///
    314/// let vector = Vector { value: vec![2, 4, 6] };
    315/// let scalar = Scalar { value: 3 };
    316/// assert_eq!(vector * scalar, Vector { value: vec![6, 12, 18] });
    317/// ```
    318#[lang = "mul"]
    319#[stable(feature = "rust1", since = "1.0.0")]
    320#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    321#[diagnostic::on_unimplemented(
    322    message = "cannot multiply `{Self}` by `{Rhs}`",
    323    label = "no implementation for `{Self} * {Rhs}`"
    324)]
    325#[doc(alias = "*")]
    326#[const_trait]
    327pub trait Mul<Rhs = Self> {
    328    /// The resulting type after applying the `*` operator.
    329    #[stable(feature = "rust1", since = "1.0.0")]
    330    type Output;
    331
    332    /// Performs the `*` operation.
    333    ///
    334    /// # Example
    335    ///
    336    /// ```
    337    /// assert_eq!(12 * 2, 24);
    338    /// ```
    339    #[must_use = "this returns the result of the operation, without modifying the original"]
    340    #[rustc_diagnostic_item = "mul"]
    341    #[stable(feature = "rust1", since = "1.0.0")]
    342    fn mul(self, rhs: Rhs) -> Self::Output;
    343}
    344
    345macro_rules! mul_impl {
    346    ($($t:ty)*) => ($(
    347        #[stable(feature = "rust1", since = "1.0.0")]
    348        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    349        impl const Mul for $t {
    350            type Output = $t;
    351
    352            #[inline]
    353            #[track_caller]
    354            #[rustc_inherit_overflow_checks]
    355            fn mul(self, other: $t) -> $t { self * other }
    356        }
    357
    358        forward_ref_binop! { impl Mul, mul for $t, $t,
    359        #[stable(feature = "rust1", since = "1.0.0")]
    360        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
    361    )*)
    362}
    363
    364mul_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
    365
    366/// The division operator `/`.
    367///
    368/// Note that `Rhs` is `Self` by default, but this is not mandatory.
    369///
    370/// # Examples
    371///
    372/// ## `Div`idable rational numbers
    373///
    374/// ```
    375/// use std::ops::Div;
    376///
    377/// // By the fundamental theorem of arithmetic, rational numbers in lowest
    378/// // terms are unique. So, by keeping `Rational`s in reduced form, we can
    379/// // derive `Eq` and `PartialEq`.
    380/// #[derive(Debug, Eq, PartialEq)]
    381/// struct Rational {
    382///     numerator: usize,
    383///     denominator: usize,
    384/// }
    385///
    386/// impl Rational {
    387///     fn new(numerator: usize, denominator: usize) -> Self {
    388///         if denominator == 0 {
    389///             panic!("Zero is an invalid denominator!");
    390///         }
    391///
    392///         // Reduce to lowest terms by dividing by the greatest common
    393///         // divisor.
    394///         let gcd = gcd(numerator, denominator);
    395///         Self {
    396///             numerator: numerator / gcd,
    397///             denominator: denominator / gcd,
    398///         }
    399///     }
    400/// }
    401///
    402/// impl Div for Rational {
    403///     // The division of rational numbers is a closed operation.
    404///     type Output = Self;
    405///
    406///     fn div(self, rhs: Self) -> Self::Output {
    407///         if rhs.numerator == 0 {
    408///             panic!("Cannot divide by zero-valued `Rational`!");
    409///         }
    410///
    411///         let numerator = self.numerator * rhs.denominator;
    412///         let denominator = self.denominator * rhs.numerator;
    413///         Self::new(numerator, denominator)
    414///     }
    415/// }
    416///
    417/// // Euclid's two-thousand-year-old algorithm for finding the greatest common
    418/// // divisor.
    419/// fn gcd(x: usize, y: usize) -> usize {
    420///     let mut x = x;
    421///     let mut y = y;
    422///     while y != 0 {
    423///         let t = y;
    424///         y = x % y;
    425///         x = t;
    426///     }
    427///     x
    428/// }
    429///
    430/// assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
    431/// assert_eq!(Rational::new(1, 2) / Rational::new(3, 4),
    432///            Rational::new(2, 3));
    433/// ```
    434///
    435/// ## Dividing vectors by scalars as in linear algebra
    436///
    437/// ```
    438/// use std::ops::Div;
    439///
    440/// struct Scalar { value: f32 }
    441///
    442/// #[derive(Debug, PartialEq)]
    443/// struct Vector { value: Vec<f32> }
    444///
    445/// impl Div<Scalar> for Vector {
    446///     type Output = Self;
    447///
    448///     fn div(self, rhs: Scalar) -> Self::Output {
    449///         Self { value: self.value.iter().map(|v| v / rhs.value).collect() }
    450///     }
    451/// }
    452///
    453/// let scalar = Scalar { value: 2f32 };
    454/// let vector = Vector { value: vec![2f32, 4f32, 6f32] };
    455/// assert_eq!(vector / scalar, Vector { value: vec![1f32, 2f32, 3f32] });
    456/// ```
    457#[lang = "div"]
    458#[stable(feature = "rust1", since = "1.0.0")]
    459#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    460#[diagnostic::on_unimplemented(
    461    message = "cannot divide `{Self}` by `{Rhs}`",
    462    label = "no implementation for `{Self} / {Rhs}`"
    463)]
    464#[doc(alias = "/")]
    465#[const_trait]
    466pub trait Div<Rhs = Self> {
    467    /// The resulting type after applying the `/` operator.
    468    #[stable(feature = "rust1", since = "1.0.0")]
    469    type Output;
    470
    471    /// Performs the `/` operation.
    472    ///
    473    /// # Example
    474    ///
    475    /// ```
    476    /// assert_eq!(12 / 2, 6);
    477    /// ```
    478    #[must_use = "this returns the result of the operation, without modifying the original"]
    479    #[rustc_diagnostic_item = "div"]
    480    #[stable(feature = "rust1", since = "1.0.0")]
    481    fn div(self, rhs: Rhs) -> Self::Output;
    482}
    483
    484macro_rules! div_impl_integer {
    485    ($(($($t:ty)*) => $panic:expr),*) => ($($(
    486        /// This operation rounds towards zero, truncating any
    487        /// fractional part of the exact result.
    488        ///
    489        /// # Panics
    490        ///
    491        #[doc = $panic]
    492        #[stable(feature = "rust1", since = "1.0.0")]
    493        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    494        impl const Div for $t {
    495            type Output = $t;
    496
    497            #[inline]
    498            #[track_caller]
    499            fn div(self, other: $t) -> $t { self / other }
    500        }
    501
    502        forward_ref_binop! { impl Div, div for $t, $t,
    503        #[stable(feature = "rust1", since = "1.0.0")]
    504        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
    505    )*)*)
    506}
    507
    508div_impl_integer! {
    509    (usize u8 u16 u32 u64 u128) => "This operation will panic if `other == 0`.",
    510    (isize i8 i16 i32 i64 i128) => "This operation will panic if `other == 0` or the division results in overflow."
    511}
    512
    513macro_rules! div_impl_float {
    514    ($($t:ty)*) => ($(
    515        #[stable(feature = "rust1", since = "1.0.0")]
    516        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    517        impl const Div for $t {
    518            type Output = $t;
    519
    520            #[inline]
    521            fn div(self, other: $t) -> $t { self / other }
    522        }
    523
    524        forward_ref_binop! { impl Div, div for $t, $t,
    525        #[stable(feature = "rust1", since = "1.0.0")]
    526        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
    527    )*)
    528}
    529
    530div_impl_float! { f16 f32 f64 f128 }
    531
    532/// The remainder operator `%`.
    533///
    534/// Note that `Rhs` is `Self` by default, but this is not mandatory.
    535///
    536/// # Examples
    537///
    538/// This example implements `Rem` on a `SplitSlice` object. After `Rem` is
    539/// implemented, one can use the `%` operator to find out what the remaining
    540/// elements of the slice would be after splitting it into equal slices of a
    541/// given length.
    542///
    543/// ```
    544/// use std::ops::Rem;
    545///
    546/// #[derive(PartialEq, Debug)]
    547/// struct SplitSlice<'a, T> {
    548///     slice: &'a [T],
    549/// }
    550///
    551/// impl<'a, T> Rem<usize> for SplitSlice<'a, T> {
    552///     type Output = Self;
    553///
    554///     fn rem(self, modulus: usize) -> Self::Output {
    555///         let len = self.slice.len();
    556///         let rem = len % modulus;
    557///         let start = len - rem;
    558///         Self {slice: &self.slice[start..]}
    559///     }
    560/// }
    561///
    562/// // If we were to divide &[0, 1, 2, 3, 4, 5, 6, 7] into slices of size 3,
    563/// // the remainder would be &[6, 7].
    564/// assert_eq!(SplitSlice { slice: &[0, 1, 2, 3, 4, 5, 6, 7] } % 3,
    565///            SplitSlice { slice: &[6, 7] });
    566/// ```
    567#[lang = "rem"]
    568#[stable(feature = "rust1", since = "1.0.0")]
    569#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    570#[diagnostic::on_unimplemented(
    571    message = "cannot calculate the remainder of `{Self}` divided by `{Rhs}`",
    572    label = "no implementation for `{Self} % {Rhs}`"
    573)]
    574#[doc(alias = "%")]
    575#[const_trait]
    576pub trait Rem<Rhs = Self> {
    577    /// The resulting type after applying the `%` operator.
    578    #[stable(feature = "rust1", since = "1.0.0")]
    579    type Output;
    580
    581    /// Performs the `%` operation.
    582    ///
    583    /// # Example
    584    ///
    585    /// ```
    586    /// assert_eq!(12 % 10, 2);
    587    /// ```
    588    #[must_use = "this returns the result of the operation, without modifying the original"]
    589    #[rustc_diagnostic_item = "rem"]
    590    #[stable(feature = "rust1", since = "1.0.0")]
    591    fn rem(self, rhs: Rhs) -> Self::Output;
    592}
    593
    594macro_rules! rem_impl_integer {
    595    ($(($($t:ty)*) => $panic:expr),*) => ($($(
    596        /// This operation satisfies `n % d == n - (n / d) * d`. The
    597        /// result has the same sign as the left operand.
    598        ///
    599        /// # Panics
    600        ///
    601        #[doc = $panic]
    602        #[stable(feature = "rust1", since = "1.0.0")]
    603        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    604        impl const Rem for $t {
    605            type Output = $t;
    606
    607            #[inline]
    608            #[track_caller]
    609            fn rem(self, other: $t) -> $t { self % other }
    610        }
    611
    612        forward_ref_binop! { impl Rem, rem for $t, $t,
    613        #[stable(feature = "rust1", since = "1.0.0")]
    614        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
    615    )*)*)
    616}
    617
    618rem_impl_integer! {
    619    (usize u8 u16 u32 u64 u128) => "This operation will panic if `other == 0`.",
    620    (isize i8 i16 i32 i64 i128) => "This operation will panic if `other == 0` or if `self / other` results in overflow."
    621}
    622
    623macro_rules! rem_impl_float {
    624    ($($t:ty)*) => ($(
    625
    626        /// The remainder from the division of two floats.
    627        ///
    628        /// The remainder has the same sign as the dividend and is computed as:
    629        /// `x - (x / y).trunc() * y`.
    630        ///
    631        /// # Examples
    632        /// ```
    633        /// let x: f32 = 50.50;
    634        /// let y: f32 = 8.125;
    635        /// let remainder = x - (x / y).trunc() * y;
    636        ///
    637        /// // The answer to both operations is 1.75
    638        /// assert_eq!(x % y, remainder);
    639        /// ```
    640        #[stable(feature = "rust1", since = "1.0.0")]
    641        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    642        impl const Rem for $t {
    643            type Output = $t;
    644
    645            #[inline]
    646            fn rem(self, other: $t) -> $t { self % other }
    647        }
    648
    649        forward_ref_binop! { impl Rem, rem for $t, $t,
    650        #[stable(feature = "rust1", since = "1.0.0")]
    651        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
    652    )*)
    653}
    654
    655rem_impl_float! { f16 f32 f64 f128 }
    656
    657/// The unary negation operator `-`.
    658///
    659/// # Examples
    660///
    661/// An implementation of `Neg` for `Sign`, which allows the use of `-` to
    662/// negate its value.
    663///
    664/// ```
    665/// use std::ops::Neg;
    666///
    667/// #[derive(Debug, PartialEq)]
    668/// enum Sign {
    669///     Negative,
    670///     Zero,
    671///     Positive,
    672/// }
    673///
    674/// impl Neg for Sign {
    675///     type Output = Self;
    676///
    677///     fn neg(self) -> Self::Output {
    678///         match self {
    679///             Sign::Negative => Sign::Positive,
    680///             Sign::Zero => Sign::Zero,
    681///             Sign::Positive => Sign::Negative,
    682///         }
    683///     }
    684/// }
    685///
    686/// // A negative positive is a negative.
    687/// assert_eq!(-Sign::Positive, Sign::Negative);
    688/// // A double negative is a positive.
    689/// assert_eq!(-Sign::Negative, Sign::Positive);
    690/// // Zero is its own negation.
    691/// assert_eq!(-Sign::Zero, Sign::Zero);
    692/// ```
    693#[lang = "neg"]
    694#[stable(feature = "rust1", since = "1.0.0")]
    695#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    696#[doc(alias = "-")]
    697#[const_trait]
    698pub trait Neg {
    699    /// The resulting type after applying the `-` operator.
    700    #[stable(feature = "rust1", since = "1.0.0")]
    701    type Output;
    702
    703    /// Performs the unary `-` operation.
    704    ///
    705    /// # Example
    706    ///
    707    /// ```
    708    /// let x: i32 = 12;
    709    /// assert_eq!(-x, -12);
    710    /// ```
    711    #[must_use = "this returns the result of the operation, without modifying the original"]
    712    #[rustc_diagnostic_item = "neg"]
    713    #[stable(feature = "rust1", since = "1.0.0")]
    714    fn neg(self) -> Self::Output;
    715}
    716
    717macro_rules! neg_impl {
    718    ($($t:ty)*) => ($(
    719        #[stable(feature = "rust1", since = "1.0.0")]
    720        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    721        impl const Neg for $t {
    722            type Output = $t;
    723
    724            #[inline]
    725            #[rustc_inherit_overflow_checks]
    726            fn neg(self) -> $t { -self }
    727        }
    728
    729        forward_ref_unop! { impl Neg, neg for $t,
    730        #[stable(feature = "rust1", since = "1.0.0")]
    731        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
    732    )*)
    733}
    734
    735neg_impl! { isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
    736
    737/// The addition assignment operator `+=`.
    738///
    739/// # Examples
    740///
    741/// This example creates a `Point` struct that implements the `AddAssign`
    742/// trait, and then demonstrates add-assigning to a mutable `Point`.
    743///
    744/// ```
    745/// use std::ops::AddAssign;
    746///
    747/// #[derive(Debug, Copy, Clone, PartialEq)]
    748/// struct Point {
    749///     x: i32,
    750///     y: i32,
    751/// }
    752///
    753/// impl AddAssign for Point {
    754///     fn add_assign(&mut self, other: Self) {
    755///         *self = Self {
    756///             x: self.x + other.x,
    757///             y: self.y + other.y,
    758///         };
    759///     }
    760/// }
    761///
    762/// let mut point = Point { x: 1, y: 0 };
    763/// point += Point { x: 2, y: 3 };
    764/// assert_eq!(point, Point { x: 3, y: 3 });
    765/// ```
    766#[lang = "add_assign"]
    767#[stable(feature = "op_assign_traits", since = "1.8.0")]
    768#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    769#[diagnostic::on_unimplemented(
    770    message = "cannot add-assign `{Rhs}` to `{Self}`",
    771    label = "no implementation for `{Self} += {Rhs}`"
    772)]
    773#[doc(alias = "+")]
    774#[doc(alias = "+=")]
    775#[const_trait]
    776pub trait AddAssign<Rhs = Self> {
    777    /// Performs the `+=` operation.
    778    ///
    779    /// # Example
    780    ///
    781    /// ```
    782    /// let mut x: u32 = 12;
    783    /// x += 1;
    784    /// assert_eq!(x, 13);
    785    /// ```
    786    #[stable(feature = "op_assign_traits", since = "1.8.0")]
    787    fn add_assign(&mut self, rhs: Rhs);
    788}
    789
    790macro_rules! add_assign_impl {
    791    ($($t:ty)+) => ($(
    792        #[stable(feature = "op_assign_traits", since = "1.8.0")]
    793        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    794        impl const AddAssign for $t {
    795            #[inline]
    796            #[track_caller]
    797            #[rustc_inherit_overflow_checks]
    798            fn add_assign(&mut self, other: $t) { *self += other }
    799        }
    800
    801        forward_ref_op_assign! { impl AddAssign, add_assign for $t, $t,
    802        #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
    803        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
    804    )+)
    805}
    806
    807add_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
    808
    809/// The subtraction assignment operator `-=`.
    810///
    811/// # Examples
    812///
    813/// This example creates a `Point` struct that implements the `SubAssign`
    814/// trait, and then demonstrates sub-assigning to a mutable `Point`.
    815///
    816/// ```
    817/// use std::ops::SubAssign;
    818///
    819/// #[derive(Debug, Copy, Clone, PartialEq)]
    820/// struct Point {
    821///     x: i32,
    822///     y: i32,
    823/// }
    824///
    825/// impl SubAssign for Point {
    826///     fn sub_assign(&mut self, other: Self) {
    827///         *self = Self {
    828///             x: self.x - other.x,
    829///             y: self.y - other.y,
    830///         };
    831///     }
    832/// }
    833///
    834/// let mut point = Point { x: 3, y: 3 };
    835/// point -= Point { x: 2, y: 3 };
    836/// assert_eq!(point, Point {x: 1, y: 0});
    837/// ```
    838#[lang = "sub_assign"]
    839#[stable(feature = "op_assign_traits", since = "1.8.0")]
    840#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    841#[diagnostic::on_unimplemented(
    842    message = "cannot subtract-assign `{Rhs}` from `{Self}`",
    843    label = "no implementation for `{Self} -= {Rhs}`"
    844)]
    845#[doc(alias = "-")]
    846#[doc(alias = "-=")]
    847#[const_trait]
    848pub trait SubAssign<Rhs = Self> {
    849    /// Performs the `-=` operation.
    850    ///
    851    /// # Example
    852    ///
    853    /// ```
    854    /// let mut x: u32 = 12;
    855    /// x -= 1;
    856    /// assert_eq!(x, 11);
    857    /// ```
    858    #[stable(feature = "op_assign_traits", since = "1.8.0")]
    859    fn sub_assign(&mut self, rhs: Rhs);
    860}
    861
    862macro_rules! sub_assign_impl {
    863    ($($t:ty)+) => ($(
    864        #[stable(feature = "op_assign_traits", since = "1.8.0")]
    865        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    866        impl const SubAssign for $t {
    867            #[inline]
    868            #[track_caller]
    869            #[rustc_inherit_overflow_checks]
    870            fn sub_assign(&mut self, other: $t) { *self -= other }
    871        }
    872
    873        forward_ref_op_assign! { impl SubAssign, sub_assign for $t, $t,
    874        #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
    875        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
    876    )+)
    877}
    878
    879sub_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
    880
    881/// The multiplication assignment operator `*=`.
    882///
    883/// # Examples
    884///
    885/// ```
    886/// use std::ops::MulAssign;
    887///
    888/// #[derive(Debug, PartialEq)]
    889/// struct Frequency { hertz: f64 }
    890///
    891/// impl MulAssign<f64> for Frequency {
    892///     fn mul_assign(&mut self, rhs: f64) {
    893///         self.hertz *= rhs;
    894///     }
    895/// }
    896///
    897/// let mut frequency = Frequency { hertz: 50.0 };
    898/// frequency *= 4.0;
    899/// assert_eq!(Frequency { hertz: 200.0 }, frequency);
    900/// ```
    901#[lang = "mul_assign"]
    902#[stable(feature = "op_assign_traits", since = "1.8.0")]
    903#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    904#[diagnostic::on_unimplemented(
    905    message = "cannot multiply-assign `{Self}` by `{Rhs}`",
    906    label = "no implementation for `{Self} *= {Rhs}`"
    907)]
    908#[doc(alias = "*")]
    909#[doc(alias = "*=")]
    910#[const_trait]
    911pub trait MulAssign<Rhs = Self> {
    912    /// Performs the `*=` operation.
    913    ///
    914    /// # Example
    915    ///
    916    /// ```
    917    /// let mut x: u32 = 12;
    918    /// x *= 2;
    919    /// assert_eq!(x, 24);
    920    /// ```
    921    #[stable(feature = "op_assign_traits", since = "1.8.0")]
    922    fn mul_assign(&mut self, rhs: Rhs);
    923}
    924
    925macro_rules! mul_assign_impl {
    926    ($($t:ty)+) => ($(
    927        #[stable(feature = "op_assign_traits", since = "1.8.0")]
    928        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    929        impl const MulAssign for $t {
    930            #[inline]
    931            #[track_caller]
    932            #[rustc_inherit_overflow_checks]
    933            fn mul_assign(&mut self, other: $t) { *self *= other }
    934        }
    935
    936        forward_ref_op_assign! { impl MulAssign, mul_assign for $t, $t,
    937        #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
    938        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
    939    )+)
    940}
    941
    942mul_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
    943
    944/// The division assignment operator `/=`.
    945///
    946/// # Examples
    947///
    948/// ```
    949/// use std::ops::DivAssign;
    950///
    951/// #[derive(Debug, PartialEq)]
    952/// struct Frequency { hertz: f64 }
    953///
    954/// impl DivAssign<f64> for Frequency {
    955///     fn div_assign(&mut self, rhs: f64) {
    956///         self.hertz /= rhs;
    957///     }
    958/// }
    959///
    960/// let mut frequency = Frequency { hertz: 200.0 };
    961/// frequency /= 4.0;
    962/// assert_eq!(Frequency { hertz: 50.0 }, frequency);
    963/// ```
    964#[lang = "div_assign"]
    965#[stable(feature = "op_assign_traits", since = "1.8.0")]
    966#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    967#[diagnostic::on_unimplemented(
    968    message = "cannot divide-assign `{Self}` by `{Rhs}`",
    969    label = "no implementation for `{Self} /= {Rhs}`"
    970)]
    971#[doc(alias = "/")]
    972#[doc(alias = "/=")]
    973#[const_trait]
    974pub trait DivAssign<Rhs = Self> {
    975    /// Performs the `/=` operation.
    976    ///
    977    /// # Example
    978    ///
    979    /// ```
    980    /// let mut x: u32 = 12;
    981    /// x /= 2;
    982    /// assert_eq!(x, 6);
    983    /// ```
    984    #[stable(feature = "op_assign_traits", since = "1.8.0")]
    985    fn div_assign(&mut self, rhs: Rhs);
    986}
    987
    988macro_rules! div_assign_impl {
    989    ($($t:ty)+) => ($(
    990        #[stable(feature = "op_assign_traits", since = "1.8.0")]
    991        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    992        impl const DivAssign for $t {
    993            #[inline]
    994            #[track_caller]
    995            fn div_assign(&mut self, other: $t) { *self /= other }
    996        }
    997
    998        forward_ref_op_assign! { impl DivAssign, div_assign for $t, $t,
    999        #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
    1000        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
    1001    )+)
    1002}
    1003
    1004div_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
    1005
    1006/// The remainder assignment operator `%=`.
    1007///
    1008/// # Examples
    1009///
    1010/// ```
    1011/// use std::ops::RemAssign;
    1012///
    1013/// struct CookieJar { cookies: u32 }
    1014///
    1015/// impl RemAssign<u32> for CookieJar {
    1016///     fn rem_assign(&mut self, piles: u32) {
    1017///         self.cookies %= piles;
    1018///     }
    1019/// }
    1020///
    1021/// let mut jar = CookieJar { cookies: 31 };
    1022/// let piles = 4;
    1023///
    1024/// println!("Splitting up {} cookies into {} even piles!", jar.cookies, piles);
    1025///
    1026/// jar %= piles;
    1027///
    1028/// println!("{} cookies remain in the cookie jar!", jar.cookies);
    1029/// ```
    1030#[lang = "rem_assign"]
    1031#[stable(feature = "op_assign_traits", since = "1.8.0")]
    1032#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    1033#[diagnostic::on_unimplemented(
    1034    message = "cannot calculate and assign the remainder of `{Self}` divided by `{Rhs}`",
    1035    label = "no implementation for `{Self} %= {Rhs}`"
    1036)]
    1037#[doc(alias = "%")]
    1038#[doc(alias = "%=")]
    1039#[const_trait]
    1040pub trait RemAssign<Rhs = Self> {
    1041    /// Performs the `%=` operation.
    1042    ///
    1043    /// # Example
    1044    ///
    1045    /// ```
    1046    /// let mut x: u32 = 12;
    1047    /// x %= 10;
    1048    /// assert_eq!(x, 2);
    1049    /// ```
    1050    #[stable(feature = "op_assign_traits", since = "1.8.0")]
    1051    fn rem_assign(&mut self, rhs: Rhs);
    1052}
    1053
    1054macro_rules! rem_assign_impl {
    1055    ($($t:ty)+) => ($(
    1056        #[stable(feature = "op_assign_traits", since = "1.8.0")]
    1057        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
    1058        impl const RemAssign for $t {
    1059            #[inline]
    1060            #[track_caller]
    1061            fn rem_assign(&mut self, other: $t) { *self %= other }
    1062        }
    1063
    1064        forward_ref_op_assign! { impl RemAssign, rem_assign for $t, $t,
    1065        #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
    1066        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
    1067    )+)
    1068}
    1069
    1070rem_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }