]> git.lizzy.rs Git - rust.git/blob - src/libcore/ops.rs
Make RangeInclusive just a two-field struct
[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 #[allow(unused_macros)]
803 macro_rules! neg_impl_unsigned {
804     ($($t:ty)*) => {
805         neg_impl_core!{ x => {
806             !x.wrapping_add(1)
807         }, $($t)*} }
808 }
809
810 // neg_impl_unsigned! { usize u8 u16 u32 u64 }
811 neg_impl_numeric! { isize i8 i16 i32 i64 i128 f32 f64 }
812
813 /// The unary logical negation operator `!`.
814 ///
815 /// # Examples
816 ///
817 /// An implementation of `Not` for `Answer`, which enables the use of `!` to
818 /// invert its value.
819 ///
820 /// ```
821 /// use std::ops::Not;
822 ///
823 /// #[derive(Debug, PartialEq)]
824 /// enum Answer {
825 ///     Yes,
826 ///     No,
827 /// }
828 ///
829 /// impl Not for Answer {
830 ///     type Output = Answer;
831 ///
832 ///     fn not(self) -> Answer {
833 ///         match self {
834 ///             Answer::Yes => Answer::No,
835 ///             Answer::No => Answer::Yes
836 ///         }
837 ///     }
838 /// }
839 ///
840 /// assert_eq!(!Answer::Yes, Answer::No);
841 /// assert_eq!(!Answer::No, Answer::Yes);
842 /// ```
843 #[lang = "not"]
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub trait Not {
846     /// The resulting type after applying the `!` operator
847     #[stable(feature = "rust1", since = "1.0.0")]
848     type Output;
849
850     /// The method for the unary `!` operator
851     #[stable(feature = "rust1", since = "1.0.0")]
852     fn not(self) -> Self::Output;
853 }
854
855 macro_rules! not_impl {
856     ($($t:ty)*) => ($(
857         #[stable(feature = "rust1", since = "1.0.0")]
858         impl Not for $t {
859             type Output = $t;
860
861             #[inline]
862             fn not(self) -> $t { !self }
863         }
864
865         forward_ref_unop! { impl Not, not for $t }
866     )*)
867 }
868
869 not_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
870
871 /// The bitwise AND operator `&`.
872 ///
873 /// # Examples
874 ///
875 /// In this example, the `&` operator is lifted to a trivial `Scalar` type.
876 ///
877 /// ```
878 /// use std::ops::BitAnd;
879 ///
880 /// #[derive(Debug, PartialEq)]
881 /// struct Scalar(bool);
882 ///
883 /// impl BitAnd for Scalar {
884 ///     type Output = Self;
885 ///
886 ///     // rhs is the "right-hand side" of the expression `a & b`
887 ///     fn bitand(self, rhs: Self) -> Self {
888 ///         Scalar(self.0 & rhs.0)
889 ///     }
890 /// }
891 ///
892 /// fn main() {
893 ///     assert_eq!(Scalar(true) & Scalar(true), Scalar(true));
894 ///     assert_eq!(Scalar(true) & Scalar(false), Scalar(false));
895 ///     assert_eq!(Scalar(false) & Scalar(true), Scalar(false));
896 ///     assert_eq!(Scalar(false) & Scalar(false), Scalar(false));
897 /// }
898 /// ```
899 ///
900 /// In this example, the `BitAnd` trait is implemented for a `BooleanVector`
901 /// struct.
902 ///
903 /// ```
904 /// use std::ops::BitAnd;
905 ///
906 /// #[derive(Debug, PartialEq)]
907 /// struct BooleanVector(Vec<bool>);
908 ///
909 /// impl BitAnd for BooleanVector {
910 ///     type Output = Self;
911 ///
912 ///     fn bitand(self, BooleanVector(rhs): Self) -> Self {
913 ///         let BooleanVector(lhs) = self;
914 ///         assert_eq!(lhs.len(), rhs.len());
915 ///         BooleanVector(lhs.iter().zip(rhs.iter()).map(|(x, y)| *x && *y).collect())
916 ///     }
917 /// }
918 ///
919 /// fn main() {
920 ///     let bv1 = BooleanVector(vec![true, true, false, false]);
921 ///     let bv2 = BooleanVector(vec![true, false, true, false]);
922 ///     let expected = BooleanVector(vec![true, false, false, false]);
923 ///     assert_eq!(bv1 & bv2, expected);
924 /// }
925 /// ```
926 #[lang = "bitand"]
927 #[stable(feature = "rust1", since = "1.0.0")]
928 #[rustc_on_unimplemented = "no implementation for `{Self} & {RHS}`"]
929 pub trait BitAnd<RHS=Self> {
930     /// The resulting type after applying the `&` operator
931     #[stable(feature = "rust1", since = "1.0.0")]
932     type Output;
933
934     /// The method for the `&` operator
935     #[stable(feature = "rust1", since = "1.0.0")]
936     fn bitand(self, rhs: RHS) -> Self::Output;
937 }
938
939 macro_rules! bitand_impl {
940     ($($t:ty)*) => ($(
941         #[stable(feature = "rust1", since = "1.0.0")]
942         impl BitAnd for $t {
943             type Output = $t;
944
945             #[inline]
946             fn bitand(self, rhs: $t) -> $t { self & rhs }
947         }
948
949         forward_ref_binop! { impl BitAnd, bitand for $t, $t }
950     )*)
951 }
952
953 bitand_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
954
955 /// The bitwise OR operator `|`.
956 ///
957 /// # Examples
958 ///
959 /// In this example, the `|` operator is lifted to a trivial `Scalar` type.
960 ///
961 /// ```
962 /// use std::ops::BitOr;
963 ///
964 /// #[derive(Debug, PartialEq)]
965 /// struct Scalar(bool);
966 ///
967 /// impl BitOr for Scalar {
968 ///     type Output = Self;
969 ///
970 ///     // rhs is the "right-hand side" of the expression `a | b`
971 ///     fn bitor(self, rhs: Self) -> Self {
972 ///         Scalar(self.0 | rhs.0)
973 ///     }
974 /// }
975 ///
976 /// fn main() {
977 ///     assert_eq!(Scalar(true) | Scalar(true), Scalar(true));
978 ///     assert_eq!(Scalar(true) | Scalar(false), Scalar(true));
979 ///     assert_eq!(Scalar(false) | Scalar(true), Scalar(true));
980 ///     assert_eq!(Scalar(false) | Scalar(false), Scalar(false));
981 /// }
982 /// ```
983 ///
984 /// In this example, the `BitOr` trait is implemented for a `BooleanVector`
985 /// struct.
986 ///
987 /// ```
988 /// use std::ops::BitOr;
989 ///
990 /// #[derive(Debug, PartialEq)]
991 /// struct BooleanVector(Vec<bool>);
992 ///
993 /// impl BitOr for BooleanVector {
994 ///     type Output = Self;
995 ///
996 ///     fn bitor(self, BooleanVector(rhs): Self) -> Self {
997 ///         let BooleanVector(lhs) = self;
998 ///         assert_eq!(lhs.len(), rhs.len());
999 ///         BooleanVector(lhs.iter().zip(rhs.iter()).map(|(x, y)| *x || *y).collect())
1000 ///     }
1001 /// }
1002 ///
1003 /// fn main() {
1004 ///     let bv1 = BooleanVector(vec![true, true, false, false]);
1005 ///     let bv2 = BooleanVector(vec![true, false, true, false]);
1006 ///     let expected = BooleanVector(vec![true, true, true, false]);
1007 ///     assert_eq!(bv1 | bv2, expected);
1008 /// }
1009 /// ```
1010 #[lang = "bitor"]
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 #[rustc_on_unimplemented = "no implementation for `{Self} | {RHS}`"]
1013 pub trait BitOr<RHS=Self> {
1014     /// The resulting type after applying the `|` operator
1015     #[stable(feature = "rust1", since = "1.0.0")]
1016     type Output;
1017
1018     /// The method for the `|` operator
1019     #[stable(feature = "rust1", since = "1.0.0")]
1020     fn bitor(self, rhs: RHS) -> Self::Output;
1021 }
1022
1023 macro_rules! bitor_impl {
1024     ($($t:ty)*) => ($(
1025         #[stable(feature = "rust1", since = "1.0.0")]
1026         impl BitOr for $t {
1027             type Output = $t;
1028
1029             #[inline]
1030             fn bitor(self, rhs: $t) -> $t { self | rhs }
1031         }
1032
1033         forward_ref_binop! { impl BitOr, bitor for $t, $t }
1034     )*)
1035 }
1036
1037 bitor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1038
1039 /// The bitwise XOR operator `^`.
1040 ///
1041 /// # Examples
1042 ///
1043 /// In this example, the `^` operator is lifted to a trivial `Scalar` type.
1044 ///
1045 /// ```
1046 /// use std::ops::BitXor;
1047 ///
1048 /// #[derive(Debug, PartialEq)]
1049 /// struct Scalar(bool);
1050 ///
1051 /// impl BitXor for Scalar {
1052 ///     type Output = Self;
1053 ///
1054 ///     // rhs is the "right-hand side" of the expression `a ^ b`
1055 ///     fn bitxor(self, rhs: Self) -> Self {
1056 ///         Scalar(self.0 ^ rhs.0)
1057 ///     }
1058 /// }
1059 ///
1060 /// fn main() {
1061 ///     assert_eq!(Scalar(true) ^ Scalar(true), Scalar(false));
1062 ///     assert_eq!(Scalar(true) ^ Scalar(false), Scalar(true));
1063 ///     assert_eq!(Scalar(false) ^ Scalar(true), Scalar(true));
1064 ///     assert_eq!(Scalar(false) ^ Scalar(false), Scalar(false));
1065 /// }
1066 /// ```
1067 ///
1068 /// In this example, the `BitXor` trait is implemented for a `BooleanVector`
1069 /// struct.
1070 ///
1071 /// ```
1072 /// use std::ops::BitXor;
1073 ///
1074 /// #[derive(Debug, PartialEq)]
1075 /// struct BooleanVector(Vec<bool>);
1076 ///
1077 /// impl BitXor for BooleanVector {
1078 ///     type Output = Self;
1079 ///
1080 ///     fn bitxor(self, BooleanVector(rhs): Self) -> Self {
1081 ///         let BooleanVector(lhs) = self;
1082 ///         assert_eq!(lhs.len(), rhs.len());
1083 ///         BooleanVector(lhs.iter()
1084 ///                          .zip(rhs.iter())
1085 ///                          .map(|(x, y)| (*x || *y) && !(*x && *y))
1086 ///                          .collect())
1087 ///     }
1088 /// }
1089 ///
1090 /// fn main() {
1091 ///     let bv1 = BooleanVector(vec![true, true, false, false]);
1092 ///     let bv2 = BooleanVector(vec![true, false, true, false]);
1093 ///     let expected = BooleanVector(vec![false, true, true, false]);
1094 ///     assert_eq!(bv1 ^ bv2, expected);
1095 /// }
1096 /// ```
1097 #[lang = "bitxor"]
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 #[rustc_on_unimplemented = "no implementation for `{Self} ^ {RHS}`"]
1100 pub trait BitXor<RHS=Self> {
1101     /// The resulting type after applying the `^` operator
1102     #[stable(feature = "rust1", since = "1.0.0")]
1103     type Output;
1104
1105     /// The method for the `^` operator
1106     #[stable(feature = "rust1", since = "1.0.0")]
1107     fn bitxor(self, rhs: RHS) -> Self::Output;
1108 }
1109
1110 macro_rules! bitxor_impl {
1111     ($($t:ty)*) => ($(
1112         #[stable(feature = "rust1", since = "1.0.0")]
1113         impl BitXor for $t {
1114             type Output = $t;
1115
1116             #[inline]
1117             fn bitxor(self, other: $t) -> $t { self ^ other }
1118         }
1119
1120         forward_ref_binop! { impl BitXor, bitxor for $t, $t }
1121     )*)
1122 }
1123
1124 bitxor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1125
1126 /// The left shift operator `<<`.
1127 ///
1128 /// # Examples
1129 ///
1130 /// An implementation of `Shl` that lifts the `<<` operation on integers to a
1131 /// `Scalar` struct.
1132 ///
1133 /// ```
1134 /// use std::ops::Shl;
1135 ///
1136 /// #[derive(PartialEq, Debug)]
1137 /// struct Scalar(usize);
1138 ///
1139 /// impl Shl<Scalar> for Scalar {
1140 ///     type Output = Self;
1141 ///
1142 ///     fn shl(self, Scalar(rhs): Self) -> Scalar {
1143 ///         let Scalar(lhs) = self;
1144 ///         Scalar(lhs << rhs)
1145 ///     }
1146 /// }
1147 /// fn main() {
1148 ///     assert_eq!(Scalar(4) << Scalar(2), Scalar(16));
1149 /// }
1150 /// ```
1151 ///
1152 /// An implementation of `Shl` that spins a vector leftward by a given amount.
1153 ///
1154 /// ```
1155 /// use std::ops::Shl;
1156 ///
1157 /// #[derive(PartialEq, Debug)]
1158 /// struct SpinVector<T: Clone> {
1159 ///     vec: Vec<T>,
1160 /// }
1161 ///
1162 /// impl<T: Clone> Shl<usize> for SpinVector<T> {
1163 ///     type Output = Self;
1164 ///
1165 ///     fn shl(self, rhs: usize) -> SpinVector<T> {
1166 ///         // rotate the vector by `rhs` places
1167 ///         let (a, b) = self.vec.split_at(rhs);
1168 ///         let mut spun_vector: Vec<T> = vec![];
1169 ///         spun_vector.extend_from_slice(b);
1170 ///         spun_vector.extend_from_slice(a);
1171 ///         SpinVector { vec: spun_vector }
1172 ///     }
1173 /// }
1174 ///
1175 /// fn main() {
1176 ///     assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } << 2,
1177 ///                SpinVector { vec: vec![2, 3, 4, 0, 1] });
1178 /// }
1179 /// ```
1180 #[lang = "shl"]
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 #[rustc_on_unimplemented = "no implementation for `{Self} << {RHS}`"]
1183 pub trait Shl<RHS> {
1184     /// The resulting type after applying the `<<` operator
1185     #[stable(feature = "rust1", since = "1.0.0")]
1186     type Output;
1187
1188     /// The method for the `<<` operator
1189     #[stable(feature = "rust1", since = "1.0.0")]
1190     fn shl(self, rhs: RHS) -> Self::Output;
1191 }
1192
1193 macro_rules! shl_impl {
1194     ($t:ty, $f:ty) => (
1195         #[stable(feature = "rust1", since = "1.0.0")]
1196         impl Shl<$f> for $t {
1197             type Output = $t;
1198
1199             #[inline]
1200             #[rustc_inherit_overflow_checks]
1201             fn shl(self, other: $f) -> $t {
1202                 self << other
1203             }
1204         }
1205
1206         forward_ref_binop! { impl Shl, shl for $t, $f }
1207     )
1208 }
1209
1210 macro_rules! shl_impl_all {
1211     ($($t:ty)*) => ($(
1212         shl_impl! { $t, u8 }
1213         shl_impl! { $t, u16 }
1214         shl_impl! { $t, u32 }
1215         shl_impl! { $t, u64 }
1216         shl_impl! { $t, u128 }
1217         shl_impl! { $t, usize }
1218
1219         shl_impl! { $t, i8 }
1220         shl_impl! { $t, i16 }
1221         shl_impl! { $t, i32 }
1222         shl_impl! { $t, i64 }
1223         shl_impl! { $t, i128 }
1224         shl_impl! { $t, isize }
1225     )*)
1226 }
1227
1228 shl_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 isize i128 }
1229
1230 /// The right shift operator `>>`.
1231 ///
1232 /// # Examples
1233 ///
1234 /// An implementation of `Shr` that lifts the `>>` operation on integers to a
1235 /// `Scalar` struct.
1236 ///
1237 /// ```
1238 /// use std::ops::Shr;
1239 ///
1240 /// #[derive(PartialEq, Debug)]
1241 /// struct Scalar(usize);
1242 ///
1243 /// impl Shr<Scalar> for Scalar {
1244 ///     type Output = Self;
1245 ///
1246 ///     fn shr(self, Scalar(rhs): Self) -> Scalar {
1247 ///         let Scalar(lhs) = self;
1248 ///         Scalar(lhs >> rhs)
1249 ///     }
1250 /// }
1251 /// fn main() {
1252 ///     assert_eq!(Scalar(16) >> Scalar(2), Scalar(4));
1253 /// }
1254 /// ```
1255 ///
1256 /// An implementation of `Shr` that spins a vector rightward by a given amount.
1257 ///
1258 /// ```
1259 /// use std::ops::Shr;
1260 ///
1261 /// #[derive(PartialEq, Debug)]
1262 /// struct SpinVector<T: Clone> {
1263 ///     vec: Vec<T>,
1264 /// }
1265 ///
1266 /// impl<T: Clone> Shr<usize> for SpinVector<T> {
1267 ///     type Output = Self;
1268 ///
1269 ///     fn shr(self, rhs: usize) -> SpinVector<T> {
1270 ///         // rotate the vector by `rhs` places
1271 ///         let (a, b) = self.vec.split_at(self.vec.len() - rhs);
1272 ///         let mut spun_vector: Vec<T> = vec![];
1273 ///         spun_vector.extend_from_slice(b);
1274 ///         spun_vector.extend_from_slice(a);
1275 ///         SpinVector { vec: spun_vector }
1276 ///     }
1277 /// }
1278 ///
1279 /// fn main() {
1280 ///     assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } >> 2,
1281 ///                SpinVector { vec: vec![3, 4, 0, 1, 2] });
1282 /// }
1283 /// ```
1284 #[lang = "shr"]
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 #[rustc_on_unimplemented = "no implementation for `{Self} >> {RHS}`"]
1287 pub trait Shr<RHS> {
1288     /// The resulting type after applying the `>>` operator
1289     #[stable(feature = "rust1", since = "1.0.0")]
1290     type Output;
1291
1292     /// The method for the `>>` operator
1293     #[stable(feature = "rust1", since = "1.0.0")]
1294     fn shr(self, rhs: RHS) -> Self::Output;
1295 }
1296
1297 macro_rules! shr_impl {
1298     ($t:ty, $f:ty) => (
1299         #[stable(feature = "rust1", since = "1.0.0")]
1300         impl Shr<$f> for $t {
1301             type Output = $t;
1302
1303             #[inline]
1304             #[rustc_inherit_overflow_checks]
1305             fn shr(self, other: $f) -> $t {
1306                 self >> other
1307             }
1308         }
1309
1310         forward_ref_binop! { impl Shr, shr for $t, $f }
1311     )
1312 }
1313
1314 macro_rules! shr_impl_all {
1315     ($($t:ty)*) => ($(
1316         shr_impl! { $t, u8 }
1317         shr_impl! { $t, u16 }
1318         shr_impl! { $t, u32 }
1319         shr_impl! { $t, u64 }
1320         shr_impl! { $t, u128 }
1321         shr_impl! { $t, usize }
1322
1323         shr_impl! { $t, i8 }
1324         shr_impl! { $t, i16 }
1325         shr_impl! { $t, i32 }
1326         shr_impl! { $t, i64 }
1327         shr_impl! { $t, i128 }
1328         shr_impl! { $t, isize }
1329     )*)
1330 }
1331
1332 shr_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
1333
1334 /// The addition assignment operator `+=`.
1335 ///
1336 /// # Examples
1337 ///
1338 /// This example creates a `Point` struct that implements the `AddAssign`
1339 /// trait, and then demonstrates add-assigning to a mutable `Point`.
1340 ///
1341 /// ```
1342 /// use std::ops::AddAssign;
1343 ///
1344 /// #[derive(Debug)]
1345 /// struct Point {
1346 ///     x: i32,
1347 ///     y: i32,
1348 /// }
1349 ///
1350 /// impl AddAssign for Point {
1351 ///     fn add_assign(&mut self, other: Point) {
1352 ///         *self = Point {
1353 ///             x: self.x + other.x,
1354 ///             y: self.y + other.y,
1355 ///         };
1356 ///     }
1357 /// }
1358 ///
1359 /// impl PartialEq for Point {
1360 ///     fn eq(&self, other: &Self) -> bool {
1361 ///         self.x == other.x && self.y == other.y
1362 ///     }
1363 /// }
1364 ///
1365 /// let mut point = Point { x: 1, y: 0 };
1366 /// point += Point { x: 2, y: 3 };
1367 /// assert_eq!(point, Point { x: 3, y: 3 });
1368 /// ```
1369 #[lang = "add_assign"]
1370 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1371 #[rustc_on_unimplemented = "no implementation for `{Self} += {Rhs}`"]
1372 pub trait AddAssign<Rhs=Self> {
1373     /// The method for the `+=` operator
1374     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1375     fn add_assign(&mut self, rhs: Rhs);
1376 }
1377
1378 macro_rules! add_assign_impl {
1379     ($($t:ty)+) => ($(
1380         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1381         impl AddAssign for $t {
1382             #[inline]
1383             #[rustc_inherit_overflow_checks]
1384             fn add_assign(&mut self, other: $t) { *self += other }
1385         }
1386     )+)
1387 }
1388
1389 add_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1390
1391 /// The subtraction assignment operator `-=`.
1392 ///
1393 /// # Examples
1394 ///
1395 /// This example creates a `Point` struct that implements the `SubAssign`
1396 /// trait, and then demonstrates sub-assigning to a mutable `Point`.
1397 ///
1398 /// ```
1399 /// use std::ops::SubAssign;
1400 ///
1401 /// #[derive(Debug)]
1402 /// struct Point {
1403 ///     x: i32,
1404 ///     y: i32,
1405 /// }
1406 ///
1407 /// impl SubAssign for Point {
1408 ///     fn sub_assign(&mut self, other: Point) {
1409 ///         *self = Point {
1410 ///             x: self.x - other.x,
1411 ///             y: self.y - other.y,
1412 ///         };
1413 ///     }
1414 /// }
1415 ///
1416 /// impl PartialEq for Point {
1417 ///     fn eq(&self, other: &Self) -> bool {
1418 ///         self.x == other.x && self.y == other.y
1419 ///     }
1420 /// }
1421 ///
1422 /// let mut point = Point { x: 3, y: 3 };
1423 /// point -= Point { x: 2, y: 3 };
1424 /// assert_eq!(point, Point {x: 1, y: 0});
1425 /// ```
1426 #[lang = "sub_assign"]
1427 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1428 #[rustc_on_unimplemented = "no implementation for `{Self} -= {Rhs}`"]
1429 pub trait SubAssign<Rhs=Self> {
1430     /// The method for the `-=` operator
1431     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1432     fn sub_assign(&mut self, rhs: Rhs);
1433 }
1434
1435 macro_rules! sub_assign_impl {
1436     ($($t:ty)+) => ($(
1437         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1438         impl SubAssign for $t {
1439             #[inline]
1440             #[rustc_inherit_overflow_checks]
1441             fn sub_assign(&mut self, other: $t) { *self -= other }
1442         }
1443     )+)
1444 }
1445
1446 sub_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1447
1448 /// The multiplication assignment operator `*=`.
1449 ///
1450 /// # Examples
1451 ///
1452 /// A trivial implementation of `MulAssign`. When `Foo *= Foo` happens, it ends up
1453 /// calling `mul_assign`, and therefore, `main` prints `Multiplying!`.
1454 ///
1455 /// ```
1456 /// use std::ops::MulAssign;
1457 ///
1458 /// struct Foo;
1459 ///
1460 /// impl MulAssign for Foo {
1461 ///     fn mul_assign(&mut self, _rhs: Foo) {
1462 ///         println!("Multiplying!");
1463 ///     }
1464 /// }
1465 ///
1466 /// # #[allow(unused_assignments)]
1467 /// fn main() {
1468 ///     let mut foo = Foo;
1469 ///     foo *= Foo;
1470 /// }
1471 /// ```
1472 #[lang = "mul_assign"]
1473 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1474 #[rustc_on_unimplemented = "no implementation for `{Self} *= {Rhs}`"]
1475 pub trait MulAssign<Rhs=Self> {
1476     /// The method for the `*=` operator
1477     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1478     fn mul_assign(&mut self, rhs: Rhs);
1479 }
1480
1481 macro_rules! mul_assign_impl {
1482     ($($t:ty)+) => ($(
1483         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1484         impl MulAssign for $t {
1485             #[inline]
1486             #[rustc_inherit_overflow_checks]
1487             fn mul_assign(&mut self, other: $t) { *self *= other }
1488         }
1489     )+)
1490 }
1491
1492 mul_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1493
1494 /// The division assignment operator `/=`.
1495 ///
1496 /// # Examples
1497 ///
1498 /// A trivial implementation of `DivAssign`. When `Foo /= Foo` happens, it ends up
1499 /// calling `div_assign`, and therefore, `main` prints `Dividing!`.
1500 ///
1501 /// ```
1502 /// use std::ops::DivAssign;
1503 ///
1504 /// struct Foo;
1505 ///
1506 /// impl DivAssign for Foo {
1507 ///     fn div_assign(&mut self, _rhs: Foo) {
1508 ///         println!("Dividing!");
1509 ///     }
1510 /// }
1511 ///
1512 /// # #[allow(unused_assignments)]
1513 /// fn main() {
1514 ///     let mut foo = Foo;
1515 ///     foo /= Foo;
1516 /// }
1517 /// ```
1518 #[lang = "div_assign"]
1519 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1520 #[rustc_on_unimplemented = "no implementation for `{Self} /= {Rhs}`"]
1521 pub trait DivAssign<Rhs=Self> {
1522     /// The method for the `/=` operator
1523     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1524     fn div_assign(&mut self, rhs: Rhs);
1525 }
1526
1527 macro_rules! div_assign_impl {
1528     ($($t:ty)+) => ($(
1529         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1530         impl DivAssign for $t {
1531             #[inline]
1532             fn div_assign(&mut self, other: $t) { *self /= other }
1533         }
1534     )+)
1535 }
1536
1537 div_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1538
1539 /// The remainder assignment operator `%=`.
1540 ///
1541 /// # Examples
1542 ///
1543 /// A trivial implementation of `RemAssign`. When `Foo %= Foo` happens, it ends up
1544 /// calling `rem_assign`, and therefore, `main` prints `Remainder-ing!`.
1545 ///
1546 /// ```
1547 /// use std::ops::RemAssign;
1548 ///
1549 /// struct Foo;
1550 ///
1551 /// impl RemAssign for Foo {
1552 ///     fn rem_assign(&mut self, _rhs: Foo) {
1553 ///         println!("Remainder-ing!");
1554 ///     }
1555 /// }
1556 ///
1557 /// # #[allow(unused_assignments)]
1558 /// fn main() {
1559 ///     let mut foo = Foo;
1560 ///     foo %= Foo;
1561 /// }
1562 /// ```
1563 #[lang = "rem_assign"]
1564 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1565 #[rustc_on_unimplemented = "no implementation for `{Self} %= {Rhs}`"]
1566 pub trait RemAssign<Rhs=Self> {
1567     /// The method for the `%=` operator
1568     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1569     fn rem_assign(&mut self, rhs: Rhs);
1570 }
1571
1572 macro_rules! rem_assign_impl {
1573     ($($t:ty)+) => ($(
1574         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1575         impl RemAssign for $t {
1576             #[inline]
1577             fn rem_assign(&mut self, other: $t) { *self %= other }
1578         }
1579     )+)
1580 }
1581
1582 rem_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1583
1584 /// The bitwise AND assignment operator `&=`.
1585 ///
1586 /// # Examples
1587 ///
1588 /// In this example, the `&=` operator is lifted to a trivial `Scalar` type.
1589 ///
1590 /// ```
1591 /// use std::ops::BitAndAssign;
1592 ///
1593 /// #[derive(Debug, PartialEq)]
1594 /// struct Scalar(bool);
1595 ///
1596 /// impl BitAndAssign for Scalar {
1597 ///     // rhs is the "right-hand side" of the expression `a &= b`
1598 ///     fn bitand_assign(&mut self, rhs: Self) {
1599 ///         *self = Scalar(self.0 & rhs.0)
1600 ///     }
1601 /// }
1602 ///
1603 /// fn main() {
1604 ///     let mut scalar = Scalar(true);
1605 ///     scalar &= Scalar(true);
1606 ///     assert_eq!(scalar, Scalar(true));
1607 ///
1608 ///     let mut scalar = Scalar(true);
1609 ///     scalar &= Scalar(false);
1610 ///     assert_eq!(scalar, Scalar(false));
1611 ///
1612 ///     let mut scalar = Scalar(false);
1613 ///     scalar &= Scalar(true);
1614 ///     assert_eq!(scalar, Scalar(false));
1615 ///
1616 ///     let mut scalar = Scalar(false);
1617 ///     scalar &= Scalar(false);
1618 ///     assert_eq!(scalar, Scalar(false));
1619 /// }
1620 /// ```
1621 ///
1622 /// In this example, the `BitAndAssign` trait is implemented for a
1623 /// `BooleanVector` struct.
1624 ///
1625 /// ```
1626 /// use std::ops::BitAndAssign;
1627 ///
1628 /// #[derive(Debug, PartialEq)]
1629 /// struct BooleanVector(Vec<bool>);
1630 ///
1631 /// impl BitAndAssign for BooleanVector {
1632 ///     // rhs is the "right-hand side" of the expression `a &= b`
1633 ///     fn bitand_assign(&mut self, rhs: Self) {
1634 ///         assert_eq!(self.0.len(), rhs.0.len());
1635 ///         *self = BooleanVector(self.0
1636 ///                                   .iter()
1637 ///                                   .zip(rhs.0.iter())
1638 ///                                   .map(|(x, y)| *x && *y)
1639 ///                                   .collect());
1640 ///     }
1641 /// }
1642 ///
1643 /// fn main() {
1644 ///     let mut bv = BooleanVector(vec![true, true, false, false]);
1645 ///     bv &= BooleanVector(vec![true, false, true, false]);
1646 ///     let expected = BooleanVector(vec![true, false, false, false]);
1647 ///     assert_eq!(bv, expected);
1648 /// }
1649 /// ```
1650 #[lang = "bitand_assign"]
1651 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1652 #[rustc_on_unimplemented = "no implementation for `{Self} &= {Rhs}`"]
1653 pub trait BitAndAssign<Rhs=Self> {
1654     /// The method for the `&=` operator
1655     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1656     fn bitand_assign(&mut self, rhs: Rhs);
1657 }
1658
1659 macro_rules! bitand_assign_impl {
1660     ($($t:ty)+) => ($(
1661         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1662         impl BitAndAssign for $t {
1663             #[inline]
1664             fn bitand_assign(&mut self, other: $t) { *self &= other }
1665         }
1666     )+)
1667 }
1668
1669 bitand_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1670
1671 /// The bitwise OR assignment operator `|=`.
1672 ///
1673 /// # Examples
1674 ///
1675 /// A trivial implementation of `BitOrAssign`. When `Foo |= Foo` happens, it ends up
1676 /// calling `bitor_assign`, and therefore, `main` prints `Bitwise Or-ing!`.
1677 ///
1678 /// ```
1679 /// use std::ops::BitOrAssign;
1680 ///
1681 /// struct Foo;
1682 ///
1683 /// impl BitOrAssign for Foo {
1684 ///     fn bitor_assign(&mut self, _rhs: Foo) {
1685 ///         println!("Bitwise Or-ing!");
1686 ///     }
1687 /// }
1688 ///
1689 /// # #[allow(unused_assignments)]
1690 /// fn main() {
1691 ///     let mut foo = Foo;
1692 ///     foo |= Foo;
1693 /// }
1694 /// ```
1695 #[lang = "bitor_assign"]
1696 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1697 #[rustc_on_unimplemented = "no implementation for `{Self} |= {Rhs}`"]
1698 pub trait BitOrAssign<Rhs=Self> {
1699     /// The method for the `|=` operator
1700     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1701     fn bitor_assign(&mut self, rhs: Rhs);
1702 }
1703
1704 macro_rules! bitor_assign_impl {
1705     ($($t:ty)+) => ($(
1706         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1707         impl BitOrAssign for $t {
1708             #[inline]
1709             fn bitor_assign(&mut self, other: $t) { *self |= other }
1710         }
1711     )+)
1712 }
1713
1714 bitor_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1715
1716 /// The bitwise XOR assignment operator `^=`.
1717 ///
1718 /// # Examples
1719 ///
1720 /// A trivial implementation of `BitXorAssign`. When `Foo ^= Foo` happens, it ends up
1721 /// calling `bitxor_assign`, and therefore, `main` prints `Bitwise Xor-ing!`.
1722 ///
1723 /// ```
1724 /// use std::ops::BitXorAssign;
1725 ///
1726 /// struct Foo;
1727 ///
1728 /// impl BitXorAssign for Foo {
1729 ///     fn bitxor_assign(&mut self, _rhs: Foo) {
1730 ///         println!("Bitwise Xor-ing!");
1731 ///     }
1732 /// }
1733 ///
1734 /// # #[allow(unused_assignments)]
1735 /// fn main() {
1736 ///     let mut foo = Foo;
1737 ///     foo ^= Foo;
1738 /// }
1739 /// ```
1740 #[lang = "bitxor_assign"]
1741 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1742 #[rustc_on_unimplemented = "no implementation for `{Self} ^= {Rhs}`"]
1743 pub trait BitXorAssign<Rhs=Self> {
1744     /// The method for the `^=` operator
1745     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1746     fn bitxor_assign(&mut self, rhs: Rhs);
1747 }
1748
1749 macro_rules! bitxor_assign_impl {
1750     ($($t:ty)+) => ($(
1751         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1752         impl BitXorAssign for $t {
1753             #[inline]
1754             fn bitxor_assign(&mut self, other: $t) { *self ^= other }
1755         }
1756     )+)
1757 }
1758
1759 bitxor_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1760
1761 /// The left shift assignment operator `<<=`.
1762 ///
1763 /// # Examples
1764 ///
1765 /// A trivial implementation of `ShlAssign`. When `Foo <<= Foo` happens, it ends up
1766 /// calling `shl_assign`, and therefore, `main` prints `Shifting left!`.
1767 ///
1768 /// ```
1769 /// use std::ops::ShlAssign;
1770 ///
1771 /// struct Foo;
1772 ///
1773 /// impl ShlAssign<Foo> for Foo {
1774 ///     fn shl_assign(&mut self, _rhs: Foo) {
1775 ///         println!("Shifting left!");
1776 ///     }
1777 /// }
1778 ///
1779 /// # #[allow(unused_assignments)]
1780 /// fn main() {
1781 ///     let mut foo = Foo;
1782 ///     foo <<= Foo;
1783 /// }
1784 /// ```
1785 #[lang = "shl_assign"]
1786 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1787 #[rustc_on_unimplemented = "no implementation for `{Self} <<= {Rhs}`"]
1788 pub trait ShlAssign<Rhs> {
1789     /// The method for the `<<=` operator
1790     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1791     fn shl_assign(&mut self, rhs: Rhs);
1792 }
1793
1794 macro_rules! shl_assign_impl {
1795     ($t:ty, $f:ty) => (
1796         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1797         impl ShlAssign<$f> for $t {
1798             #[inline]
1799             #[rustc_inherit_overflow_checks]
1800             fn shl_assign(&mut self, other: $f) {
1801                 *self <<= other
1802             }
1803         }
1804     )
1805 }
1806
1807 macro_rules! shl_assign_impl_all {
1808     ($($t:ty)*) => ($(
1809         shl_assign_impl! { $t, u8 }
1810         shl_assign_impl! { $t, u16 }
1811         shl_assign_impl! { $t, u32 }
1812         shl_assign_impl! { $t, u64 }
1813         shl_assign_impl! { $t, u128 }
1814         shl_assign_impl! { $t, usize }
1815
1816         shl_assign_impl! { $t, i8 }
1817         shl_assign_impl! { $t, i16 }
1818         shl_assign_impl! { $t, i32 }
1819         shl_assign_impl! { $t, i64 }
1820         shl_assign_impl! { $t, i128 }
1821         shl_assign_impl! { $t, isize }
1822     )*)
1823 }
1824
1825 shl_assign_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
1826
1827 /// The right shift assignment operator `>>=`.
1828 ///
1829 /// # Examples
1830 ///
1831 /// A trivial implementation of `ShrAssign`. When `Foo >>= Foo` happens, it ends up
1832 /// calling `shr_assign`, and therefore, `main` prints `Shifting right!`.
1833 ///
1834 /// ```
1835 /// use std::ops::ShrAssign;
1836 ///
1837 /// struct Foo;
1838 ///
1839 /// impl ShrAssign<Foo> for Foo {
1840 ///     fn shr_assign(&mut self, _rhs: Foo) {
1841 ///         println!("Shifting right!");
1842 ///     }
1843 /// }
1844 ///
1845 /// # #[allow(unused_assignments)]
1846 /// fn main() {
1847 ///     let mut foo = Foo;
1848 ///     foo >>= Foo;
1849 /// }
1850 /// ```
1851 #[lang = "shr_assign"]
1852 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1853 #[rustc_on_unimplemented = "no implementation for `{Self} >>= {Rhs}`"]
1854 pub trait ShrAssign<Rhs=Self> {
1855     /// The method for the `>>=` operator
1856     #[stable(feature = "op_assign_traits", since = "1.8.0")]
1857     fn shr_assign(&mut self, rhs: Rhs);
1858 }
1859
1860 macro_rules! shr_assign_impl {
1861     ($t:ty, $f:ty) => (
1862         #[stable(feature = "op_assign_traits", since = "1.8.0")]
1863         impl ShrAssign<$f> for $t {
1864             #[inline]
1865             #[rustc_inherit_overflow_checks]
1866             fn shr_assign(&mut self, other: $f) {
1867                 *self >>= other
1868             }
1869         }
1870     )
1871 }
1872
1873 macro_rules! shr_assign_impl_all {
1874     ($($t:ty)*) => ($(
1875         shr_assign_impl! { $t, u8 }
1876         shr_assign_impl! { $t, u16 }
1877         shr_assign_impl! { $t, u32 }
1878         shr_assign_impl! { $t, u64 }
1879         shr_assign_impl! { $t, u128 }
1880         shr_assign_impl! { $t, usize }
1881
1882         shr_assign_impl! { $t, i8 }
1883         shr_assign_impl! { $t, i16 }
1884         shr_assign_impl! { $t, i32 }
1885         shr_assign_impl! { $t, i64 }
1886         shr_assign_impl! { $t, i128 }
1887         shr_assign_impl! { $t, isize }
1888     )*)
1889 }
1890
1891 shr_assign_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
1892
1893 /// The `Index` trait is used to specify the functionality of indexing operations
1894 /// like `container[index]` when used in an immutable context.
1895 ///
1896 /// `container[index]` is actually syntactic sugar for `*container.index(index)`,
1897 /// but only when used as an immutable value. If a mutable value is requested,
1898 /// [`IndexMut`] is used instead. This allows nice things such as
1899 /// `let value = v[index]` if `value` implements [`Copy`].
1900 ///
1901 /// [`IndexMut`]: ../../std/ops/trait.IndexMut.html
1902 /// [`Copy`]: ../../std/marker/trait.Copy.html
1903 ///
1904 /// # Examples
1905 ///
1906 /// The following example implements `Index` on a read-only `NucleotideCount`
1907 /// container, enabling individual counts to be retrieved with index syntax.
1908 ///
1909 /// ```
1910 /// use std::ops::Index;
1911 ///
1912 /// enum Nucleotide {
1913 ///     A,
1914 ///     C,
1915 ///     G,
1916 ///     T,
1917 /// }
1918 ///
1919 /// struct NucleotideCount {
1920 ///     a: usize,
1921 ///     c: usize,
1922 ///     g: usize,
1923 ///     t: usize,
1924 /// }
1925 ///
1926 /// impl Index<Nucleotide> for NucleotideCount {
1927 ///     type Output = usize;
1928 ///
1929 ///     fn index(&self, nucleotide: Nucleotide) -> &usize {
1930 ///         match nucleotide {
1931 ///             Nucleotide::A => &self.a,
1932 ///             Nucleotide::C => &self.c,
1933 ///             Nucleotide::G => &self.g,
1934 ///             Nucleotide::T => &self.t,
1935 ///         }
1936 ///     }
1937 /// }
1938 ///
1939 /// let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12};
1940 /// assert_eq!(nucleotide_count[Nucleotide::A], 14);
1941 /// assert_eq!(nucleotide_count[Nucleotide::C], 9);
1942 /// assert_eq!(nucleotide_count[Nucleotide::G], 10);
1943 /// assert_eq!(nucleotide_count[Nucleotide::T], 12);
1944 /// ```
1945 #[lang = "index"]
1946 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1947 #[stable(feature = "rust1", since = "1.0.0")]
1948 pub trait Index<Idx: ?Sized> {
1949     /// The returned type after indexing
1950     #[stable(feature = "rust1", since = "1.0.0")]
1951     type Output: ?Sized;
1952
1953     /// The method for the indexing (`container[index]`) operation
1954     #[stable(feature = "rust1", since = "1.0.0")]
1955     fn index(&self, index: Idx) -> &Self::Output;
1956 }
1957
1958 /// The `IndexMut` trait is used to specify the functionality of indexing
1959 /// operations like `container[index]` when used in a mutable context.
1960 ///
1961 /// `container[index]` is actually syntactic sugar for
1962 /// `*container.index_mut(index)`, but only when used as a mutable value. If
1963 /// an immutable value is requested, the [`Index`] trait is used instead. This
1964 /// allows nice things such as `v[index] = value` if `value` implements [`Copy`].
1965 ///
1966 /// [`Index`]: ../../std/ops/trait.Index.html
1967 /// [`Copy`]: ../../std/marker/trait.Copy.html
1968 ///
1969 /// # Examples
1970 ///
1971 /// A very simple implementation of a `Balance` struct that has two sides, where
1972 /// each can be indexed mutably and immutably.
1973 ///
1974 /// ```
1975 /// use std::ops::{Index,IndexMut};
1976 ///
1977 /// #[derive(Debug)]
1978 /// enum Side {
1979 ///     Left,
1980 ///     Right,
1981 /// }
1982 ///
1983 /// #[derive(Debug, PartialEq)]
1984 /// enum Weight {
1985 ///     Kilogram(f32),
1986 ///     Pound(f32),
1987 /// }
1988 ///
1989 /// struct Balance {
1990 ///     pub left: Weight,
1991 ///     pub right:Weight,
1992 /// }
1993 ///
1994 /// impl Index<Side> for Balance {
1995 ///     type Output = Weight;
1996 ///
1997 ///     fn index<'a>(&'a self, index: Side) -> &'a Weight {
1998 ///         println!("Accessing {:?}-side of balance immutably", index);
1999 ///         match index {
2000 ///             Side::Left => &self.left,
2001 ///             Side::Right => &self.right,
2002 ///         }
2003 ///     }
2004 /// }
2005 ///
2006 /// impl IndexMut<Side> for Balance {
2007 ///     fn index_mut<'a>(&'a mut self, index: Side) -> &'a mut Weight {
2008 ///         println!("Accessing {:?}-side of balance mutably", index);
2009 ///         match index {
2010 ///             Side::Left => &mut self.left,
2011 ///             Side::Right => &mut self.right,
2012 ///         }
2013 ///     }
2014 /// }
2015 ///
2016 /// fn main() {
2017 ///     let mut balance = Balance {
2018 ///         right: Weight::Kilogram(2.5),
2019 ///         left: Weight::Pound(1.5),
2020 ///     };
2021 ///
2022 ///     // In this case balance[Side::Right] is sugar for
2023 ///     // *balance.index(Side::Right), since we are only reading
2024 ///     // balance[Side::Right], not writing it.
2025 ///     assert_eq!(balance[Side::Right],Weight::Kilogram(2.5));
2026 ///
2027 ///     // However in this case balance[Side::Left] is sugar for
2028 ///     // *balance.index_mut(Side::Left), since we are writing
2029 ///     // balance[Side::Left].
2030 ///     balance[Side::Left] = Weight::Kilogram(3.0);
2031 /// }
2032 /// ```
2033 #[lang = "index_mut"]
2034 #[rustc_on_unimplemented = "the type `{Self}` cannot be mutably indexed by `{Idx}`"]
2035 #[stable(feature = "rust1", since = "1.0.0")]
2036 pub trait IndexMut<Idx: ?Sized>: Index<Idx> {
2037     /// The method for the mutable indexing (`container[index]`) operation
2038     #[stable(feature = "rust1", since = "1.0.0")]
2039     fn index_mut(&mut self, index: Idx) -> &mut Self::Output;
2040 }
2041
2042 /// An unbounded range. Use `..` (two dots) for its shorthand.
2043 ///
2044 /// Its primary use case is slicing index. It cannot serve as an iterator
2045 /// because it doesn't have a starting point.
2046 ///
2047 /// # Examples
2048 ///
2049 /// The `..` syntax is a `RangeFull`:
2050 ///
2051 /// ```
2052 /// assert_eq!((..), std::ops::RangeFull);
2053 /// ```
2054 ///
2055 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2056 /// `for` loop directly. This won't compile:
2057 ///
2058 /// ```ignore
2059 /// for i in .. {
2060 ///    // ...
2061 /// }
2062 /// ```
2063 ///
2064 /// Used as a slicing index, `RangeFull` produces the full array as a slice.
2065 ///
2066 /// ```
2067 /// let arr = [0, 1, 2, 3];
2068 /// assert_eq!(arr[ .. ], [0,1,2,3]);  // RangeFull
2069 /// assert_eq!(arr[ ..3], [0,1,2  ]);
2070 /// assert_eq!(arr[1.. ], [  1,2,3]);
2071 /// assert_eq!(arr[1..3], [  1,2  ]);
2072 /// ```
2073 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2074 #[stable(feature = "rust1", since = "1.0.0")]
2075 pub struct RangeFull;
2076
2077 #[stable(feature = "rust1", since = "1.0.0")]
2078 impl fmt::Debug for RangeFull {
2079     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2080         write!(fmt, "..")
2081     }
2082 }
2083
2084 /// A (half-open) range which is bounded at both ends: { x | start <= x < end }.
2085 /// Use `start..end` (two dots) for its shorthand.
2086 ///
2087 /// See the [`contains`](#method.contains) method for its characterization.
2088 ///
2089 /// # Examples
2090 ///
2091 /// ```
2092 /// fn main() {
2093 ///     assert_eq!((3..5), std::ops::Range{ start: 3, end: 5 });
2094 ///     assert_eq!(3+4+5, (3..6).sum());
2095 ///
2096 ///     let arr = [0, 1, 2, 3];
2097 ///     assert_eq!(arr[ .. ], [0,1,2,3]);
2098 ///     assert_eq!(arr[ ..3], [0,1,2  ]);
2099 ///     assert_eq!(arr[1.. ], [  1,2,3]);
2100 ///     assert_eq!(arr[1..3], [  1,2  ]);  // Range
2101 /// }
2102 /// ```
2103 #[derive(Clone, PartialEq, Eq, Hash)]  // not Copy -- see #27186
2104 #[stable(feature = "rust1", since = "1.0.0")]
2105 pub struct Range<Idx> {
2106     /// The lower bound of the range (inclusive).
2107     #[stable(feature = "rust1", since = "1.0.0")]
2108     pub start: Idx,
2109     /// The upper bound of the range (exclusive).
2110     #[stable(feature = "rust1", since = "1.0.0")]
2111     pub end: Idx,
2112 }
2113
2114 #[stable(feature = "rust1", since = "1.0.0")]
2115 impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
2116     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2117         write!(fmt, "{:?}..{:?}", self.start, self.end)
2118     }
2119 }
2120
2121 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2122 impl<Idx: PartialOrd<Idx>> Range<Idx> {
2123     /// # Examples
2124     ///
2125     /// ```
2126     /// #![feature(range_contains)]
2127     /// fn main() {
2128     ///     assert!( ! (3..5).contains(2));
2129     ///     assert!(   (3..5).contains(3));
2130     ///     assert!(   (3..5).contains(4));
2131     ///     assert!( ! (3..5).contains(5));
2132     ///
2133     ///     assert!( ! (3..3).contains(3));
2134     ///     assert!( ! (3..2).contains(3));
2135     /// }
2136     /// ```
2137     pub fn contains(&self, item: Idx) -> bool {
2138         (self.start <= item) && (item < self.end)
2139     }
2140 }
2141
2142 /// A range which is only bounded below: { x | start <= x }.
2143 /// Use `start..` for its shorthand.
2144 ///
2145 /// See the [`contains`](#method.contains) method for its characterization.
2146 ///
2147 /// Note: Currently, no overflow checking is done for the iterator
2148 /// implementation; if you use an integer range and the integer overflows, it
2149 /// might panic in debug mode or create an endless loop in release mode. This
2150 /// overflow behavior might change in the future.
2151 ///
2152 /// # Examples
2153 ///
2154 /// ```
2155 /// fn main() {
2156 ///     assert_eq!((2..), std::ops::RangeFrom{ start: 2 });
2157 ///     assert_eq!(2+3+4, (2..).take(3).sum());
2158 ///
2159 ///     let arr = [0, 1, 2, 3];
2160 ///     assert_eq!(arr[ .. ], [0,1,2,3]);
2161 ///     assert_eq!(arr[ ..3], [0,1,2  ]);
2162 ///     assert_eq!(arr[1.. ], [  1,2,3]);  // RangeFrom
2163 ///     assert_eq!(arr[1..3], [  1,2  ]);
2164 /// }
2165 /// ```
2166 #[derive(Clone, PartialEq, Eq, Hash)]  // not Copy -- see #27186
2167 #[stable(feature = "rust1", since = "1.0.0")]
2168 pub struct RangeFrom<Idx> {
2169     /// The lower bound of the range (inclusive).
2170     #[stable(feature = "rust1", since = "1.0.0")]
2171     pub start: Idx,
2172 }
2173
2174 #[stable(feature = "rust1", since = "1.0.0")]
2175 impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
2176     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2177         write!(fmt, "{:?}..", self.start)
2178     }
2179 }
2180
2181 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2182 impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
2183     /// # Examples
2184     ///
2185     /// ```
2186     /// #![feature(range_contains)]
2187     /// fn main() {
2188     ///     assert!( ! (3..).contains(2));
2189     ///     assert!(   (3..).contains(3));
2190     ///     assert!(   (3..).contains(1_000_000_000));
2191     /// }
2192     /// ```
2193     pub fn contains(&self, item: Idx) -> bool {
2194         (self.start <= item)
2195     }
2196 }
2197
2198 /// A range which is only bounded above: { x | x < end }.
2199 /// Use `..end` (two dots) for its shorthand.
2200 ///
2201 /// See the [`contains`](#method.contains) method for its characterization.
2202 ///
2203 /// It cannot serve as an iterator because it doesn't have a starting point.
2204 ///
2205 /// # Examples
2206 ///
2207 /// The `..{integer}` syntax is a `RangeTo`:
2208 ///
2209 /// ```
2210 /// assert_eq!((..5), std::ops::RangeTo{ end: 5 });
2211 /// ```
2212 ///
2213 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2214 /// `for` loop directly. This won't compile:
2215 ///
2216 /// ```ignore
2217 /// for i in ..5 {
2218 ///     // ...
2219 /// }
2220 /// ```
2221 ///
2222 /// When used as a slicing index, `RangeTo` produces a slice of all array
2223 /// elements before the index indicated by `end`.
2224 ///
2225 /// ```
2226 /// let arr = [0, 1, 2, 3];
2227 /// assert_eq!(arr[ .. ], [0,1,2,3]);
2228 /// assert_eq!(arr[ ..3], [0,1,2  ]);  // RangeTo
2229 /// assert_eq!(arr[1.. ], [  1,2,3]);
2230 /// assert_eq!(arr[1..3], [  1,2  ]);
2231 /// ```
2232 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2233 #[stable(feature = "rust1", since = "1.0.0")]
2234 pub struct RangeTo<Idx> {
2235     /// The upper bound of the range (exclusive).
2236     #[stable(feature = "rust1", since = "1.0.0")]
2237     pub end: Idx,
2238 }
2239
2240 #[stable(feature = "rust1", since = "1.0.0")]
2241 impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> {
2242     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2243         write!(fmt, "..{:?}", self.end)
2244     }
2245 }
2246
2247 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2248 impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
2249     /// # Examples
2250     ///
2251     /// ```
2252     /// #![feature(range_contains)]
2253     /// fn main() {
2254     ///     assert!(   (..5).contains(-1_000_000_000));
2255     ///     assert!(   (..5).contains(4));
2256     ///     assert!( ! (..5).contains(5));
2257     /// }
2258     /// ```
2259     pub fn contains(&self, item: Idx) -> bool {
2260         (item < self.end)
2261     }
2262 }
2263
2264 /// An inclusive range which is bounded at both ends: { x | start <= x <= end }.
2265 /// Use `start...end` (three dots) for its shorthand.
2266 ///
2267 /// See the [`contains`](#method.contains) method for its characterization.
2268 ///
2269 /// # Examples
2270 ///
2271 /// ```
2272 /// #![feature(inclusive_range,inclusive_range_syntax)]
2273 /// fn main() {
2274 ///     assert_eq!((3...5), std::ops::RangeInclusive{ start: 3, end: 5 });
2275 ///     assert_eq!(3+4+5, (3...5).sum());
2276 ///
2277 ///     let arr = [0, 1, 2, 3];
2278 ///     assert_eq!(arr[ ...2], [0,1,2  ]);
2279 ///     assert_eq!(arr[1...2], [  1,2  ]);  // RangeInclusive
2280 /// }
2281 /// ```
2282 #[derive(Clone, PartialEq, Eq, Hash)]  // not Copy -- see #27186
2283 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2284 pub struct RangeInclusive<Idx> {
2285     /// The lower bound of the range (inclusive).
2286     #[unstable(feature = "inclusive_range",
2287                reason = "recently added, follows RFC",
2288                issue = "28237")]
2289     pub start: Idx,
2290     /// The upper bound of the range (inclusive).
2291     #[unstable(feature = "inclusive_range",
2292                reason = "recently added, follows RFC",
2293                issue = "28237")]
2294     pub end: Idx,
2295 }
2296
2297 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2298 impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
2299     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2300         write!(fmt, "{:?}...{:?}", self.start, self.end)
2301     }
2302 }
2303
2304 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2305 impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
2306     /// # Examples
2307     ///
2308     /// ```
2309     /// #![feature(range_contains,inclusive_range_syntax)]
2310     /// fn main() {
2311     ///     assert!( ! (3...5).contains(2));
2312     ///     assert!(   (3...5).contains(3));
2313     ///     assert!(   (3...5).contains(4));
2314     ///     assert!(   (3...5).contains(5));
2315     ///     assert!( ! (3...5).contains(6));
2316     ///
2317     ///     assert!(   (3...3).contains(3));
2318     ///     assert!( ! (3...2).contains(3));
2319     /// }
2320     /// ```
2321     pub fn contains(&self, item: Idx) -> bool {
2322         self.start <= item && item <= self.end
2323     }
2324 }
2325
2326 /// An inclusive range which is only bounded above: { x | x <= end }.
2327 /// Use `...end` (three dots) for its shorthand.
2328 ///
2329 /// See the [`contains`](#method.contains) method for its characterization.
2330 ///
2331 /// It cannot serve as an iterator because it doesn't have a starting point.
2332 ///
2333 /// # Examples
2334 ///
2335 /// The `...{integer}` syntax is a `RangeToInclusive`:
2336 ///
2337 /// ```
2338 /// #![feature(inclusive_range,inclusive_range_syntax)]
2339 /// assert_eq!((...5), std::ops::RangeToInclusive{ end: 5 });
2340 /// ```
2341 ///
2342 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2343 /// `for` loop directly. This won't compile:
2344 ///
2345 /// ```ignore
2346 /// for i in ...5 {
2347 ///     // ...
2348 /// }
2349 /// ```
2350 ///
2351 /// When used as a slicing index, `RangeToInclusive` produces a slice of all
2352 /// array elements up to and including the index indicated by `end`.
2353 ///
2354 /// ```
2355 /// #![feature(inclusive_range_syntax)]
2356 /// let arr = [0, 1, 2, 3];
2357 /// assert_eq!(arr[ ...2], [0,1,2  ]);  // RangeToInclusive
2358 /// assert_eq!(arr[1...2], [  1,2  ]);
2359 /// ```
2360 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2361 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2362 pub struct RangeToInclusive<Idx> {
2363     /// The upper bound of the range (inclusive)
2364     #[unstable(feature = "inclusive_range",
2365                reason = "recently added, follows RFC",
2366                issue = "28237")]
2367     pub end: Idx,
2368 }
2369
2370 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2371 impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
2372     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2373         write!(fmt, "...{:?}", self.end)
2374     }
2375 }
2376
2377 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2378 impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
2379     /// # Examples
2380     ///
2381     /// ```
2382     /// #![feature(range_contains,inclusive_range_syntax)]
2383     /// fn main() {
2384     ///     assert!(   (...5).contains(-1_000_000_000));
2385     ///     assert!(   (...5).contains(5));
2386     ///     assert!( ! (...5).contains(6));
2387     /// }
2388     /// ```
2389     pub fn contains(&self, item: Idx) -> bool {
2390         (item <= self.end)
2391     }
2392 }
2393
2394 // RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
2395 // because underflow would be possible with (..0).into()
2396
2397 /// The `Deref` trait is used to specify the functionality of dereferencing
2398 /// operations, like `*v`.
2399 ///
2400 /// `Deref` also enables ['`Deref` coercions'][coercions].
2401 ///
2402 /// [coercions]: ../../book/deref-coercions.html
2403 ///
2404 /// # Examples
2405 ///
2406 /// A struct with a single field which is accessible via dereferencing the
2407 /// struct.
2408 ///
2409 /// ```
2410 /// use std::ops::Deref;
2411 ///
2412 /// struct DerefExample<T> {
2413 ///     value: T
2414 /// }
2415 ///
2416 /// impl<T> Deref for DerefExample<T> {
2417 ///     type Target = T;
2418 ///
2419 ///     fn deref(&self) -> &T {
2420 ///         &self.value
2421 ///     }
2422 /// }
2423 ///
2424 /// fn main() {
2425 ///     let x = DerefExample { value: 'a' };
2426 ///     assert_eq!('a', *x);
2427 /// }
2428 /// ```
2429 #[lang = "deref"]
2430 #[stable(feature = "rust1", since = "1.0.0")]
2431 pub trait Deref {
2432     /// The resulting type after dereferencing
2433     #[stable(feature = "rust1", since = "1.0.0")]
2434     type Target: ?Sized;
2435
2436     /// The method called to dereference a value
2437     #[stable(feature = "rust1", since = "1.0.0")]
2438     fn deref(&self) -> &Self::Target;
2439 }
2440
2441 #[stable(feature = "rust1", since = "1.0.0")]
2442 impl<'a, T: ?Sized> Deref for &'a T {
2443     type Target = T;
2444
2445     fn deref(&self) -> &T { *self }
2446 }
2447
2448 #[stable(feature = "rust1", since = "1.0.0")]
2449 impl<'a, T: ?Sized> Deref for &'a mut T {
2450     type Target = T;
2451
2452     fn deref(&self) -> &T { *self }
2453 }
2454
2455 /// The `DerefMut` trait is used to specify the functionality of dereferencing
2456 /// mutably like `*v = 1;`
2457 ///
2458 /// `DerefMut` also enables ['`Deref` coercions'][coercions].
2459 ///
2460 /// [coercions]: ../../book/deref-coercions.html
2461 ///
2462 /// # Examples
2463 ///
2464 /// A struct with a single field which is modifiable via dereferencing the
2465 /// struct.
2466 ///
2467 /// ```
2468 /// use std::ops::{Deref, DerefMut};
2469 ///
2470 /// struct DerefMutExample<T> {
2471 ///     value: T
2472 /// }
2473 ///
2474 /// impl<T> Deref for DerefMutExample<T> {
2475 ///     type Target = T;
2476 ///
2477 ///     fn deref(&self) -> &T {
2478 ///         &self.value
2479 ///     }
2480 /// }
2481 ///
2482 /// impl<T> DerefMut for DerefMutExample<T> {
2483 ///     fn deref_mut(&mut self) -> &mut T {
2484 ///         &mut self.value
2485 ///     }
2486 /// }
2487 ///
2488 /// fn main() {
2489 ///     let mut x = DerefMutExample { value: 'a' };
2490 ///     *x = 'b';
2491 ///     assert_eq!('b', *x);
2492 /// }
2493 /// ```
2494 #[lang = "deref_mut"]
2495 #[stable(feature = "rust1", since = "1.0.0")]
2496 pub trait DerefMut: Deref {
2497     /// The method called to mutably dereference a value
2498     #[stable(feature = "rust1", since = "1.0.0")]
2499     fn deref_mut(&mut self) -> &mut Self::Target;
2500 }
2501
2502 #[stable(feature = "rust1", since = "1.0.0")]
2503 impl<'a, T: ?Sized> DerefMut for &'a mut T {
2504     fn deref_mut(&mut self) -> &mut T { *self }
2505 }
2506
2507 /// A version of the call operator that takes an immutable receiver.
2508 ///
2509 /// # Examples
2510 ///
2511 /// Closures automatically implement this trait, which allows them to be
2512 /// invoked. Note, however, that `Fn` takes an immutable reference to any
2513 /// captured variables. To take a mutable capture, implement [`FnMut`], and to
2514 /// consume the capture, implement [`FnOnce`].
2515 ///
2516 /// [`FnMut`]: trait.FnMut.html
2517 /// [`FnOnce`]: trait.FnOnce.html
2518 ///
2519 /// ```
2520 /// let square = |x| x * x;
2521 /// assert_eq!(square(5), 25);
2522 /// ```
2523 ///
2524 /// Closures can also be passed to higher-level functions through a `Fn`
2525 /// parameter (or a `FnMut` or `FnOnce` parameter, which are supertraits of
2526 /// `Fn`).
2527 ///
2528 /// ```
2529 /// fn call_with_one<F>(func: F) -> usize
2530 ///     where F: Fn(usize) -> usize {
2531 ///     func(1)
2532 /// }
2533 ///
2534 /// let double = |x| x * 2;
2535 /// assert_eq!(call_with_one(double), 2);
2536 /// ```
2537 #[lang = "fn"]
2538 #[stable(feature = "rust1", since = "1.0.0")]
2539 #[rustc_paren_sugar]
2540 #[fundamental] // so that regex can rely that `&str: !FnMut`
2541 pub trait Fn<Args> : FnMut<Args> {
2542     /// This is called when the call operator is used.
2543     #[unstable(feature = "fn_traits", issue = "29625")]
2544     extern "rust-call" fn call(&self, args: Args) -> Self::Output;
2545 }
2546
2547 /// A version of the call operator that takes a mutable receiver.
2548 ///
2549 /// # Examples
2550 ///
2551 /// Closures that mutably capture variables automatically implement this trait,
2552 /// which allows them to be invoked.
2553 ///
2554 /// ```
2555 /// let mut x = 5;
2556 /// {
2557 ///     let mut square_x = || x *= x;
2558 ///     square_x();
2559 /// }
2560 /// assert_eq!(x, 25);
2561 /// ```
2562 ///
2563 /// Closures can also be passed to higher-level functions through a `FnMut`
2564 /// parameter (or a `FnOnce` parameter, which is a supertrait of `FnMut`).
2565 ///
2566 /// ```
2567 /// fn do_twice<F>(mut func: F)
2568 ///     where F: FnMut()
2569 /// {
2570 ///     func();
2571 ///     func();
2572 /// }
2573 ///
2574 /// let mut x: usize = 1;
2575 /// {
2576 ///     let add_two_to_x = || x += 2;
2577 ///     do_twice(add_two_to_x);
2578 /// }
2579 ///
2580 /// assert_eq!(x, 5);
2581 /// ```
2582 #[lang = "fn_mut"]
2583 #[stable(feature = "rust1", since = "1.0.0")]
2584 #[rustc_paren_sugar]
2585 #[fundamental] // so that regex can rely that `&str: !FnMut`
2586 pub trait FnMut<Args> : FnOnce<Args> {
2587     /// This is called when the call operator is used.
2588     #[unstable(feature = "fn_traits", issue = "29625")]
2589     extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
2590 }
2591
2592 /// A version of the call operator that takes a by-value receiver.
2593 ///
2594 /// # Examples
2595 ///
2596 /// By-value closures automatically implement this trait, which allows them to
2597 /// be invoked.
2598 ///
2599 /// ```
2600 /// let x = 5;
2601 /// let square_x = move || x * x;
2602 /// assert_eq!(square_x(), 25);
2603 /// ```
2604 ///
2605 /// By-value Closures can also be passed to higher-level functions through a
2606 /// `FnOnce` parameter.
2607 ///
2608 /// ```
2609 /// fn consume_with_relish<F>(func: F)
2610 ///     where F: FnOnce() -> String
2611 /// {
2612 ///     // `func` consumes its captured variables, so it cannot be run more
2613 ///     // than once
2614 ///     println!("Consumed: {}", func());
2615 ///
2616 ///     println!("Delicious!");
2617 ///
2618 ///     // Attempting to invoke `func()` again will throw a `use of moved
2619 ///     // value` error for `func`
2620 /// }
2621 ///
2622 /// let x = String::from("x");
2623 /// let consume_and_return_x = move || x;
2624 /// consume_with_relish(consume_and_return_x);
2625 ///
2626 /// // `consume_and_return_x` can no longer be invoked at this point
2627 /// ```
2628 #[lang = "fn_once"]
2629 #[stable(feature = "rust1", since = "1.0.0")]
2630 #[rustc_paren_sugar]
2631 #[fundamental] // so that regex can rely that `&str: !FnMut`
2632 pub trait FnOnce<Args> {
2633     /// The returned type after the call operator is used.
2634     #[stable(feature = "fn_once_output", since = "1.12.0")]
2635     type Output;
2636
2637     /// This is called when the call operator is used.
2638     #[unstable(feature = "fn_traits", issue = "29625")]
2639     extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
2640 }
2641
2642 mod impls {
2643     #[stable(feature = "rust1", since = "1.0.0")]
2644     impl<'a,A,F:?Sized> Fn<A> for &'a F
2645         where F : Fn<A>
2646     {
2647         extern "rust-call" fn call(&self, args: A) -> F::Output {
2648             (**self).call(args)
2649         }
2650     }
2651
2652     #[stable(feature = "rust1", since = "1.0.0")]
2653     impl<'a,A,F:?Sized> FnMut<A> for &'a F
2654         where F : Fn<A>
2655     {
2656         extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
2657             (**self).call(args)
2658         }
2659     }
2660
2661     #[stable(feature = "rust1", since = "1.0.0")]
2662     impl<'a,A,F:?Sized> FnOnce<A> for &'a F
2663         where F : Fn<A>
2664     {
2665         type Output = F::Output;
2666
2667         extern "rust-call" fn call_once(self, args: A) -> F::Output {
2668             (*self).call(args)
2669         }
2670     }
2671
2672     #[stable(feature = "rust1", since = "1.0.0")]
2673     impl<'a,A,F:?Sized> FnMut<A> for &'a mut F
2674         where F : FnMut<A>
2675     {
2676         extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
2677             (*self).call_mut(args)
2678         }
2679     }
2680
2681     #[stable(feature = "rust1", since = "1.0.0")]
2682     impl<'a,A,F:?Sized> FnOnce<A> for &'a mut F
2683         where F : FnMut<A>
2684     {
2685         type Output = F::Output;
2686         extern "rust-call" fn call_once(mut self, args: A) -> F::Output {
2687             (*self).call_mut(args)
2688         }
2689     }
2690 }
2691
2692 /// Trait that indicates that this is a pointer or a wrapper for one,
2693 /// where unsizing can be performed on the pointee.
2694 ///
2695 /// See the [DST coercion RfC][dst-coerce] and [the nomicon entry on coercion][nomicon-coerce]
2696 /// for more details.
2697 ///
2698 /// For builtin pointer types, pointers to `T` will coerce to pointers to `U` if `T: Unsize<U>`
2699 /// by converting from a thin pointer to a fat pointer.
2700 ///
2701 /// For custom types, the coercion here works by coercing `Foo<T>` to `Foo<U>`
2702 /// provided an impl of `CoerceUnsized<Foo<U>> for Foo<T>` exists.
2703 /// Such an impl can only be written if `Foo<T>` has only a single non-phantomdata
2704 /// field involving `T`. If the type of that field is `Bar<T>`, an implementation
2705 /// of `CoerceUnsized<Bar<U>> for Bar<T>` must exist. The coercion will work by
2706 /// by coercing the `Bar<T>` field into `Bar<U>` and filling in the rest of the fields
2707 /// from `Foo<T>` to create a `Foo<U>`. This will effectively drill down to a pointer
2708 /// field and coerce that.
2709 ///
2710 /// Generally, for smart pointers you will implement
2711 /// `CoerceUnsized<Ptr<U>> for Ptr<T> where T: Unsize<U>, U: ?Sized`, with an
2712 /// optional `?Sized` bound on `T` itself. For wrapper types that directly embed `T`
2713 /// like `Cell<T>` and `RefCell<T>`, you
2714 /// can directly implement `CoerceUnsized<Wrap<U>> for Wrap<T> where T: CoerceUnsized<U>`.
2715 /// This will let coercions of types like `Cell<Box<T>>` work.
2716 ///
2717 /// [`Unsize`][unsize] is used to mark types which can be coerced to DSTs if behind
2718 /// pointers. It is implemented automatically by the compiler.
2719 ///
2720 /// [dst-coerce]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
2721 /// [unsize]: ../marker/trait.Unsize.html
2722 /// [nomicon-coerce]: ../../nomicon/coercions.html
2723 #[unstable(feature = "coerce_unsized", issue = "27732")]
2724 #[lang="coerce_unsized"]
2725 pub trait CoerceUnsized<T> {
2726     // Empty.
2727 }
2728
2729 // &mut T -> &mut U
2730 #[unstable(feature = "coerce_unsized", issue = "27732")]
2731 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a mut U> for &'a mut T {}
2732 // &mut T -> &U
2733 #[unstable(feature = "coerce_unsized", issue = "27732")]
2734 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b mut T {}
2735 // &mut T -> *mut U
2736 #[unstable(feature = "coerce_unsized", issue = "27732")]
2737 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for &'a mut T {}
2738 // &mut T -> *const U
2739 #[unstable(feature = "coerce_unsized", issue = "27732")]
2740 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a mut T {}
2741
2742 // &T -> &U
2743 #[unstable(feature = "coerce_unsized", issue = "27732")]
2744 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b T {}
2745 // &T -> *const U
2746 #[unstable(feature = "coerce_unsized", issue = "27732")]
2747 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a T {}
2748
2749 // *mut T -> *mut U
2750 #[unstable(feature = "coerce_unsized", issue = "27732")]
2751 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for *mut T {}
2752 // *mut T -> *const U
2753 #[unstable(feature = "coerce_unsized", issue = "27732")]
2754 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *mut T {}
2755
2756 // *const T -> *const U
2757 #[unstable(feature = "coerce_unsized", issue = "27732")]
2758 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *const T {}
2759
2760 /// Both `PLACE <- EXPR` and `box EXPR` desugar into expressions
2761 /// that allocate an intermediate "place" that holds uninitialized
2762 /// state.  The desugaring evaluates EXPR, and writes the result at
2763 /// the address returned by the `pointer` method of this trait.
2764 ///
2765 /// A `Place` can be thought of as a special representation for a
2766 /// hypothetical `&uninit` reference (which Rust cannot currently
2767 /// express directly). That is, it represents a pointer to
2768 /// uninitialized storage.
2769 ///
2770 /// The client is responsible for two steps: First, initializing the
2771 /// payload (it can access its address via `pointer`). Second,
2772 /// converting the agent to an instance of the owning pointer, via the
2773 /// appropriate `finalize` method (see the `InPlace`.
2774 ///
2775 /// If evaluating EXPR fails, then it is up to the destructor for the
2776 /// implementation of Place to clean up any intermediate state
2777 /// (e.g. deallocate box storage, pop a stack, etc).
2778 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2779 pub trait Place<Data: ?Sized> {
2780     /// Returns the address where the input value will be written.
2781     /// Note that the data at this address is generally uninitialized,
2782     /// and thus one should use `ptr::write` for initializing it.
2783     fn pointer(&mut self) -> *mut Data;
2784 }
2785
2786 /// Interface to implementations of  `PLACE <- EXPR`.
2787 ///
2788 /// `PLACE <- EXPR` effectively desugars into:
2789 ///
2790 /// ```rust,ignore
2791 /// let p = PLACE;
2792 /// let mut place = Placer::make_place(p);
2793 /// let raw_place = Place::pointer(&mut place);
2794 /// let value = EXPR;
2795 /// unsafe {
2796 ///     std::ptr::write(raw_place, value);
2797 ///     InPlace::finalize(place)
2798 /// }
2799 /// ```
2800 ///
2801 /// The type of `PLACE <- EXPR` is derived from the type of `PLACE`;
2802 /// if the type of `PLACE` is `P`, then the final type of the whole
2803 /// expression is `P::Place::Owner` (see the `InPlace` and `Boxed`
2804 /// traits).
2805 ///
2806 /// Values for types implementing this trait usually are transient
2807 /// intermediate values (e.g. the return value of `Vec::emplace_back`)
2808 /// or `Copy`, since the `make_place` method takes `self` by value.
2809 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2810 pub trait Placer<Data: ?Sized> {
2811     /// `Place` is the intermedate agent guarding the
2812     /// uninitialized state for `Data`.
2813     type Place: InPlace<Data>;
2814
2815     /// Creates a fresh place from `self`.
2816     fn make_place(self) -> Self::Place;
2817 }
2818
2819 /// Specialization of `Place` trait supporting `PLACE <- EXPR`.
2820 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2821 pub trait InPlace<Data: ?Sized>: Place<Data> {
2822     /// `Owner` is the type of the end value of `PLACE <- EXPR`
2823     ///
2824     /// Note that when `PLACE <- EXPR` is solely used for
2825     /// side-effecting an existing data-structure,
2826     /// e.g. `Vec::emplace_back`, then `Owner` need not carry any
2827     /// information at all (e.g. it can be the unit type `()` in that
2828     /// case).
2829     type Owner;
2830
2831     /// Converts self into the final value, shifting
2832     /// deallocation/cleanup responsibilities (if any remain), over to
2833     /// the returned instance of `Owner` and forgetting self.
2834     unsafe fn finalize(self) -> Self::Owner;
2835 }
2836
2837 /// Core trait for the `box EXPR` form.
2838 ///
2839 /// `box EXPR` effectively desugars into:
2840 ///
2841 /// ```rust,ignore
2842 /// let mut place = BoxPlace::make_place();
2843 /// let raw_place = Place::pointer(&mut place);
2844 /// let value = EXPR;
2845 /// unsafe {
2846 ///     ::std::ptr::write(raw_place, value);
2847 ///     Boxed::finalize(place)
2848 /// }
2849 /// ```
2850 ///
2851 /// The type of `box EXPR` is supplied from its surrounding
2852 /// context; in the above expansion, the result type `T` is used
2853 /// to determine which implementation of `Boxed` to use, and that
2854 /// `<T as Boxed>` in turn dictates determines which
2855 /// implementation of `BoxPlace` to use, namely:
2856 /// `<<T as Boxed>::Place as BoxPlace>`.
2857 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2858 pub trait Boxed {
2859     /// The kind of data that is stored in this kind of box.
2860     type Data;  /* (`Data` unused b/c cannot yet express below bound.) */
2861     /// The place that will negotiate the storage of the data.
2862     type Place: BoxPlace<Self::Data>;
2863
2864     /// Converts filled place into final owning value, shifting
2865     /// deallocation/cleanup responsibilities (if any remain), over to
2866     /// returned instance of `Self` and forgetting `filled`.
2867     unsafe fn finalize(filled: Self::Place) -> Self;
2868 }
2869
2870 /// Specialization of `Place` trait supporting `box EXPR`.
2871 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2872 pub trait BoxPlace<Data: ?Sized> : Place<Data> {
2873     /// Creates a globally fresh place.
2874     fn make_place() -> Self;
2875 }
2876
2877 /// A trait for types which have success and error states and are meant to work
2878 /// with the question mark operator.
2879 /// When the `?` operator is used with a value, whether the value is in the
2880 /// success or error state is determined by calling `translate`.
2881 ///
2882 /// This trait is **very** experimental, it will probably be iterated on heavily
2883 /// before it is stabilised. Implementors should expect change. Users of `?`
2884 /// should not rely on any implementations of `Carrier` other than `Result`,
2885 /// i.e., you should not expect `?` to continue to work with `Option`, etc.
2886 #[unstable(feature = "question_mark_carrier", issue = "31436")]
2887 pub trait Carrier {
2888     /// The type of the value when computation succeeds.
2889     type Success;
2890     /// The type of the value when computation errors out.
2891     type Error;
2892
2893     /// Create a `Carrier` from a success value.
2894     fn from_success(_: Self::Success) -> Self;
2895
2896     /// Create a `Carrier` from an error value.
2897     fn from_error(_: Self::Error) -> Self;
2898
2899     /// Translate this `Carrier` to another implementation of `Carrier` with the
2900     /// same associated types.
2901     fn translate<T>(self) -> T where T: Carrier<Success=Self::Success, Error=Self::Error>;
2902 }
2903
2904 #[unstable(feature = "question_mark_carrier", issue = "31436")]
2905 impl<U, V> Carrier for Result<U, V> {
2906     type Success = U;
2907     type Error = V;
2908
2909     fn from_success(u: U) -> Result<U, V> {
2910         Ok(u)
2911     }
2912
2913     fn from_error(e: V) -> Result<U, V> {
2914         Err(e)
2915     }
2916
2917     fn translate<T>(self) -> T
2918         where T: Carrier<Success=U, Error=V>
2919     {
2920         match self {
2921             Ok(u) => T::from_success(u),
2922             Err(e) => T::from_error(e),
2923         }
2924     }
2925 }
2926
2927 struct _DummyErrorType;
2928
2929 impl Carrier for _DummyErrorType {
2930     type Success = ();
2931     type Error = ();
2932
2933     fn from_success(_: ()) -> _DummyErrorType {
2934         _DummyErrorType
2935     }
2936
2937     fn from_error(_: ()) -> _DummyErrorType {
2938         _DummyErrorType
2939     }
2940
2941     fn translate<T>(self) -> T
2942         where T: Carrier<Success=(), Error=()>
2943     {
2944         T::from_success(())
2945     }
2946 }