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