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