]> git.lizzy.rs Git - rust.git/blob - src/libcore/ops.rs
Rollup merge of #41957 - llogiq:clippy-libsyntax, r=petrochenkov
[rust.git] / src / libcore / ops.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Overloadable operators.
12 //!
13 //! Implementing these traits allows you to overload certain operators.
14 //!
15 //! Some of these traits are imported by the prelude, so they are available in
16 //! every Rust program. Only operators backed by traits can be overloaded. For
17 //! example, the addition operator (`+`) can be overloaded through the [`Add`]
18 //! trait, but since the assignment operator (`=`) has no backing trait, there
19 //! is no way of overloading its semantics. Additionally, this module does not
20 //! provide any mechanism to create new operators. If traitless overloading or
21 //! custom operators are required, you should look toward macros or compiler
22 //! plugins to extend Rust's syntax.
23 //!
24 //! Note that the `&&` and `||` operators short-circuit, i.e. they only
25 //! evaluate their second operand if it contributes to the result. Since this
26 //! behavior is not enforceable by traits, `&&` and `||` are not supported as
27 //! overloadable operators.
28 //!
29 //! Many of the operators take their operands by value. In non-generic
30 //! contexts involving built-in types, this is usually not a problem.
31 //! However, using these operators in generic code, requires some
32 //! attention if values have to be reused as opposed to letting the operators
33 //! consume them. One option is to occasionally use [`clone`].
34 //! Another option is to rely on the types involved providing additional
35 //! operator implementations for references. For example, for a user-defined
36 //! type `T` which is supposed to support addition, it is probably a good
37 //! idea to have both `T` and `&T` implement the traits [`Add<T>`][`Add`] and
38 //! [`Add<&T>`][`Add`] so that generic code can be written without unnecessary
39 //! cloning.
40 //!
41 //! # Examples
42 //!
43 //! This example creates a `Point` struct that implements [`Add`] and [`Sub`],
44 //! and then demonstrates adding and subtracting two `Point`s.
45 //!
46 //! ```rust
47 //! use std::ops::{Add, Sub};
48 //!
49 //! #[derive(Debug)]
50 //! struct Point {
51 //!     x: i32,
52 //!     y: i32,
53 //! }
54 //!
55 //! impl Add for Point {
56 //!     type Output = Point;
57 //!
58 //!     fn add(self, other: Point) -> Point {
59 //!         Point {x: self.x + other.x, y: self.y + other.y}
60 //!     }
61 //! }
62 //!
63 //! impl Sub for Point {
64 //!     type Output = Point;
65 //!
66 //!     fn sub(self, other: Point) -> Point {
67 //!         Point {x: self.x - other.x, y: self.y - other.y}
68 //!     }
69 //! }
70 //! fn main() {
71 //!     println!("{:?}", Point {x: 1, y: 0} + Point {x: 2, y: 3});
72 //!     println!("{:?}", Point {x: 1, y: 0} - Point {x: 2, y: 3});
73 //! }
74 //! ```
75 //!
76 //! See the documentation for each trait for an example implementation.
77 //!
78 //! The [`Fn`], [`FnMut`], and [`FnOnce`] traits are implemented by types that can be
79 //! invoked like functions. Note that [`Fn`] takes `&self`, [`FnMut`] takes `&mut
80 //! self` and [`FnOnce`] takes `self`. These correspond to the three kinds of
81 //! methods that can be invoked on an instance: call-by-reference,
82 //! call-by-mutable-reference, and call-by-value. The most common use of these
83 //! traits is to act as bounds to higher-level functions that take functions or
84 //! closures as arguments.
85 //!
86 //! Taking a [`Fn`] as a parameter:
87 //!
88 //! ```rust
89 //! fn call_with_one<F>(func: F) -> usize
90 //!     where F: Fn(usize) -> usize
91 //! {
92 //!     func(1)
93 //! }
94 //!
95 //! let double = |x| x * 2;
96 //! assert_eq!(call_with_one(double), 2);
97 //! ```
98 //!
99 //! Taking a [`FnMut`] as a parameter:
100 //!
101 //! ```rust
102 //! fn do_twice<F>(mut func: F)
103 //!     where F: FnMut()
104 //! {
105 //!     func();
106 //!     func();
107 //! }
108 //!
109 //! let mut x: usize = 1;
110 //! {
111 //!     let add_two_to_x = || x += 2;
112 //!     do_twice(add_two_to_x);
113 //! }
114 //!
115 //! assert_eq!(x, 5);
116 //! ```
117 //!
118 //! Taking a [`FnOnce`] as a parameter:
119 //!
120 //! ```rust
121 //! fn consume_with_relish<F>(func: F)
122 //!     where F: FnOnce() -> String
123 //! {
124 //!     // `func` consumes its captured variables, so it cannot be run more
125 //!     // than once
126 //!     println!("Consumed: {}", func());
127 //!
128 //!     println!("Delicious!");
129 //!
130 //!     // Attempting to invoke `func()` again will throw a `use of moved
131 //!     // value` error for `func`
132 //! }
133 //!
134 //! let x = String::from("x");
135 //! let consume_and_return_x = move || x;
136 //! consume_with_relish(consume_and_return_x);
137 //!
138 //! // `consume_and_return_x` can no longer be invoked at this point
139 //! ```
140 //!
141 //! [`Fn`]: trait.Fn.html
142 //! [`FnMut`]: trait.FnMut.html
143 //! [`FnOnce`]: trait.FnOnce.html
144 //! [`Add`]: trait.Add.html
145 //! [`Sub`]: trait.Sub.html
146 //! [`clone`]: ../clone/trait.Clone.html#tymethod.clone
147
148 #![stable(feature = "rust1", since = "1.0.0")]
149
150 use fmt;
151 use marker::Unsize;
152
153 /// The `Drop` trait is used to run some code when a value goes out of scope.
154 /// This is sometimes called a 'destructor'.
155 ///
156 /// # Examples
157 ///
158 /// A trivial implementation of `Drop`. The `drop` method is called when `_x`
159 /// goes out of scope, and therefore `main` prints `Dropping!`.
160 ///
161 /// ```
162 /// struct HasDrop;
163 ///
164 /// impl Drop for HasDrop {
165 ///     fn drop(&mut self) {
166 ///         println!("Dropping!");
167 ///     }
168 /// }
169 ///
170 /// fn main() {
171 ///     let _x = HasDrop;
172 /// }
173 /// ```
174 #[lang = "drop"]
175 #[stable(feature = "rust1", since = "1.0.0")]
176 pub trait Drop {
177     /// A method called when the value goes out of scope.
178     ///
179     /// When this method has been called, `self` has not yet been deallocated.
180     /// If it were, `self` would be a dangling reference.
181     ///
182     /// After this function is over, the memory of `self` will be deallocated.
183     ///
184     /// This function cannot be called explicitly. This is compiler error
185     /// [E0040]. However, the [`std::mem::drop`] function in the prelude can be
186     /// used to call the argument's `Drop` implementation.
187     ///
188     /// [E0040]: ../../error-index.html#E0040
189     /// [`std::mem::drop`]: ../../std/mem/fn.drop.html
190     ///
191     /// # Panics
192     ///
193     /// Given that a `panic!` will call `drop()` as it unwinds, any `panic!` in
194     /// a `drop()` implementation will likely abort.
195     #[stable(feature = "rust1", since = "1.0.0")]
196     fn drop(&mut self);
197 }
198
199 /// The addition operator `+`.
200 ///
201 /// # Examples
202 ///
203 /// This example creates a `Point` struct that implements the `Add` trait, and
204 /// then demonstrates adding two `Point`s.
205 ///
206 /// ```
207 /// use std::ops::Add;
208 ///
209 /// #[derive(Debug)]
210 /// struct Point {
211 ///     x: i32,
212 ///     y: i32,
213 /// }
214 ///
215 /// impl Add for Point {
216 ///     type Output = Point;
217 ///
218 ///     fn add(self, other: Point) -> Point {
219 ///         Point {
220 ///             x: self.x + other.x,
221 ///             y: self.y + other.y,
222 ///         }
223 ///     }
224 /// }
225 ///
226 /// impl PartialEq for Point {
227 ///     fn eq(&self, other: &Self) -> bool {
228 ///         self.x == other.x && self.y == other.y
229 ///     }
230 /// }
231 ///
232 /// fn main() {
233 ///     assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
234 ///                Point { x: 3, y: 3 });
235 /// }
236 /// ```
237 ///
238 /// Here is an example of the same `Point` struct implementing the `Add` trait
239 /// using generics.
240 ///
241 /// ```
242 /// use std::ops::Add;
243 ///
244 /// #[derive(Debug)]
245 /// struct Point<T> {
246 ///     x: T,
247 ///     y: T,
248 /// }
249 ///
250 /// // Notice that the implementation uses the `Output` associated type
251 /// impl<T: Add<Output=T>> Add for Point<T> {
252 ///     type Output = Point<T>;
253 ///
254 ///     fn add(self, other: Point<T>) -> Point<T> {
255 ///         Point {
256 ///             x: self.x + other.x,
257 ///             y: self.y + other.y,
258 ///         }
259 ///     }
260 /// }
261 ///
262 /// impl<T: PartialEq> PartialEq for Point<T> {
263 ///     fn eq(&self, other: &Self) -> bool {
264 ///         self.x == other.x && self.y == other.y
265 ///     }
266 /// }
267 ///
268 /// fn main() {
269 ///     assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
270 ///                Point { x: 3, y: 3 });
271 /// }
272 /// ```
273 ///
274 /// Note that `RHS = Self` by default, but this is not mandatory. For example,
275 /// [std::time::SystemTime] implements `Add<Duration>`, which permits
276 /// operations of the form `SystemTime = SystemTime + Duration`.
277 ///
278 /// [std::time::SystemTime]: ../../std/time/struct.SystemTime.html
279 #[lang = "add"]
280 #[stable(feature = "rust1", since = "1.0.0")]
281 #[rustc_on_unimplemented = "no implementation for `{Self} + {RHS}`"]
282 pub trait Add<RHS=Self> {
283     /// The resulting type after applying the `+` operator
284     #[stable(feature = "rust1", since = "1.0.0")]
285     type Output;
286
287     /// The method for the `+` operator
288     #[stable(feature = "rust1", since = "1.0.0")]
289     fn add(self, rhs: RHS) -> Self::Output;
290 }
291
292 macro_rules! add_impl {
293     ($($t:ty)*) => ($(
294         #[stable(feature = "rust1", since = "1.0.0")]
295         impl Add for $t {
296             type Output = $t;
297
298             #[inline]
299             #[rustc_inherit_overflow_checks]
300             fn add(self, other: $t) -> $t { self + other }
301         }
302
303         forward_ref_binop! { impl Add, add for $t, $t }
304     )*)
305 }
306
307 add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
308
309 /// The subtraction operator `-`.
310 ///
311 /// # Examples
312 ///
313 /// This example creates a `Point` struct that implements the `Sub` trait, and
314 /// then demonstrates subtracting two `Point`s.
315 ///
316 /// ```
317 /// use std::ops::Sub;
318 ///
319 /// #[derive(Debug)]
320 /// struct Point {
321 ///     x: i32,
322 ///     y: i32,
323 /// }
324 ///
325 /// impl Sub for Point {
326 ///     type Output = Point;
327 ///
328 ///     fn sub(self, other: Point) -> Point {
329 ///         Point {
330 ///             x: self.x - other.x,
331 ///             y: self.y - other.y,
332 ///         }
333 ///     }
334 /// }
335 ///
336 /// impl PartialEq for Point {
337 ///     fn eq(&self, other: &Self) -> bool {
338 ///         self.x == other.x && self.y == other.y
339 ///     }
340 /// }
341 ///
342 /// fn main() {
343 ///     assert_eq!(Point { x: 3, y: 3 } - Point { x: 2, y: 3 },
344 ///                Point { x: 1, y: 0 });
345 /// }
346 /// ```
347 ///
348 /// Note that `RHS = Self` by default, but this is not mandatory. For example,
349 /// [std::time::SystemTime] implements `Sub<Duration>`, which permits
350 /// operations of the form `SystemTime = SystemTime - Duration`.
351 ///
352 /// [std::time::SystemTime]: ../../std/time/struct.SystemTime.html
353 #[lang = "sub"]
354 #[stable(feature = "rust1", since = "1.0.0")]
355 #[rustc_on_unimplemented = "no implementation for `{Self} - {RHS}`"]
356 pub trait Sub<RHS=Self> {
357     /// The resulting type after applying the `-` operator
358     #[stable(feature = "rust1", since = "1.0.0")]
359     type Output;
360
361     /// The method for the `-` operator
362     #[stable(feature = "rust1", since = "1.0.0")]
363     fn sub(self, rhs: RHS) -> Self::Output;
364 }
365
366 macro_rules! sub_impl {
367     ($($t:ty)*) => ($(
368         #[stable(feature = "rust1", since = "1.0.0")]
369         impl Sub for $t {
370             type Output = $t;
371
372             #[inline]
373             #[rustc_inherit_overflow_checks]
374             fn sub(self, other: $t) -> $t { self - other }
375         }
376
377         forward_ref_binop! { impl Sub, sub for $t, $t }
378     )*)
379 }
380
381 sub_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
382
383 /// The multiplication operator `*`.
384 ///
385 /// # Examples
386 ///
387 /// Implementing a `Mul`tipliable rational number struct:
388 ///
389 /// ```
390 /// use std::ops::Mul;
391 ///
392 /// // The uniqueness of rational numbers in lowest terms is a consequence of
393 /// // the fundamental theorem of arithmetic.
394 /// #[derive(Eq)]
395 /// #[derive(PartialEq, Debug)]
396 /// struct Rational {
397 ///     nominator: usize,
398 ///     denominator: usize,
399 /// }
400 ///
401 /// impl Rational {
402 ///     fn new(nominator: usize, denominator: usize) -> Self {
403 ///         if denominator == 0 {
404 ///             panic!("Zero is an invalid denominator!");
405 ///         }
406 ///
407 ///         // Reduce to lowest terms by dividing by the greatest common
408 ///         // divisor.
409 ///         let gcd = gcd(nominator, denominator);
410 ///         Rational {
411 ///             nominator: nominator / gcd,
412 ///             denominator: denominator / gcd,
413 ///         }
414 ///     }
415 /// }
416 ///
417 /// impl Mul for Rational {
418 ///     // The multiplication of rational numbers is a closed operation.
419 ///     type Output = Self;
420 ///
421 ///     fn mul(self, rhs: Self) -> Self {
422 ///         let nominator = self.nominator * rhs.nominator;
423 ///         let denominator = self.denominator * rhs.denominator;
424 ///         Rational::new(nominator, denominator)
425 ///     }
426 /// }
427 ///
428 /// // Euclid's two-thousand-year-old algorithm for finding the greatest common
429 /// // divisor.
430 /// fn gcd(x: usize, y: usize) -> usize {
431 ///     let mut x = x;
432 ///     let mut y = y;
433 ///     while y != 0 {
434 ///         let t = y;
435 ///         y = x % y;
436 ///         x = t;
437 ///     }
438 ///     x
439 /// }
440 ///
441 /// assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
442 /// assert_eq!(Rational::new(2, 3) * Rational::new(3, 4),
443 ///            Rational::new(1, 2));
444 /// ```
445 ///
446 /// Note that `RHS = Self` by default, but this is not mandatory. Here is an
447 /// implementation which enables multiplication of vectors by scalars, as is
448 /// done in linear algebra.
449 ///
450 /// ```
451 /// use std::ops::Mul;
452 ///
453 /// struct Scalar {value: usize};
454 ///
455 /// #[derive(Debug)]
456 /// struct Vector {value: Vec<usize>};
457 ///
458 /// impl Mul<Vector> for Scalar {
459 ///     type Output = Vector;
460 ///
461 ///     fn mul(self, rhs: Vector) -> Vector {
462 ///         Vector {value: rhs.value.iter().map(|v| self.value * v).collect()}
463 ///     }
464 /// }
465 ///
466 /// impl PartialEq<Vector> for Vector {
467 ///     fn eq(&self, other: &Self) -> bool {
468 ///         self.value == other.value
469 ///     }
470 /// }
471 ///
472 /// let scalar = Scalar{value: 3};
473 /// let vector = Vector{value: vec![2, 4, 6]};
474 /// assert_eq!(scalar * vector, Vector{value: vec![6, 12, 18]});
475 /// ```
476 #[lang = "mul"]
477 #[stable(feature = "rust1", since = "1.0.0")]
478 #[rustc_on_unimplemented = "no implementation for `{Self} * {RHS}`"]
479 pub trait Mul<RHS=Self> {
480     /// The resulting type after applying the `*` operator
481     #[stable(feature = "rust1", since = "1.0.0")]
482     type Output;
483
484     /// The method for the `*` operator
485     #[stable(feature = "rust1", since = "1.0.0")]
486     fn mul(self, rhs: RHS) -> Self::Output;
487 }
488
489 macro_rules! mul_impl {
490     ($($t:ty)*) => ($(
491         #[stable(feature = "rust1", since = "1.0.0")]
492         impl Mul for $t {
493             type Output = $t;
494
495             #[inline]
496             #[rustc_inherit_overflow_checks]
497             fn mul(self, other: $t) -> $t { self * other }
498         }
499
500         forward_ref_binop! { impl Mul, mul for $t, $t }
501     )*)
502 }
503
504 mul_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
505
506 /// The division operator `/`.
507 ///
508 /// # Examples
509 ///
510 /// Implementing a `Div`idable rational number struct:
511 ///
512 /// ```
513 /// use std::ops::Div;
514 ///
515 /// // The uniqueness of rational numbers in lowest terms is a consequence of
516 /// // the fundamental theorem of arithmetic.
517 /// #[derive(Eq)]
518 /// #[derive(PartialEq, Debug)]
519 /// struct Rational {
520 ///     nominator: usize,
521 ///     denominator: usize,
522 /// }
523 ///
524 /// impl Rational {
525 ///     fn new(nominator: usize, denominator: usize) -> Self {
526 ///         if denominator == 0 {
527 ///             panic!("Zero is an invalid denominator!");
528 ///         }
529 ///
530 ///         // Reduce to lowest terms by dividing by the greatest common
531 ///         // divisor.
532 ///         let gcd = gcd(nominator, denominator);
533 ///         Rational {
534 ///             nominator: nominator / gcd,
535 ///             denominator: denominator / gcd,
536 ///         }
537 ///     }
538 /// }
539 ///
540 /// impl Div for Rational {
541 ///     // The division of rational numbers is a closed operation.
542 ///     type Output = Self;
543 ///
544 ///     fn div(self, rhs: Self) -> Self {
545 ///         if rhs.nominator == 0 {
546 ///             panic!("Cannot divide by zero-valued `Rational`!");
547 ///         }
548 ///
549 ///         let nominator = self.nominator * rhs.denominator;
550 ///         let denominator = self.denominator * rhs.nominator;
551 ///         Rational::new(nominator, denominator)
552 ///     }
553 /// }
554 ///
555 /// // Euclid's two-thousand-year-old algorithm for finding the greatest common
556 /// // divisor.
557 /// fn gcd(x: usize, y: usize) -> usize {
558 ///     let mut x = x;
559 ///     let mut y = y;
560 ///     while y != 0 {
561 ///         let t = y;
562 ///         y = x % y;
563 ///         x = t;
564 ///     }
565 ///     x
566 /// }
567 ///
568 /// fn main() {
569 ///     assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
570 ///     assert_eq!(Rational::new(1, 2) / Rational::new(3, 4),
571 ///                Rational::new(2, 3));
572 /// }
573 /// ```
574 ///
575 /// Note that `RHS = Self` by default, but this is not mandatory. Here is an
576 /// implementation which enables division of vectors by scalars, as is done in
577 /// linear algebra.
578 ///
579 /// ```
580 /// use std::ops::Div;
581 ///
582 /// struct Scalar {value: f32};
583 ///
584 /// #[derive(Debug)]
585 /// struct Vector {value: Vec<f32>};
586 ///
587 /// impl Div<Scalar> for Vector {
588 ///     type Output = Vector;
589 ///
590 ///     fn div(self, rhs: Scalar) -> Vector {
591 ///         Vector {value: self.value.iter().map(|v| v / rhs.value).collect()}
592 ///     }
593 /// }
594 ///
595 /// impl PartialEq<Vector> for Vector {
596 ///     fn eq(&self, other: &Self) -> bool {
597 ///         self.value == other.value
598 ///     }
599 /// }
600 ///
601 /// let scalar = Scalar{value: 2f32};
602 /// let vector = Vector{value: vec![2f32, 4f32, 6f32]};
603 /// assert_eq!(vector / scalar, Vector{value: vec![1f32, 2f32, 3f32]});
604 /// ```
605 #[lang = "div"]
606 #[stable(feature = "rust1", since = "1.0.0")]
607 #[rustc_on_unimplemented = "no implementation for `{Self} / {RHS}`"]
608 pub trait Div<RHS=Self> {
609     /// The resulting type after applying the `/` operator
610     #[stable(feature = "rust1", since = "1.0.0")]
611     type Output;
612
613     /// The method for the `/` operator
614     #[stable(feature = "rust1", since = "1.0.0")]
615     fn div(self, rhs: RHS) -> Self::Output;
616 }
617
618 macro_rules! div_impl_integer {
619     ($($t:ty)*) => ($(
620         /// This operation rounds towards zero, truncating any
621         /// fractional part of the exact result.
622         #[stable(feature = "rust1", since = "1.0.0")]
623         impl Div for $t {
624             type Output = $t;
625
626             #[inline]
627             fn div(self, other: $t) -> $t { self / other }
628         }
629
630         forward_ref_binop! { impl Div, div for $t, $t }
631     )*)
632 }
633
634 div_impl_integer! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
635
636 macro_rules! div_impl_float {
637     ($($t:ty)*) => ($(
638         #[stable(feature = "rust1", since = "1.0.0")]
639         impl Div for $t {
640             type Output = $t;
641
642             #[inline]
643             fn div(self, other: $t) -> $t { self / other }
644         }
645
646         forward_ref_binop! { impl Div, div for $t, $t }
647     )*)
648 }
649
650 div_impl_float! { f32 f64 }
651
652 /// The remainder operator `%`.
653 ///
654 /// # Examples
655 ///
656 /// This example implements `Rem` on a `SplitSlice` object. After `Rem` is
657 /// implemented, one can use the `%` operator to find out what the remaining
658 /// elements of the slice would be after splitting it into equal slices of a
659 /// given length.
660 ///
661 /// ```
662 /// use std::ops::Rem;
663 ///
664 /// #[derive(PartialEq, Debug)]
665 /// struct SplitSlice<'a, T: 'a> {
666 ///     slice: &'a [T],
667 /// }
668 ///
669 /// impl<'a, T> Rem<usize> for SplitSlice<'a, T> {
670 ///     type Output = SplitSlice<'a, T>;
671 ///
672 ///     fn rem(self, modulus: usize) -> Self {
673 ///         let len = self.slice.len();
674 ///         let rem = len % modulus;
675 ///         let start = len - rem;
676 ///         SplitSlice {slice: &self.slice[start..]}
677 ///     }
678 /// }
679 ///
680 /// // If we were to divide &[0, 1, 2, 3, 4, 5, 6, 7] into slices of size 3,
681 /// // the remainder would be &[6, 7]
682 /// assert_eq!(SplitSlice { slice: &[0, 1, 2, 3, 4, 5, 6, 7] } % 3,
683 ///            SplitSlice { slice: &[6, 7] });
684 /// ```
685 #[lang = "rem"]
686 #[stable(feature = "rust1", since = "1.0.0")]
687 #[rustc_on_unimplemented = "no implementation for `{Self} % {RHS}`"]
688 pub trait Rem<RHS=Self> {
689     /// The resulting type after applying the `%` operator
690     #[stable(feature = "rust1", since = "1.0.0")]
691     type Output = Self;
692
693     /// The method for the `%` operator
694     #[stable(feature = "rust1", since = "1.0.0")]
695     fn rem(self, rhs: RHS) -> Self::Output;
696 }
697
698 macro_rules! rem_impl_integer {
699     ($($t:ty)*) => ($(
700         /// This operation satisfies `n % d == n - (n / d) * d`.  The
701         /// result has the same sign as the left operand.
702         #[stable(feature = "rust1", since = "1.0.0")]
703         impl Rem for $t {
704             type Output = $t;
705
706             #[inline]
707             fn rem(self, other: $t) -> $t { self % other }
708         }
709
710         forward_ref_binop! { impl Rem, rem for $t, $t }
711     )*)
712 }
713
714 rem_impl_integer! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
715
716
717 macro_rules! rem_impl_float {
718     ($($t:ty)*) => ($(
719         #[stable(feature = "rust1", since = "1.0.0")]
720         impl Rem for $t {
721             type Output = $t;
722
723             #[inline]
724             fn rem(self, other: $t) -> $t { self % other }
725         }
726
727         forward_ref_binop! { impl Rem, rem for $t, $t }
728     )*)
729 }
730
731 rem_impl_float! { f32 f64 }
732
733 /// The unary negation operator `-`.
734 ///
735 /// # Examples
736 ///
737 /// An implementation of `Neg` for `Sign`, which allows the use of `-` to
738 /// negate its value.
739 ///
740 /// ```
741 /// use std::ops::Neg;
742 ///
743 /// #[derive(Debug, PartialEq)]
744 /// enum Sign {
745 ///     Negative,
746 ///     Zero,
747 ///     Positive,
748 /// }
749 ///
750 /// impl Neg for Sign {
751 ///     type Output = Sign;
752 ///
753 ///     fn neg(self) -> Sign {
754 ///         match self {
755 ///             Sign::Negative => Sign::Positive,
756 ///             Sign::Zero => Sign::Zero,
757 ///             Sign::Positive => Sign::Negative,
758 ///         }
759 ///     }
760 /// }
761 ///
762 /// // a negative positive is a negative
763 /// assert_eq!(-Sign::Positive, Sign::Negative);
764 /// // a double negative is a positive
765 /// assert_eq!(-Sign::Negative, Sign::Positive);
766 /// // zero is its own negation
767 /// assert_eq!(-Sign::Zero, Sign::Zero);
768 /// ```
769 #[lang = "neg"]
770 #[stable(feature = "rust1", since = "1.0.0")]
771 pub trait Neg {
772     /// The resulting type after applying the `-` operator
773     #[stable(feature = "rust1", since = "1.0.0")]
774     type Output;
775
776     /// The method for the unary `-` operator
777     #[stable(feature = "rust1", since = "1.0.0")]
778     fn neg(self) -> Self::Output;
779 }
780
781
782
783 macro_rules! neg_impl_core {
784     ($id:ident => $body:expr, $($t:ty)*) => ($(
785         #[stable(feature = "rust1", since = "1.0.0")]
786         impl Neg for $t {
787             type Output = $t;
788
789             #[inline]
790             #[rustc_inherit_overflow_checks]
791             fn neg(self) -> $t { let $id = self; $body }
792         }
793
794         forward_ref_unop! { impl Neg, neg for $t }
795     )*)
796 }
797
798 macro_rules! neg_impl_numeric {
799     ($($t:ty)*) => { neg_impl_core!{ x => -x, $($t)*} }
800 }
801
802 macro_rules! neg_impl_unsigned {
803     ($($t:ty)*) => {
804         neg_impl_core!{ x => {
805             !x.wrapping_add(1)
806         }, $($t)*} }
807 }
808
809 // neg_impl_unsigned! { usize u8 u16 u32 u64 }
810 neg_impl_numeric! { isize i8 i16 i32 i64 i128 f32 f64 }
811
812 /// The unary logical negation operator `!`.
813 ///
814 /// # Examples
815 ///
816 /// An implementation of `Not` for `Answer`, which enables the use of `!` to
817 /// invert its value.
818 ///
819 /// ```
820 /// use std::ops::Not;
821 ///
822 /// #[derive(Debug, PartialEq)]
823 /// enum Answer {
824 ///     Yes,
825 ///     No,
826 /// }
827 ///
828 /// impl Not for Answer {
829 ///     type Output = Answer;
830 ///
831 ///     fn not(self) -> Answer {
832 ///         match self {
833 ///             Answer::Yes => Answer::No,
834 ///             Answer::No => Answer::Yes
835 ///         }
836 ///     }
837 /// }
838 ///
839 /// assert_eq!(!Answer::Yes, Answer::No);
840 /// assert_eq!(!Answer::No, Answer::Yes);
841 /// ```
842 #[lang = "not"]
843 #[stable(feature = "rust1", since = "1.0.0")]
844 pub trait Not {
845     /// The resulting type after applying the `!` operator
846     #[stable(feature = "rust1", since = "1.0.0")]
847     type Output;
848
849     /// The method for the unary `!` operator
850     #[stable(feature = "rust1", since = "1.0.0")]
851     fn not(self) -> Self::Output;
852 }
853
854 macro_rules! not_impl {
855     ($($t:ty)*) => ($(
856         #[stable(feature = "rust1", since = "1.0.0")]
857         impl Not for $t {
858             type Output = $t;
859
860             #[inline]
861             fn not(self) -> $t { !self }
862         }
863
864         forward_ref_unop! { impl Not, not for $t }
865     )*)
866 }
867
868 not_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
869
870 /// The bitwise AND operator `&`.
871 ///
872 /// # Examples
873 ///
874 /// In this example, the `&` operator is lifted to a trivial `Scalar` type.
875 ///
876 /// ```
877 /// use std::ops::BitAnd;
878 ///
879 /// #[derive(Debug, PartialEq)]
880 /// struct Scalar(bool);
881 ///
882 /// impl BitAnd for Scalar {
883 ///     type Output = Self;
884 ///
885 ///     // rhs is the "right-hand side" of the expression `a & b`
886 ///     fn bitand(self, rhs: Self) -> Self {
887 ///         Scalar(self.0 & rhs.0)
888 ///     }
889 /// }
890 ///
891 /// fn main() {
892 ///     assert_eq!(Scalar(true) & Scalar(true), Scalar(true));
893 ///     assert_eq!(Scalar(true) & Scalar(false), Scalar(false));
894 ///     assert_eq!(Scalar(false) & Scalar(true), Scalar(false));
895 ///     assert_eq!(Scalar(false) & Scalar(false), Scalar(false));
896 /// }
897 /// ```
898 ///
899 /// In this example, the `BitAnd` trait is implemented for a `BooleanVector`
900 /// struct.
901 ///
902 /// ```
903 /// use std::ops::BitAnd;
904 ///
905 /// #[derive(Debug, PartialEq)]
906 /// struct BooleanVector(Vec<bool>);
907 ///
908 /// impl BitAnd for BooleanVector {
909 ///     type Output = Self;
910 ///
911 ///     fn bitand(self, BooleanVector(rhs): Self) -> Self {
912 ///         let BooleanVector(lhs) = self;
913 ///         assert_eq!(lhs.len(), rhs.len());
914 ///         BooleanVector(lhs.iter().zip(rhs.iter()).map(|(x, y)| *x && *y).collect())
915 ///     }
916 /// }
917 ///
918 /// fn main() {
919 ///     let bv1 = BooleanVector(vec![true, true, false, false]);
920 ///     let bv2 = BooleanVector(vec![true, false, true, false]);
921 ///     let expected = BooleanVector(vec![true, false, false, false]);
922 ///     assert_eq!(bv1 & bv2, expected);
923 /// }
924 /// ```
925 #[lang = "bitand"]
926 #[stable(feature = "rust1", since = "1.0.0")]
927 #[rustc_on_unimplemented = "no implementation for `{Self} & {RHS}`"]
928 pub trait BitAnd<RHS=Self> {
929     /// The resulting type after applying the `&` operator
930     #[stable(feature = "rust1", since = "1.0.0")]
931     type Output;
932
933     /// The method for the `&` operator
934     #[stable(feature = "rust1", since = "1.0.0")]
935     fn bitand(self, rhs: RHS) -> Self::Output;
936 }
937
938 macro_rules! bitand_impl {
939     ($($t:ty)*) => ($(
940         #[stable(feature = "rust1", since = "1.0.0")]
941         impl BitAnd for $t {
942             type Output = $t;
943
944             #[inline]
945             fn bitand(self, rhs: $t) -> $t { self & rhs }
946         }
947
948         forward_ref_binop! { impl BitAnd, bitand for $t, $t }
949     )*)
950 }
951
952 bitand_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
953
954 /// The bitwise OR operator `|`.
955 ///
956 /// # Examples
957 ///
958 /// In this example, the `|` operator is lifted to a trivial `Scalar` type.
959 ///
960 /// ```
961 /// use std::ops::BitOr;
962 ///
963 /// #[derive(Debug, PartialEq)]
964 /// struct Scalar(bool);
965 ///
966 /// impl BitOr for Scalar {
967 ///     type Output = Self;
968 ///
969 ///     // rhs is the "right-hand side" of the expression `a | b`
970 ///     fn bitor(self, rhs: Self) -> Self {
971 ///         Scalar(self.0 | rhs.0)
972 ///     }
973 /// }
974 ///
975 /// fn main() {
976 ///     assert_eq!(Scalar(true) | Scalar(true), Scalar(true));
977 ///     assert_eq!(Scalar(true) | Scalar(false), Scalar(true));
978 ///     assert_eq!(Scalar(false) | Scalar(true), Scalar(true));
979 ///     assert_eq!(Scalar(false) | Scalar(false), Scalar(false));
980 /// }
981 /// ```
982 ///
983 /// In this example, the `BitOr` trait is implemented for a `BooleanVector`
984 /// struct.
985 ///
986 /// ```
987 /// use std::ops::BitOr;
988 ///
989 /// #[derive(Debug, PartialEq)]
990 /// struct BooleanVector(Vec<bool>);
991 ///
992 /// impl BitOr for BooleanVector {
993 ///     type Output = Self;
994 ///
995 ///     fn bitor(self, BooleanVector(rhs): Self) -> Self {
996 ///         let BooleanVector(lhs) = self;
997 ///         assert_eq!(lhs.len(), rhs.len());
998 ///         BooleanVector(lhs.iter().zip(rhs.iter()).map(|(x, y)| *x || *y).collect())
999 ///     }
1000 /// }
1001 ///
1002 /// fn main() {
1003 ///     let bv1 = BooleanVector(vec![true, true, false, false]);
1004 ///     let bv2 = BooleanVector(vec![true, false, true, false]);
1005 ///     let expected = BooleanVector(vec![true, true, true, false]);
1006 ///     assert_eq!(bv1 | bv2, expected);
1007 /// }
1008 /// ```
1009 #[lang = "bitor"]
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 #[rustc_on_unimplemented = "no implementation for `{Self} | {RHS}`"]
1012 pub trait BitOr<RHS=Self> {
1013     /// The resulting type after applying the `|` operator
1014     #[stable(feature = "rust1", since = "1.0.0")]
1015     type Output;
1016
1017     /// The method for the `|` operator
1018     #[stable(feature = "rust1", since = "1.0.0")]
1019     fn bitor(self, rhs: RHS) -> Self::Output;
1020 }
1021
1022 macro_rules! bitor_impl {
1023     ($($t:ty)*) => ($(
1024         #[stable(feature = "rust1", since = "1.0.0")]
1025         impl BitOr for $t {
1026             type Output = $t;
1027
1028             #[inline]
1029             fn bitor(self, rhs: $t) -> $t { self | rhs }
1030         }
1031
1032         forward_ref_binop! { impl BitOr, bitor for $t, $t }
1033     )*)
1034 }
1035
1036 bitor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1037
1038 /// The bitwise XOR operator `^`.
1039 ///
1040 /// # Examples
1041 ///
1042 /// In this example, the `^` operator is lifted to a trivial `Scalar` type.
1043 ///
1044 /// ```
1045 /// use std::ops::BitXor;
1046 ///
1047 /// #[derive(Debug, PartialEq)]
1048 /// struct Scalar(bool);
1049 ///
1050 /// impl BitXor for Scalar {
1051 ///     type Output = Self;
1052 ///
1053 ///     // rhs is the "right-hand side" of the expression `a ^ b`
1054 ///     fn bitxor(self, rhs: Self) -> Self {
1055 ///         Scalar(self.0 ^ rhs.0)
1056 ///     }
1057 /// }
1058 ///
1059 /// fn main() {
1060 ///     assert_eq!(Scalar(true) ^ Scalar(true), Scalar(false));
1061 ///     assert_eq!(Scalar(true) ^ Scalar(false), Scalar(true));
1062 ///     assert_eq!(Scalar(false) ^ Scalar(true), Scalar(true));
1063 ///     assert_eq!(Scalar(false) ^ Scalar(false), Scalar(false));
1064 /// }
1065 /// ```
1066 ///
1067 /// In this example, the `BitXor` trait is implemented for a `BooleanVector`
1068 /// struct.
1069 ///
1070 /// ```
1071 /// use std::ops::BitXor;
1072 ///
1073 /// #[derive(Debug, PartialEq)]
1074 /// struct BooleanVector(Vec<bool>);
1075 ///
1076 /// impl BitXor for BooleanVector {
1077 ///     type Output = Self;
1078 ///
1079 ///     fn bitxor(self, BooleanVector(rhs): Self) -> Self {
1080 ///         let BooleanVector(lhs) = self;
1081 ///         assert_eq!(lhs.len(), rhs.len());
1082 ///         BooleanVector(lhs.iter()
1083 ///                          .zip(rhs.iter())
1084 ///                          .map(|(x, y)| (*x || *y) && !(*x && *y))
1085 ///                          .collect())
1086 ///     }
1087 /// }
1088 ///
1089 /// fn main() {
1090 ///     let bv1 = BooleanVector(vec![true, true, false, false]);
1091 ///     let bv2 = BooleanVector(vec![true, false, true, false]);
1092 ///     let expected = BooleanVector(vec![false, true, true, false]);
1093 ///     assert_eq!(bv1 ^ bv2, expected);
1094 /// }
1095 /// ```
1096 #[lang = "bitxor"]
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 #[rustc_on_unimplemented = "no implementation for `{Self} ^ {RHS}`"]
1099 pub trait BitXor<RHS=Self> {
1100     /// The resulting type after applying the `^` operator
1101     #[stable(feature = "rust1", since = "1.0.0")]
1102     type Output;
1103
1104     /// The method for the `^` operator
1105     #[stable(feature = "rust1", since = "1.0.0")]
1106     fn bitxor(self, rhs: RHS) -> Self::Output;
1107 }
1108
1109 macro_rules! bitxor_impl {
1110     ($($t:ty)*) => ($(
1111         #[stable(feature = "rust1", since = "1.0.0")]
1112         impl BitXor for $t {
1113             type Output = $t;
1114
1115             #[inline]
1116             fn bitxor(self, other: $t) -> $t { self ^ other }
1117         }
1118
1119         forward_ref_binop! { impl BitXor, bitxor for $t, $t }
1120     )*)
1121 }
1122
1123 bitxor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1124
1125 /// The left shift operator `<<`.
1126 ///
1127 /// # Examples
1128 ///
1129 /// An implementation of `Shl` that lifts the `<<` operation on integers to a
1130 /// `Scalar` struct.
1131 ///
1132 /// ```
1133 /// use std::ops::Shl;
1134 ///
1135 /// #[derive(PartialEq, Debug)]
1136 /// struct Scalar(usize);
1137 ///
1138 /// impl Shl<Scalar> for Scalar {
1139 ///     type Output = Self;
1140 ///
1141 ///     fn shl(self, Scalar(rhs): Self) -> Scalar {
1142 ///         let Scalar(lhs) = self;
1143 ///         Scalar(lhs << rhs)
1144 ///     }
1145 /// }
1146 /// fn main() {
1147 ///     assert_eq!(Scalar(4) << Scalar(2), Scalar(16));
1148 /// }
1149 /// ```
1150 ///
1151 /// An implementation of `Shl` that spins a vector leftward by a given amount.
1152 ///
1153 /// ```
1154 /// use std::ops::Shl;
1155 ///
1156 /// #[derive(PartialEq, Debug)]
1157 /// struct SpinVector<T: Clone> {
1158 ///     vec: Vec<T>,
1159 /// }
1160 ///
1161 /// impl<T: Clone> Shl<usize> for SpinVector<T> {
1162 ///     type Output = Self;
1163 ///
1164 ///     fn shl(self, rhs: usize) -> SpinVector<T> {
1165 ///         // rotate the vector by `rhs` places
1166 ///         let (a, b) = self.vec.split_at(rhs);
1167 ///         let mut spun_vector: Vec<T> = vec![];
1168 ///         spun_vector.extend_from_slice(b);
1169 ///         spun_vector.extend_from_slice(a);
1170 ///         SpinVector { vec: spun_vector }
1171 ///     }
1172 /// }
1173 ///
1174 /// fn main() {
1175 ///     assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } << 2,
1176 ///                SpinVector { vec: vec![2, 3, 4, 0, 1] });
1177 /// }
1178 /// ```
1179 #[lang = "shl"]
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 #[rustc_on_unimplemented = "no implementation for `{Self} << {RHS}`"]
1182 pub trait Shl<RHS> {
1183     /// The resulting type after applying the `<<` operator
1184     #[stable(feature = "rust1", since = "1.0.0")]
1185     type Output;
1186
1187     /// The method for the `<<` operator
1188     #[stable(feature = "rust1", since = "1.0.0")]
1189     fn shl(self, rhs: RHS) -> Self::Output;
1190 }
1191
1192 macro_rules! shl_impl {
1193     ($t:ty, $f:ty) => (
1194         #[stable(feature = "rust1", since = "1.0.0")]
1195         impl Shl<$f> for $t {
1196             type Output = $t;
1197
1198             #[inline]
1199             #[rustc_inherit_overflow_checks]
1200             fn shl(self, other: $f) -> $t {
1201                 self << other
1202             }
1203         }
1204
1205         forward_ref_binop! { impl Shl, shl for $t, $f }
1206     )
1207 }
1208
1209 macro_rules! shl_impl_all {
1210     ($($t:ty)*) => ($(
1211         shl_impl! { $t, u8 }
1212         shl_impl! { $t, u16 }
1213         shl_impl! { $t, u32 }
1214         shl_impl! { $t, u64 }
1215         shl_impl! { $t, u128 }
1216         shl_impl! { $t, usize }
1217
1218         shl_impl! { $t, i8 }
1219         shl_impl! { $t, i16 }
1220         shl_impl! { $t, i32 }
1221         shl_impl! { $t, i64 }
1222         shl_impl! { $t, i128 }
1223         shl_impl! { $t, isize }
1224     )*)
1225 }
1226
1227 shl_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 isize i128 }
1228
1229 /// The right shift operator `>>`.
1230 ///
1231 /// # Examples
1232 ///
1233 /// An implementation of `Shr` that lifts the `>>` operation on integers to a
1234 /// `Scalar` struct.
1235 ///
1236 /// ```
1237 /// use std::ops::Shr;
1238 ///
1239 /// #[derive(PartialEq, Debug)]
1240 /// struct Scalar(usize);
1241 ///
1242 /// impl Shr<Scalar> for Scalar {
1243 ///     type Output = Self;
1244 ///
1245 ///     fn shr(self, Scalar(rhs): Self) -> Scalar {
1246 ///         let Scalar(lhs) = self;
1247 ///         Scalar(lhs >> rhs)
1248 ///     }
1249 /// }
1250 /// fn main() {
1251 ///     assert_eq!(Scalar(16) >> Scalar(2), Scalar(4));
1252 /// }
1253 /// ```
1254 ///
1255 /// An implementation of `Shr` that spins a vector rightward by a given amount.
1256 ///
1257 /// ```
1258 /// use std::ops::Shr;
1259 ///
1260 /// #[derive(PartialEq, Debug)]
1261 /// struct SpinVector<T: Clone> {
1262 ///     vec: Vec<T>,
1263 /// }
1264 ///
1265 /// impl<T: Clone> Shr<usize> for SpinVector<T> {
1266 ///     type Output = Self;
1267 ///
1268 ///     fn shr(self, rhs: usize) -> SpinVector<T> {
1269 ///         // rotate the vector by `rhs` places
1270 ///         let (a, b) = self.vec.split_at(self.vec.len() - rhs);
1271 ///         let mut spun_vector: Vec<T> = vec![];
1272 ///         spun_vector.extend_from_slice(b);
1273 ///         spun_vector.extend_from_slice(a);
1274 ///         SpinVector { vec: spun_vector }
1275 ///     }
1276 /// }
1277 ///
1278 /// fn main() {
1279 ///     assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } >> 2,
1280 ///                SpinVector { vec: vec![3, 4, 0, 1, 2] });
1281 /// }
1282 /// ```
1283 #[lang = "shr"]
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 #[rustc_on_unimplemented = "no implementation for `{Self} >> {RHS}`"]
1286 pub trait Shr<RHS> {
1287     /// The resulting type after applying the `>>` operator
1288     #[stable(feature = "rust1", since = "1.0.0")]
1289     type Output;
1290
1291     /// The method for the `>>` operator
1292     #[stable(feature = "rust1", since = "1.0.0")]
1293     fn shr(self, rhs: RHS) -> Self::Output;
1294 }
1295
1296 macro_rules! shr_impl {
1297     ($t:ty, $f:ty) => (
1298         #[stable(feature = "rust1", since = "1.0.0")]
1299         impl Shr<$f> for $t {
1300             type Output = $t;
1301
1302             #[inline]
1303             #[rustc_inherit_overflow_checks]
1304             fn shr(self, other: $f) -> $t {
1305                 self >> other
1306             }
1307         }
1308
1309         forward_ref_binop! { impl Shr, shr for $t, $f }
1310     )
1311 }
1312
1313 macro_rules! shr_impl_all {
1314     ($($t:ty)*) => ($(
1315         shr_impl! { $t, u8 }
1316         shr_impl! { $t, u16 }
1317         shr_impl! { $t, u32 }
1318         shr_impl! { $t, u64 }
1319         shr_impl! { $t, u128 }
1320         shr_impl! { $t, usize }
1321
1322         shr_impl! { $t, i8 }
1323         shr_impl! { $t, i16 }
1324         shr_impl! { $t, i32 }
1325         shr_impl! { $t, i64 }
1326         shr_impl! { $t, i128 }
1327         shr_impl! { $t, isize }
1328     )*)
1329 }
1330
1331 shr_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
1332
1333 /// The addition assignment operator `+=`.
1334 ///
1335 /// # Examples
1336 ///
1337 /// This example creates a `Point` struct that implements the `AddAssign`
1338 /// trait, and then demonstrates add-assigning to a mutable `Point`.
1339 ///
1340 /// ```
1341 /// use std::ops::AddAssign;
1342 ///
1343 /// #[derive(Debug)]
1344 /// struct Point {
1345 ///     x: i32,
1346 ///     y: i32,
1347 /// }
1348 ///
1349 /// impl AddAssign for Point {
1350 ///     fn add_assign(&mut self, other: Point) {
1351 ///         *self = Point {
1352 ///             x: self.x + other.x,
1353 ///             y: self.y + other.y,
1354 ///         };
1355 ///     }
1356 /// }
1357 ///
1358 /// impl PartialEq for Point {
1359 ///     fn eq(&self, other: &Self) -> bool {
1360 ///         self.x == other.x && self.y == other.y
1361 ///     }
1362 /// }
1363 ///
1364 /// let mut point = Point { x: 1, y: 0 };
1365 /// point += Point { x: 2, y: 3 };
1366 /// assert_eq!(point, Point { x: 3, y: 3 });
1367 /// ```
1368 #[lang = "add_assign"]
1369 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1370 #[rustc_on_unimplemented = "no implementation for `{Self} += {Rhs}`"]
1371 pub trait AddAssign<Rhs=Self> {
1372     /// The method for the `+=` operator
1373     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1374     fn add_assign(&mut self, rhs: Rhs);
1375 }
1376
1377 macro_rules! add_assign_impl {
1378     ($($t:ty)+) => ($(
1379         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1380         impl AddAssign for $t {
1381             #[inline]
1382             #[rustc_inherit_overflow_checks]
1383             fn add_assign(&mut self, other: $t) { *self += other }
1384         }
1385     )+)
1386 }
1387
1388 add_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1389
1390 /// The subtraction assignment operator `-=`.
1391 ///
1392 /// # Examples
1393 ///
1394 /// This example creates a `Point` struct that implements the `SubAssign`
1395 /// trait, and then demonstrates sub-assigning to a mutable `Point`.
1396 ///
1397 /// ```
1398 /// use std::ops::SubAssign;
1399 ///
1400 /// #[derive(Debug)]
1401 /// struct Point {
1402 ///     x: i32,
1403 ///     y: i32,
1404 /// }
1405 ///
1406 /// impl SubAssign for Point {
1407 ///     fn sub_assign(&mut self, other: Point) {
1408 ///         *self = Point {
1409 ///             x: self.x - other.x,
1410 ///             y: self.y - other.y,
1411 ///         };
1412 ///     }
1413 /// }
1414 ///
1415 /// impl PartialEq for Point {
1416 ///     fn eq(&self, other: &Self) -> bool {
1417 ///         self.x == other.x && self.y == other.y
1418 ///     }
1419 /// }
1420 ///
1421 /// let mut point = Point { x: 3, y: 3 };
1422 /// point -= Point { x: 2, y: 3 };
1423 /// assert_eq!(point, Point {x: 1, y: 0});
1424 /// ```
1425 #[lang = "sub_assign"]
1426 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1427 #[rustc_on_unimplemented = "no implementation for `{Self} -= {Rhs}`"]
1428 pub trait SubAssign<Rhs=Self> {
1429     /// The method for the `-=` operator
1430     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1431     fn sub_assign(&mut self, rhs: Rhs);
1432 }
1433
1434 macro_rules! sub_assign_impl {
1435     ($($t:ty)+) => ($(
1436         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1437         impl SubAssign for $t {
1438             #[inline]
1439             #[rustc_inherit_overflow_checks]
1440             fn sub_assign(&mut self, other: $t) { *self -= other }
1441         }
1442     )+)
1443 }
1444
1445 sub_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1446
1447 /// The multiplication assignment operator `*=`.
1448 ///
1449 /// # Examples
1450 ///
1451 /// A trivial implementation of `MulAssign`. When `Foo *= Foo` happens, it ends up
1452 /// calling `mul_assign`, and therefore, `main` prints `Multiplying!`.
1453 ///
1454 /// ```
1455 /// use std::ops::MulAssign;
1456 ///
1457 /// struct Foo;
1458 ///
1459 /// impl MulAssign for Foo {
1460 ///     fn mul_assign(&mut self, _rhs: Foo) {
1461 ///         println!("Multiplying!");
1462 ///     }
1463 /// }
1464 ///
1465 /// # #[allow(unused_assignments)]
1466 /// fn main() {
1467 ///     let mut foo = Foo;
1468 ///     foo *= Foo;
1469 /// }
1470 /// ```
1471 #[lang = "mul_assign"]
1472 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1473 #[rustc_on_unimplemented = "no implementation for `{Self} *= {Rhs}`"]
1474 pub trait MulAssign<Rhs=Self> {
1475     /// The method for the `*=` operator
1476     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1477     fn mul_assign(&mut self, rhs: Rhs);
1478 }
1479
1480 macro_rules! mul_assign_impl {
1481     ($($t:ty)+) => ($(
1482         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1483         impl MulAssign for $t {
1484             #[inline]
1485             #[rustc_inherit_overflow_checks]
1486             fn mul_assign(&mut self, other: $t) { *self *= other }
1487         }
1488     )+)
1489 }
1490
1491 mul_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1492
1493 /// The division assignment operator `/=`.
1494 ///
1495 /// # Examples
1496 ///
1497 /// A trivial implementation of `DivAssign`. When `Foo /= Foo` happens, it ends up
1498 /// calling `div_assign`, and therefore, `main` prints `Dividing!`.
1499 ///
1500 /// ```
1501 /// use std::ops::DivAssign;
1502 ///
1503 /// struct Foo;
1504 ///
1505 /// impl DivAssign for Foo {
1506 ///     fn div_assign(&mut self, _rhs: Foo) {
1507 ///         println!("Dividing!");
1508 ///     }
1509 /// }
1510 ///
1511 /// # #[allow(unused_assignments)]
1512 /// fn main() {
1513 ///     let mut foo = Foo;
1514 ///     foo /= Foo;
1515 /// }
1516 /// ```
1517 #[lang = "div_assign"]
1518 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1519 #[rustc_on_unimplemented = "no implementation for `{Self} /= {Rhs}`"]
1520 pub trait DivAssign<Rhs=Self> {
1521     /// The method for the `/=` operator
1522     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1523     fn div_assign(&mut self, rhs: Rhs);
1524 }
1525
1526 macro_rules! div_assign_impl {
1527     ($($t:ty)+) => ($(
1528         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1529         impl DivAssign for $t {
1530             #[inline]
1531             fn div_assign(&mut self, other: $t) { *self /= other }
1532         }
1533     )+)
1534 }
1535
1536 div_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1537
1538 /// The remainder assignment operator `%=`.
1539 ///
1540 /// # Examples
1541 ///
1542 /// A trivial implementation of `RemAssign`. When `Foo %= Foo` happens, it ends up
1543 /// calling `rem_assign`, and therefore, `main` prints `Remainder-ing!`.
1544 ///
1545 /// ```
1546 /// use std::ops::RemAssign;
1547 ///
1548 /// struct Foo;
1549 ///
1550 /// impl RemAssign for Foo {
1551 ///     fn rem_assign(&mut self, _rhs: Foo) {
1552 ///         println!("Remainder-ing!");
1553 ///     }
1554 /// }
1555 ///
1556 /// # #[allow(unused_assignments)]
1557 /// fn main() {
1558 ///     let mut foo = Foo;
1559 ///     foo %= Foo;
1560 /// }
1561 /// ```
1562 #[lang = "rem_assign"]
1563 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1564 #[rustc_on_unimplemented = "no implementation for `{Self} %= {Rhs}`"]
1565 pub trait RemAssign<Rhs=Self> {
1566     /// The method for the `%=` operator
1567     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1568     fn rem_assign(&mut self, rhs: Rhs);
1569 }
1570
1571 macro_rules! rem_assign_impl {
1572     ($($t:ty)+) => ($(
1573         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1574         impl RemAssign for $t {
1575             #[inline]
1576             fn rem_assign(&mut self, other: $t) { *self %= other }
1577         }
1578     )+)
1579 }
1580
1581 rem_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1582
1583 /// The bitwise AND assignment operator `&=`.
1584 ///
1585 /// # Examples
1586 ///
1587 /// In this example, the `&=` operator is lifted to a trivial `Scalar` type.
1588 ///
1589 /// ```
1590 /// use std::ops::BitAndAssign;
1591 ///
1592 /// #[derive(Debug, PartialEq)]
1593 /// struct Scalar(bool);
1594 ///
1595 /// impl BitAndAssign for Scalar {
1596 ///     // rhs is the "right-hand side" of the expression `a &= b`
1597 ///     fn bitand_assign(&mut self, rhs: Self) {
1598 ///         *self = Scalar(self.0 & rhs.0)
1599 ///     }
1600 /// }
1601 ///
1602 /// fn main() {
1603 ///     let mut scalar = Scalar(true);
1604 ///     scalar &= Scalar(true);
1605 ///     assert_eq!(scalar, Scalar(true));
1606 ///
1607 ///     let mut scalar = Scalar(true);
1608 ///     scalar &= Scalar(false);
1609 ///     assert_eq!(scalar, Scalar(false));
1610 ///
1611 ///     let mut scalar = Scalar(false);
1612 ///     scalar &= Scalar(true);
1613 ///     assert_eq!(scalar, Scalar(false));
1614 ///
1615 ///     let mut scalar = Scalar(false);
1616 ///     scalar &= Scalar(false);
1617 ///     assert_eq!(scalar, Scalar(false));
1618 /// }
1619 /// ```
1620 ///
1621 /// In this example, the `BitAndAssign` trait is implemented for a
1622 /// `BooleanVector` struct.
1623 ///
1624 /// ```
1625 /// use std::ops::BitAndAssign;
1626 ///
1627 /// #[derive(Debug, PartialEq)]
1628 /// struct BooleanVector(Vec<bool>);
1629 ///
1630 /// impl BitAndAssign for BooleanVector {
1631 ///     // rhs is the "right-hand side" of the expression `a &= b`
1632 ///     fn bitand_assign(&mut self, rhs: Self) {
1633 ///         assert_eq!(self.0.len(), rhs.0.len());
1634 ///         *self = BooleanVector(self.0
1635 ///                                   .iter()
1636 ///                                   .zip(rhs.0.iter())
1637 ///                                   .map(|(x, y)| *x && *y)
1638 ///                                   .collect());
1639 ///     }
1640 /// }
1641 ///
1642 /// fn main() {
1643 ///     let mut bv = BooleanVector(vec![true, true, false, false]);
1644 ///     bv &= BooleanVector(vec![true, false, true, false]);
1645 ///     let expected = BooleanVector(vec![true, false, false, false]);
1646 ///     assert_eq!(bv, expected);
1647 /// }
1648 /// ```
1649 #[lang = "bitand_assign"]
1650 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1651 #[rustc_on_unimplemented = "no implementation for `{Self} &= {Rhs}`"]
1652 pub trait BitAndAssign<Rhs=Self> {
1653     /// The method for the `&=` operator
1654     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1655     fn bitand_assign(&mut self, rhs: Rhs);
1656 }
1657
1658 macro_rules! bitand_assign_impl {
1659     ($($t:ty)+) => ($(
1660         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1661         impl BitAndAssign for $t {
1662             #[inline]
1663             fn bitand_assign(&mut self, other: $t) { *self &= other }
1664         }
1665     )+)
1666 }
1667
1668 bitand_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1669
1670 /// The bitwise OR assignment operator `|=`.
1671 ///
1672 /// # Examples
1673 ///
1674 /// A trivial implementation of `BitOrAssign`. When `Foo |= Foo` happens, it ends up
1675 /// calling `bitor_assign`, and therefore, `main` prints `Bitwise Or-ing!`.
1676 ///
1677 /// ```
1678 /// use std::ops::BitOrAssign;
1679 ///
1680 /// struct Foo;
1681 ///
1682 /// impl BitOrAssign for Foo {
1683 ///     fn bitor_assign(&mut self, _rhs: Foo) {
1684 ///         println!("Bitwise Or-ing!");
1685 ///     }
1686 /// }
1687 ///
1688 /// # #[allow(unused_assignments)]
1689 /// fn main() {
1690 ///     let mut foo = Foo;
1691 ///     foo |= Foo;
1692 /// }
1693 /// ```
1694 #[lang = "bitor_assign"]
1695 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1696 #[rustc_on_unimplemented = "no implementation for `{Self} |= {Rhs}`"]
1697 pub trait BitOrAssign<Rhs=Self> {
1698     /// The method for the `|=` operator
1699     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1700     fn bitor_assign(&mut self, rhs: Rhs);
1701 }
1702
1703 macro_rules! bitor_assign_impl {
1704     ($($t:ty)+) => ($(
1705         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1706         impl BitOrAssign for $t {
1707             #[inline]
1708             fn bitor_assign(&mut self, other: $t) { *self |= other }
1709         }
1710     )+)
1711 }
1712
1713 bitor_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1714
1715 /// The bitwise XOR assignment operator `^=`.
1716 ///
1717 /// # Examples
1718 ///
1719 /// A trivial implementation of `BitXorAssign`. When `Foo ^= Foo` happens, it ends up
1720 /// calling `bitxor_assign`, and therefore, `main` prints `Bitwise Xor-ing!`.
1721 ///
1722 /// ```
1723 /// use std::ops::BitXorAssign;
1724 ///
1725 /// struct Foo;
1726 ///
1727 /// impl BitXorAssign for Foo {
1728 ///     fn bitxor_assign(&mut self, _rhs: Foo) {
1729 ///         println!("Bitwise Xor-ing!");
1730 ///     }
1731 /// }
1732 ///
1733 /// # #[allow(unused_assignments)]
1734 /// fn main() {
1735 ///     let mut foo = Foo;
1736 ///     foo ^= Foo;
1737 /// }
1738 /// ```
1739 #[lang = "bitxor_assign"]
1740 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1741 #[rustc_on_unimplemented = "no implementation for `{Self} ^= {Rhs}`"]
1742 pub trait BitXorAssign<Rhs=Self> {
1743     /// The method for the `^=` operator
1744     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1745     fn bitxor_assign(&mut self, rhs: Rhs);
1746 }
1747
1748 macro_rules! bitxor_assign_impl {
1749     ($($t:ty)+) => ($(
1750         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1751         impl BitXorAssign for $t {
1752             #[inline]
1753             fn bitxor_assign(&mut self, other: $t) { *self ^= other }
1754         }
1755     )+)
1756 }
1757
1758 bitxor_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1759
1760 /// The left shift assignment operator `<<=`.
1761 ///
1762 /// # Examples
1763 ///
1764 /// A trivial implementation of `ShlAssign`. When `Foo <<= Foo` happens, it ends up
1765 /// calling `shl_assign`, and therefore, `main` prints `Shifting left!`.
1766 ///
1767 /// ```
1768 /// use std::ops::ShlAssign;
1769 ///
1770 /// struct Foo;
1771 ///
1772 /// impl ShlAssign<Foo> for Foo {
1773 ///     fn shl_assign(&mut self, _rhs: Foo) {
1774 ///         println!("Shifting left!");
1775 ///     }
1776 /// }
1777 ///
1778 /// # #[allow(unused_assignments)]
1779 /// fn main() {
1780 ///     let mut foo = Foo;
1781 ///     foo <<= Foo;
1782 /// }
1783 /// ```
1784 #[lang = "shl_assign"]
1785 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1786 #[rustc_on_unimplemented = "no implementation for `{Self} <<= {Rhs}`"]
1787 pub trait ShlAssign<Rhs> {
1788     /// The method for the `<<=` operator
1789     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1790     fn shl_assign(&mut self, rhs: Rhs);
1791 }
1792
1793 macro_rules! shl_assign_impl {
1794     ($t:ty, $f:ty) => (
1795         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1796         impl ShlAssign<$f> for $t {
1797             #[inline]
1798             #[rustc_inherit_overflow_checks]
1799             fn shl_assign(&mut self, other: $f) {
1800                 *self <<= other
1801             }
1802         }
1803     )
1804 }
1805
1806 macro_rules! shl_assign_impl_all {
1807     ($($t:ty)*) => ($(
1808         shl_assign_impl! { $t, u8 }
1809         shl_assign_impl! { $t, u16 }
1810         shl_assign_impl! { $t, u32 }
1811         shl_assign_impl! { $t, u64 }
1812         shl_assign_impl! { $t, u128 }
1813         shl_assign_impl! { $t, usize }
1814
1815         shl_assign_impl! { $t, i8 }
1816         shl_assign_impl! { $t, i16 }
1817         shl_assign_impl! { $t, i32 }
1818         shl_assign_impl! { $t, i64 }
1819         shl_assign_impl! { $t, i128 }
1820         shl_assign_impl! { $t, isize }
1821     )*)
1822 }
1823
1824 shl_assign_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
1825
1826 /// The right shift assignment operator `>>=`.
1827 ///
1828 /// # Examples
1829 ///
1830 /// A trivial implementation of `ShrAssign`. When `Foo >>= Foo` happens, it ends up
1831 /// calling `shr_assign`, and therefore, `main` prints `Shifting right!`.
1832 ///
1833 /// ```
1834 /// use std::ops::ShrAssign;
1835 ///
1836 /// struct Foo;
1837 ///
1838 /// impl ShrAssign<Foo> for Foo {
1839 ///     fn shr_assign(&mut self, _rhs: Foo) {
1840 ///         println!("Shifting right!");
1841 ///     }
1842 /// }
1843 ///
1844 /// # #[allow(unused_assignments)]
1845 /// fn main() {
1846 ///     let mut foo = Foo;
1847 ///     foo >>= Foo;
1848 /// }
1849 /// ```
1850 #[lang = "shr_assign"]
1851 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1852 #[rustc_on_unimplemented = "no implementation for `{Self} >>= {Rhs}`"]
1853 pub trait ShrAssign<Rhs=Self> {
1854     /// The method for the `>>=` operator
1855     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1856     fn shr_assign(&mut self, rhs: Rhs);
1857 }
1858
1859 macro_rules! shr_assign_impl {
1860     ($t:ty, $f:ty) => (
1861         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1862         impl ShrAssign<$f> for $t {
1863             #[inline]
1864             #[rustc_inherit_overflow_checks]
1865             fn shr_assign(&mut self, other: $f) {
1866                 *self >>= other
1867             }
1868         }
1869     )
1870 }
1871
1872 macro_rules! shr_assign_impl_all {
1873     ($($t:ty)*) => ($(
1874         shr_assign_impl! { $t, u8 }
1875         shr_assign_impl! { $t, u16 }
1876         shr_assign_impl! { $t, u32 }
1877         shr_assign_impl! { $t, u64 }
1878         shr_assign_impl! { $t, u128 }
1879         shr_assign_impl! { $t, usize }
1880
1881         shr_assign_impl! { $t, i8 }
1882         shr_assign_impl! { $t, i16 }
1883         shr_assign_impl! { $t, i32 }
1884         shr_assign_impl! { $t, i64 }
1885         shr_assign_impl! { $t, i128 }
1886         shr_assign_impl! { $t, isize }
1887     )*)
1888 }
1889
1890 shr_assign_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
1891
1892 /// The `Index` trait is used to specify the functionality of indexing operations
1893 /// like `container[index]` when used in an immutable context.
1894 ///
1895 /// `container[index]` is actually syntactic sugar for `*container.index(index)`,
1896 /// but only when used as an immutable value. If a mutable value is requested,
1897 /// [`IndexMut`] is used instead. This allows nice things such as
1898 /// `let value = v[index]` if `value` implements [`Copy`].
1899 ///
1900 /// [`IndexMut`]: ../../std/ops/trait.IndexMut.html
1901 /// [`Copy`]: ../../std/marker/trait.Copy.html
1902 ///
1903 /// # Examples
1904 ///
1905 /// The following example implements `Index` on a read-only `NucleotideCount`
1906 /// container, enabling individual counts to be retrieved with index syntax.
1907 ///
1908 /// ```
1909 /// use std::ops::Index;
1910 ///
1911 /// enum Nucleotide {
1912 ///     A,
1913 ///     C,
1914 ///     G,
1915 ///     T,
1916 /// }
1917 ///
1918 /// struct NucleotideCount {
1919 ///     a: usize,
1920 ///     c: usize,
1921 ///     g: usize,
1922 ///     t: usize,
1923 /// }
1924 ///
1925 /// impl Index<Nucleotide> for NucleotideCount {
1926 ///     type Output = usize;
1927 ///
1928 ///     fn index(&self, nucleotide: Nucleotide) -> &usize {
1929 ///         match nucleotide {
1930 ///             Nucleotide::A => &self.a,
1931 ///             Nucleotide::C => &self.c,
1932 ///             Nucleotide::G => &self.g,
1933 ///             Nucleotide::T => &self.t,
1934 ///         }
1935 ///     }
1936 /// }
1937 ///
1938 /// let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12};
1939 /// assert_eq!(nucleotide_count[Nucleotide::A], 14);
1940 /// assert_eq!(nucleotide_count[Nucleotide::C], 9);
1941 /// assert_eq!(nucleotide_count[Nucleotide::G], 10);
1942 /// assert_eq!(nucleotide_count[Nucleotide::T], 12);
1943 /// ```
1944 #[lang = "index"]
1945 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 pub trait Index<Idx: ?Sized> {
1948     /// The returned type after indexing
1949     #[stable(feature = "rust1", since = "1.0.0")]
1950     type Output: ?Sized;
1951
1952     /// The method for the indexing (`container[index]`) operation
1953     #[stable(feature = "rust1", since = "1.0.0")]
1954     fn index(&self, index: Idx) -> &Self::Output;
1955 }
1956
1957 /// The `IndexMut` trait is used to specify the functionality of indexing
1958 /// operations like `container[index]` when used in a mutable context.
1959 ///
1960 /// `container[index]` is actually syntactic sugar for
1961 /// `*container.index_mut(index)`, but only when used as a mutable value. If
1962 /// an immutable value is requested, the [`Index`] trait is used instead. This
1963 /// allows nice things such as `v[index] = value` if `value` implements [`Copy`].
1964 ///
1965 /// [`Index`]: ../../std/ops/trait.Index.html
1966 /// [`Copy`]: ../../std/marker/trait.Copy.html
1967 ///
1968 /// # Examples
1969 ///
1970 /// A very simple implementation of a `Balance` struct that has two sides, where
1971 /// each can be indexed mutably and immutably.
1972 ///
1973 /// ```
1974 /// use std::ops::{Index,IndexMut};
1975 ///
1976 /// #[derive(Debug)]
1977 /// enum Side {
1978 ///     Left,
1979 ///     Right,
1980 /// }
1981 ///
1982 /// #[derive(Debug, PartialEq)]
1983 /// enum Weight {
1984 ///     Kilogram(f32),
1985 ///     Pound(f32),
1986 /// }
1987 ///
1988 /// struct Balance {
1989 ///     pub left: Weight,
1990 ///     pub right:Weight,
1991 /// }
1992 ///
1993 /// impl Index<Side> for Balance {
1994 ///     type Output = Weight;
1995 ///
1996 ///     fn index<'a>(&'a self, index: Side) -> &'a Weight {
1997 ///         println!("Accessing {:?}-side of balance immutably", index);
1998 ///         match index {
1999 ///             Side::Left => &self.left,
2000 ///             Side::Right => &self.right,
2001 ///         }
2002 ///     }
2003 /// }
2004 ///
2005 /// impl IndexMut<Side> for Balance {
2006 ///     fn index_mut<'a>(&'a mut self, index: Side) -> &'a mut Weight {
2007 ///         println!("Accessing {:?}-side of balance mutably", index);
2008 ///         match index {
2009 ///             Side::Left => &mut self.left,
2010 ///             Side::Right => &mut self.right,
2011 ///         }
2012 ///     }
2013 /// }
2014 ///
2015 /// fn main() {
2016 ///     let mut balance = Balance {
2017 ///         right: Weight::Kilogram(2.5),
2018 ///         left: Weight::Pound(1.5),
2019 ///     };
2020 ///
2021 ///     // In this case balance[Side::Right] is sugar for
2022 ///     // *balance.index(Side::Right), since we are only reading
2023 ///     // balance[Side::Right], not writing it.
2024 ///     assert_eq!(balance[Side::Right],Weight::Kilogram(2.5));
2025 ///
2026 ///     // However in this case balance[Side::Left] is sugar for
2027 ///     // *balance.index_mut(Side::Left), since we are writing
2028 ///     // balance[Side::Left].
2029 ///     balance[Side::Left] = Weight::Kilogram(3.0);
2030 /// }
2031 /// ```
2032 #[lang = "index_mut"]
2033 #[rustc_on_unimplemented = "the type `{Self}` cannot be mutably indexed by `{Idx}`"]
2034 #[stable(feature = "rust1", since = "1.0.0")]
2035 pub trait IndexMut<Idx: ?Sized>: Index<Idx> {
2036     /// The method for the mutable indexing (`container[index]`) operation
2037     #[stable(feature = "rust1", since = "1.0.0")]
2038     fn index_mut(&mut self, index: Idx) -> &mut Self::Output;
2039 }
2040
2041 /// An unbounded range. Use `..` (two dots) for its shorthand.
2042 ///
2043 /// Its primary use case is slicing index. It cannot serve as an iterator
2044 /// because it doesn't have a starting point.
2045 ///
2046 /// # Examples
2047 ///
2048 /// The `..` syntax is a `RangeFull`:
2049 ///
2050 /// ```
2051 /// assert_eq!((..), std::ops::RangeFull);
2052 /// ```
2053 ///
2054 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2055 /// `for` loop directly. This won't compile:
2056 ///
2057 /// ```ignore
2058 /// for i in .. {
2059 ///    // ...
2060 /// }
2061 /// ```
2062 ///
2063 /// Used as a slicing index, `RangeFull` produces the full array as a slice.
2064 ///
2065 /// ```
2066 /// let arr = [0, 1, 2, 3];
2067 /// assert_eq!(arr[ .. ], [0,1,2,3]);  // RangeFull
2068 /// assert_eq!(arr[ ..3], [0,1,2  ]);
2069 /// assert_eq!(arr[1.. ], [  1,2,3]);
2070 /// assert_eq!(arr[1..3], [  1,2  ]);
2071 /// ```
2072 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2073 #[stable(feature = "rust1", since = "1.0.0")]
2074 pub struct RangeFull;
2075
2076 #[stable(feature = "rust1", since = "1.0.0")]
2077 impl fmt::Debug for RangeFull {
2078     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2079         write!(fmt, "..")
2080     }
2081 }
2082
2083 /// A (half-open) range which is bounded at both ends: { x | start <= x < end }.
2084 /// Use `start..end` (two dots) for its shorthand.
2085 ///
2086 /// See the [`contains`](#method.contains) method for its characterization.
2087 ///
2088 /// # Examples
2089 ///
2090 /// ```
2091 /// fn main() {
2092 ///     assert_eq!((3..5), std::ops::Range{ start: 3, end: 5 });
2093 ///     assert_eq!(3+4+5, (3..6).sum());
2094 ///
2095 ///     let arr = [0, 1, 2, 3];
2096 ///     assert_eq!(arr[ .. ], [0,1,2,3]);
2097 ///     assert_eq!(arr[ ..3], [0,1,2  ]);
2098 ///     assert_eq!(arr[1.. ], [  1,2,3]);
2099 ///     assert_eq!(arr[1..3], [  1,2  ]);  // Range
2100 /// }
2101 /// ```
2102 #[derive(Clone, PartialEq, Eq, Hash)]  // not Copy -- see #27186
2103 #[stable(feature = "rust1", since = "1.0.0")]
2104 pub struct Range<Idx> {
2105     /// The lower bound of the range (inclusive).
2106     #[stable(feature = "rust1", since = "1.0.0")]
2107     pub start: Idx,
2108     /// The upper bound of the range (exclusive).
2109     #[stable(feature = "rust1", since = "1.0.0")]
2110     pub end: Idx,
2111 }
2112
2113 #[stable(feature = "rust1", since = "1.0.0")]
2114 impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
2115     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2116         write!(fmt, "{:?}..{:?}", self.start, self.end)
2117     }
2118 }
2119
2120 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2121 impl<Idx: PartialOrd<Idx>> Range<Idx> {
2122     /// # Examples
2123     ///
2124     /// ```
2125     /// #![feature(range_contains)]
2126     /// fn main() {
2127     ///     assert!( ! (3..5).contains(2));
2128     ///     assert!(   (3..5).contains(3));
2129     ///     assert!(   (3..5).contains(4));
2130     ///     assert!( ! (3..5).contains(5));
2131     ///
2132     ///     assert!( ! (3..3).contains(3));
2133     ///     assert!( ! (3..2).contains(3));
2134     /// }
2135     /// ```
2136     pub fn contains(&self, item: Idx) -> bool {
2137         (self.start <= item) && (item < self.end)
2138     }
2139 }
2140
2141 /// A range which is only bounded below: { x | start <= x }.
2142 /// Use `start..` for its shorthand.
2143 ///
2144 /// See the [`contains`](#method.contains) method for its characterization.
2145 ///
2146 /// Note: Currently, no overflow checking is done for the iterator
2147 /// implementation; if you use an integer range and the integer overflows, it
2148 /// might panic in debug mode or create an endless loop in release mode. This
2149 /// overflow behavior might change in the future.
2150 ///
2151 /// # Examples
2152 ///
2153 /// ```
2154 /// fn main() {
2155 ///     assert_eq!((2..), std::ops::RangeFrom{ start: 2 });
2156 ///     assert_eq!(2+3+4, (2..).take(3).sum());
2157 ///
2158 ///     let arr = [0, 1, 2, 3];
2159 ///     assert_eq!(arr[ .. ], [0,1,2,3]);
2160 ///     assert_eq!(arr[ ..3], [0,1,2  ]);
2161 ///     assert_eq!(arr[1.. ], [  1,2,3]);  // RangeFrom
2162 ///     assert_eq!(arr[1..3], [  1,2  ]);
2163 /// }
2164 /// ```
2165 #[derive(Clone, PartialEq, Eq, Hash)]  // not Copy -- see #27186
2166 #[stable(feature = "rust1", since = "1.0.0")]
2167 pub struct RangeFrom<Idx> {
2168     /// The lower bound of the range (inclusive).
2169     #[stable(feature = "rust1", since = "1.0.0")]
2170     pub start: Idx,
2171 }
2172
2173 #[stable(feature = "rust1", since = "1.0.0")]
2174 impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
2175     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2176         write!(fmt, "{:?}..", self.start)
2177     }
2178 }
2179
2180 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2181 impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
2182     /// # Examples
2183     ///
2184     /// ```
2185     /// #![feature(range_contains)]
2186     /// fn main() {
2187     ///     assert!( ! (3..).contains(2));
2188     ///     assert!(   (3..).contains(3));
2189     ///     assert!(   (3..).contains(1_000_000_000));
2190     /// }
2191     /// ```
2192     pub fn contains(&self, item: Idx) -> bool {
2193         (self.start <= item)
2194     }
2195 }
2196
2197 /// A range which is only bounded above: { x | x < end }.
2198 /// Use `..end` (two dots) for its shorthand.
2199 ///
2200 /// See the [`contains`](#method.contains) method for its characterization.
2201 ///
2202 /// It cannot serve as an iterator because it doesn't have a starting point.
2203 ///
2204 /// # Examples
2205 ///
2206 /// The `..{integer}` syntax is a `RangeTo`:
2207 ///
2208 /// ```
2209 /// assert_eq!((..5), std::ops::RangeTo{ end: 5 });
2210 /// ```
2211 ///
2212 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2213 /// `for` loop directly. This won't compile:
2214 ///
2215 /// ```ignore
2216 /// for i in ..5 {
2217 ///     // ...
2218 /// }
2219 /// ```
2220 ///
2221 /// When used as a slicing index, `RangeTo` produces a slice of all array
2222 /// elements before the index indicated by `end`.
2223 ///
2224 /// ```
2225 /// let arr = [0, 1, 2, 3];
2226 /// assert_eq!(arr[ .. ], [0,1,2,3]);
2227 /// assert_eq!(arr[ ..3], [0,1,2  ]);  // RangeTo
2228 /// assert_eq!(arr[1.. ], [  1,2,3]);
2229 /// assert_eq!(arr[1..3], [  1,2  ]);
2230 /// ```
2231 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2232 #[stable(feature = "rust1", since = "1.0.0")]
2233 pub struct RangeTo<Idx> {
2234     /// The upper bound of the range (exclusive).
2235     #[stable(feature = "rust1", since = "1.0.0")]
2236     pub end: Idx,
2237 }
2238
2239 #[stable(feature = "rust1", since = "1.0.0")]
2240 impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> {
2241     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2242         write!(fmt, "..{:?}", self.end)
2243     }
2244 }
2245
2246 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2247 impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
2248     /// # Examples
2249     ///
2250     /// ```
2251     /// #![feature(range_contains)]
2252     /// fn main() {
2253     ///     assert!(   (..5).contains(-1_000_000_000));
2254     ///     assert!(   (..5).contains(4));
2255     ///     assert!( ! (..5).contains(5));
2256     /// }
2257     /// ```
2258     pub fn contains(&self, item: Idx) -> bool {
2259         (item < self.end)
2260     }
2261 }
2262
2263 /// An inclusive range which is bounded at both ends: { x | start <= x <= end }.
2264 /// Use `start...end` (three dots) for its shorthand.
2265 ///
2266 /// See the [`contains`](#method.contains) method for its characterization.
2267 ///
2268 /// # Examples
2269 ///
2270 /// ```
2271 /// #![feature(inclusive_range,inclusive_range_syntax)]
2272 /// fn main() {
2273 ///     assert_eq!((3...5), std::ops::RangeInclusive::NonEmpty{ start: 3, end: 5 });
2274 ///     assert_eq!(3+4+5, (3...5).sum());
2275 ///
2276 ///     let arr = [0, 1, 2, 3];
2277 ///     assert_eq!(arr[ ...2], [0,1,2  ]);
2278 ///     assert_eq!(arr[1...2], [  1,2  ]);  // RangeInclusive
2279 /// }
2280 /// ```
2281 #[derive(Clone, PartialEq, Eq, Hash)]  // not Copy -- see #27186
2282 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2283 pub enum RangeInclusive<Idx> {
2284     /// Empty range (iteration has finished)
2285     #[unstable(feature = "inclusive_range",
2286                reason = "recently added, follows RFC",
2287                issue = "28237")]
2288     Empty {
2289         /// The point at which iteration finished
2290         #[unstable(feature = "inclusive_range",
2291                    reason = "recently added, follows RFC",
2292                    issue = "28237")]
2293         at: Idx
2294     },
2295     /// Non-empty range (iteration will yield value(s))
2296     #[unstable(feature = "inclusive_range",
2297                reason = "recently added, follows RFC",
2298                issue = "28237")]
2299     NonEmpty {
2300         /// The lower bound of the range (inclusive).
2301         #[unstable(feature = "inclusive_range",
2302                    reason = "recently added, follows RFC",
2303                    issue = "28237")]
2304         start: Idx,
2305         /// The upper bound of the range (inclusive).
2306         #[unstable(feature = "inclusive_range",
2307                    reason = "recently added, follows RFC",
2308                    issue = "28237")]
2309         end: Idx,
2310     },
2311 }
2312
2313 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2314 impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
2315     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2316         use self::RangeInclusive::*;
2317
2318         match *self {
2319             Empty { ref at } => write!(fmt, "[empty range @ {:?}]", at),
2320             NonEmpty { ref start, ref end } => write!(fmt, "{:?}...{:?}", start, end),
2321         }
2322     }
2323 }
2324
2325 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2326 impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
2327     /// # Examples
2328     ///
2329     /// ```
2330     /// #![feature(range_contains,inclusive_range_syntax)]
2331     /// fn main() {
2332     ///     assert!( ! (3...5).contains(2));
2333     ///     assert!(   (3...5).contains(3));
2334     ///     assert!(   (3...5).contains(4));
2335     ///     assert!(   (3...5).contains(5));
2336     ///     assert!( ! (3...5).contains(6));
2337     ///
2338     ///     assert!(   (3...3).contains(3));
2339     ///     assert!( ! (3...2).contains(3));
2340     /// }
2341     /// ```
2342     pub fn contains(&self, item: Idx) -> bool {
2343         if let &RangeInclusive::NonEmpty{ref start, ref end} = self {
2344             (*start <= item) && (item <= *end)
2345         } else { false }
2346     }
2347 }
2348
2349 /// An inclusive range which is only bounded above: { x | x <= end }.
2350 /// Use `...end` (three dots) for its shorthand.
2351 ///
2352 /// See the [`contains`](#method.contains) method for its characterization.
2353 ///
2354 /// It cannot serve as an iterator because it doesn't have a starting point.
2355 ///
2356 /// # Examples
2357 ///
2358 /// The `...{integer}` syntax is a `RangeToInclusive`:
2359 ///
2360 /// ```
2361 /// #![feature(inclusive_range,inclusive_range_syntax)]
2362 /// assert_eq!((...5), std::ops::RangeToInclusive{ end: 5 });
2363 /// ```
2364 ///
2365 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2366 /// `for` loop directly. This won't compile:
2367 ///
2368 /// ```ignore
2369 /// for i in ...5 {
2370 ///     // ...
2371 /// }
2372 /// ```
2373 ///
2374 /// When used as a slicing index, `RangeToInclusive` produces a slice of all
2375 /// array elements up to and including the index indicated by `end`.
2376 ///
2377 /// ```
2378 /// #![feature(inclusive_range_syntax)]
2379 /// let arr = [0, 1, 2, 3];
2380 /// assert_eq!(arr[ ...2], [0,1,2  ]);  // RangeToInclusive
2381 /// assert_eq!(arr[1...2], [  1,2  ]);
2382 /// ```
2383 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2384 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2385 pub struct RangeToInclusive<Idx> {
2386     /// The upper bound of the range (inclusive)
2387     #[unstable(feature = "inclusive_range",
2388                reason = "recently added, follows RFC",
2389                issue = "28237")]
2390     pub end: Idx,
2391 }
2392
2393 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2394 impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
2395     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2396         write!(fmt, "...{:?}", self.end)
2397     }
2398 }
2399
2400 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2401 impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
2402     /// # Examples
2403     ///
2404     /// ```
2405     /// #![feature(range_contains,inclusive_range_syntax)]
2406     /// fn main() {
2407     ///     assert!(   (...5).contains(-1_000_000_000));
2408     ///     assert!(   (...5).contains(5));
2409     ///     assert!( ! (...5).contains(6));
2410     /// }
2411     /// ```
2412     pub fn contains(&self, item: Idx) -> bool {
2413         (item <= self.end)
2414     }
2415 }
2416
2417 // RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
2418 // because underflow would be possible with (..0).into()
2419
2420 /// The `Deref` trait is used to specify the functionality of dereferencing
2421 /// operations, like `*v`.
2422 ///
2423 /// `Deref` also enables ['`Deref` coercions'][coercions].
2424 ///
2425 /// [coercions]: ../../book/deref-coercions.html
2426 ///
2427 /// # Examples
2428 ///
2429 /// A struct with a single field which is accessible via dereferencing the
2430 /// struct.
2431 ///
2432 /// ```
2433 /// use std::ops::Deref;
2434 ///
2435 /// struct DerefExample<T> {
2436 ///     value: T
2437 /// }
2438 ///
2439 /// impl<T> Deref for DerefExample<T> {
2440 ///     type Target = T;
2441 ///
2442 ///     fn deref(&self) -> &T {
2443 ///         &self.value
2444 ///     }
2445 /// }
2446 ///
2447 /// fn main() {
2448 ///     let x = DerefExample { value: 'a' };
2449 ///     assert_eq!('a', *x);
2450 /// }
2451 /// ```
2452 #[lang = "deref"]
2453 #[stable(feature = "rust1", since = "1.0.0")]
2454 pub trait Deref {
2455     /// The resulting type after dereferencing
2456     #[stable(feature = "rust1", since = "1.0.0")]
2457     type Target: ?Sized;
2458
2459     /// The method called to dereference a value
2460     #[stable(feature = "rust1", since = "1.0.0")]
2461     fn deref(&self) -> &Self::Target;
2462 }
2463
2464 #[stable(feature = "rust1", since = "1.0.0")]
2465 impl<'a, T: ?Sized> Deref for &'a T {
2466     type Target = T;
2467
2468     fn deref(&self) -> &T { *self }
2469 }
2470
2471 #[stable(feature = "rust1", since = "1.0.0")]
2472 impl<'a, T: ?Sized> Deref for &'a mut T {
2473     type Target = T;
2474
2475     fn deref(&self) -> &T { *self }
2476 }
2477
2478 /// The `DerefMut` trait is used to specify the functionality of dereferencing
2479 /// mutably like `*v = 1;`
2480 ///
2481 /// `DerefMut` also enables ['`Deref` coercions'][coercions].
2482 ///
2483 /// [coercions]: ../../book/deref-coercions.html
2484 ///
2485 /// # Examples
2486 ///
2487 /// A struct with a single field which is modifiable via dereferencing the
2488 /// struct.
2489 ///
2490 /// ```
2491 /// use std::ops::{Deref, DerefMut};
2492 ///
2493 /// struct DerefMutExample<T> {
2494 ///     value: T
2495 /// }
2496 ///
2497 /// impl<T> Deref for DerefMutExample<T> {
2498 ///     type Target = T;
2499 ///
2500 ///     fn deref(&self) -> &T {
2501 ///         &self.value
2502 ///     }
2503 /// }
2504 ///
2505 /// impl<T> DerefMut for DerefMutExample<T> {
2506 ///     fn deref_mut(&mut self) -> &mut T {
2507 ///         &mut self.value
2508 ///     }
2509 /// }
2510 ///
2511 /// fn main() {
2512 ///     let mut x = DerefMutExample { value: 'a' };
2513 ///     *x = 'b';
2514 ///     assert_eq!('b', *x);
2515 /// }
2516 /// ```
2517 #[lang = "deref_mut"]
2518 #[stable(feature = "rust1", since = "1.0.0")]
2519 pub trait DerefMut: Deref {
2520     /// The method called to mutably dereference a value
2521     #[stable(feature = "rust1", since = "1.0.0")]
2522     fn deref_mut(&mut self) -> &mut Self::Target;
2523 }
2524
2525 #[stable(feature = "rust1", since = "1.0.0")]
2526 impl<'a, T: ?Sized> DerefMut for &'a mut T {
2527     fn deref_mut(&mut self) -> &mut T { *self }
2528 }
2529
2530 /// A version of the call operator that takes an immutable receiver.
2531 ///
2532 /// # Examples
2533 ///
2534 /// Closures automatically implement this trait, which allows them to be
2535 /// invoked. Note, however, that `Fn` takes an immutable reference to any
2536 /// captured variables. To take a mutable capture, implement [`FnMut`], and to
2537 /// consume the capture, implement [`FnOnce`].
2538 ///
2539 /// [`FnMut`]: trait.FnMut.html
2540 /// [`FnOnce`]: trait.FnOnce.html
2541 ///
2542 /// ```
2543 /// let square = |x| x * x;
2544 /// assert_eq!(square(5), 25);
2545 /// ```
2546 ///
2547 /// Closures can also be passed to higher-level functions through a `Fn`
2548 /// parameter (or a `FnMut` or `FnOnce` parameter, which are supertraits of
2549 /// `Fn`).
2550 ///
2551 /// ```
2552 /// fn call_with_one<F>(func: F) -> usize
2553 ///     where F: Fn(usize) -> usize {
2554 ///     func(1)
2555 /// }
2556 ///
2557 /// let double = |x| x * 2;
2558 /// assert_eq!(call_with_one(double), 2);
2559 /// ```
2560 #[lang = "fn"]
2561 #[stable(feature = "rust1", since = "1.0.0")]
2562 #[rustc_paren_sugar]
2563 #[fundamental] // so that regex can rely that `&str: !FnMut`
2564 pub trait Fn<Args> : FnMut<Args> {
2565     /// This is called when the call operator is used.
2566     #[unstable(feature = "fn_traits", issue = "29625")]
2567     extern "rust-call" fn call(&self, args: Args) -> Self::Output;
2568 }
2569
2570 /// A version of the call operator that takes a mutable receiver.
2571 ///
2572 /// # Examples
2573 ///
2574 /// Closures that mutably capture variables automatically implement this trait,
2575 /// which allows them to be invoked.
2576 ///
2577 /// ```
2578 /// let mut x = 5;
2579 /// {
2580 ///     let mut square_x = || x *= x;
2581 ///     square_x();
2582 /// }
2583 /// assert_eq!(x, 25);
2584 /// ```
2585 ///
2586 /// Closures can also be passed to higher-level functions through a `FnMut`
2587 /// parameter (or a `FnOnce` parameter, which is a supertrait of `FnMut`).
2588 ///
2589 /// ```
2590 /// fn do_twice<F>(mut func: F)
2591 ///     where F: FnMut()
2592 /// {
2593 ///     func();
2594 ///     func();
2595 /// }
2596 ///
2597 /// let mut x: usize = 1;
2598 /// {
2599 ///     let add_two_to_x = || x += 2;
2600 ///     do_twice(add_two_to_x);
2601 /// }
2602 ///
2603 /// assert_eq!(x, 5);
2604 /// ```
2605 #[lang = "fn_mut"]
2606 #[stable(feature = "rust1", since = "1.0.0")]
2607 #[rustc_paren_sugar]
2608 #[fundamental] // so that regex can rely that `&str: !FnMut`
2609 pub trait FnMut<Args> : FnOnce<Args> {
2610     /// This is called when the call operator is used.
2611     #[unstable(feature = "fn_traits", issue = "29625")]
2612     extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
2613 }
2614
2615 /// A version of the call operator that takes a by-value receiver.
2616 ///
2617 /// # Examples
2618 ///
2619 /// By-value closures automatically implement this trait, which allows them to
2620 /// be invoked.
2621 ///
2622 /// ```
2623 /// let x = 5;
2624 /// let square_x = move || x * x;
2625 /// assert_eq!(square_x(), 25);
2626 /// ```
2627 ///
2628 /// By-value Closures can also be passed to higher-level functions through a
2629 /// `FnOnce` parameter.
2630 ///
2631 /// ```
2632 /// fn consume_with_relish<F>(func: F)
2633 ///     where F: FnOnce() -> String
2634 /// {
2635 ///     // `func` consumes its captured variables, so it cannot be run more
2636 ///     // than once
2637 ///     println!("Consumed: {}", func());
2638 ///
2639 ///     println!("Delicious!");
2640 ///
2641 ///     // Attempting to invoke `func()` again will throw a `use of moved
2642 ///     // value` error for `func`
2643 /// }
2644 ///
2645 /// let x = String::from("x");
2646 /// let consume_and_return_x = move || x;
2647 /// consume_with_relish(consume_and_return_x);
2648 ///
2649 /// // `consume_and_return_x` can no longer be invoked at this point
2650 /// ```
2651 #[lang = "fn_once"]
2652 #[stable(feature = "rust1", since = "1.0.0")]
2653 #[rustc_paren_sugar]
2654 #[fundamental] // so that regex can rely that `&str: !FnMut`
2655 pub trait FnOnce<Args> {
2656     /// The returned type after the call operator is used.
2657     #[stable(feature = "fn_once_output", since = "1.12.0")]
2658     type Output;
2659
2660     /// This is called when the call operator is used.
2661     #[unstable(feature = "fn_traits", issue = "29625")]
2662     extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
2663 }
2664
2665 mod impls {
2666     #[stable(feature = "rust1", since = "1.0.0")]
2667     impl<'a,A,F:?Sized> Fn<A> for &'a F
2668         where F : Fn<A>
2669     {
2670         extern "rust-call" fn call(&self, args: A) -> F::Output {
2671             (**self).call(args)
2672         }
2673     }
2674
2675     #[stable(feature = "rust1", since = "1.0.0")]
2676     impl<'a,A,F:?Sized> FnMut<A> for &'a F
2677         where F : Fn<A>
2678     {
2679         extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
2680             (**self).call(args)
2681         }
2682     }
2683
2684     #[stable(feature = "rust1", since = "1.0.0")]
2685     impl<'a,A,F:?Sized> FnOnce<A> for &'a F
2686         where F : Fn<A>
2687     {
2688         type Output = F::Output;
2689
2690         extern "rust-call" fn call_once(self, args: A) -> F::Output {
2691             (*self).call(args)
2692         }
2693     }
2694
2695     #[stable(feature = "rust1", since = "1.0.0")]
2696     impl<'a,A,F:?Sized> FnMut<A> for &'a mut F
2697         where F : FnMut<A>
2698     {
2699         extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
2700             (*self).call_mut(args)
2701         }
2702     }
2703
2704     #[stable(feature = "rust1", since = "1.0.0")]
2705     impl<'a,A,F:?Sized> FnOnce<A> for &'a mut F
2706         where F : FnMut<A>
2707     {
2708         type Output = F::Output;
2709         extern "rust-call" fn call_once(mut self, args: A) -> F::Output {
2710             (*self).call_mut(args)
2711         }
2712     }
2713 }
2714
2715 /// Trait that indicates that this is a pointer or a wrapper for one,
2716 /// where unsizing can be performed on the pointee.
2717 ///
2718 /// See the [DST coercion RfC][dst-coerce] and [the nomicon entry on coercion][nomicon-coerce]
2719 /// for more details.
2720 ///
2721 /// For builtin pointer types, pointers to `T` will coerce to pointers to `U` if `T: Unsize<U>`
2722 /// by converting from a thin pointer to a fat pointer.
2723 ///
2724 /// For custom types, the coercion here works by coercing `Foo<T>` to `Foo<U>`
2725 /// provided an impl of `CoerceUnsized<Foo<U>> for Foo<T>` exists.
2726 /// Such an impl can only be written if `Foo<T>` has only a single non-phantomdata
2727 /// field involving `T`. If the type of that field is `Bar<T>`, an implementation
2728 /// of `CoerceUnsized<Bar<U>> for Bar<T>` must exist. The coercion will work by
2729 /// by coercing the `Bar<T>` field into `Bar<U>` and filling in the rest of the fields
2730 /// from `Foo<T>` to create a `Foo<U>`. This will effectively drill down to a pointer
2731 /// field and coerce that.
2732 ///
2733 /// Generally, for smart pointers you will implement
2734 /// `CoerceUnsized<Ptr<U>> for Ptr<T> where T: Unsize<U>, U: ?Sized`, with an
2735 /// optional `?Sized` bound on `T` itself. For wrapper types that directly embed `T`
2736 /// like `Cell<T>` and `RefCell<T>`, you
2737 /// can directly implement `CoerceUnsized<Wrap<U>> for Wrap<T> where T: CoerceUnsized<U>`.
2738 /// This will let coercions of types like `Cell<Box<T>>` work.
2739 ///
2740 /// [`Unsize`][unsize] is used to mark types which can be coerced to DSTs if behind
2741 /// pointers. It is implemented automatically by the compiler.
2742 ///
2743 /// [dst-coerce]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
2744 /// [unsize]: ../marker/trait.Unsize.html
2745 /// [nomicon-coerce]: ../../nomicon/coercions.html
2746 #[unstable(feature = "coerce_unsized", issue = "27732")]
2747 #[lang="coerce_unsized"]
2748 pub trait CoerceUnsized<T> {
2749     // Empty.
2750 }
2751
2752 // &mut T -> &mut U
2753 #[unstable(feature = "coerce_unsized", issue = "27732")]
2754 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a mut U> for &'a mut T {}
2755 // &mut T -> &U
2756 #[unstable(feature = "coerce_unsized", issue = "27732")]
2757 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b mut T {}
2758 // &mut T -> *mut U
2759 #[unstable(feature = "coerce_unsized", issue = "27732")]
2760 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for &'a mut T {}
2761 // &mut T -> *const U
2762 #[unstable(feature = "coerce_unsized", issue = "27732")]
2763 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a mut T {}
2764
2765 // &T -> &U
2766 #[unstable(feature = "coerce_unsized", issue = "27732")]
2767 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b T {}
2768 // &T -> *const U
2769 #[unstable(feature = "coerce_unsized", issue = "27732")]
2770 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a T {}
2771
2772 // *mut T -> *mut U
2773 #[unstable(feature = "coerce_unsized", issue = "27732")]
2774 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for *mut T {}
2775 // *mut T -> *const U
2776 #[unstable(feature = "coerce_unsized", issue = "27732")]
2777 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *mut T {}
2778
2779 // *const T -> *const U
2780 #[unstable(feature = "coerce_unsized", issue = "27732")]
2781 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *const T {}
2782
2783 /// Both `PLACE <- EXPR` and `box EXPR` desugar into expressions
2784 /// that allocate an intermediate "place" that holds uninitialized
2785 /// state.  The desugaring evaluates EXPR, and writes the result at
2786 /// the address returned by the `pointer` method of this trait.
2787 ///
2788 /// A `Place` can be thought of as a special representation for a
2789 /// hypothetical `&uninit` reference (which Rust cannot currently
2790 /// express directly). That is, it represents a pointer to
2791 /// uninitialized storage.
2792 ///
2793 /// The client is responsible for two steps: First, initializing the
2794 /// payload (it can access its address via `pointer`). Second,
2795 /// converting the agent to an instance of the owning pointer, via the
2796 /// appropriate `finalize` method (see the `InPlace`.
2797 ///
2798 /// If evaluating EXPR fails, then it is up to the destructor for the
2799 /// implementation of Place to clean up any intermediate state
2800 /// (e.g. deallocate box storage, pop a stack, etc).
2801 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2802 pub trait Place<Data: ?Sized> {
2803     /// Returns the address where the input value will be written.
2804     /// Note that the data at this address is generally uninitialized,
2805     /// and thus one should use `ptr::write` for initializing it.
2806     fn pointer(&mut self) -> *mut Data;
2807 }
2808
2809 /// Interface to implementations of  `PLACE <- EXPR`.
2810 ///
2811 /// `PLACE <- EXPR` effectively desugars into:
2812 ///
2813 /// ```rust,ignore
2814 /// let p = PLACE;
2815 /// let mut place = Placer::make_place(p);
2816 /// let raw_place = Place::pointer(&mut place);
2817 /// let value = EXPR;
2818 /// unsafe {
2819 ///     std::ptr::write(raw_place, value);
2820 ///     InPlace::finalize(place)
2821 /// }
2822 /// ```
2823 ///
2824 /// The type of `PLACE <- EXPR` is derived from the type of `PLACE`;
2825 /// if the type of `PLACE` is `P`, then the final type of the whole
2826 /// expression is `P::Place::Owner` (see the `InPlace` and `Boxed`
2827 /// traits).
2828 ///
2829 /// Values for types implementing this trait usually are transient
2830 /// intermediate values (e.g. the return value of `Vec::emplace_back`)
2831 /// or `Copy`, since the `make_place` method takes `self` by value.
2832 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2833 pub trait Placer<Data: ?Sized> {
2834     /// `Place` is the intermedate agent guarding the
2835     /// uninitialized state for `Data`.
2836     type Place: InPlace<Data>;
2837
2838     /// Creates a fresh place from `self`.
2839     fn make_place(self) -> Self::Place;
2840 }
2841
2842 /// Specialization of `Place` trait supporting `PLACE <- EXPR`.
2843 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2844 pub trait InPlace<Data: ?Sized>: Place<Data> {
2845     /// `Owner` is the type of the end value of `PLACE <- EXPR`
2846     ///
2847     /// Note that when `PLACE <- EXPR` is solely used for
2848     /// side-effecting an existing data-structure,
2849     /// e.g. `Vec::emplace_back`, then `Owner` need not carry any
2850     /// information at all (e.g. it can be the unit type `()` in that
2851     /// case).
2852     type Owner;
2853
2854     /// Converts self into the final value, shifting
2855     /// deallocation/cleanup responsibilities (if any remain), over to
2856     /// the returned instance of `Owner` and forgetting self.
2857     unsafe fn finalize(self) -> Self::Owner;
2858 }
2859
2860 /// Core trait for the `box EXPR` form.
2861 ///
2862 /// `box EXPR` effectively desugars into:
2863 ///
2864 /// ```rust,ignore
2865 /// let mut place = BoxPlace::make_place();
2866 /// let raw_place = Place::pointer(&mut place);
2867 /// let value = EXPR;
2868 /// unsafe {
2869 ///     ::std::ptr::write(raw_place, value);
2870 ///     Boxed::finalize(place)
2871 /// }
2872 /// ```
2873 ///
2874 /// The type of `box EXPR` is supplied from its surrounding
2875 /// context; in the above expansion, the result type `T` is used
2876 /// to determine which implementation of `Boxed` to use, and that
2877 /// `<T as Boxed>` in turn dictates determines which
2878 /// implementation of `BoxPlace` to use, namely:
2879 /// `<<T as Boxed>::Place as BoxPlace>`.
2880 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2881 pub trait Boxed {
2882     /// The kind of data that is stored in this kind of box.
2883     type Data;  /* (`Data` unused b/c cannot yet express below bound.) */
2884     /// The place that will negotiate the storage of the data.
2885     type Place: BoxPlace<Self::Data>;
2886
2887     /// Converts filled place into final owning value, shifting
2888     /// deallocation/cleanup responsibilities (if any remain), over to
2889     /// returned instance of `Self` and forgetting `filled`.
2890     unsafe fn finalize(filled: Self::Place) -> Self;
2891 }
2892
2893 /// Specialization of `Place` trait supporting `box EXPR`.
2894 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2895 pub trait BoxPlace<Data: ?Sized> : Place<Data> {
2896     /// Creates a globally fresh place.
2897     fn make_place() -> Self;
2898 }
2899
2900 /// A trait for types which have success and error states and are meant to work
2901 /// with the question mark operator.
2902 /// When the `?` operator is used with a value, whether the value is in the
2903 /// success or error state is determined by calling `translate`.
2904 ///
2905 /// This trait is **very** experimental, it will probably be iterated on heavily
2906 /// before it is stabilised. Implementors should expect change. Users of `?`
2907 /// should not rely on any implementations of `Carrier` other than `Result`,
2908 /// i.e., you should not expect `?` to continue to work with `Option`, etc.
2909 #[unstable(feature = "question_mark_carrier", issue = "31436")]
2910 pub trait Carrier {
2911     /// The type of the value when computation succeeds.
2912     type Success;
2913     /// The type of the value when computation errors out.
2914     type Error;
2915
2916     /// Create a `Carrier` from a success value.
2917     fn from_success(_: Self::Success) -> Self;
2918
2919     /// Create a `Carrier` from an error value.
2920     fn from_error(_: Self::Error) -> Self;
2921
2922     /// Translate this `Carrier` to another implementation of `Carrier` with the
2923     /// same associated types.
2924     fn translate<T>(self) -> T where T: Carrier<Success=Self::Success, Error=Self::Error>;
2925 }
2926
2927 #[unstable(feature = "question_mark_carrier", issue = "31436")]
2928 impl<U, V> Carrier for Result<U, V> {
2929     type Success = U;
2930     type Error = V;
2931
2932     fn from_success(u: U) -> Result<U, V> {
2933         Ok(u)
2934     }
2935
2936     fn from_error(e: V) -> Result<U, V> {
2937         Err(e)
2938     }
2939
2940     fn translate<T>(self) -> T
2941         where T: Carrier<Success=U, Error=V>
2942     {
2943         match self {
2944             Ok(u) => T::from_success(u),
2945             Err(e) => T::from_error(e),
2946         }
2947     }
2948 }
2949
2950 struct _DummyErrorType;
2951
2952 impl Carrier for _DummyErrorType {
2953     type Success = ();
2954     type Error = ();
2955
2956     fn from_success(_: ()) -> _DummyErrorType {
2957         _DummyErrorType
2958     }
2959
2960     fn from_error(_: ()) -> _DummyErrorType {
2961         _DummyErrorType
2962     }
2963
2964     fn translate<T>(self) -> T
2965         where T: Carrier<Success=(), Error=()>
2966     {
2967         T::from_success(())
2968     }
2969 }