Skip to main content

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 = "+")]
77pub const trait Add<Rhs = Self> {
78    /// The resulting type after applying the `+` operator.
79    #[stable(feature = "rust1", since = "1.0.0")]
80    type Output;
81
82    /// Performs the `+` operation.
83    ///
84    /// # Example
85    ///
86    /// ```
87    /// assert_eq!(12 + 1, 13);
88    /// ```
89    #[must_use = "this returns the result of the operation, without modifying the original"]
90    #[rustc_diagnostic_item = "add"]
91    #[stable(feature = "rust1", since = "1.0.0")]
92    fn add(self, rhs: Rhs) -> Self::Output;
93}
94
95macro_rules! add_impl {
96    ($($t:ty)*) => ($(
97        #[stable(feature = "rust1", since = "1.0.0")]
98        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
99        impl const Add for $t {
100            type Output = $t;
101
102            #[inline]
103            #[track_caller]
104            #[rustc_inherit_overflow_checks]
105            #[ferrocene::prevalidated]
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 = "-")]
191pub const trait Sub<Rhs = Self> {
192    /// The resulting type after applying the `-` operator.
193    #[stable(feature = "rust1", since = "1.0.0")]
194    type Output;
195
196    /// Performs the `-` operation.
197    ///
198    /// # Example
199    ///
200    /// ```
201    /// assert_eq!(12 - 1, 11);
202    /// ```
203    #[must_use = "this returns the result of the operation, without modifying the original"]
204    #[rustc_diagnostic_item = "sub"]
205    #[stable(feature = "rust1", since = "1.0.0")]
206    fn sub(self, rhs: Rhs) -> Self::Output;
207}
208
209macro_rules! sub_impl {
210    ($($t:ty)*) => ($(
211        #[stable(feature = "rust1", since = "1.0.0")]
212        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
213        impl const Sub for $t {
214            type Output = $t;
215
216            #[inline]
217            #[track_caller]
218            #[rustc_inherit_overflow_checks]
219            #[ferrocene::prevalidated]
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 = "*")]
326pub const trait Mul<Rhs = Self> {
327    /// The resulting type after applying the `*` operator.
328    #[stable(feature = "rust1", since = "1.0.0")]
329    type Output;
330
331    /// Performs the `*` operation.
332    ///
333    /// # Example
334    ///
335    /// ```
336    /// assert_eq!(12 * 2, 24);
337    /// ```
338    #[must_use = "this returns the result of the operation, without modifying the original"]
339    #[rustc_diagnostic_item = "mul"]
340    #[stable(feature = "rust1", since = "1.0.0")]
341    fn mul(self, rhs: Rhs) -> Self::Output;
342}
343
344macro_rules! mul_impl {
345    ($($t:ty)*) => ($(
346        #[stable(feature = "rust1", since = "1.0.0")]
347        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
348        impl const Mul for $t {
349            type Output = $t;
350
351            #[inline]
352            #[track_caller]
353            #[rustc_inherit_overflow_checks]
354            #[ferrocene::prevalidated]
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 = "/")]
465pub const trait Div<Rhs = Self> {
466    /// The resulting type after applying the `/` operator.
467    #[stable(feature = "rust1", since = "1.0.0")]
468    type Output;
469
470    /// Performs the `/` operation.
471    ///
472    /// # Example
473    ///
474    /// ```
475    /// assert_eq!(12 / 2, 6);
476    /// ```
477    #[must_use = "this returns the result of the operation, without modifying the original"]
478    #[rustc_diagnostic_item = "div"]
479    #[stable(feature = "rust1", since = "1.0.0")]
480    fn div(self, rhs: Rhs) -> Self::Output;
481}
482
483macro_rules! div_impl_integer {
484    ($(($($t:ty)*) => $panic:expr),*) => ($($(
485        /// This operation rounds towards zero, truncating any
486        /// fractional part of the exact result.
487        ///
488        /// # Panics
489        ///
490        #[doc = $panic]
491        #[stable(feature = "rust1", since = "1.0.0")]
492        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
493        impl const Div for $t {
494            type Output = $t;
495
496            #[inline]
497            #[track_caller]
498            #[ferrocene::prevalidated]
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            #[ferrocene::prevalidated]
522            fn div(self, other: $t) -> $t { self / other }
523        }
524
525        forward_ref_binop! { impl Div, div for $t, $t,
526        #[stable(feature = "rust1", since = "1.0.0")]
527        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
528    )*)
529}
530
531div_impl_float! { f16 f32 f64 f128 }
532
533/// The remainder operator `%`.
534///
535/// Note that `Rhs` is `Self` by default, but this is not mandatory.
536///
537/// # Examples
538///
539/// This example implements `Rem` on a `SplitSlice` object. After `Rem` is
540/// implemented, one can use the `%` operator to find out what the remaining
541/// elements of the slice would be after splitting it into equal slices of a
542/// given length.
543///
544/// ```
545/// use std::ops::Rem;
546///
547/// #[derive(PartialEq, Debug)]
548/// struct SplitSlice<'a, T> {
549///     slice: &'a [T],
550/// }
551///
552/// impl<'a, T> Rem<usize> for SplitSlice<'a, T> {
553///     type Output = Self;
554///
555///     fn rem(self, modulus: usize) -> Self::Output {
556///         let len = self.slice.len();
557///         let rem = len % modulus;
558///         let start = len - rem;
559///         Self {slice: &self.slice[start..]}
560///     }
561/// }
562///
563/// // If we were to divide &[0, 1, 2, 3, 4, 5, 6, 7] into slices of size 3,
564/// // the remainder would be &[6, 7].
565/// assert_eq!(SplitSlice { slice: &[0, 1, 2, 3, 4, 5, 6, 7] } % 3,
566///            SplitSlice { slice: &[6, 7] });
567/// ```
568#[lang = "rem"]
569#[stable(feature = "rust1", since = "1.0.0")]
570#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
571#[diagnostic::on_unimplemented(
572    message = "cannot calculate the remainder of `{Self}` divided by `{Rhs}`",
573    label = "no implementation for `{Self} % {Rhs}`"
574)]
575#[doc(alias = "%")]
576pub const 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            #[ferrocene::prevalidated]
610            fn rem(self, other: $t) -> $t { self % other }
611        }
612
613        forward_ref_binop! { impl Rem, rem for $t, $t,
614        #[stable(feature = "rust1", since = "1.0.0")]
615        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
616    )*)*)
617}
618
619rem_impl_integer! {
620    (usize u8 u16 u32 u64 u128) => "This operation will panic if `other == 0`.",
621    (isize i8 i16 i32 i64 i128) => "This operation will panic if `other == 0` or if `self / other` results in overflow."
622}
623
624macro_rules! rem_impl_float {
625    ($($t:ty)*) => ($(
626
627        /// The remainder from the division of two floats.
628        ///
629        /// The remainder has the same sign as the dividend and is computed as:
630        /// `x - (x / y).trunc() * y`.
631        ///
632        /// # Examples
633        /// ```
634        /// let x: f32 = 50.50;
635        /// let y: f32 = 8.125;
636        /// let remainder = x - (x / y).trunc() * y;
637        ///
638        /// // The answer to both operations is 1.75
639        /// assert_eq!(x % y, remainder);
640        /// ```
641        #[stable(feature = "rust1", since = "1.0.0")]
642        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
643        impl const Rem for $t {
644            type Output = $t;
645
646            #[inline]
647            #[ferrocene::prevalidated]
648            fn rem(self, other: $t) -> $t { self % other }
649        }
650
651        forward_ref_binop! { impl Rem, rem for $t, $t,
652        #[stable(feature = "rust1", since = "1.0.0")]
653        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
654    )*)
655}
656
657rem_impl_float! { f16 f32 f64 f128 }
658
659/// The unary negation operator `-`.
660///
661/// # Examples
662///
663/// An implementation of `Neg` for `Sign`, which allows the use of `-` to
664/// negate its value.
665///
666/// ```
667/// use std::ops::Neg;
668///
669/// #[derive(Debug, PartialEq)]
670/// enum Sign {
671///     Negative,
672///     Zero,
673///     Positive,
674/// }
675///
676/// impl Neg for Sign {
677///     type Output = Self;
678///
679///     fn neg(self) -> Self::Output {
680///         match self {
681///             Sign::Negative => Sign::Positive,
682///             Sign::Zero => Sign::Zero,
683///             Sign::Positive => Sign::Negative,
684///         }
685///     }
686/// }
687///
688/// // A negative positive is a negative.
689/// assert_eq!(-Sign::Positive, Sign::Negative);
690/// // A double negative is a positive.
691/// assert_eq!(-Sign::Negative, Sign::Positive);
692/// // Zero is its own negation.
693/// assert_eq!(-Sign::Zero, Sign::Zero);
694/// ```
695#[lang = "neg"]
696#[stable(feature = "rust1", since = "1.0.0")]
697#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
698#[doc(alias = "-")]
699pub const trait Neg {
700    /// The resulting type after applying the `-` operator.
701    #[stable(feature = "rust1", since = "1.0.0")]
702    type Output;
703
704    /// Performs the unary `-` operation.
705    ///
706    /// # Example
707    ///
708    /// ```
709    /// let x: i32 = 12;
710    /// assert_eq!(-x, -12);
711    /// ```
712    #[must_use = "this returns the result of the operation, without modifying the original"]
713    #[rustc_diagnostic_item = "neg"]
714    #[stable(feature = "rust1", since = "1.0.0")]
715    fn neg(self) -> Self::Output;
716}
717
718macro_rules! neg_impl {
719    ($($t:ty)*) => ($(
720        #[stable(feature = "rust1", since = "1.0.0")]
721        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
722        impl const Neg for $t {
723            type Output = $t;
724
725            #[inline]
726            #[track_caller]
727            #[rustc_inherit_overflow_checks]
728            #[ferrocene::prevalidated]
729            fn neg(self) -> $t { -self }
730        }
731
732        forward_ref_unop! { impl Neg, neg for $t,
733        #[stable(feature = "rust1", since = "1.0.0")]
734        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
735    )*)
736}
737
738neg_impl! { isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
739
740/// The addition assignment operator `+=`.
741///
742/// # Examples
743///
744/// This example creates a `Point` struct that implements the `AddAssign`
745/// trait, and then demonstrates add-assigning to a mutable `Point`.
746///
747/// ```
748/// use std::ops::AddAssign;
749///
750/// #[derive(Debug, Copy, Clone, PartialEq)]
751/// struct Point {
752///     x: i32,
753///     y: i32,
754/// }
755///
756/// impl AddAssign for Point {
757///     fn add_assign(&mut self, other: Self) {
758///         *self = Self {
759///             x: self.x + other.x,
760///             y: self.y + other.y,
761///         };
762///     }
763/// }
764///
765/// let mut point = Point { x: 1, y: 0 };
766/// point += Point { x: 2, y: 3 };
767/// assert_eq!(point, Point { x: 3, y: 3 });
768/// ```
769#[lang = "add_assign"]
770#[stable(feature = "op_assign_traits", since = "1.8.0")]
771#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
772#[diagnostic::on_unimplemented(
773    message = "cannot add-assign `{Rhs}` to `{Self}`",
774    label = "no implementation for `{Self} += {Rhs}`"
775)]
776#[doc(alias = "+")]
777#[doc(alias = "+=")]
778pub const trait AddAssign<Rhs = Self> {
779    /// Performs the `+=` operation.
780    ///
781    /// # Example
782    ///
783    /// ```
784    /// let mut x: u32 = 12;
785    /// x += 1;
786    /// assert_eq!(x, 13);
787    /// ```
788    #[stable(feature = "op_assign_traits", since = "1.8.0")]
789    fn add_assign(&mut self, rhs: Rhs);
790}
791
792macro_rules! add_assign_impl {
793    ($($t:ty)+) => ($(
794        #[stable(feature = "op_assign_traits", since = "1.8.0")]
795        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
796        impl const AddAssign for $t {
797            #[inline]
798            #[track_caller]
799            #[rustc_inherit_overflow_checks]
800            #[ferrocene::prevalidated]
801            fn add_assign(&mut self, other: $t) { *self += other }
802        }
803
804        forward_ref_op_assign! { impl AddAssign, add_assign for $t, $t,
805        #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
806        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
807    )+)
808}
809
810add_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
811
812/// The subtraction assignment operator `-=`.
813///
814/// # Examples
815///
816/// This example creates a `Point` struct that implements the `SubAssign`
817/// trait, and then demonstrates sub-assigning to a mutable `Point`.
818///
819/// ```
820/// use std::ops::SubAssign;
821///
822/// #[derive(Debug, Copy, Clone, PartialEq)]
823/// struct Point {
824///     x: i32,
825///     y: i32,
826/// }
827///
828/// impl SubAssign for Point {
829///     fn sub_assign(&mut self, other: Self) {
830///         *self = Self {
831///             x: self.x - other.x,
832///             y: self.y - other.y,
833///         };
834///     }
835/// }
836///
837/// let mut point = Point { x: 3, y: 3 };
838/// point -= Point { x: 2, y: 3 };
839/// assert_eq!(point, Point {x: 1, y: 0});
840/// ```
841#[lang = "sub_assign"]
842#[stable(feature = "op_assign_traits", since = "1.8.0")]
843#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
844#[diagnostic::on_unimplemented(
845    message = "cannot subtract-assign `{Rhs}` from `{Self}`",
846    label = "no implementation for `{Self} -= {Rhs}`"
847)]
848#[doc(alias = "-")]
849#[doc(alias = "-=")]
850pub const trait SubAssign<Rhs = Self> {
851    /// Performs the `-=` operation.
852    ///
853    /// # Example
854    ///
855    /// ```
856    /// let mut x: u32 = 12;
857    /// x -= 1;
858    /// assert_eq!(x, 11);
859    /// ```
860    #[stable(feature = "op_assign_traits", since = "1.8.0")]
861    fn sub_assign(&mut self, rhs: Rhs);
862}
863
864macro_rules! sub_assign_impl {
865    ($($t:ty)+) => ($(
866        #[stable(feature = "op_assign_traits", since = "1.8.0")]
867        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
868        impl const SubAssign for $t {
869            #[inline]
870            #[track_caller]
871            #[rustc_inherit_overflow_checks]
872            #[ferrocene::prevalidated]
873            fn sub_assign(&mut self, other: $t) { *self -= other }
874        }
875
876        forward_ref_op_assign! { impl SubAssign, sub_assign for $t, $t,
877        #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
878        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
879    )+)
880}
881
882sub_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
883
884/// The multiplication assignment operator `*=`.
885///
886/// # Examples
887///
888/// ```
889/// use std::ops::MulAssign;
890///
891/// #[derive(Debug, PartialEq)]
892/// struct Frequency { hertz: f64 }
893///
894/// impl MulAssign<f64> for Frequency {
895///     fn mul_assign(&mut self, rhs: f64) {
896///         self.hertz *= rhs;
897///     }
898/// }
899///
900/// let mut frequency = Frequency { hertz: 50.0 };
901/// frequency *= 4.0;
902/// assert_eq!(Frequency { hertz: 200.0 }, frequency);
903/// ```
904#[lang = "mul_assign"]
905#[stable(feature = "op_assign_traits", since = "1.8.0")]
906#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
907#[diagnostic::on_unimplemented(
908    message = "cannot multiply-assign `{Self}` by `{Rhs}`",
909    label = "no implementation for `{Self} *= {Rhs}`"
910)]
911#[doc(alias = "*")]
912#[doc(alias = "*=")]
913pub const trait MulAssign<Rhs = Self> {
914    /// Performs the `*=` operation.
915    ///
916    /// # Example
917    ///
918    /// ```
919    /// let mut x: u32 = 12;
920    /// x *= 2;
921    /// assert_eq!(x, 24);
922    /// ```
923    #[stable(feature = "op_assign_traits", since = "1.8.0")]
924    fn mul_assign(&mut self, rhs: Rhs);
925}
926
927macro_rules! mul_assign_impl {
928    ($($t:ty)+) => ($(
929        #[stable(feature = "op_assign_traits", since = "1.8.0")]
930        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
931        impl const MulAssign for $t {
932            #[inline]
933            #[track_caller]
934            #[rustc_inherit_overflow_checks]
935            #[ferrocene::prevalidated]
936            fn mul_assign(&mut self, other: $t) { *self *= other }
937        }
938
939        forward_ref_op_assign! { impl MulAssign, mul_assign for $t, $t,
940        #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
941        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
942    )+)
943}
944
945mul_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
946
947/// The division assignment operator `/=`.
948///
949/// # Examples
950///
951/// ```
952/// use std::ops::DivAssign;
953///
954/// #[derive(Debug, PartialEq)]
955/// struct Frequency { hertz: f64 }
956///
957/// impl DivAssign<f64> for Frequency {
958///     fn div_assign(&mut self, rhs: f64) {
959///         self.hertz /= rhs;
960///     }
961/// }
962///
963/// let mut frequency = Frequency { hertz: 200.0 };
964/// frequency /= 4.0;
965/// assert_eq!(Frequency { hertz: 50.0 }, frequency);
966/// ```
967#[lang = "div_assign"]
968#[stable(feature = "op_assign_traits", since = "1.8.0")]
969#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
970#[diagnostic::on_unimplemented(
971    message = "cannot divide-assign `{Self}` by `{Rhs}`",
972    label = "no implementation for `{Self} /= {Rhs}`"
973)]
974#[doc(alias = "/")]
975#[doc(alias = "/=")]
976pub const trait DivAssign<Rhs = Self> {
977    /// Performs the `/=` operation.
978    ///
979    /// # Example
980    ///
981    /// ```
982    /// let mut x: u32 = 12;
983    /// x /= 2;
984    /// assert_eq!(x, 6);
985    /// ```
986    #[stable(feature = "op_assign_traits", since = "1.8.0")]
987    fn div_assign(&mut self, rhs: Rhs);
988}
989
990macro_rules! div_assign_impl {
991    ($($t:ty)+) => ($(
992        #[stable(feature = "op_assign_traits", since = "1.8.0")]
993        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
994        impl const DivAssign for $t {
995            #[inline]
996            #[track_caller]
997            #[ferrocene::prevalidated]
998            fn div_assign(&mut self, other: $t) { *self /= other }
999        }
1000
1001        forward_ref_op_assign! { impl DivAssign, div_assign for $t, $t,
1002        #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
1003        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
1004    )+)
1005}
1006
1007div_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
1008
1009/// The remainder assignment operator `%=`.
1010///
1011/// # Examples
1012///
1013/// ```
1014/// use std::ops::RemAssign;
1015///
1016/// struct CookieJar { cookies: u32 }
1017///
1018/// impl RemAssign<u32> for CookieJar {
1019///     fn rem_assign(&mut self, piles: u32) {
1020///         self.cookies %= piles;
1021///     }
1022/// }
1023///
1024/// let mut jar = CookieJar { cookies: 31 };
1025/// let piles = 4;
1026///
1027/// println!("Splitting up {} cookies into {} even piles!", jar.cookies, piles);
1028///
1029/// jar %= piles;
1030///
1031/// println!("{} cookies remain in the cookie jar!", jar.cookies);
1032/// ```
1033#[lang = "rem_assign"]
1034#[stable(feature = "op_assign_traits", since = "1.8.0")]
1035#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1036#[diagnostic::on_unimplemented(
1037    message = "cannot calculate and assign the remainder of `{Self}` divided by `{Rhs}`",
1038    label = "no implementation for `{Self} %= {Rhs}`"
1039)]
1040#[doc(alias = "%")]
1041#[doc(alias = "%=")]
1042pub const trait RemAssign<Rhs = Self> {
1043    /// Performs the `%=` operation.
1044    ///
1045    /// # Example
1046    ///
1047    /// ```
1048    /// let mut x: u32 = 12;
1049    /// x %= 10;
1050    /// assert_eq!(x, 2);
1051    /// ```
1052    #[stable(feature = "op_assign_traits", since = "1.8.0")]
1053    fn rem_assign(&mut self, rhs: Rhs);
1054}
1055
1056macro_rules! rem_assign_impl {
1057    ($($t:ty)+) => ($(
1058        #[stable(feature = "op_assign_traits", since = "1.8.0")]
1059        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1060        impl const RemAssign for $t {
1061            #[inline]
1062            #[track_caller]
1063            #[ferrocene::prevalidated]
1064            fn rem_assign(&mut self, other: $t) { *self %= other }
1065        }
1066
1067        forward_ref_op_assign! { impl RemAssign, rem_assign for $t, $t,
1068        #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
1069        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
1070    )+)
1071}
1072
1073rem_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }