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.
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.
11 //! Overloadable operators.
13 //! Implementing these traits allows you to overload certain operators.
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.
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.
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.
42 //! This example creates a `Point` struct that implements `Add` and `Sub`, and
43 //! then demonstrates adding and subtracting two `Point`s.
46 //! use std::ops::{Add, Sub};
54 //! impl Add for Point {
55 //! type Output = Point;
57 //! fn add(self, other: Point) -> Point {
58 //! Point {x: self.x + other.x, y: self.y + other.y}
62 //! impl Sub for Point {
63 //! type Output = Point;
65 //! fn sub(self, other: Point) -> Point {
66 //! Point {x: self.x - other.x, y: self.y - other.y}
70 //! println!("{:?}", Point {x: 1, y: 0} + Point {x: 2, y: 3});
71 //! println!("{:?}", Point {x: 1, y: 0} - Point {x: 2, y: 3});
75 //! See the documentation for each trait for an example implementation.
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.
85 //! [`Fn`]: trait.Fn.html
86 //! [`FnMut`]: trait.FnMut.html
87 //! [`FnOnce`]: trait.FnOnce.html
89 //! Taking a `Fn` as a parameter:
92 //! fn call_with_one<F>(func: F) -> usize
93 //! where F: Fn(usize) -> usize
98 //! let double = |x| x * 2;
99 //! assert_eq!(call_with_one(double), 2);
102 //! Taking a `FnMut` as a parameter:
105 //! fn do_twice<F>(mut func: F)
112 //! let mut x: usize = 1;
114 //! let add_two_to_x = || x += 2;
115 //! do_twice(add_two_to_x);
118 //! assert_eq!(x, 5);
121 //! Taking a `FnOnce` as a parameter:
124 //! fn consume_with_relish<F>(func: F)
125 //! where F: FnOnce() -> String
127 //! // `func` consumes its captured variables, so it cannot be run more
129 //! println!("Consumed: {}", func());
131 //! println!("Delicious!");
133 //! // Attempting to invoke `func()` again will throw a `use of moved
134 //! // value` error for `func`
137 //! let x = String::from("x");
138 //! let consume_and_return_x = move || x;
139 //! consume_with_relish(consume_and_return_x);
141 //! // `consume_and_return_x` can no longer be invoked at this point
144 #![stable(feature = "rust1", since = "1.0.0")]
149 /// The `Drop` trait is used to run some code when a value goes out of scope.
150 /// This is sometimes called a 'destructor'.
154 /// A trivial implementation of `Drop`. The `drop` method is called when `_x`
155 /// goes out of scope, and therefore `main` prints `Dropping!`.
160 /// impl Drop for HasDrop {
161 /// fn drop(&mut self) {
162 /// println!("Dropping!");
167 /// let _x = HasDrop;
171 #[stable(feature = "rust1", since = "1.0.0")]
173 /// A method called when the value goes out of scope.
175 /// When this method has been called, `self` has not yet been deallocated.
176 /// If it were, `self` would be a dangling reference.
178 /// After this function is over, the memory of `self` will be deallocated.
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.
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
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")]
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;
204 fn $method(self) -> <$t as $imp>::Output {
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;
220 fn $method(self, other: $u) -> <$t as $imp<$u>>::Output {
221 $imp::$method(*self, other)
225 #[stable(feature = "rust1", since = "1.0.0")]
226 impl<'a> $imp<&'a $u> for $t {
227 type Output = <$t as $imp<$u>>::Output;
230 fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output {
231 $imp::$method(self, *other)
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;
240 fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output {
241 $imp::$method(*self, *other)
247 /// The `Add` trait is used to specify the functionality of `+`.
251 /// This example creates a `Point` struct that implements the `Add` trait, and
252 /// then demonstrates adding two `Point`s.
255 /// use std::ops::Add;
263 /// impl Add for Point {
264 /// type Output = Point;
266 /// fn add(self, other: Point) -> Point {
268 /// x: self.x + other.x,
269 /// y: self.y + other.y,
274 /// impl PartialEq for Point {
275 /// fn eq(&self, other: &Self) -> bool {
276 /// self.x == other.x && self.y == other.y
281 /// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
282 /// Point { x: 3, y: 3 });
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")]
292 /// The method for the `+` operator
293 #[stable(feature = "rust1", since = "1.0.0")]
294 fn add(self, rhs: RHS) -> Self::Output;
297 macro_rules! add_impl {
299 #[stable(feature = "rust1", since = "1.0.0")]
304 #[rustc_inherit_overflow_checks]
305 fn add(self, other: $t) -> $t { self + other }
308 forward_ref_binop! { impl Add, add for $t, $t }
312 add_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
314 /// The `Sub` trait is used to specify the functionality of `-`.
318 /// This example creates a `Point` struct that implements the `Sub` trait, and
319 /// then demonstrates subtracting two `Point`s.
322 /// use std::ops::Sub;
330 /// impl Sub for Point {
331 /// type Output = Point;
333 /// fn sub(self, other: Point) -> Point {
335 /// x: self.x - other.x,
336 /// y: self.y - other.y,
341 /// impl PartialEq for Point {
342 /// fn eq(&self, other: &Self) -> bool {
343 /// self.x == other.x && self.y == other.y
348 /// assert_eq!(Point { x: 3, y: 3 } - Point { x: 2, y: 3 },
349 /// Point { x: 1, y: 0 });
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")]
359 /// The method for the `-` operator
360 #[stable(feature = "rust1", since = "1.0.0")]
361 fn sub(self, rhs: RHS) -> Self::Output;
364 macro_rules! sub_impl {
366 #[stable(feature = "rust1", since = "1.0.0")]
371 #[rustc_inherit_overflow_checks]
372 fn sub(self, other: $t) -> $t { self - other }
375 forward_ref_binop! { impl Sub, sub for $t, $t }
379 sub_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
381 /// The `Mul` trait is used to specify the functionality of `*`.
385 /// Implementing a `Mul`tipliable rational number struct:
388 /// use std::ops::Mul;
390 /// // The uniqueness of rational numbers in lowest terms is a consequence of
391 /// // the fundamental theorem of arithmetic.
393 /// #[derive(PartialEq, Debug)]
394 /// struct Rational {
395 /// nominator: usize,
396 /// denominator: usize,
400 /// fn new(nominator: usize, denominator: usize) -> Self {
401 /// if denominator == 0 {
402 /// panic!("Zero is an invalid denominator!");
405 /// // Reduce to lowest terms by dividing by the greatest common
407 /// let gcd = gcd(nominator, denominator);
409 /// nominator: nominator / gcd,
410 /// denominator: denominator / gcd,
415 /// impl Mul for Rational {
416 /// // The multiplication of rational numbers is a closed operation.
417 /// type Output = Self;
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)
426 /// // Euclid's two-thousand-year-old algorithm for finding the greatest common
428 /// fn gcd(x: usize, y: usize) -> usize {
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));
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.
449 /// use std::ops::Mul;
451 /// struct Scalar {value: usize};
454 /// struct Vector {value: Vec<usize>};
456 /// impl Mul<Vector> for Scalar {
457 /// type Output = Vector;
459 /// fn mul(self, rhs: Vector) -> Vector {
460 /// Vector {value: rhs.value.iter().map(|v| self.value * v).collect()}
464 /// impl PartialEq<Vector> for Vector {
465 /// fn eq(&self, other: &Self) -> bool {
466 /// self.value == other.value
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]});
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")]
481 /// The method for the `*` operator
482 #[stable(feature = "rust1", since = "1.0.0")]
483 fn mul(self, rhs: RHS) -> Self::Output;
486 macro_rules! mul_impl {
488 #[stable(feature = "rust1", since = "1.0.0")]
493 #[rustc_inherit_overflow_checks]
494 fn mul(self, other: $t) -> $t { self * other }
497 forward_ref_binop! { impl Mul, mul for $t, $t }
501 mul_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
503 /// The `Div` trait is used to specify the functionality of `/`.
507 /// Implementing a `Div`idable rational number struct:
510 /// use std::ops::Div;
512 /// // The uniqueness of rational numbers in lowest terms is a consequence of
513 /// // the fundamental theorem of arithmetic.
515 /// #[derive(PartialEq, Debug)]
516 /// struct Rational {
517 /// nominator: usize,
518 /// denominator: usize,
522 /// fn new(nominator: usize, denominator: usize) -> Self {
523 /// if denominator == 0 {
524 /// panic!("Zero is an invalid denominator!");
527 /// // Reduce to lowest terms by dividing by the greatest common
529 /// let gcd = gcd(nominator, denominator);
531 /// nominator: nominator / gcd,
532 /// denominator: denominator / gcd,
537 /// impl Div for Rational {
538 /// // The division of rational numbers is a closed operation.
539 /// type Output = Self;
541 /// fn div(self, rhs: Self) -> Self {
542 /// if rhs.nominator == 0 {
543 /// panic!("Cannot divide by zero-valued `Rational`!");
546 /// let nominator = self.nominator * rhs.denominator;
547 /// let denominator = self.denominator * rhs.nominator;
548 /// Rational::new(nominator, denominator)
552 /// // Euclid's two-thousand-year-old algorithm for finding the greatest common
554 /// fn gcd(x: usize, y: usize) -> usize {
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));
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
577 /// use std::ops::Div;
579 /// struct Scalar {value: f32};
582 /// struct Vector {value: Vec<f32>};
584 /// impl Div<Scalar> for Vector {
585 /// type Output = Vector;
587 /// fn div(self, rhs: Scalar) -> Vector {
588 /// Vector {value: self.value.iter().map(|v| v / rhs.value).collect()}
592 /// impl PartialEq<Vector> for Vector {
593 /// fn eq(&self, other: &Self) -> bool {
594 /// self.value == other.value
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]});
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")]
609 /// The method for the `/` operator
610 #[stable(feature = "rust1", since = "1.0.0")]
611 fn div(self, rhs: RHS) -> Self::Output;
614 macro_rules! div_impl_integer {
616 /// This operation rounds towards zero, truncating any
617 /// fractional part of the exact result.
618 #[stable(feature = "rust1", since = "1.0.0")]
623 fn div(self, other: $t) -> $t { self / other }
626 forward_ref_binop! { impl Div, div for $t, $t }
630 div_impl_integer! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
632 macro_rules! div_impl_float {
634 #[stable(feature = "rust1", since = "1.0.0")]
639 fn div(self, other: $t) -> $t { self / other }
642 forward_ref_binop! { impl Div, div for $t, $t }
646 div_impl_float! { f32 f64 }
648 /// The `Rem` trait is used to specify the functionality of `%`.
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
658 /// use std::ops::Rem;
660 /// #[derive(PartialEq, Debug)]
661 /// struct SplitSlice<'a, T: 'a> {
665 /// impl<'a, T> Rem<usize> for SplitSlice<'a, T> {
666 /// type Output = SplitSlice<'a, T>;
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..]}
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] });
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")]
688 /// The method for the `%` operator
689 #[stable(feature = "rust1", since = "1.0.0")]
690 fn rem(self, rhs: RHS) -> Self::Output;
693 macro_rules! rem_impl_integer {
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")]
702 fn rem(self, other: $t) -> $t { self % other }
705 forward_ref_binop! { impl Rem, rem for $t, $t }
709 rem_impl_integer! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
711 macro_rules! rem_impl_float {
713 #[stable(feature = "rust1", since = "1.0.0")]
718 fn rem(self, other: $t) -> $t { self % other }
721 forward_ref_binop! { impl Rem, rem for $t, $t }
725 rem_impl_float! { f32 f64 }
727 /// The `Neg` trait is used to specify the functionality of unary `-`.
731 /// An implementation of `Neg` for `Sign`, which allows the use of `-` to
732 /// negate its value.
735 /// use std::ops::Neg;
737 /// #[derive(Debug, PartialEq)]
744 /// impl Neg for Sign {
745 /// type Output = Sign;
747 /// fn neg(self) -> Sign {
749 /// Sign::Negative => Sign::Positive,
750 /// Sign::Zero => Sign::Zero,
751 /// Sign::Positive => Sign::Negative,
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);
764 #[stable(feature = "rust1", since = "1.0.0")]
766 /// The resulting type after applying the `-` operator
767 #[stable(feature = "rust1", since = "1.0.0")]
770 /// The method for the unary `-` operator
771 #[stable(feature = "rust1", since = "1.0.0")]
772 fn neg(self) -> Self::Output;
777 macro_rules! neg_impl_core {
778 ($id:ident => $body:expr, $($t:ty)*) => ($(
779 #[stable(feature = "rust1", since = "1.0.0")]
784 #[rustc_inherit_overflow_checks]
785 fn neg(self) -> $t { let $id = self; $body }
788 forward_ref_unop! { impl Neg, neg for $t }
792 macro_rules! neg_impl_numeric {
793 ($($t:ty)*) => { neg_impl_core!{ x => -x, $($t)*} }
796 macro_rules! neg_impl_unsigned {
798 neg_impl_core!{ x => {
803 // neg_impl_unsigned! { usize u8 u16 u32 u64 }
804 neg_impl_numeric! { isize i8 i16 i32 i64 f32 f64 }
806 /// The `Not` trait is used to specify the functionality of unary `!`.
810 /// An implementation of `Not` for `Answer`, which enables the use of `!` to
811 /// invert its value.
814 /// use std::ops::Not;
816 /// #[derive(Debug, PartialEq)]
822 /// impl Not for Answer {
823 /// type Output = Answer;
825 /// fn not(self) -> Answer {
827 /// Answer::Yes => Answer::No,
828 /// Answer::No => Answer::Yes
833 /// assert_eq!(!Answer::Yes, Answer::No);
834 /// assert_eq!(!Answer::No, Answer::Yes);
837 #[stable(feature = "rust1", since = "1.0.0")]
839 /// The resulting type after applying the `!` operator
840 #[stable(feature = "rust1", since = "1.0.0")]
843 /// The method for the unary `!` operator
844 #[stable(feature = "rust1", since = "1.0.0")]
845 fn not(self) -> Self::Output;
848 macro_rules! not_impl {
850 #[stable(feature = "rust1", since = "1.0.0")]
855 fn not(self) -> $t { !self }
858 forward_ref_unop! { impl Not, not for $t }
862 not_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
864 /// The `BitAnd` trait is used to specify the functionality of `&`.
868 /// In this example, the `&` operator is lifted to a trivial `Scalar` type.
871 /// use std::ops::BitAnd;
873 /// #[derive(Debug, PartialEq)]
874 /// struct Scalar(bool);
876 /// impl BitAnd for Scalar {
877 /// type Output = Self;
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)
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));
893 /// In this example, the `BitAnd` trait is implemented for a `BooleanVector`
897 /// use std::ops::BitAnd;
899 /// #[derive(Debug, PartialEq)]
900 /// struct BooleanVector(Vec<bool>);
902 /// impl BitAnd for BooleanVector {
903 /// type Output = Self;
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())
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);
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")]
926 /// The method for the `&` operator
927 #[stable(feature = "rust1", since = "1.0.0")]
928 fn bitand(self, rhs: RHS) -> Self::Output;
931 macro_rules! bitand_impl {
933 #[stable(feature = "rust1", since = "1.0.0")]
938 fn bitand(self, rhs: $t) -> $t { self & rhs }
941 forward_ref_binop! { impl BitAnd, bitand for $t, $t }
945 bitand_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
947 /// The `BitOr` trait is used to specify the functionality of `|`.
951 /// In this example, the `|` operator is lifted to a trivial `Scalar` type.
954 /// use std::ops::BitOr;
956 /// #[derive(Debug, PartialEq)]
957 /// struct Scalar(bool);
959 /// impl BitOr for Scalar {
960 /// type Output = Self;
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)
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));
976 /// In this example, the `BitOr` trait is implemented for a `BooleanVector`
980 /// use std::ops::BitOr;
982 /// #[derive(Debug, PartialEq)]
983 /// struct BooleanVector(Vec<bool>);
985 /// impl BitOr for BooleanVector {
986 /// type Output = Self;
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())
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);
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")]
1009 /// The method for the `|` operator
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 fn bitor(self, rhs: RHS) -> Self::Output;
1014 macro_rules! bitor_impl {
1016 #[stable(feature = "rust1", since = "1.0.0")]
1021 fn bitor(self, rhs: $t) -> $t { self | rhs }
1024 forward_ref_binop! { impl BitOr, bitor for $t, $t }
1028 bitor_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1030 /// The `BitXor` trait is used to specify the functionality of `^`.
1034 /// In this example, the `^` operator is lifted to a trivial `Scalar` type.
1037 /// use std::ops::BitXor;
1039 /// #[derive(Debug, PartialEq)]
1040 /// struct Scalar(bool);
1042 /// impl BitXor for Scalar {
1043 /// type Output = Self;
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)
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));
1059 /// In this example, the `BitXor` trait is implemented for a `BooleanVector`
1063 /// use std::ops::BitXor;
1065 /// #[derive(Debug, PartialEq)]
1066 /// struct BooleanVector(Vec<bool>);
1068 /// impl BitXor for BooleanVector {
1069 /// type Output = Self;
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))
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);
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")]
1095 /// The method for the `^` operator
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 fn bitxor(self, rhs: RHS) -> Self::Output;
1100 macro_rules! bitxor_impl {
1102 #[stable(feature = "rust1", since = "1.0.0")]
1103 impl BitXor for $t {
1107 fn bitxor(self, other: $t) -> $t { self ^ other }
1110 forward_ref_binop! { impl BitXor, bitxor for $t, $t }
1114 bitxor_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1116 /// The `Shl` trait is used to specify the functionality of `<<`.
1120 /// An implementation of `Shl` that lifts the `<<` operation on integers to a
1121 /// `Scalar` struct.
1124 /// use std::ops::Shl;
1126 /// #[derive(PartialEq, Debug)]
1127 /// struct Scalar(usize);
1129 /// impl Shl<Scalar> for Scalar {
1130 /// type Output = Self;
1132 /// fn shl(self, Scalar(rhs): Self) -> Scalar {
1133 /// let Scalar(lhs) = self;
1134 /// Scalar(lhs << rhs)
1138 /// assert_eq!(Scalar(4) << Scalar(2), Scalar(16));
1142 /// An implementation of `Shl` that spins a vector leftward by a given amount.
1145 /// use std::ops::Shl;
1147 /// #[derive(PartialEq, Debug)]
1148 /// struct SpinVector<T: Clone> {
1152 /// impl<T: Clone> Shl<usize> for SpinVector<T> {
1153 /// type Output = Self;
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 }
1166 /// assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } << 2,
1167 /// SpinVector { vec: vec![2, 3, 4, 0, 1] });
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")]
1177 /// The method for the `<<` operator
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 fn shl(self, rhs: RHS) -> Self::Output;
1182 macro_rules! shl_impl {
1184 #[stable(feature = "rust1", since = "1.0.0")]
1185 impl Shl<$f> for $t {
1189 #[rustc_inherit_overflow_checks]
1190 fn shl(self, other: $f) -> $t {
1195 forward_ref_binop! { impl Shl, shl for $t, $f }
1199 macro_rules! shl_impl_all {
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 }
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 }
1215 shl_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
1217 /// The `Shr` trait is used to specify the functionality of `>>`.
1221 /// An implementation of `Shr` that lifts the `>>` operation on integers to a
1222 /// `Scalar` struct.
1225 /// use std::ops::Shr;
1227 /// #[derive(PartialEq, Debug)]
1228 /// struct Scalar(usize);
1230 /// impl Shr<Scalar> for Scalar {
1231 /// type Output = Self;
1233 /// fn shr(self, Scalar(rhs): Self) -> Scalar {
1234 /// let Scalar(lhs) = self;
1235 /// Scalar(lhs >> rhs)
1239 /// assert_eq!(Scalar(16) >> Scalar(2), Scalar(4));
1243 /// An implementation of `Shr` that spins a vector rightward by a given amount.
1246 /// use std::ops::Shr;
1248 /// #[derive(PartialEq, Debug)]
1249 /// struct SpinVector<T: Clone> {
1253 /// impl<T: Clone> Shr<usize> for SpinVector<T> {
1254 /// type Output = Self;
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 }
1267 /// assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } >> 2,
1268 /// SpinVector { vec: vec![3, 4, 0, 1, 2] });
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")]
1278 /// The method for the `>>` operator
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 fn shr(self, rhs: RHS) -> Self::Output;
1283 macro_rules! shr_impl {
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 impl Shr<$f> for $t {
1290 #[rustc_inherit_overflow_checks]
1291 fn shr(self, other: $f) -> $t {
1296 forward_ref_binop! { impl Shr, shr for $t, $f }
1300 macro_rules! shr_impl_all {
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 }
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 }
1316 shr_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
1318 /// The `AddAssign` trait is used to specify the functionality of `+=`.
1322 /// This example creates a `Point` struct that implements the `AddAssign`
1323 /// trait, and then demonstrates add-assigning to a mutable `Point`.
1326 /// use std::ops::AddAssign;
1328 /// #[derive(Debug)]
1334 /// impl AddAssign for Point {
1335 /// fn add_assign(&mut self, other: Point) {
1337 /// x: self.x + other.x,
1338 /// y: self.y + other.y,
1343 /// impl PartialEq for Point {
1344 /// fn eq(&self, other: &Self) -> bool {
1345 /// self.x == other.x && self.y == other.y
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 });
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);
1361 macro_rules! add_assign_impl {
1363 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1364 impl AddAssign for $t {
1366 #[rustc_inherit_overflow_checks]
1367 fn add_assign(&mut self, other: $t) { *self += other }
1372 add_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1374 /// The `SubAssign` trait is used to specify the functionality of `-=`.
1378 /// This example creates a `Point` struct that implements the `SubAssign`
1379 /// trait, and then demonstrates sub-assigning to a mutable `Point`.
1382 /// use std::ops::SubAssign;
1384 /// #[derive(Debug)]
1390 /// impl SubAssign for Point {
1391 /// fn sub_assign(&mut self, other: Point) {
1393 /// x: self.x - other.x,
1394 /// y: self.y - other.y,
1399 /// impl PartialEq for Point {
1400 /// fn eq(&self, other: &Self) -> bool {
1401 /// self.x == other.x && self.y == other.y
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});
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);
1417 macro_rules! sub_assign_impl {
1419 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1420 impl SubAssign for $t {
1422 #[rustc_inherit_overflow_checks]
1423 fn sub_assign(&mut self, other: $t) { *self -= other }
1428 sub_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1430 /// The `MulAssign` trait is used to specify the functionality of `*=`.
1434 /// A trivial implementation of `MulAssign`. When `Foo *= Foo` happens, it ends up
1435 /// calling `mul_assign`, and therefore, `main` prints `Multiplying!`.
1438 /// use std::ops::MulAssign;
1442 /// impl MulAssign for Foo {
1443 /// fn mul_assign(&mut self, _rhs: Foo) {
1444 /// println!("Multiplying!");
1448 /// # #[allow(unused_assignments)]
1450 /// let mut foo = Foo;
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);
1462 macro_rules! mul_assign_impl {
1464 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1465 impl MulAssign for $t {
1467 #[rustc_inherit_overflow_checks]
1468 fn mul_assign(&mut self, other: $t) { *self *= other }
1473 mul_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1475 /// The `DivAssign` trait is used to specify the functionality of `/=`.
1479 /// A trivial implementation of `DivAssign`. When `Foo /= Foo` happens, it ends up
1480 /// calling `div_assign`, and therefore, `main` prints `Dividing!`.
1483 /// use std::ops::DivAssign;
1487 /// impl DivAssign for Foo {
1488 /// fn div_assign(&mut self, _rhs: Foo) {
1489 /// println!("Dividing!");
1493 /// # #[allow(unused_assignments)]
1495 /// let mut foo = Foo;
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);
1507 macro_rules! div_assign_impl {
1509 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1510 impl DivAssign for $t {
1512 fn div_assign(&mut self, other: $t) { *self /= other }
1517 div_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1519 /// The `RemAssign` trait is used to specify the functionality of `%=`.
1523 /// A trivial implementation of `RemAssign`. When `Foo %= Foo` happens, it ends up
1524 /// calling `rem_assign`, and therefore, `main` prints `Remainder-ing!`.
1527 /// use std::ops::RemAssign;
1531 /// impl RemAssign for Foo {
1532 /// fn rem_assign(&mut self, _rhs: Foo) {
1533 /// println!("Remainder-ing!");
1537 /// # #[allow(unused_assignments)]
1539 /// let mut foo = Foo;
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);
1551 macro_rules! rem_assign_impl {
1553 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1554 impl RemAssign for $t {
1556 fn rem_assign(&mut self, other: $t) { *self %= other }
1561 rem_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1563 /// The `BitAndAssign` trait is used to specify the functionality of `&=`.
1567 /// In this example, the `&=` operator is lifted to a trivial `Scalar` type.
1570 /// use std::ops::BitAndAssign;
1572 /// #[derive(Debug, PartialEq)]
1573 /// struct Scalar(bool);
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)
1583 /// let mut scalar = Scalar(true);
1584 /// scalar &= Scalar(true);
1585 /// assert_eq!(scalar, Scalar(true));
1587 /// let mut scalar = Scalar(true);
1588 /// scalar &= Scalar(false);
1589 /// assert_eq!(scalar, Scalar(false));
1591 /// let mut scalar = Scalar(false);
1592 /// scalar &= Scalar(true);
1593 /// assert_eq!(scalar, Scalar(false));
1595 /// let mut scalar = Scalar(false);
1596 /// scalar &= Scalar(false);
1597 /// assert_eq!(scalar, Scalar(false));
1601 /// In this example, the `BitAndAssign` trait is implemented for a
1602 /// `BooleanVector` struct.
1605 /// use std::ops::BitAndAssign;
1607 /// #[derive(Debug, PartialEq)]
1608 /// struct BooleanVector(Vec<bool>);
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
1616 /// .zip(rhs.0.iter())
1617 /// .map(|(x, y)| *x && *y)
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);
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);
1637 macro_rules! bitand_assign_impl {
1639 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1640 impl BitAndAssign for $t {
1642 fn bitand_assign(&mut self, other: $t) { *self &= other }
1647 bitand_assign_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1649 /// The `BitOrAssign` trait is used to specify the functionality of `|=`.
1653 /// A trivial implementation of `BitOrAssign`. When `Foo |= Foo` happens, it ends up
1654 /// calling `bitor_assign`, and therefore, `main` prints `Bitwise Or-ing!`.
1657 /// use std::ops::BitOrAssign;
1661 /// impl BitOrAssign for Foo {
1662 /// fn bitor_assign(&mut self, _rhs: Foo) {
1663 /// println!("Bitwise Or-ing!");
1667 /// # #[allow(unused_assignments)]
1669 /// let mut foo = Foo;
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);
1681 macro_rules! bitor_assign_impl {
1683 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1684 impl BitOrAssign for $t {
1686 fn bitor_assign(&mut self, other: $t) { *self |= other }
1691 bitor_assign_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1693 /// The `BitXorAssign` trait is used to specify the functionality of `^=`.
1697 /// A trivial implementation of `BitXorAssign`. When `Foo ^= Foo` happens, it ends up
1698 /// calling `bitxor_assign`, and therefore, `main` prints `Bitwise Xor-ing!`.
1701 /// use std::ops::BitXorAssign;
1705 /// impl BitXorAssign for Foo {
1706 /// fn bitxor_assign(&mut self, _rhs: Foo) {
1707 /// println!("Bitwise Xor-ing!");
1711 /// # #[allow(unused_assignments)]
1713 /// let mut foo = Foo;
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);
1725 macro_rules! bitxor_assign_impl {
1727 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1728 impl BitXorAssign for $t {
1730 fn bitxor_assign(&mut self, other: $t) { *self ^= other }
1735 bitxor_assign_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1737 /// The `ShlAssign` trait is used to specify the functionality of `<<=`.
1741 /// A trivial implementation of `ShlAssign`. When `Foo <<= Foo` happens, it ends up
1742 /// calling `shl_assign`, and therefore, `main` prints `Shifting left!`.
1745 /// use std::ops::ShlAssign;
1749 /// impl ShlAssign<Foo> for Foo {
1750 /// fn shl_assign(&mut self, _rhs: Foo) {
1751 /// println!("Shifting left!");
1755 /// # #[allow(unused_assignments)]
1757 /// let mut foo = Foo;
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);
1769 macro_rules! shl_assign_impl {
1771 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1772 impl ShlAssign<$f> for $t {
1774 #[rustc_inherit_overflow_checks]
1775 fn shl_assign(&mut self, other: $f) {
1782 macro_rules! shl_assign_impl_all {
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 }
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 }
1798 shl_assign_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
1800 /// The `ShrAssign` trait is used to specify the functionality of `>>=`.
1804 /// A trivial implementation of `ShrAssign`. When `Foo >>= Foo` happens, it ends up
1805 /// calling `shr_assign`, and therefore, `main` prints `Shifting right!`.
1808 /// use std::ops::ShrAssign;
1812 /// impl ShrAssign<Foo> for Foo {
1813 /// fn shr_assign(&mut self, _rhs: Foo) {
1814 /// println!("Shifting right!");
1818 /// # #[allow(unused_assignments)]
1820 /// let mut foo = Foo;
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);
1832 macro_rules! shr_assign_impl {
1834 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1835 impl ShrAssign<$f> for $t {
1837 #[rustc_inherit_overflow_checks]
1838 fn shr_assign(&mut self, other: $f) {
1845 macro_rules! shr_assign_impl_all {
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 }
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 }
1861 shr_assign_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
1863 /// The `Index` trait is used to specify the functionality of indexing operations
1864 /// like `arr[idx]` when used in an immutable context.
1868 /// This example implements `Index` on a read-only `NucleotideCount` container,
1869 /// enabling individual counts to be retrieved with index syntax.
1872 /// use std::ops::Index;
1874 /// enum Nucleotide {
1881 /// struct NucleotideCount {
1888 /// impl Index<Nucleotide> for NucleotideCount {
1889 /// type Output = usize;
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,
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);
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;
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;
1920 /// The `IndexMut` trait is used to specify the functionality of indexing
1921 /// operations like `arr[idx]`, when used in a mutable context.
1925 /// A trivial implementation of `IndexMut`. When `Foo[Bar]` happens, it ends up
1926 /// calling `index_mut`, and therefore, `main` prints `Indexing!`.
1929 /// use std::ops::{Index, IndexMut};
1931 /// #[derive(Copy, Clone)]
1935 /// impl Index<Bar> for Foo {
1936 /// type Output = Foo;
1938 /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
1943 /// impl IndexMut<Bar> for Foo {
1944 /// fn index_mut<'a>(&'a mut self, _index: Bar) -> &'a mut Foo {
1945 /// println!("Indexing!");
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;
1963 /// An unbounded range. Use `..` (two dots) for its shorthand.
1965 /// Its primary use case is slicing index. It cannot serve as an iterator
1966 /// because it doesn't have a starting point.
1970 /// The `..` syntax is a `RangeFull`:
1973 /// assert_eq!((..), std::ops::RangeFull);
1976 /// It does not have an `IntoIterator` implementation, so you can't use it in a
1977 /// `for` loop directly. This won't compile:
1985 /// Used as a slicing index, `RangeFull` produces the full array as a slice.
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 ]);
1994 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
1995 #[stable(feature = "rust1", since = "1.0.0")]
1996 pub struct RangeFull;
1998 #[stable(feature = "rust1", since = "1.0.0")]
1999 impl fmt::Debug for RangeFull {
2000 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2005 /// A (half-open) range which is bounded at both ends: { x | start <= x < end }.
2006 /// Use `start..end` (two dots) for its shorthand.
2008 /// See the [`contains()`](#method.contains) method for its characterization.
2014 /// assert_eq!((3..5), std::ops::Range{ start: 3, end: 5 });
2015 /// assert_eq!(3+4+5, (3..6).sum());
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
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")]
2030 /// The upper bound of the range (exclusive).
2031 #[stable(feature = "rust1", since = "1.0.0")]
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)
2042 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2043 impl<Idx: PartialOrd<Idx>> Range<Idx> {
2047 /// #![feature(range_contains)]
2049 /// assert!( ! (3..5).contains(2));
2050 /// assert!( (3..5).contains(3));
2051 /// assert!( (3..5).contains(4));
2052 /// assert!( ! (3..5).contains(5));
2054 /// assert!( ! (3..3).contains(3));
2055 /// assert!( ! (3..2).contains(3));
2058 pub fn contains(&self, item: Idx) -> bool {
2059 (self.start <= item) && (item < self.end)
2063 /// A range which is only bounded below: { x | start <= x }.
2064 /// Use `start..` for its shorthand.
2066 /// See the [`contains()`](#method.contains) method for its characterization.
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.
2077 /// assert_eq!((2..), std::ops::RangeFrom{ start: 2 });
2078 /// assert_eq!(2+3+4, (2..).take(3).sum());
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 ]);
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")]
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)
2102 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2103 impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
2107 /// #![feature(range_contains)]
2109 /// assert!( ! (3..).contains(2));
2110 /// assert!( (3..).contains(3));
2111 /// assert!( (3..).contains(1_000_000_000));
2114 pub fn contains(&self, item: Idx) -> bool {
2115 (self.start <= item)
2119 /// A range which is only bounded above: { x | x < end }.
2120 /// Use `..end` (two dots) for its shorthand.
2122 /// See the [`contains()`](#method.contains) method for its characterization.
2124 /// It cannot serve as an iterator because it doesn't have a starting point.
2128 /// The `..{integer}` syntax is a `RangeTo`:
2131 /// assert_eq!((..5), std::ops::RangeTo{ end: 5 });
2134 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2135 /// `for` loop directly. This won't compile:
2143 /// When used as a slicing index, `RangeTo` produces a slice of all array
2144 /// elements before the index indicated by `end`.
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 ]);
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")]
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)
2168 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2169 impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
2173 /// #![feature(range_contains)]
2175 /// assert!( (..5).contains(-1_000_000_000));
2176 /// assert!( (..5).contains(4));
2177 /// assert!( ! (..5).contains(5));
2180 pub fn contains(&self, item: Idx) -> bool {
2185 /// An inclusive range which is bounded at both ends: { x | start <= x <= end }.
2186 /// Use `start...end` (three dots) for its shorthand.
2188 /// See the [`contains()`](#method.contains) method for its characterization.
2193 /// #![feature(inclusive_range,inclusive_range_syntax)]
2195 /// assert_eq!((3...5), std::ops::RangeInclusive::NonEmpty{ start: 3, end: 5 });
2196 /// assert_eq!(3+4+5, (3...5).sum());
2198 /// let arr = [0, 1, 2, 3];
2199 /// assert_eq!(arr[ ...2], [0,1,2 ]);
2200 /// assert_eq!(arr[1...2], [ 1,2 ]); // RangeInclusive
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",
2211 /// The point at which iteration finished
2212 #[unstable(feature = "inclusive_range",
2213 reason = "recently added, follows RFC",
2217 /// Non-empty range (iteration will yield value(s))
2218 #[unstable(feature = "inclusive_range",
2219 reason = "recently added, follows RFC",
2222 /// The lower bound of the range (inclusive).
2223 #[unstable(feature = "inclusive_range",
2224 reason = "recently added, follows RFC",
2227 /// The upper bound of the range (inclusive).
2228 #[unstable(feature = "inclusive_range",
2229 reason = "recently added, follows RFC",
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::*;
2241 Empty { ref at } => write!(fmt, "[empty range @ {:?}]", at),
2242 NonEmpty { ref start, ref end } => write!(fmt, "{:?}...{:?}", start, end),
2247 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2248 impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
2252 /// #![feature(range_contains,inclusive_range_syntax)]
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));
2260 /// assert!( (3...3).contains(3));
2261 /// assert!( ! (3...2).contains(3));
2264 pub fn contains(&self, item: Idx) -> bool {
2265 if let &RangeInclusive::NonEmpty{ref start, ref end} = self {
2266 (*start <= item) && (item <= *end)
2271 /// An inclusive range which is only bounded above: { x | x <= end }.
2272 /// Use `...end` (three dots) for its shorthand.
2274 /// See the [`contains()`](#method.contains) method for its characterization.
2276 /// It cannot serve as an iterator because it doesn't have a starting point.
2280 /// The `...{integer}` syntax is a `RangeToInclusive`:
2283 /// #![feature(inclusive_range,inclusive_range_syntax)]
2284 /// assert_eq!((...5), std::ops::RangeToInclusive{ end: 5 });
2287 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2288 /// `for` loop directly. This won't compile:
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`.
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 ]);
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",
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)
2322 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2323 impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
2327 /// #![feature(range_contains,inclusive_range_syntax)]
2329 /// assert!( (...5).contains(-1_000_000_000));
2330 /// assert!( (...5).contains(5));
2331 /// assert!( ! (...5).contains(6));
2334 pub fn contains(&self, item: Idx) -> bool {
2339 // RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
2340 // because underflow would be possible with (..0).into()
2342 /// The `Deref` trait is used to specify the functionality of dereferencing
2343 /// operations, like `*v`.
2345 /// `Deref` also enables ['`Deref` coercions'][coercions].
2347 /// [coercions]: ../../book/deref-coercions.html
2351 /// A struct with a single field which is accessible via dereferencing the
2355 /// use std::ops::Deref;
2357 /// struct DerefExample<T> {
2361 /// impl<T> Deref for DerefExample<T> {
2362 /// type Target = T;
2364 /// fn deref(&self) -> &T {
2370 /// let x = DerefExample { value: 'a' };
2371 /// assert_eq!('a', *x);
2375 #[stable(feature = "rust1", since = "1.0.0")]
2377 /// The resulting type after dereferencing
2378 #[stable(feature = "rust1", since = "1.0.0")]
2379 type Target: ?Sized;
2381 /// The method called to dereference a value
2382 #[stable(feature = "rust1", since = "1.0.0")]
2383 fn deref(&self) -> &Self::Target;
2386 #[stable(feature = "rust1", since = "1.0.0")]
2387 impl<'a, T: ?Sized> Deref for &'a T {
2390 fn deref(&self) -> &T { *self }
2393 #[stable(feature = "rust1", since = "1.0.0")]
2394 impl<'a, T: ?Sized> Deref for &'a mut T {
2397 fn deref(&self) -> &T { *self }
2400 /// The `DerefMut` trait is used to specify the functionality of dereferencing
2401 /// mutably like `*v = 1;`
2403 /// `DerefMut` also enables ['`Deref` coercions'][coercions].
2405 /// [coercions]: ../../book/deref-coercions.html
2409 /// A struct with a single field which is modifiable via dereferencing the
2413 /// use std::ops::{Deref, DerefMut};
2415 /// struct DerefMutExample<T> {
2419 /// impl<T> Deref for DerefMutExample<T> {
2420 /// type Target = T;
2422 /// fn deref<'a>(&'a self) -> &'a T {
2427 /// impl<T> DerefMut for DerefMutExample<T> {
2428 /// fn deref_mut<'a>(&'a mut self) -> &'a mut T {
2434 /// let mut x = DerefMutExample { value: 'a' };
2436 /// assert_eq!('b', *x);
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;
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 }
2452 /// A version of the call operator that takes an immutable receiver.
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`].
2461 /// [`FnMut`]: trait.FnMut.html
2462 /// [`FnOnce`]: trait.FnOnce.html
2465 /// let square = |x| x * x;
2466 /// assert_eq!(square(5), 25);
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
2474 /// fn call_with_one<F>(func: F) -> usize
2475 /// where F: Fn(usize) -> usize {
2479 /// let double = |x| x * 2;
2480 /// assert_eq!(call_with_one(double), 2);
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;
2492 /// A version of the call operator that takes a mutable receiver.
2496 /// Closures that mutably capture variables automatically implement this trait,
2497 /// which allows them to be invoked.
2502 /// let mut square_x = || x *= x;
2505 /// assert_eq!(x, 25);
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`).
2512 /// fn do_twice<F>(mut func: F)
2513 /// where F: FnMut()
2519 /// let mut x: usize = 1;
2521 /// let add_two_to_x = || x += 2;
2522 /// do_twice(add_two_to_x);
2525 /// assert_eq!(x, 5);
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;
2537 /// A version of the call operator that takes a by-value receiver.
2541 /// By-value closures automatically implement this trait, which allows them to
2546 /// let square_x = move || x * x;
2547 /// assert_eq!(square_x(), 25);
2550 /// By-value Closures can also be passed to higher-level functions through a
2551 /// `FnOnce` parameter.
2554 /// fn consume_with_relish<F>(func: F)
2555 /// where F: FnOnce() -> String
2557 /// // `func` consumes its captured variables, so it cannot be run more
2559 /// println!("Consumed: {}", func());
2561 /// println!("Delicious!");
2563 /// // Attempting to invoke `func()` again will throw a `use of moved
2564 /// // value` error for `func`
2567 /// let x = String::from("x");
2568 /// let consume_and_return_x = move || x;
2569 /// consume_with_relish(consume_and_return_x);
2571 /// // `consume_and_return_x` can no longer be invoked at this point
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")]
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;
2588 #[stable(feature = "rust1", since = "1.0.0")]
2589 impl<'a,A,F:?Sized> Fn<A> for &'a F
2592 extern "rust-call" fn call(&self, args: A) -> F::Output {
2597 #[stable(feature = "rust1", since = "1.0.0")]
2598 impl<'a,A,F:?Sized> FnMut<A> for &'a F
2601 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
2606 #[stable(feature = "rust1", since = "1.0.0")]
2607 impl<'a,A,F:?Sized> FnOnce<A> for &'a F
2610 type Output = F::Output;
2612 extern "rust-call" fn call_once(self, args: A) -> F::Output {
2617 #[stable(feature = "rust1", since = "1.0.0")]
2618 impl<'a,A,F:?Sized> FnMut<A> for &'a mut F
2621 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
2622 (*self).call_mut(args)
2626 #[stable(feature = "rust1", since = "1.0.0")]
2627 impl<'a,A,F:?Sized> FnOnce<A> for &'a mut F
2630 type Output = F::Output;
2631 extern "rust-call" fn call_once(mut self, args: A) -> F::Output {
2632 (*self).call_mut(args)
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> {
2646 #[unstable(feature = "coerce_unsized", issue = "27732")]
2647 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a mut U> for &'a mut T {}
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 {}
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 {}
2659 #[unstable(feature = "coerce_unsized", issue = "27732")]
2660 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b T {}
2662 #[unstable(feature = "coerce_unsized", issue = "27732")]
2663 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a T {}
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 {}
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 {}
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.
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.
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`.
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;
2702 /// Interface to implementations of `in (PLACE) EXPR`.
2704 /// `in (PLACE) EXPR` effectively desugars into:
2708 /// let mut place = Placer::make_place(p);
2709 /// let raw_place = Place::pointer(&mut place);
2710 /// let value = EXPR;
2712 /// std::ptr::write(raw_place, value);
2713 /// InPlace::finalize(place)
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`
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>;
2731 /// Creates a fresh place from `self`.
2732 fn make_place(self) -> Self::Place;
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`
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
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;
2753 /// Core trait for the `box EXPR` form.
2755 /// `box EXPR` effectively desugars into:
2758 /// let mut place = BoxPlace::make_place();
2759 /// let raw_place = Place::pointer(&mut place);
2760 /// let value = EXPR;
2762 /// ::std::ptr::write(raw_place, value);
2763 /// Boxed::finalize(place)
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")]
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>;
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;
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;
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`.
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")]
2804 /// The type of the value when computation succeeds.
2806 /// The type of the value when computation errors out.
2809 /// Create a `Carrier` from a success value.
2810 fn from_success(Self::Success) -> Self;
2812 /// Create a `Carrier` from an error value.
2813 fn from_error(Self::Error) -> Self;
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>;
2820 #[unstable(feature = "question_mark_carrier", issue = "31436")]
2821 impl<U, V> Carrier for Result<U, V> {
2825 fn from_success(u: U) -> Result<U, V> {
2829 fn from_error(e: V) -> Result<U, V> {
2833 fn translate<T>(self) -> T
2834 where T: Carrier<Success=U, Error=V>
2837 Ok(u) => T::from_success(u),
2838 Err(e) => T::from_error(e),
2843 struct _DummyErrorType;
2845 impl Carrier for _DummyErrorType {
2849 fn from_success(_: ()) -> _DummyErrorType {
2853 fn from_error(_: ()) -> _DummyErrorType {
2857 fn translate<T>(self) -> T
2858 where T: Carrier<Success=(), Error=()>