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 get an effect similar to
14 //! overloading operators.
16 //! Some of these traits are imported by the prelude, so they are available in
17 //! every Rust program.
19 //! Many of the operators take their operands by value. In non-generic
20 //! contexts involving built-in types, this is usually not a problem.
21 //! However, using these operators in generic code, requires some
22 //! attention if values have to be reused as opposed to letting the operators
23 //! consume them. One option is to occasionally use `clone()`.
24 //! Another option is to rely on the types involved providing additional
25 //! operator implementations for references. For example, for a user-defined
26 //! type `T` which is supposed to support addition, it is probably a good
27 //! idea to have both `T` and `&T` implement the traits `Add<T>` and `Add<&T>`
28 //! so that generic code can be written without unnecessary cloning.
32 //! This example creates a `Point` struct that implements `Add` and `Sub`, and
33 //! then demonstrates adding and subtracting two `Point`s.
36 //! use std::ops::{Add, Sub};
44 //! impl Add for Point {
45 //! type Output = Point;
47 //! fn add(self, other: Point) -> Point {
48 //! Point {x: self.x + other.x, y: self.y + other.y}
52 //! impl Sub for Point {
53 //! type Output = Point;
55 //! fn sub(self, other: Point) -> Point {
56 //! Point {x: self.x - other.x, y: self.y - other.y}
60 //! println!("{:?}", Point {x: 1, y: 0} + Point {x: 2, y: 3});
61 //! println!("{:?}", Point {x: 1, y: 0} - Point {x: 2, y: 3});
65 //! See the documentation for each trait for a minimum implementation that
66 //! prints something to the screen.
68 #![stable(feature = "rust1", since = "1.0.0")]
73 use marker::{Sized, Unsize};
76 /// The `Drop` trait is used to run some code when a value goes out of scope.
77 /// This is sometimes called a 'destructor'.
81 /// A trivial implementation of `Drop`. The `drop` method is called when `_x`
82 /// goes out of scope, and therefore `main` prints `Dropping!`.
87 /// impl Drop for HasDrop {
88 /// fn drop(&mut self) {
89 /// println!("Dropping!");
98 #[stable(feature = "rust1", since = "1.0.0")]
100 /// A method called when the value goes out of scope.
102 /// When this method has been called, `self` has not yet been deallocated.
103 /// If it were, `self` would be a dangling reference.
105 /// After this function is over, the memory of `self` will be deallocated.
109 /// Given that a `panic!` will call `drop()` as it unwinds, any `panic!` in
110 /// a `drop()` implementation will likely abort.
111 #[stable(feature = "rust1", since = "1.0.0")]
115 // implements the unary operator "op &T"
116 // based on "op T" where T is expected to be `Copy`able
117 macro_rules! forward_ref_unop {
118 (impl $imp:ident, $method:ident for $t:ty) => {
119 #[stable(feature = "rust1", since = "1.0.0")]
120 impl<'a> $imp for &'a $t {
121 type Output = <$t as $imp>::Output;
124 fn $method(self) -> <$t as $imp>::Output {
131 // implements binary operators "&T op U", "T op &U", "&T op &U"
132 // based on "T op U" where T and U are expected to be `Copy`able
133 macro_rules! forward_ref_binop {
134 (impl $imp:ident, $method:ident for $t:ty, $u:ty) => {
135 #[stable(feature = "rust1", since = "1.0.0")]
136 impl<'a> $imp<$u> for &'a $t {
137 type Output = <$t as $imp<$u>>::Output;
140 fn $method(self, other: $u) -> <$t as $imp<$u>>::Output {
141 $imp::$method(*self, other)
145 #[stable(feature = "rust1", since = "1.0.0")]
146 impl<'a> $imp<&'a $u> for $t {
147 type Output = <$t as $imp<$u>>::Output;
150 fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output {
151 $imp::$method(self, *other)
155 #[stable(feature = "rust1", since = "1.0.0")]
156 impl<'a, 'b> $imp<&'a $u> for &'b $t {
157 type Output = <$t as $imp<$u>>::Output;
160 fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output {
161 $imp::$method(*self, *other)
167 /// The `Add` trait is used to specify the functionality of `+`.
171 /// A trivial implementation of `Add`. When `Foo + Foo` happens, it ends up
172 /// calling `add`, and therefore, `main` prints `Adding!`.
175 /// use std::ops::Add;
179 /// impl Add for Foo {
180 /// type Output = Foo;
182 /// fn add(self, _rhs: Foo) -> Foo {
183 /// println!("Adding!");
193 #[stable(feature = "rust1", since = "1.0.0")]
194 pub trait Add<RHS=Self> {
195 /// The resulting type after applying the `+` operator
196 #[stable(feature = "rust1", since = "1.0.0")]
199 /// The method for the `+` operator
200 #[stable(feature = "rust1", since = "1.0.0")]
201 fn add(self, rhs: RHS) -> Self::Output;
204 macro_rules! add_impl {
206 #[stable(feature = "rust1", since = "1.0.0")]
211 fn add(self, other: $t) -> $t { self + other }
214 forward_ref_binop! { impl Add, add for $t, $t }
218 add_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
220 /// The `Sub` trait is used to specify the functionality of `-`.
224 /// A trivial implementation of `Sub`. When `Foo - Foo` happens, it ends up
225 /// calling `sub`, and therefore, `main` prints `Subtracting!`.
228 /// use std::ops::Sub;
232 /// impl Sub for Foo {
233 /// type Output = Foo;
235 /// fn sub(self, _rhs: Foo) -> Foo {
236 /// println!("Subtracting!");
246 #[stable(feature = "rust1", since = "1.0.0")]
247 pub trait Sub<RHS=Self> {
248 /// The resulting type after applying the `-` operator
249 #[stable(feature = "rust1", since = "1.0.0")]
252 /// The method for the `-` operator
253 #[stable(feature = "rust1", since = "1.0.0")]
254 fn sub(self, rhs: RHS) -> Self::Output;
257 macro_rules! sub_impl {
259 #[stable(feature = "rust1", since = "1.0.0")]
264 fn sub(self, other: $t) -> $t { self - other }
267 forward_ref_binop! { impl Sub, sub for $t, $t }
271 sub_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
273 /// The `Mul` trait is used to specify the functionality of `*`.
277 /// A trivial implementation of `Mul`. When `Foo * Foo` happens, it ends up
278 /// calling `mul`, and therefore, `main` prints `Multiplying!`.
281 /// use std::ops::Mul;
285 /// impl Mul for Foo {
286 /// type Output = Foo;
288 /// fn mul(self, _rhs: Foo) -> Foo {
289 /// println!("Multiplying!");
299 #[stable(feature = "rust1", since = "1.0.0")]
300 pub trait Mul<RHS=Self> {
301 /// The resulting type after applying the `*` operator
302 #[stable(feature = "rust1", since = "1.0.0")]
305 /// The method for the `*` operator
306 #[stable(feature = "rust1", since = "1.0.0")]
307 fn mul(self, rhs: RHS) -> Self::Output;
310 macro_rules! mul_impl {
312 #[stable(feature = "rust1", since = "1.0.0")]
317 fn mul(self, other: $t) -> $t { self * other }
320 forward_ref_binop! { impl Mul, mul for $t, $t }
324 mul_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
326 /// The `Div` trait is used to specify the functionality of `/`.
330 /// A trivial implementation of `Div`. When `Foo / Foo` happens, it ends up
331 /// calling `div`, and therefore, `main` prints `Dividing!`.
334 /// use std::ops::Div;
338 /// impl Div for Foo {
339 /// type Output = Foo;
341 /// fn div(self, _rhs: Foo) -> Foo {
342 /// println!("Dividing!");
352 #[stable(feature = "rust1", since = "1.0.0")]
353 pub trait Div<RHS=Self> {
354 /// The resulting type after applying the `/` operator
355 #[stable(feature = "rust1", since = "1.0.0")]
358 /// The method for the `/` operator
359 #[stable(feature = "rust1", since = "1.0.0")]
360 fn div(self, rhs: RHS) -> Self::Output;
363 macro_rules! div_impl_integer {
365 /// This operation rounds towards zero, truncating any
366 /// fractional part of the exact result.
367 #[stable(feature = "rust1", since = "1.0.0")]
372 fn div(self, other: $t) -> $t { self / other }
375 forward_ref_binop! { impl Div, div for $t, $t }
379 div_impl_integer! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
381 macro_rules! div_impl_float {
383 #[stable(feature = "rust1", since = "1.0.0")]
388 fn div(self, other: $t) -> $t { self / other }
391 forward_ref_binop! { impl Div, div for $t, $t }
395 div_impl_float! { f32 f64 }
397 /// The `Rem` trait is used to specify the functionality of `%`.
401 /// A trivial implementation of `Rem`. When `Foo % Foo` happens, it ends up
402 /// calling `rem`, and therefore, `main` prints `Remainder-ing!`.
405 /// use std::ops::Rem;
409 /// impl Rem for Foo {
410 /// type Output = Foo;
412 /// fn rem(self, _rhs: Foo) -> Foo {
413 /// println!("Remainder-ing!");
423 #[stable(feature = "rust1", since = "1.0.0")]
424 pub trait Rem<RHS=Self> {
425 /// The resulting type after applying the `%` operator
426 #[stable(feature = "rust1", since = "1.0.0")]
429 /// The method for the `%` operator
430 #[stable(feature = "rust1", since = "1.0.0")]
431 fn rem(self, rhs: RHS) -> Self::Output;
434 macro_rules! rem_impl_integer {
436 /// This operation satisfies `n % d == n - (n / d) * d`. The
437 /// result has the same sign as the left operand.
438 #[stable(feature = "rust1", since = "1.0.0")]
443 fn rem(self, other: $t) -> $t { self % other }
446 forward_ref_binop! { impl Rem, rem for $t, $t }
450 rem_impl_integer! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
452 macro_rules! rem_impl_float {
454 #[stable(feature = "rust1", since = "1.0.0")]
459 fn rem(self, other: $t) -> $t { self % other }
462 forward_ref_binop! { impl Rem, rem for $t, $t }
466 rem_impl_float! { f32 f64 }
468 /// The `Neg` trait is used to specify the functionality of unary `-`.
472 /// A trivial implementation of `Neg`. When `-Foo` happens, it ends up calling
473 /// `neg`, and therefore, `main` prints `Negating!`.
476 /// use std::ops::Neg;
480 /// impl Neg for Foo {
481 /// type Output = Foo;
483 /// fn neg(self) -> Foo {
484 /// println!("Negating!");
494 #[stable(feature = "rust1", since = "1.0.0")]
496 /// The resulting type after applying the `-` operator
497 #[stable(feature = "rust1", since = "1.0.0")]
500 /// The method for the unary `-` operator
501 #[stable(feature = "rust1", since = "1.0.0")]
502 fn neg(self) -> Self::Output;
507 macro_rules! neg_impl_core {
508 ($id:ident => $body:expr, $($t:ty)*) => ($(
509 #[stable(feature = "rust1", since = "1.0.0")]
514 fn neg(self) -> $t { let $id = self; $body }
517 forward_ref_unop! { impl Neg, neg for $t }
521 macro_rules! neg_impl_numeric {
522 ($($t:ty)*) => { neg_impl_core!{ x => -x, $($t)*} }
525 macro_rules! neg_impl_unsigned {
527 neg_impl_core!{ x => {
532 // neg_impl_unsigned! { usize u8 u16 u32 u64 }
533 neg_impl_numeric! { isize i8 i16 i32 i64 f32 f64 }
535 /// The `Not` trait is used to specify the functionality of unary `!`.
539 /// A trivial implementation of `Not`. When `!Foo` happens, it ends up calling
540 /// `not`, and therefore, `main` prints `Not-ing!`.
543 /// use std::ops::Not;
547 /// impl Not for Foo {
548 /// type Output = Foo;
550 /// fn not(self) -> Foo {
551 /// println!("Not-ing!");
561 #[stable(feature = "rust1", since = "1.0.0")]
563 /// The resulting type after applying the `!` operator
564 #[stable(feature = "rust1", since = "1.0.0")]
567 /// The method for the unary `!` operator
568 #[stable(feature = "rust1", since = "1.0.0")]
569 fn not(self) -> Self::Output;
572 macro_rules! not_impl {
574 #[stable(feature = "rust1", since = "1.0.0")]
579 fn not(self) -> $t { !self }
582 forward_ref_unop! { impl Not, not for $t }
586 not_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
588 /// The `BitAnd` trait is used to specify the functionality of `&`.
592 /// A trivial implementation of `BitAnd`. When `Foo & Foo` happens, it ends up
593 /// calling `bitand`, and therefore, `main` prints `Bitwise And-ing!`.
596 /// use std::ops::BitAnd;
600 /// impl BitAnd for Foo {
601 /// type Output = Foo;
603 /// fn bitand(self, _rhs: Foo) -> Foo {
604 /// println!("Bitwise And-ing!");
614 #[stable(feature = "rust1", since = "1.0.0")]
615 pub trait BitAnd<RHS=Self> {
616 /// The resulting type after applying the `&` operator
617 #[stable(feature = "rust1", since = "1.0.0")]
620 /// The method for the `&` operator
621 #[stable(feature = "rust1", since = "1.0.0")]
622 fn bitand(self, rhs: RHS) -> Self::Output;
625 macro_rules! bitand_impl {
627 #[stable(feature = "rust1", since = "1.0.0")]
632 fn bitand(self, rhs: $t) -> $t { self & rhs }
635 forward_ref_binop! { impl BitAnd, bitand for $t, $t }
639 bitand_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
641 /// The `BitOr` trait is used to specify the functionality of `|`.
645 /// A trivial implementation of `BitOr`. When `Foo | Foo` happens, it ends up
646 /// calling `bitor`, and therefore, `main` prints `Bitwise Or-ing!`.
649 /// use std::ops::BitOr;
653 /// impl BitOr for Foo {
654 /// type Output = Foo;
656 /// fn bitor(self, _rhs: Foo) -> Foo {
657 /// println!("Bitwise Or-ing!");
667 #[stable(feature = "rust1", since = "1.0.0")]
668 pub trait BitOr<RHS=Self> {
669 /// The resulting type after applying the `|` operator
670 #[stable(feature = "rust1", since = "1.0.0")]
673 /// The method for the `|` operator
674 #[stable(feature = "rust1", since = "1.0.0")]
675 fn bitor(self, rhs: RHS) -> Self::Output;
678 macro_rules! bitor_impl {
680 #[stable(feature = "rust1", since = "1.0.0")]
685 fn bitor(self, rhs: $t) -> $t { self | rhs }
688 forward_ref_binop! { impl BitOr, bitor for $t, $t }
692 bitor_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
694 /// The `BitXor` trait is used to specify the functionality of `^`.
698 /// A trivial implementation of `BitXor`. When `Foo ^ Foo` happens, it ends up
699 /// calling `bitxor`, and therefore, `main` prints `Bitwise Xor-ing!`.
702 /// use std::ops::BitXor;
706 /// impl BitXor for Foo {
707 /// type Output = Foo;
709 /// fn bitxor(self, _rhs: Foo) -> Foo {
710 /// println!("Bitwise Xor-ing!");
720 #[stable(feature = "rust1", since = "1.0.0")]
721 pub trait BitXor<RHS=Self> {
722 /// The resulting type after applying the `^` operator
723 #[stable(feature = "rust1", since = "1.0.0")]
726 /// The method for the `^` operator
727 #[stable(feature = "rust1", since = "1.0.0")]
728 fn bitxor(self, rhs: RHS) -> Self::Output;
731 macro_rules! bitxor_impl {
733 #[stable(feature = "rust1", since = "1.0.0")]
738 fn bitxor(self, other: $t) -> $t { self ^ other }
741 forward_ref_binop! { impl BitXor, bitxor for $t, $t }
745 bitxor_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
747 /// The `Shl` trait is used to specify the functionality of `<<`.
751 /// A trivial implementation of `Shl`. When `Foo << Foo` happens, it ends up
752 /// calling `shl`, and therefore, `main` prints `Shifting left!`.
755 /// use std::ops::Shl;
759 /// impl Shl<Foo> for Foo {
760 /// type Output = Foo;
762 /// fn shl(self, _rhs: Foo) -> Foo {
763 /// println!("Shifting left!");
773 #[stable(feature = "rust1", since = "1.0.0")]
775 /// The resulting type after applying the `<<` operator
776 #[stable(feature = "rust1", since = "1.0.0")]
779 /// The method for the `<<` operator
780 #[stable(feature = "rust1", since = "1.0.0")]
781 fn shl(self, rhs: RHS) -> Self::Output;
784 macro_rules! shl_impl {
786 #[stable(feature = "rust1", since = "1.0.0")]
787 impl Shl<$f> for $t {
791 fn shl(self, other: $f) -> $t {
796 forward_ref_binop! { impl Shl, shl for $t, $f }
800 macro_rules! shl_impl_all {
803 shl_impl! { $t, u16 }
804 shl_impl! { $t, u32 }
805 shl_impl! { $t, u64 }
806 shl_impl! { $t, usize }
809 shl_impl! { $t, i16 }
810 shl_impl! { $t, i32 }
811 shl_impl! { $t, i64 }
812 shl_impl! { $t, isize }
816 shl_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
818 /// The `Shr` trait is used to specify the functionality of `>>`.
822 /// A trivial implementation of `Shr`. When `Foo >> Foo` happens, it ends up
823 /// calling `shr`, and therefore, `main` prints `Shifting right!`.
826 /// use std::ops::Shr;
830 /// impl Shr<Foo> for Foo {
831 /// type Output = Foo;
833 /// fn shr(self, _rhs: Foo) -> Foo {
834 /// println!("Shifting right!");
844 #[stable(feature = "rust1", since = "1.0.0")]
846 /// The resulting type after applying the `>>` operator
847 #[stable(feature = "rust1", since = "1.0.0")]
850 /// The method for the `>>` operator
851 #[stable(feature = "rust1", since = "1.0.0")]
852 fn shr(self, rhs: RHS) -> Self::Output;
855 macro_rules! shr_impl {
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl Shr<$f> for $t {
862 fn shr(self, other: $f) -> $t {
867 forward_ref_binop! { impl Shr, shr for $t, $f }
871 macro_rules! shr_impl_all {
874 shr_impl! { $t, u16 }
875 shr_impl! { $t, u32 }
876 shr_impl! { $t, u64 }
877 shr_impl! { $t, usize }
880 shr_impl! { $t, i16 }
881 shr_impl! { $t, i32 }
882 shr_impl! { $t, i64 }
883 shr_impl! { $t, isize }
887 shr_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
889 /// The `AddAssign` trait is used to specify the functionality of `+=`.
893 /// A trivial implementation of `AddAssign`. When `Foo += Foo` happens, it ends up
894 /// calling `add_assign`, and therefore, `main` prints `Adding!`.
897 /// use std::ops::AddAssign;
901 /// impl AddAssign for Foo {
902 /// fn add_assign(&mut self, _rhs: Foo) {
903 /// println!("Adding!");
907 /// # #[allow(unused_assignments)]
909 /// let mut foo = Foo;
913 #[lang = "add_assign"]
914 #[stable(feature = "op_assign_traits", since = "1.8.0")]
915 pub trait AddAssign<Rhs=Self> {
916 /// The method for the `+=` operator
917 #[stable(feature = "op_assign_traits", since = "1.8.0")]
918 fn add_assign(&mut self, Rhs);
921 macro_rules! add_assign_impl {
923 #[stable(feature = "op_assign_traits", since = "1.8.0")]
924 impl AddAssign for $t {
926 fn add_assign(&mut self, other: $t) { *self += other }
931 add_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
933 /// The `SubAssign` trait is used to specify the functionality of `-=`.
937 /// A trivial implementation of `SubAssign`. When `Foo -= Foo` happens, it ends up
938 /// calling `sub_assign`, and therefore, `main` prints `Subtracting!`.
941 /// use std::ops::SubAssign;
945 /// impl SubAssign for Foo {
946 /// fn sub_assign(&mut self, _rhs: Foo) {
947 /// println!("Subtracting!");
951 /// # #[allow(unused_assignments)]
953 /// let mut foo = Foo;
957 #[lang = "sub_assign"]
958 #[stable(feature = "op_assign_traits", since = "1.8.0")]
959 pub trait SubAssign<Rhs=Self> {
960 /// The method for the `-=` operator
961 #[stable(feature = "op_assign_traits", since = "1.8.0")]
962 fn sub_assign(&mut self, Rhs);
965 macro_rules! sub_assign_impl {
967 #[stable(feature = "op_assign_traits", since = "1.8.0")]
968 impl SubAssign for $t {
970 fn sub_assign(&mut self, other: $t) { *self -= other }
975 sub_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
977 /// The `MulAssign` trait is used to specify the functionality of `*=`.
981 /// A trivial implementation of `MulAssign`. When `Foo *= Foo` happens, it ends up
982 /// calling `mul_assign`, and therefore, `main` prints `Multiplying!`.
985 /// use std::ops::MulAssign;
989 /// impl MulAssign for Foo {
990 /// fn mul_assign(&mut self, _rhs: Foo) {
991 /// println!("Multiplying!");
995 /// # #[allow(unused_assignments)]
997 /// let mut foo = Foo;
1001 #[lang = "mul_assign"]
1002 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1003 pub trait MulAssign<Rhs=Self> {
1004 /// The method for the `*=` operator
1005 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1006 fn mul_assign(&mut self, Rhs);
1009 macro_rules! mul_assign_impl {
1011 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1012 impl MulAssign for $t {
1014 fn mul_assign(&mut self, other: $t) { *self *= other }
1019 mul_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1021 /// The `DivAssign` trait is used to specify the functionality of `/=`.
1025 /// A trivial implementation of `DivAssign`. When `Foo /= Foo` happens, it ends up
1026 /// calling `div_assign`, and therefore, `main` prints `Dividing!`.
1029 /// use std::ops::DivAssign;
1033 /// impl DivAssign for Foo {
1034 /// fn div_assign(&mut self, _rhs: Foo) {
1035 /// println!("Dividing!");
1039 /// # #[allow(unused_assignments)]
1041 /// let mut foo = Foo;
1045 #[lang = "div_assign"]
1046 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1047 pub trait DivAssign<Rhs=Self> {
1048 /// The method for the `/=` operator
1049 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1050 fn div_assign(&mut self, Rhs);
1053 macro_rules! div_assign_impl {
1055 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1056 impl DivAssign for $t {
1058 fn div_assign(&mut self, other: $t) { *self /= other }
1063 div_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1065 /// The `RemAssign` trait is used to specify the functionality of `%=`.
1069 /// A trivial implementation of `RemAssign`. When `Foo %= Foo` happens, it ends up
1070 /// calling `rem_assign`, and therefore, `main` prints `Remainder-ing!`.
1073 /// use std::ops::RemAssign;
1077 /// impl RemAssign for Foo {
1078 /// fn rem_assign(&mut self, _rhs: Foo) {
1079 /// println!("Remainder-ing!");
1083 /// # #[allow(unused_assignments)]
1085 /// let mut foo = Foo;
1089 #[lang = "rem_assign"]
1090 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1091 pub trait RemAssign<Rhs=Self> {
1092 /// The method for the `%=` operator
1093 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1094 fn rem_assign(&mut self, Rhs);
1097 macro_rules! rem_assign_impl {
1099 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1100 impl RemAssign for $t {
1102 fn rem_assign(&mut self, other: $t) { *self %= other }
1107 rem_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1109 /// The `BitAndAssign` trait is used to specify the functionality of `&=`.
1113 /// A trivial implementation of `BitAndAssign`. When `Foo &= Foo` happens, it ends up
1114 /// calling `bitand_assign`, and therefore, `main` prints `Bitwise And-ing!`.
1117 /// use std::ops::BitAndAssign;
1121 /// impl BitAndAssign for Foo {
1122 /// fn bitand_assign(&mut self, _rhs: Foo) {
1123 /// println!("Bitwise And-ing!");
1127 /// # #[allow(unused_assignments)]
1129 /// let mut foo = Foo;
1133 #[lang = "bitand_assign"]
1134 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1135 pub trait BitAndAssign<Rhs=Self> {
1136 /// The method for the `&` operator
1137 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1138 fn bitand_assign(&mut self, Rhs);
1141 macro_rules! bitand_assign_impl {
1143 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1144 impl BitAndAssign for $t {
1146 fn bitand_assign(&mut self, other: $t) { *self &= other }
1151 bitand_assign_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1153 /// The `BitOrAssign` trait is used to specify the functionality of `|=`.
1157 /// A trivial implementation of `BitOrAssign`. When `Foo |= Foo` happens, it ends up
1158 /// calling `bitor_assign`, and therefore, `main` prints `Bitwise Or-ing!`.
1161 /// use std::ops::BitOrAssign;
1165 /// impl BitOrAssign for Foo {
1166 /// fn bitor_assign(&mut self, _rhs: Foo) {
1167 /// println!("Bitwise Or-ing!");
1171 /// # #[allow(unused_assignments)]
1173 /// let mut foo = Foo;
1177 #[lang = "bitor_assign"]
1178 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1179 pub trait BitOrAssign<Rhs=Self> {
1180 /// The method for the `|=` operator
1181 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1182 fn bitor_assign(&mut self, Rhs);
1185 macro_rules! bitor_assign_impl {
1187 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1188 impl BitOrAssign for $t {
1190 fn bitor_assign(&mut self, other: $t) { *self |= other }
1195 bitor_assign_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1197 /// The `BitXorAssign` trait is used to specify the functionality of `^=`.
1201 /// A trivial implementation of `BitXorAssign`. When `Foo ^= Foo` happens, it ends up
1202 /// calling `bitxor_assign`, and therefore, `main` prints `Bitwise Xor-ing!`.
1205 /// use std::ops::BitXorAssign;
1209 /// impl BitXorAssign for Foo {
1210 /// fn bitxor_assign(&mut self, _rhs: Foo) {
1211 /// println!("Bitwise Xor-ing!");
1215 /// # #[allow(unused_assignments)]
1217 /// let mut foo = Foo;
1221 #[lang = "bitxor_assign"]
1222 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1223 pub trait BitXorAssign<Rhs=Self> {
1224 /// The method for the `^=` operator
1225 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1226 fn bitxor_assign(&mut self, Rhs);
1229 macro_rules! bitxor_assign_impl {
1231 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1232 impl BitXorAssign for $t {
1234 fn bitxor_assign(&mut self, other: $t) { *self ^= other }
1239 bitxor_assign_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1241 /// The `ShlAssign` trait is used to specify the functionality of `<<=`.
1245 /// A trivial implementation of `ShlAssign`. When `Foo <<= Foo` happens, it ends up
1246 /// calling `shl_assign`, and therefore, `main` prints `Shifting left!`.
1249 /// use std::ops::ShlAssign;
1253 /// impl ShlAssign<Foo> for Foo {
1254 /// fn shl_assign(&mut self, _rhs: Foo) {
1255 /// println!("Shifting left!");
1259 /// # #[allow(unused_assignments)]
1261 /// let mut foo = Foo;
1265 #[lang = "shl_assign"]
1266 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1267 pub trait ShlAssign<Rhs> {
1268 /// The method for the `<<=` operator
1269 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1270 fn shl_assign(&mut self, Rhs);
1273 macro_rules! shl_assign_impl {
1275 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1276 impl ShlAssign<$f> for $t {
1278 fn shl_assign(&mut self, other: $f) {
1285 macro_rules! shl_assign_impl_all {
1287 shl_assign_impl! { $t, u8 }
1288 shl_assign_impl! { $t, u16 }
1289 shl_assign_impl! { $t, u32 }
1290 shl_assign_impl! { $t, u64 }
1291 shl_assign_impl! { $t, usize }
1293 shl_assign_impl! { $t, i8 }
1294 shl_assign_impl! { $t, i16 }
1295 shl_assign_impl! { $t, i32 }
1296 shl_assign_impl! { $t, i64 }
1297 shl_assign_impl! { $t, isize }
1301 shl_assign_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
1303 /// The `ShrAssign` trait is used to specify the functionality of `>>=`.
1307 /// A trivial implementation of `ShrAssign`. When `Foo >>= Foo` happens, it ends up
1308 /// calling `shr_assign`, and therefore, `main` prints `Shifting right!`.
1311 /// use std::ops::ShrAssign;
1315 /// impl ShrAssign<Foo> for Foo {
1316 /// fn shr_assign(&mut self, _rhs: Foo) {
1317 /// println!("Shifting right!");
1321 /// # #[allow(unused_assignments)]
1323 /// let mut foo = Foo;
1327 #[lang = "shr_assign"]
1328 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1329 pub trait ShrAssign<Rhs=Self> {
1330 /// The method for the `>>=` operator
1331 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1332 fn shr_assign(&mut self, Rhs);
1335 macro_rules! shr_assign_impl {
1337 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1338 impl ShrAssign<$f> for $t {
1340 fn shr_assign(&mut self, other: $f) {
1347 macro_rules! shr_assign_impl_all {
1349 shr_assign_impl! { $t, u8 }
1350 shr_assign_impl! { $t, u16 }
1351 shr_assign_impl! { $t, u32 }
1352 shr_assign_impl! { $t, u64 }
1353 shr_assign_impl! { $t, usize }
1355 shr_assign_impl! { $t, i8 }
1356 shr_assign_impl! { $t, i16 }
1357 shr_assign_impl! { $t, i32 }
1358 shr_assign_impl! { $t, i64 }
1359 shr_assign_impl! { $t, isize }
1363 shr_assign_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
1365 /// The `Index` trait is used to specify the functionality of indexing operations
1366 /// like `arr[idx]` when used in an immutable context.
1370 /// A trivial implementation of `Index`. When `Foo[Bar]` happens, it ends up
1371 /// calling `index`, and therefore, `main` prints `Indexing!`.
1374 /// use std::ops::Index;
1376 /// #[derive(Copy, Clone)]
1380 /// impl Index<Bar> for Foo {
1381 /// type Output = Foo;
1383 /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
1384 /// println!("Indexing!");
1394 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 pub trait Index<Idx: ?Sized> {
1397 /// The returned type after indexing
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 type Output: ?Sized;
1401 /// The method for the indexing (`Foo[Bar]`) operation
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 fn index(&self, index: Idx) -> &Self::Output;
1406 /// The `IndexMut` trait is used to specify the functionality of indexing
1407 /// operations like `arr[idx]`, when used in a mutable context.
1411 /// A trivial implementation of `IndexMut`. When `Foo[Bar]` happens, it ends up
1412 /// calling `index_mut`, and therefore, `main` prints `Indexing!`.
1415 /// use std::ops::{Index, IndexMut};
1417 /// #[derive(Copy, Clone)]
1421 /// impl Index<Bar> for Foo {
1422 /// type Output = Foo;
1424 /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
1429 /// impl IndexMut<Bar> for Foo {
1430 /// fn index_mut<'a>(&'a mut self, _index: Bar) -> &'a mut Foo {
1431 /// println!("Indexing!");
1440 #[lang = "index_mut"]
1441 #[rustc_on_unimplemented = "the type `{Self}` cannot be mutably indexed by `{Idx}`"]
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 pub trait IndexMut<Idx: ?Sized>: Index<Idx> {
1444 /// The method for the indexing (`Foo[Bar]`) operation
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 fn index_mut(&mut self, index: Idx) -> &mut Self::Output;
1449 /// An unbounded range. Use `..` (two dots) for its shorthand.
1451 /// Its primary use case is slicing index. It cannot serve as an iterator
1452 /// because it doesn't have a starting point.
1458 /// assert_eq!((..), std::ops::RangeFull);
1460 /// let arr = [0, 1, 2, 3];
1461 /// assert_eq!(arr[ .. ], [0,1,2,3]); // RangeFull
1462 /// assert_eq!(arr[ ..3], [0,1,2 ]);
1463 /// assert_eq!(arr[1.. ], [ 1,2,3]);
1464 /// assert_eq!(arr[1..3], [ 1,2 ]);
1467 #[derive(Copy, Clone, PartialEq, Eq)]
1468 #[stable(feature = "rust1", since = "1.0.0")]
1469 pub struct RangeFull;
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 impl fmt::Debug for RangeFull {
1473 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1478 /// A (half-open) range which is bounded at both ends: { x | start <= x < end }.
1479 /// Use `start..end` (two dots) for its shorthand.
1481 /// See the [`contains()`](#method.contains) method for its characterization.
1486 /// #![feature(iter_arith)]
1488 /// assert_eq!((3..5), std::ops::Range{ start: 3, end: 5 });
1489 /// assert_eq!(3+4+5, (3..6).sum());
1491 /// let arr = [0, 1, 2, 3];
1492 /// assert_eq!(arr[ .. ], [0,1,2,3]);
1493 /// assert_eq!(arr[ ..3], [0,1,2 ]);
1494 /// assert_eq!(arr[1.. ], [ 1,2,3]);
1495 /// assert_eq!(arr[1..3], [ 1,2 ]); // Range
1498 #[derive(Clone, PartialEq, Eq)]
1499 #[stable(feature = "rust1", since = "1.0.0")]
1500 pub struct Range<Idx> {
1501 /// The lower bound of the range (inclusive).
1502 #[stable(feature = "rust1", since = "1.0.0")]
1504 /// The upper bound of the range (exclusive).
1505 #[stable(feature = "rust1", since = "1.0.0")]
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
1511 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1512 write!(fmt, "{:?}..{:?}", self.start, self.end)
1516 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1517 impl<Idx: PartialOrd<Idx>> Range<Idx> {
1521 /// #![feature(range_contains)]
1523 /// assert!( ! (3..5).contains(2));
1524 /// assert!( (3..5).contains(3));
1525 /// assert!( (3..5).contains(4));
1526 /// assert!( ! (3..5).contains(5));
1528 /// assert!( ! (3..3).contains(3));
1529 /// assert!( ! (3..2).contains(3));
1532 pub fn contains(&self, item: Idx) -> bool {
1533 (self.start <= item) && (item < self.end)
1537 /// A range which is only bounded below: { x | start <= x }.
1538 /// Use `start..` for its shorthand.
1540 /// See the [`contains()`](#method.contains) method for its characterization.
1545 /// #![feature(iter_arith)]
1547 /// assert_eq!((2..), std::ops::RangeFrom{ start: 2 });
1548 /// assert_eq!(2+3+4, (2..).take(3).sum());
1550 /// let arr = [0, 1, 2, 3];
1551 /// assert_eq!(arr[ .. ], [0,1,2,3]);
1552 /// assert_eq!(arr[ ..3], [0,1,2 ]);
1553 /// assert_eq!(arr[1.. ], [ 1,2,3]); // RangeFrom
1554 /// assert_eq!(arr[1..3], [ 1,2 ]);
1557 #[derive(Clone, PartialEq, Eq)]
1558 #[stable(feature = "rust1", since = "1.0.0")]
1559 pub struct RangeFrom<Idx> {
1560 /// The lower bound of the range (inclusive).
1561 #[stable(feature = "rust1", since = "1.0.0")]
1565 #[stable(feature = "rust1", since = "1.0.0")]
1566 impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
1567 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1568 write!(fmt, "{:?}..", self.start)
1572 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1573 impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
1577 /// #![feature(range_contains)]
1579 /// assert!( ! (3..).contains(2));
1580 /// assert!( (3..).contains(3));
1581 /// assert!( (3..).contains(1_000_000_000));
1584 pub fn contains(&self, item: Idx) -> bool {
1585 (self.start <= item)
1589 /// A range which is only bounded above: { x | x < end }.
1590 /// Use `..end` (two dots) for its shorthand.
1592 /// See the [`contains()`](#method.contains) method for its characterization.
1594 /// It cannot serve as an iterator because it doesn't have a starting point.
1597 /// assert_eq!((..5), std::ops::RangeTo{ end: 5 });
1599 /// let arr = [0, 1, 2, 3];
1600 /// assert_eq!(arr[ .. ], [0,1,2,3]);
1601 /// assert_eq!(arr[ ..3], [0,1,2 ]); // RangeTo
1602 /// assert_eq!(arr[1.. ], [ 1,2,3]);
1603 /// assert_eq!(arr[1..3], [ 1,2 ]);
1606 #[derive(Copy, Clone, PartialEq, Eq)]
1607 #[stable(feature = "rust1", since = "1.0.0")]
1608 pub struct RangeTo<Idx> {
1609 /// The upper bound of the range (exclusive).
1610 #[stable(feature = "rust1", since = "1.0.0")]
1614 #[stable(feature = "rust1", since = "1.0.0")]
1615 impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> {
1616 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1617 write!(fmt, "..{:?}", self.end)
1621 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1622 impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
1626 /// #![feature(range_contains)]
1628 /// assert!( (..5).contains(-1_000_000_000));
1629 /// assert!( (..5).contains(4));
1630 /// assert!( ! (..5).contains(5));
1633 pub fn contains(&self, item: Idx) -> bool {
1638 /// An inclusive range which is bounded at both ends: { x | start <= x <= end }.
1639 /// Use `start...end` (three dots) for its shorthand.
1641 /// See the [`contains()`](#method.contains) method for its characterization.
1646 /// #![feature(inclusive_range,inclusive_range_syntax,iter_arith)]
1648 /// assert_eq!((3...5), std::ops::RangeInclusive::NonEmpty{ start: 3, end: 5 });
1649 /// assert_eq!(3+4+5, (3...5).sum());
1651 /// let arr = [0, 1, 2, 3];
1652 /// assert_eq!(arr[ ...2], [0,1,2 ]);
1653 /// assert_eq!(arr[1...2], [ 1,2 ]); // RangeInclusive
1656 #[derive(Copy, Clone, PartialEq, Eq)]
1657 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1658 pub enum RangeInclusive<Idx> {
1659 /// Empty range (iteration has finished)
1660 #[unstable(feature = "inclusive_range",
1661 reason = "recently added, follows RFC",
1664 /// The point at which iteration finished
1665 #[unstable(feature = "inclusive_range",
1666 reason = "recently added, follows RFC",
1670 /// Non-empty range (iteration will yield value(s))
1671 #[unstable(feature = "inclusive_range",
1672 reason = "recently added, follows RFC",
1675 /// The lower bound of the range (inclusive).
1676 #[unstable(feature = "inclusive_range",
1677 reason = "recently added, follows RFC",
1680 /// The upper bound of the range (inclusive).
1681 #[unstable(feature = "inclusive_range",
1682 reason = "recently added, follows RFC",
1688 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1689 impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
1690 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1691 use self::RangeInclusive::*;
1694 Empty { ref at } => write!(fmt, "[empty range @ {:?}]", at),
1695 NonEmpty { ref start, ref end } => write!(fmt, "{:?}...{:?}", start, end),
1700 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1701 impl<Idx: PartialOrd + One + Sub<Output=Idx>> From<Range<Idx>> for RangeInclusive<Idx> {
1702 fn from(range: Range<Idx>) -> RangeInclusive<Idx> {
1703 use self::RangeInclusive::*;
1705 if range.start < range.end {
1708 end: range.end - Idx::one() // can't underflow because end > start >= MIN
1718 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1719 impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
1723 /// #![feature(range_contains,inclusive_range_syntax)]
1725 /// assert!( ! (3...5).contains(2));
1726 /// assert!( (3...5).contains(3));
1727 /// assert!( (3...5).contains(4));
1728 /// assert!( (3...5).contains(5));
1729 /// assert!( ! (3...5).contains(6));
1731 /// assert!( (3...3).contains(3));
1732 /// assert!( ! (3...2).contains(3));
1735 pub fn contains(&self, item: Idx) -> bool {
1736 if let &RangeInclusive::NonEmpty{ref start, ref end} = self {
1737 (*start <= item) && (item <= *end)
1742 /// An inclusive range which is only bounded above: { x | x <= end }.
1743 /// Use `...end` (three dots) for its shorthand.
1745 /// See the [`contains()`](#method.contains) method for its characterization.
1747 /// It cannot serve as an iterator because it doesn't have a starting point.
1752 /// #![feature(inclusive_range,inclusive_range_syntax)]
1754 /// assert_eq!((...5), std::ops::RangeToInclusive{ end: 5 });
1756 /// let arr = [0, 1, 2, 3];
1757 /// assert_eq!(arr[ ...2], [0,1,2 ]); // RangeToInclusive
1758 /// assert_eq!(arr[1...2], [ 1,2 ]);
1761 #[derive(Copy, Clone, PartialEq, Eq)]
1762 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1763 pub struct RangeToInclusive<Idx> {
1764 /// The upper bound of the range (inclusive)
1765 #[unstable(feature = "inclusive_range",
1766 reason = "recently added, follows RFC",
1771 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1772 impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
1773 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1774 write!(fmt, "...{:?}", self.end)
1778 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1779 impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
1783 /// #![feature(range_contains,inclusive_range_syntax)]
1785 /// assert!( (...5).contains(-1_000_000_000));
1786 /// assert!( (...5).contains(5));
1787 /// assert!( ! (...5).contains(6));
1790 pub fn contains(&self, item: Idx) -> bool {
1795 // RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
1796 // because underflow would be possible with (..0).into()
1798 /// The `Deref` trait is used to specify the functionality of dereferencing
1799 /// operations, like `*v`.
1801 /// `Deref` also enables ['`Deref` coercions'][coercions].
1803 /// [coercions]: ../../book/deref-coercions.html
1807 /// A struct with a single field which is accessible via dereferencing the
1811 /// use std::ops::Deref;
1813 /// struct DerefExample<T> {
1817 /// impl<T> Deref for DerefExample<T> {
1818 /// type Target = T;
1820 /// fn deref(&self) -> &T {
1826 /// let x = DerefExample { value: 'a' };
1827 /// assert_eq!('a', *x);
1831 #[stable(feature = "rust1", since = "1.0.0")]
1833 /// The resulting type after dereferencing
1834 #[stable(feature = "rust1", since = "1.0.0")]
1835 type Target: ?Sized;
1837 /// The method called to dereference a value
1838 #[stable(feature = "rust1", since = "1.0.0")]
1839 fn deref(&self) -> &Self::Target;
1842 #[stable(feature = "rust1", since = "1.0.0")]
1843 impl<'a, T: ?Sized> Deref for &'a T {
1846 fn deref(&self) -> &T { *self }
1849 #[stable(feature = "rust1", since = "1.0.0")]
1850 impl<'a, T: ?Sized> Deref for &'a mut T {
1853 fn deref(&self) -> &T { *self }
1856 /// The `DerefMut` trait is used to specify the functionality of dereferencing
1857 /// mutably like `*v = 1;`
1859 /// `DerefMut` also enables ['`Deref` coercions'][coercions].
1861 /// [coercions]: ../../book/deref-coercions.html
1865 /// A struct with a single field which is modifiable via dereferencing the
1869 /// use std::ops::{Deref, DerefMut};
1871 /// struct DerefMutExample<T> {
1875 /// impl<T> Deref for DerefMutExample<T> {
1876 /// type Target = T;
1878 /// fn deref<'a>(&'a self) -> &'a T {
1883 /// impl<T> DerefMut for DerefMutExample<T> {
1884 /// fn deref_mut<'a>(&'a mut self) -> &'a mut T {
1890 /// let mut x = DerefMutExample { value: 'a' };
1892 /// assert_eq!('b', *x);
1895 #[lang = "deref_mut"]
1896 #[stable(feature = "rust1", since = "1.0.0")]
1897 pub trait DerefMut: Deref {
1898 /// The method called to mutably dereference a value
1899 #[stable(feature = "rust1", since = "1.0.0")]
1900 fn deref_mut(&mut self) -> &mut Self::Target;
1903 #[stable(feature = "rust1", since = "1.0.0")]
1904 impl<'a, T: ?Sized> DerefMut for &'a mut T {
1905 fn deref_mut(&mut self) -> &mut T { *self }
1908 /// A version of the call operator that takes an immutable receiver.
1910 #[stable(feature = "rust1", since = "1.0.0")]
1911 #[rustc_paren_sugar]
1912 #[fundamental] // so that regex can rely that `&str: !FnMut`
1913 pub trait Fn<Args> : FnMut<Args> {
1914 /// This is called when the call operator is used.
1915 #[unstable(feature = "fn_traits", issue = "29625")]
1916 extern "rust-call" fn call(&self, args: Args) -> Self::Output;
1919 /// A version of the call operator that takes a mutable receiver.
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 #[rustc_paren_sugar]
1923 #[fundamental] // so that regex can rely that `&str: !FnMut`
1924 pub trait FnMut<Args> : FnOnce<Args> {
1925 /// This is called when the call operator is used.
1926 #[unstable(feature = "fn_traits", issue = "29625")]
1927 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
1930 /// A version of the call operator that takes a by-value receiver.
1932 #[stable(feature = "rust1", since = "1.0.0")]
1933 #[rustc_paren_sugar]
1934 #[fundamental] // so that regex can rely that `&str: !FnMut`
1935 pub trait FnOnce<Args> {
1936 /// The returned type after the call operator is used.
1937 #[unstable(feature = "fn_traits", issue = "29625")]
1940 /// This is called when the call operator is used.
1941 #[unstable(feature = "fn_traits", issue = "29625")]
1942 extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
1947 use super::{Fn, FnMut, FnOnce};
1949 #[stable(feature = "rust1", since = "1.0.0")]
1950 impl<'a,A,F:?Sized> Fn<A> for &'a F
1953 extern "rust-call" fn call(&self, args: A) -> F::Output {
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 impl<'a,A,F:?Sized> FnMut<A> for &'a F
1962 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
1967 #[stable(feature = "rust1", since = "1.0.0")]
1968 impl<'a,A,F:?Sized> FnOnce<A> for &'a F
1971 type Output = F::Output;
1973 extern "rust-call" fn call_once(self, args: A) -> F::Output {
1978 #[stable(feature = "rust1", since = "1.0.0")]
1979 impl<'a,A,F:?Sized> FnMut<A> for &'a mut F
1982 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
1983 (*self).call_mut(args)
1987 #[stable(feature = "rust1", since = "1.0.0")]
1988 impl<'a,A,F:?Sized> FnOnce<A> for &'a mut F
1991 type Output = F::Output;
1992 extern "rust-call" fn call_once(mut self, args: A) -> F::Output {
1993 (*self).call_mut(args)
1998 /// Trait that indicates that this is a pointer or a wrapper for one,
1999 /// where unsizing can be performed on the pointee.
2000 #[unstable(feature = "coerce_unsized", issue = "27732")]
2001 #[lang="coerce_unsized"]
2002 pub trait CoerceUnsized<T> {
2007 #[unstable(feature = "coerce_unsized", issue = "27732")]
2008 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a mut U> for &'a mut T {}
2010 #[unstable(feature = "coerce_unsized", issue = "27732")]
2011 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b mut T {}
2013 #[unstable(feature = "coerce_unsized", issue = "27732")]
2014 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for &'a mut T {}
2015 // &mut T -> *const U
2016 #[unstable(feature = "coerce_unsized", issue = "27732")]
2017 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a mut T {}
2020 #[unstable(feature = "coerce_unsized", issue = "27732")]
2021 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b T {}
2023 #[unstable(feature = "coerce_unsized", issue = "27732")]
2024 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a T {}
2027 #[unstable(feature = "coerce_unsized", issue = "27732")]
2028 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for *mut T {}
2029 // *mut T -> *const U
2030 #[unstable(feature = "coerce_unsized", issue = "27732")]
2031 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *mut T {}
2033 // *const T -> *const U
2034 #[unstable(feature = "coerce_unsized", issue = "27732")]
2035 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *const T {}
2037 /// Both `in (PLACE) EXPR` and `box EXPR` desugar into expressions
2038 /// that allocate an intermediate "place" that holds uninitialized
2039 /// state. The desugaring evaluates EXPR, and writes the result at
2040 /// the address returned by the `pointer` method of this trait.
2042 /// A `Place` can be thought of as a special representation for a
2043 /// hypothetical `&uninit` reference (which Rust cannot currently
2044 /// express directly). That is, it represents a pointer to
2045 /// uninitialized storage.
2047 /// The client is responsible for two steps: First, initializing the
2048 /// payload (it can access its address via `pointer`). Second,
2049 /// converting the agent to an instance of the owning pointer, via the
2050 /// appropriate `finalize` method (see the `InPlace`.
2052 /// If evaluating EXPR fails, then the destructor for the
2053 /// implementation of Place to clean up any intermediate state
2054 /// (e.g. deallocate box storage, pop a stack, etc).
2055 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2056 pub trait Place<Data: ?Sized> {
2057 /// Returns the address where the input value will be written.
2058 /// Note that the data at this address is generally uninitialized,
2059 /// and thus one should use `ptr::write` for initializing it.
2060 fn pointer(&mut self) -> *mut Data;
2063 /// Interface to implementations of `in (PLACE) EXPR`.
2065 /// `in (PLACE) EXPR` effectively desugars into:
2069 /// let mut place = Placer::make_place(p);
2070 /// let raw_place = Place::pointer(&mut place);
2071 /// let value = EXPR;
2073 /// std::ptr::write(raw_place, value);
2074 /// InPlace::finalize(place)
2078 /// The type of `in (PLACE) EXPR` is derived from the type of `PLACE`;
2079 /// if the type of `PLACE` is `P`, then the final type of the whole
2080 /// expression is `P::Place::Owner` (see the `InPlace` and `Boxed`
2083 /// Values for types implementing this trait usually are transient
2084 /// intermediate values (e.g. the return value of `Vec::emplace_back`)
2085 /// or `Copy`, since the `make_place` method takes `self` by value.
2086 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2087 pub trait Placer<Data: ?Sized> {
2088 /// `Place` is the intermedate agent guarding the
2089 /// uninitialized state for `Data`.
2090 type Place: InPlace<Data>;
2092 /// Creates a fresh place from `self`.
2093 fn make_place(self) -> Self::Place;
2096 /// Specialization of `Place` trait supporting `in (PLACE) EXPR`.
2097 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2098 pub trait InPlace<Data: ?Sized>: Place<Data> {
2099 /// `Owner` is the type of the end value of `in (PLACE) EXPR`
2101 /// Note that when `in (PLACE) EXPR` is solely used for
2102 /// side-effecting an existing data-structure,
2103 /// e.g. `Vec::emplace_back`, then `Owner` need not carry any
2104 /// information at all (e.g. it can be the unit type `()` in that
2108 /// Converts self into the final value, shifting
2109 /// deallocation/cleanup responsibilities (if any remain), over to
2110 /// the returned instance of `Owner` and forgetting self.
2111 unsafe fn finalize(self) -> Self::Owner;
2114 /// Core trait for the `box EXPR` form.
2116 /// `box EXPR` effectively desugars into:
2119 /// let mut place = BoxPlace::make_place();
2120 /// let raw_place = Place::pointer(&mut place);
2121 /// let value = EXPR;
2123 /// ::std::ptr::write(raw_place, value);
2124 /// Boxed::finalize(place)
2128 /// The type of `box EXPR` is supplied from its surrounding
2129 /// context; in the above expansion, the result type `T` is used
2130 /// to determine which implementation of `Boxed` to use, and that
2131 /// `<T as Boxed>` in turn dictates determines which
2132 /// implementation of `BoxPlace` to use, namely:
2133 /// `<<T as Boxed>::Place as BoxPlace>`.
2134 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2136 /// The kind of data that is stored in this kind of box.
2137 type Data; /* (`Data` unused b/c cannot yet express below bound.) */
2138 /// The place that will negotiate the storage of the data.
2139 type Place: BoxPlace<Self::Data>;
2141 /// Converts filled place into final owning value, shifting
2142 /// deallocation/cleanup responsibilities (if any remain), over to
2143 /// returned instance of `Self` and forgetting `filled`.
2144 unsafe fn finalize(filled: Self::Place) -> Self;
2147 /// Specialization of `Place` trait supporting `box EXPR`.
2148 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2149 pub trait BoxPlace<Data: ?Sized> : Place<Data> {
2150 /// Creates a globally fresh place.
2151 fn make_place() -> Self;