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