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 #[rustc_inherit_overflow_checks]
727 #[ferrocene::prevalidated]
728 fn neg(self) -> $t { -self }
729 }
730
731 forward_ref_unop! { impl Neg, neg for $t,
732 #[stable(feature = "rust1", since = "1.0.0")]
733 #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
734 )*)
735}
736
737neg_impl! { isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
738
739/// The addition assignment operator `+=`.
740///
741/// # Examples
742///
743/// This example creates a `Point` struct that implements the `AddAssign`
744/// trait, and then demonstrates add-assigning to a mutable `Point`.
745///
746/// ```
747/// use std::ops::AddAssign;
748///
749/// #[derive(Debug, Copy, Clone, PartialEq)]
750/// struct Point {
751/// x: i32,
752/// y: i32,
753/// }
754///
755/// impl AddAssign for Point {
756/// fn add_assign(&mut self, other: Self) {
757/// *self = Self {
758/// x: self.x + other.x,
759/// y: self.y + other.y,
760/// };
761/// }
762/// }
763///
764/// let mut point = Point { x: 1, y: 0 };
765/// point += Point { x: 2, y: 3 };
766/// assert_eq!(point, Point { x: 3, y: 3 });
767/// ```
768#[lang = "add_assign"]
769#[stable(feature = "op_assign_traits", since = "1.8.0")]
770#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
771#[diagnostic::on_unimplemented(
772 message = "cannot add-assign `{Rhs}` to `{Self}`",
773 label = "no implementation for `{Self} += {Rhs}`"
774)]
775#[doc(alias = "+")]
776#[doc(alias = "+=")]
777pub const trait AddAssign<Rhs = Self> {
778 /// Performs the `+=` operation.
779 ///
780 /// # Example
781 ///
782 /// ```
783 /// let mut x: u32 = 12;
784 /// x += 1;
785 /// assert_eq!(x, 13);
786 /// ```
787 #[stable(feature = "op_assign_traits", since = "1.8.0")]
788 fn add_assign(&mut self, rhs: Rhs);
789}
790
791macro_rules! add_assign_impl {
792 ($($t:ty)+) => ($(
793 #[stable(feature = "op_assign_traits", since = "1.8.0")]
794 #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
795 impl const AddAssign for $t {
796 #[inline]
797 #[track_caller]
798 #[rustc_inherit_overflow_checks]
799 #[ferrocene::prevalidated]
800 fn add_assign(&mut self, other: $t) { *self += other }
801 }
802
803 forward_ref_op_assign! { impl AddAssign, add_assign for $t, $t,
804 #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
805 #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
806 )+)
807}
808
809add_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
810
811/// The subtraction assignment operator `-=`.
812///
813/// # Examples
814///
815/// This example creates a `Point` struct that implements the `SubAssign`
816/// trait, and then demonstrates sub-assigning to a mutable `Point`.
817///
818/// ```
819/// use std::ops::SubAssign;
820///
821/// #[derive(Debug, Copy, Clone, PartialEq)]
822/// struct Point {
823/// x: i32,
824/// y: i32,
825/// }
826///
827/// impl SubAssign for Point {
828/// fn sub_assign(&mut self, other: Self) {
829/// *self = Self {
830/// x: self.x - other.x,
831/// y: self.y - other.y,
832/// };
833/// }
834/// }
835///
836/// let mut point = Point { x: 3, y: 3 };
837/// point -= Point { x: 2, y: 3 };
838/// assert_eq!(point, Point {x: 1, y: 0});
839/// ```
840#[lang = "sub_assign"]
841#[stable(feature = "op_assign_traits", since = "1.8.0")]
842#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
843#[diagnostic::on_unimplemented(
844 message = "cannot subtract-assign `{Rhs}` from `{Self}`",
845 label = "no implementation for `{Self} -= {Rhs}`"
846)]
847#[doc(alias = "-")]
848#[doc(alias = "-=")]
849pub const trait SubAssign<Rhs = Self> {
850 /// Performs the `-=` operation.
851 ///
852 /// # Example
853 ///
854 /// ```
855 /// let mut x: u32 = 12;
856 /// x -= 1;
857 /// assert_eq!(x, 11);
858 /// ```
859 #[stable(feature = "op_assign_traits", since = "1.8.0")]
860 fn sub_assign(&mut self, rhs: Rhs);
861}
862
863macro_rules! sub_assign_impl {
864 ($($t:ty)+) => ($(
865 #[stable(feature = "op_assign_traits", since = "1.8.0")]
866 #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
867 impl const SubAssign for $t {
868 #[inline]
869 #[track_caller]
870 #[rustc_inherit_overflow_checks]
871 #[ferrocene::prevalidated]
872 fn sub_assign(&mut self, other: $t) { *self -= other }
873 }
874
875 forward_ref_op_assign! { impl SubAssign, sub_assign for $t, $t,
876 #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
877 #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
878 )+)
879}
880
881sub_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
882
883/// The multiplication assignment operator `*=`.
884///
885/// # Examples
886///
887/// ```
888/// use std::ops::MulAssign;
889///
890/// #[derive(Debug, PartialEq)]
891/// struct Frequency { hertz: f64 }
892///
893/// impl MulAssign<f64> for Frequency {
894/// fn mul_assign(&mut self, rhs: f64) {
895/// self.hertz *= rhs;
896/// }
897/// }
898///
899/// let mut frequency = Frequency { hertz: 50.0 };
900/// frequency *= 4.0;
901/// assert_eq!(Frequency { hertz: 200.0 }, frequency);
902/// ```
903#[lang = "mul_assign"]
904#[stable(feature = "op_assign_traits", since = "1.8.0")]
905#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
906#[diagnostic::on_unimplemented(
907 message = "cannot multiply-assign `{Self}` by `{Rhs}`",
908 label = "no implementation for `{Self} *= {Rhs}`"
909)]
910#[doc(alias = "*")]
911#[doc(alias = "*=")]
912pub const trait MulAssign<Rhs = Self> {
913 /// Performs the `*=` operation.
914 ///
915 /// # Example
916 ///
917 /// ```
918 /// let mut x: u32 = 12;
919 /// x *= 2;
920 /// assert_eq!(x, 24);
921 /// ```
922 #[stable(feature = "op_assign_traits", since = "1.8.0")]
923 fn mul_assign(&mut self, rhs: Rhs);
924}
925
926macro_rules! mul_assign_impl {
927 ($($t:ty)+) => ($(
928 #[stable(feature = "op_assign_traits", since = "1.8.0")]
929 #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
930 impl const MulAssign for $t {
931 #[inline]
932 #[track_caller]
933 #[rustc_inherit_overflow_checks]
934 #[ferrocene::prevalidated]
935 fn mul_assign(&mut self, other: $t) { *self *= other }
936 }
937
938 forward_ref_op_assign! { impl MulAssign, mul_assign for $t, $t,
939 #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
940 #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
941 )+)
942}
943
944mul_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
945
946/// The division assignment operator `/=`.
947///
948/// # Examples
949///
950/// ```
951/// use std::ops::DivAssign;
952///
953/// #[derive(Debug, PartialEq)]
954/// struct Frequency { hertz: f64 }
955///
956/// impl DivAssign<f64> for Frequency {
957/// fn div_assign(&mut self, rhs: f64) {
958/// self.hertz /= rhs;
959/// }
960/// }
961///
962/// let mut frequency = Frequency { hertz: 200.0 };
963/// frequency /= 4.0;
964/// assert_eq!(Frequency { hertz: 50.0 }, frequency);
965/// ```
966#[lang = "div_assign"]
967#[stable(feature = "op_assign_traits", since = "1.8.0")]
968#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
969#[diagnostic::on_unimplemented(
970 message = "cannot divide-assign `{Self}` by `{Rhs}`",
971 label = "no implementation for `{Self} /= {Rhs}`"
972)]
973#[doc(alias = "/")]
974#[doc(alias = "/=")]
975pub const trait DivAssign<Rhs = Self> {
976 /// Performs the `/=` operation.
977 ///
978 /// # Example
979 ///
980 /// ```
981 /// let mut x: u32 = 12;
982 /// x /= 2;
983 /// assert_eq!(x, 6);
984 /// ```
985 #[stable(feature = "op_assign_traits", since = "1.8.0")]
986 fn div_assign(&mut self, rhs: Rhs);
987}
988
989macro_rules! div_assign_impl {
990 ($($t:ty)+) => ($(
991 #[stable(feature = "op_assign_traits", since = "1.8.0")]
992 #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
993 impl const DivAssign for $t {
994 #[inline]
995 #[track_caller]
996 #[ferrocene::prevalidated]
997 fn div_assign(&mut self, other: $t) { *self /= other }
998 }
999
1000 forward_ref_op_assign! { impl DivAssign, div_assign for $t, $t,
1001 #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
1002 #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
1003 )+)
1004}
1005
1006div_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
1007
1008/// The remainder assignment operator `%=`.
1009///
1010/// # Examples
1011///
1012/// ```
1013/// use std::ops::RemAssign;
1014///
1015/// struct CookieJar { cookies: u32 }
1016///
1017/// impl RemAssign<u32> for CookieJar {
1018/// fn rem_assign(&mut self, piles: u32) {
1019/// self.cookies %= piles;
1020/// }
1021/// }
1022///
1023/// let mut jar = CookieJar { cookies: 31 };
1024/// let piles = 4;
1025///
1026/// println!("Splitting up {} cookies into {} even piles!", jar.cookies, piles);
1027///
1028/// jar %= piles;
1029///
1030/// println!("{} cookies remain in the cookie jar!", jar.cookies);
1031/// ```
1032#[lang = "rem_assign"]
1033#[stable(feature = "op_assign_traits", since = "1.8.0")]
1034#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1035#[diagnostic::on_unimplemented(
1036 message = "cannot calculate and assign the remainder of `{Self}` divided by `{Rhs}`",
1037 label = "no implementation for `{Self} %= {Rhs}`"
1038)]
1039#[doc(alias = "%")]
1040#[doc(alias = "%=")]
1041pub const trait RemAssign<Rhs = Self> {
1042 /// Performs the `%=` operation.
1043 ///
1044 /// # Example
1045 ///
1046 /// ```
1047 /// let mut x: u32 = 12;
1048 /// x %= 10;
1049 /// assert_eq!(x, 2);
1050 /// ```
1051 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1052 fn rem_assign(&mut self, rhs: Rhs);
1053}
1054
1055macro_rules! rem_assign_impl {
1056 ($($t:ty)+) => ($(
1057 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1058 #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1059 impl const RemAssign for $t {
1060 #[inline]
1061 #[track_caller]
1062 #[ferrocene::prevalidated]
1063 fn rem_assign(&mut self, other: $t) { *self %= other }
1064 }
1065
1066 forward_ref_op_assign! { impl RemAssign, rem_assign for $t, $t,
1067 #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]
1068 #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
1069 )+)
1070}
1071
1072rem_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }