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