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