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")]
70 use marker::{Sized, Unsize};
73 /// The `Drop` trait is used to run some code when a value goes out of scope.
74 /// This is sometimes called a 'destructor'.
78 /// A trivial implementation of `Drop`. The `drop` method is called when `_x`
79 /// goes out of scope, and therefore `main` prints `Dropping!`.
84 /// impl Drop for HasDrop {
85 /// fn drop(&mut self) {
86 /// println!("Dropping!");
95 #[stable(feature = "rust1", since = "1.0.0")]
97 /// The `drop` method, called when the value goes out of scope.
98 #[stable(feature = "rust1", since = "1.0.0")]
102 // implements the unary operator "op &T"
103 // based on "op T" where T is expected to be `Copy`able
104 macro_rules! forward_ref_unop {
105 (impl $imp:ident, $method:ident for $t:ty) => {
106 #[stable(feature = "rust1", since = "1.0.0")]
107 impl<'a> $imp for &'a $t {
108 type Output = <$t as $imp>::Output;
111 fn $method(self) -> <$t as $imp>::Output {
118 // implements binary operators "&T op U", "T op &U", "&T op &U"
119 // based on "T op U" where T and U are expected to be `Copy`able
120 macro_rules! forward_ref_binop {
121 (impl $imp:ident, $method:ident for $t:ty, $u:ty) => {
122 #[stable(feature = "rust1", since = "1.0.0")]
123 impl<'a> $imp<$u> for &'a $t {
124 type Output = <$t as $imp<$u>>::Output;
127 fn $method(self, other: $u) -> <$t as $imp<$u>>::Output {
128 $imp::$method(*self, other)
132 #[stable(feature = "rust1", since = "1.0.0")]
133 impl<'a> $imp<&'a $u> for $t {
134 type Output = <$t as $imp<$u>>::Output;
137 fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output {
138 $imp::$method(self, *other)
142 #[stable(feature = "rust1", since = "1.0.0")]
143 impl<'a, 'b> $imp<&'a $u> for &'b $t {
144 type Output = <$t as $imp<$u>>::Output;
147 fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output {
148 $imp::$method(*self, *other)
154 /// The `Add` trait is used to specify the functionality of `+`.
158 /// A trivial implementation of `Add`. When `Foo + Foo` happens, it ends up
159 /// calling `add`, and therefore, `main` prints `Adding!`.
162 /// use std::ops::Add;
164 /// #[derive(Copy, Clone)]
167 /// impl Add for Foo {
168 /// type Output = Foo;
170 /// fn add(self, _rhs: Foo) -> Foo {
171 /// println!("Adding!");
181 #[stable(feature = "rust1", since = "1.0.0")]
182 pub trait Add<RHS=Self> {
183 /// The resulting type after applying the `+` operator
184 #[stable(feature = "rust1", since = "1.0.0")]
187 /// The method for the `+` operator
188 #[stable(feature = "rust1", since = "1.0.0")]
189 fn add(self, rhs: RHS) -> Self::Output;
192 macro_rules! add_impl {
194 #[stable(feature = "rust1", since = "1.0.0")]
199 fn add(self, other: $t) -> $t { self + other }
202 forward_ref_binop! { impl Add, add for $t, $t }
206 add_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
208 /// The `Sub` trait is used to specify the functionality of `-`.
212 /// A trivial implementation of `Sub`. When `Foo - Foo` happens, it ends up
213 /// calling `sub`, and therefore, `main` prints `Subtracting!`.
216 /// use std::ops::Sub;
218 /// #[derive(Copy, Clone)]
221 /// impl Sub for Foo {
222 /// type Output = Foo;
224 /// fn sub(self, _rhs: Foo) -> Foo {
225 /// println!("Subtracting!");
235 #[stable(feature = "rust1", since = "1.0.0")]
236 pub trait Sub<RHS=Self> {
237 /// The resulting type after applying the `-` operator
238 #[stable(feature = "rust1", since = "1.0.0")]
241 /// The method for the `-` operator
242 #[stable(feature = "rust1", since = "1.0.0")]
243 fn sub(self, rhs: RHS) -> Self::Output;
246 macro_rules! sub_impl {
248 #[stable(feature = "rust1", since = "1.0.0")]
253 fn sub(self, other: $t) -> $t { self - other }
256 forward_ref_binop! { impl Sub, sub for $t, $t }
260 sub_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
262 /// The `Mul` trait is used to specify the functionality of `*`.
266 /// A trivial implementation of `Mul`. When `Foo * Foo` happens, it ends up
267 /// calling `mul`, and therefore, `main` prints `Multiplying!`.
270 /// use std::ops::Mul;
272 /// #[derive(Copy, Clone)]
275 /// impl Mul for Foo {
276 /// type Output = Foo;
278 /// fn mul(self, _rhs: Foo) -> Foo {
279 /// println!("Multiplying!");
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub trait Mul<RHS=Self> {
291 /// The resulting type after applying the `*` operator
292 #[stable(feature = "rust1", since = "1.0.0")]
295 /// The method for the `*` operator
296 #[stable(feature = "rust1", since = "1.0.0")]
297 fn mul(self, rhs: RHS) -> Self::Output;
300 macro_rules! mul_impl {
302 #[stable(feature = "rust1", since = "1.0.0")]
307 fn mul(self, other: $t) -> $t { self * other }
310 forward_ref_binop! { impl Mul, mul for $t, $t }
314 mul_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
316 /// The `Div` trait is used to specify the functionality of `/`.
320 /// A trivial implementation of `Div`. When `Foo / Foo` happens, it ends up
321 /// calling `div`, and therefore, `main` prints `Dividing!`.
324 /// use std::ops::Div;
326 /// #[derive(Copy, Clone)]
329 /// impl Div for Foo {
330 /// type Output = Foo;
332 /// fn div(self, _rhs: Foo) -> Foo {
333 /// println!("Dividing!");
343 #[stable(feature = "rust1", since = "1.0.0")]
344 pub trait Div<RHS=Self> {
345 /// The resulting type after applying the `/` operator
346 #[stable(feature = "rust1", since = "1.0.0")]
349 /// The method for the `/` operator
350 #[stable(feature = "rust1", since = "1.0.0")]
351 fn div(self, rhs: RHS) -> Self::Output;
354 macro_rules! div_impl_integer {
356 /// This operation rounds towards zero, truncating any
357 /// fractional part of the exact result.
358 #[stable(feature = "rust1", since = "1.0.0")]
363 fn div(self, other: $t) -> $t { self / other }
366 forward_ref_binop! { impl Div, div for $t, $t }
370 div_impl_integer! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
372 macro_rules! div_impl_float {
374 #[stable(feature = "rust1", since = "1.0.0")]
379 fn div(self, other: $t) -> $t { self / other }
382 forward_ref_binop! { impl Div, div for $t, $t }
386 div_impl_float! { f32 f64 }
388 /// The `Rem` trait is used to specify the functionality of `%`.
392 /// A trivial implementation of `Rem`. When `Foo % Foo` happens, it ends up
393 /// calling `rem`, and therefore, `main` prints `Remainder-ing!`.
396 /// use std::ops::Rem;
398 /// #[derive(Copy, Clone)]
401 /// impl Rem for Foo {
402 /// type Output = Foo;
404 /// fn rem(self, _rhs: Foo) -> Foo {
405 /// println!("Remainder-ing!");
415 #[stable(feature = "rust1", since = "1.0.0")]
416 pub trait Rem<RHS=Self> {
417 /// The resulting type after applying the `%` operator
418 #[stable(feature = "rust1", since = "1.0.0")]
421 /// The method for the `%` operator
422 #[stable(feature = "rust1", since = "1.0.0")]
423 fn rem(self, rhs: RHS) -> Self::Output;
426 macro_rules! rem_impl {
428 /// This operation satisfies `n % d == n - (n / d) * d`. The
429 /// result has the same sign as the left operand.
430 #[stable(feature = "rust1", since = "1.0.0")]
435 fn rem(self, other: $t) -> $t { self % other }
438 forward_ref_binop! { impl Rem, rem for $t, $t }
442 rem_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
444 #[stable(feature = "rust1", since = "1.0.0")]
448 // see notes in `core::f32::Float::floor`
450 #[cfg(target_env = "msvc")]
451 fn rem(self, other: f32) -> f32 {
452 (self as f64).rem(other as f64) as f32
456 #[cfg(not(target_env = "msvc"))]
457 fn rem(self, other: f32) -> f32 {
458 extern { fn fmodf(a: f32, b: f32) -> f32; }
459 unsafe { fmodf(self, other) }
463 #[stable(feature = "rust1", since = "1.0.0")]
468 fn rem(self, other: f64) -> f64 {
469 extern { fn fmod(a: f64, b: f64) -> f64; }
470 unsafe { fmod(self, other) }
474 forward_ref_binop! { impl Rem, rem for f64, f64 }
475 forward_ref_binop! { impl Rem, rem for f32, f32 }
477 /// The `Neg` trait is used to specify the functionality of unary `-`.
481 /// A trivial implementation of `Neg`. When `-Foo` happens, it ends up calling
482 /// `neg`, and therefore, `main` prints `Negating!`.
485 /// use std::ops::Neg;
487 /// #[derive(Copy, Clone)]
490 /// impl Neg for Foo {
491 /// type Output = Foo;
493 /// fn neg(self) -> Foo {
494 /// println!("Negating!");
504 #[stable(feature = "rust1", since = "1.0.0")]
506 /// The resulting type after applying the `-` operator
507 #[stable(feature = "rust1", since = "1.0.0")]
510 /// The method for the unary `-` operator
511 #[stable(feature = "rust1", since = "1.0.0")]
512 fn neg(self) -> Self::Output;
517 macro_rules! neg_impl_core {
518 ($id:ident => $body:expr, $($t:ty)*) => ($(
519 #[stable(feature = "rust1", since = "1.0.0")]
521 #[stable(feature = "rust1", since = "1.0.0")]
525 #[stable(feature = "rust1", since = "1.0.0")]
526 fn neg(self) -> $t { let $id = self; $body }
529 forward_ref_unop! { impl Neg, neg for $t }
533 macro_rules! neg_impl_numeric {
534 ($($t:ty)*) => { neg_impl_core!{ x => -x, $($t)*} }
537 macro_rules! neg_impl_unsigned {
539 neg_impl_core!{ x => {
544 // neg_impl_unsigned! { usize u8 u16 u32 u64 }
545 neg_impl_numeric! { isize i8 i16 i32 i64 f32 f64 }
547 /// The `Not` trait is used to specify the functionality of unary `!`.
551 /// A trivial implementation of `Not`. When `!Foo` happens, it ends up calling
552 /// `not`, and therefore, `main` prints `Not-ing!`.
555 /// use std::ops::Not;
557 /// #[derive(Copy, Clone)]
560 /// impl Not for Foo {
561 /// type Output = Foo;
563 /// fn not(self) -> Foo {
564 /// println!("Not-ing!");
574 #[stable(feature = "rust1", since = "1.0.0")]
576 /// The resulting type after applying the `!` operator
577 #[stable(feature = "rust1", since = "1.0.0")]
580 /// The method for the unary `!` operator
581 #[stable(feature = "rust1", since = "1.0.0")]
582 fn not(self) -> Self::Output;
585 macro_rules! not_impl {
587 #[stable(feature = "rust1", since = "1.0.0")]
592 fn not(self) -> $t { !self }
595 forward_ref_unop! { impl Not, not for $t }
599 not_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
601 /// The `BitAnd` trait is used to specify the functionality of `&`.
605 /// A trivial implementation of `BitAnd`. When `Foo & Foo` happens, it ends up
606 /// calling `bitand`, and therefore, `main` prints `Bitwise And-ing!`.
609 /// use std::ops::BitAnd;
611 /// #[derive(Copy, Clone)]
614 /// impl BitAnd for Foo {
615 /// type Output = Foo;
617 /// fn bitand(self, _rhs: Foo) -> Foo {
618 /// println!("Bitwise And-ing!");
628 #[stable(feature = "rust1", since = "1.0.0")]
629 pub trait BitAnd<RHS=Self> {
630 /// The resulting type after applying the `&` operator
631 #[stable(feature = "rust1", since = "1.0.0")]
634 /// The method for the `&` operator
635 #[stable(feature = "rust1", since = "1.0.0")]
636 fn bitand(self, rhs: RHS) -> Self::Output;
639 macro_rules! bitand_impl {
641 #[stable(feature = "rust1", since = "1.0.0")]
646 fn bitand(self, rhs: $t) -> $t { self & rhs }
649 forward_ref_binop! { impl BitAnd, bitand for $t, $t }
653 bitand_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
655 /// The `BitOr` trait is used to specify the functionality of `|`.
659 /// A trivial implementation of `BitOr`. When `Foo | Foo` happens, it ends up
660 /// calling `bitor`, and therefore, `main` prints `Bitwise Or-ing!`.
663 /// use std::ops::BitOr;
665 /// #[derive(Copy, Clone)]
668 /// impl BitOr for Foo {
669 /// type Output = Foo;
671 /// fn bitor(self, _rhs: Foo) -> Foo {
672 /// println!("Bitwise Or-ing!");
682 #[stable(feature = "rust1", since = "1.0.0")]
683 pub trait BitOr<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 bitor(self, rhs: RHS) -> Self::Output;
693 macro_rules! bitor_impl {
695 #[stable(feature = "rust1", since = "1.0.0")]
700 fn bitor(self, rhs: $t) -> $t { self | rhs }
703 forward_ref_binop! { impl BitOr, bitor for $t, $t }
707 bitor_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
709 /// The `BitXor` trait is used to specify the functionality of `^`.
713 /// A trivial implementation of `BitXor`. When `Foo ^ Foo` happens, it ends up
714 /// calling `bitxor`, and therefore, `main` prints `Bitwise Xor-ing!`.
717 /// use std::ops::BitXor;
719 /// #[derive(Copy, Clone)]
722 /// impl BitXor for Foo {
723 /// type Output = Foo;
725 /// fn bitxor(self, _rhs: Foo) -> Foo {
726 /// println!("Bitwise Xor-ing!");
736 #[stable(feature = "rust1", since = "1.0.0")]
737 pub trait BitXor<RHS=Self> {
738 /// The resulting type after applying the `^` operator
739 #[stable(feature = "rust1", since = "1.0.0")]
742 /// The method for the `^` operator
743 #[stable(feature = "rust1", since = "1.0.0")]
744 fn bitxor(self, rhs: RHS) -> Self::Output;
747 macro_rules! bitxor_impl {
749 #[stable(feature = "rust1", since = "1.0.0")]
754 fn bitxor(self, other: $t) -> $t { self ^ other }
757 forward_ref_binop! { impl BitXor, bitxor for $t, $t }
761 bitxor_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
763 /// The `Shl` trait is used to specify the functionality of `<<`.
767 /// A trivial implementation of `Shl`. When `Foo << Foo` happens, it ends up
768 /// calling `shl`, and therefore, `main` prints `Shifting left!`.
771 /// use std::ops::Shl;
773 /// #[derive(Copy, Clone)]
776 /// impl Shl<Foo> for Foo {
777 /// type Output = Foo;
779 /// fn shl(self, _rhs: Foo) -> Foo {
780 /// println!("Shifting left!");
790 #[stable(feature = "rust1", since = "1.0.0")]
792 /// The resulting type after applying the `<<` operator
793 #[stable(feature = "rust1", since = "1.0.0")]
796 /// The method for the `<<` operator
797 #[stable(feature = "rust1", since = "1.0.0")]
798 fn shl(self, rhs: RHS) -> Self::Output;
801 macro_rules! shl_impl {
803 #[stable(feature = "rust1", since = "1.0.0")]
804 impl Shl<$f> for $t {
808 fn shl(self, other: $f) -> $t {
813 forward_ref_binop! { impl Shl, shl for $t, $f }
817 macro_rules! shl_impl_all {
820 shl_impl! { $t, u16 }
821 shl_impl! { $t, u32 }
822 shl_impl! { $t, u64 }
823 shl_impl! { $t, usize }
826 shl_impl! { $t, i16 }
827 shl_impl! { $t, i32 }
828 shl_impl! { $t, i64 }
829 shl_impl! { $t, isize }
833 shl_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
835 /// The `Shr` trait is used to specify the functionality of `>>`.
839 /// A trivial implementation of `Shr`. When `Foo >> Foo` happens, it ends up
840 /// calling `shr`, and therefore, `main` prints `Shifting right!`.
843 /// use std::ops::Shr;
845 /// #[derive(Copy, Clone)]
848 /// impl Shr<Foo> for Foo {
849 /// type Output = Foo;
851 /// fn shr(self, _rhs: Foo) -> Foo {
852 /// println!("Shifting right!");
862 #[stable(feature = "rust1", since = "1.0.0")]
864 /// The resulting type after applying the `>>` operator
865 #[stable(feature = "rust1", since = "1.0.0")]
868 /// The method for the `>>` operator
869 #[stable(feature = "rust1", since = "1.0.0")]
870 fn shr(self, rhs: RHS) -> Self::Output;
873 macro_rules! shr_impl {
875 impl Shr<$f> for $t {
879 fn shr(self, other: $f) -> $t {
884 forward_ref_binop! { impl Shr, shr for $t, $f }
888 macro_rules! shr_impl_all {
891 shr_impl! { $t, u16 }
892 shr_impl! { $t, u32 }
893 shr_impl! { $t, u64 }
894 shr_impl! { $t, usize }
897 shr_impl! { $t, i16 }
898 shr_impl! { $t, i32 }
899 shr_impl! { $t, i64 }
900 shr_impl! { $t, isize }
904 shr_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
906 /// The `Index` trait is used to specify the functionality of indexing operations
907 /// like `arr[idx]` when used in an immutable context.
911 /// A trivial implementation of `Index`. When `Foo[Bar]` happens, it ends up
912 /// calling `index`, and therefore, `main` prints `Indexing!`.
915 /// use std::ops::Index;
917 /// #[derive(Copy, Clone)]
921 /// impl Index<Bar> for Foo {
922 /// type Output = Foo;
924 /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
925 /// println!("Indexing!");
935 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
936 #[stable(feature = "rust1", since = "1.0.0")]
937 pub trait Index<Idx: ?Sized> {
938 /// The returned type after indexing
939 #[stable(feature = "rust1", since = "1.0.0")]
942 /// The method for the indexing (`Foo[Bar]`) operation
943 #[stable(feature = "rust1", since = "1.0.0")]
944 fn index<'a>(&'a self, index: Idx) -> &'a Self::Output;
947 /// The `IndexMut` trait is used to specify the functionality of indexing
948 /// operations like `arr[idx]`, when used in a mutable context.
952 /// A trivial implementation of `IndexMut`. When `Foo[Bar]` happens, it ends up
953 /// calling `index_mut`, and therefore, `main` prints `Indexing!`.
956 /// use std::ops::{Index, IndexMut};
958 /// #[derive(Copy, Clone)]
962 /// impl Index<Bar> for Foo {
963 /// type Output = Foo;
965 /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
970 /// impl IndexMut<Bar> for Foo {
971 /// fn index_mut<'a>(&'a mut self, _index: Bar) -> &'a mut Foo {
972 /// println!("Indexing!");
981 #[lang = "index_mut"]
982 #[rustc_on_unimplemented = "the type `{Self}` cannot be mutably indexed by `{Idx}`"]
983 #[stable(feature = "rust1", since = "1.0.0")]
984 pub trait IndexMut<Idx: ?Sized>: Index<Idx> {
985 /// The method for the indexing (`Foo[Bar]`) operation
986 #[stable(feature = "rust1", since = "1.0.0")]
987 fn index_mut<'a>(&'a mut self, index: Idx) -> &'a mut Self::Output;
990 /// An unbounded range.
991 #[derive(Copy, Clone, PartialEq, Eq)]
992 #[lang = "range_full"]
993 #[stable(feature = "rust1", since = "1.0.0")]
994 pub struct RangeFull;
996 #[stable(feature = "rust1", since = "1.0.0")]
997 impl fmt::Debug for RangeFull {
998 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1003 /// A (half-open) range which is bounded at both ends.
1004 #[derive(Clone, PartialEq, Eq)]
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 pub struct Range<Idx> {
1008 /// The lower bound of the range (inclusive).
1009 #[stable(feature = "rust1", since = "1.0.0")]
1011 /// The upper bound of the range (exclusive).
1012 #[stable(feature = "rust1", since = "1.0.0")]
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
1018 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1019 write!(fmt, "{:?}..{:?}", self.start, self.end)
1023 /// A range which is only bounded below.
1024 #[derive(Clone, PartialEq, Eq)]
1025 #[lang = "range_from"]
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 pub struct RangeFrom<Idx> {
1028 /// The lower bound of the range (inclusive).
1029 #[stable(feature = "rust1", since = "1.0.0")]
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
1035 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1036 write!(fmt, "{:?}..", self.start)
1040 /// A range which is only bounded above.
1041 #[derive(Copy, Clone, PartialEq, Eq)]
1042 #[lang = "range_to"]
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 pub struct RangeTo<Idx> {
1045 /// The upper bound of the range (exclusive).
1046 #[stable(feature = "rust1", since = "1.0.0")]
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> {
1052 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1053 write!(fmt, "..{:?}", self.end)
1057 /// The `Deref` trait is used to specify the functionality of dereferencing
1058 /// operations like `*v`.
1060 /// `Deref` also enables ['`Deref` coercions'][coercions].
1062 /// [coercions]: ../../book/deref-coercions.html
1066 /// A struct with a single field which is accessible via dereferencing the
1070 /// use std::ops::Deref;
1072 /// struct DerefExample<T> {
1076 /// impl<T> Deref for DerefExample<T> {
1077 /// type Target = T;
1079 /// fn deref<'a>(&'a self) -> &'a T {
1085 /// let x = DerefExample { value: 'a' };
1086 /// assert_eq!('a', *x);
1090 #[stable(feature = "rust1", since = "1.0.0")]
1092 /// The resulting type after dereferencing
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 type Target: ?Sized;
1096 /// The method called to dereference a value
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 fn deref<'a>(&'a self) -> &'a Self::Target;
1101 #[stable(feature = "rust1", since = "1.0.0")]
1102 impl<'a, T: ?Sized> Deref for &'a T {
1105 fn deref(&self) -> &T { *self }
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 impl<'a, T: ?Sized> Deref for &'a mut T {
1112 fn deref(&self) -> &T { *self }
1115 /// The `DerefMut` trait is used to specify the functionality of dereferencing
1116 /// mutably like `*v = 1;`
1118 /// `DerefMut` also enables ['`Deref` coercions'][coercions].
1120 /// [coercions]: ../../book/deref-coercions.html
1124 /// A struct with a single field which is modifiable via dereferencing the
1128 /// use std::ops::{Deref, DerefMut};
1130 /// struct DerefMutExample<T> {
1134 /// impl<T> Deref for DerefMutExample<T> {
1135 /// type Target = T;
1137 /// fn deref<'a>(&'a self) -> &'a T {
1142 /// impl<T> DerefMut for DerefMutExample<T> {
1143 /// fn deref_mut<'a>(&'a mut self) -> &'a mut T {
1149 /// let mut x = DerefMutExample { value: 'a' };
1151 /// assert_eq!('b', *x);
1154 #[lang = "deref_mut"]
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 pub trait DerefMut: Deref {
1157 /// The method called to mutably dereference a value
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 fn deref_mut<'a>(&'a mut self) -> &'a mut Self::Target;
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 impl<'a, T: ?Sized> DerefMut for &'a mut T {
1164 fn deref_mut(&mut self) -> &mut T { *self }
1167 /// A version of the call operator that takes an immutable receiver.
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 #[rustc_paren_sugar]
1171 #[fundamental] // so that regex can rely that `&str: !FnMut`
1172 pub trait Fn<Args> : FnMut<Args> {
1173 /// This is called when the call operator is used.
1174 extern "rust-call" fn call(&self, args: Args) -> Self::Output;
1177 /// A version of the call operator that takes a mutable receiver.
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 #[rustc_paren_sugar]
1181 #[fundamental] // so that regex can rely that `&str: !FnMut`
1182 pub trait FnMut<Args> : FnOnce<Args> {
1183 /// This is called when the call operator is used.
1184 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
1187 /// A version of the call operator that takes a by-value receiver.
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 #[rustc_paren_sugar]
1191 #[fundamental] // so that regex can rely that `&str: !FnMut`
1192 pub trait FnOnce<Args> {
1193 /// The returned type after the call operator is used.
1196 /// This is called when the call operator is used.
1197 extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
1202 use super::{Fn, FnMut, FnOnce};
1204 impl<'a,A,F:?Sized> Fn<A> for &'a F
1207 extern "rust-call" fn call(&self, args: A) -> F::Output {
1212 impl<'a,A,F:?Sized> FnMut<A> for &'a F
1215 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
1220 impl<'a,A,F:?Sized> FnOnce<A> for &'a F
1223 type Output = F::Output;
1225 extern "rust-call" fn call_once(self, args: A) -> F::Output {
1230 impl<'a,A,F:?Sized> FnMut<A> for &'a mut F
1233 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
1234 (*self).call_mut(args)
1238 impl<'a,A,F:?Sized> FnOnce<A> for &'a mut F
1241 type Output = F::Output;
1242 extern "rust-call" fn call_once(mut self, args: A) -> F::Output {
1243 (*self).call_mut(args)
1248 /// Trait that indicates that this is a pointer or a wrapper for one,
1249 /// where unsizing can be performed on the pointee.
1250 #[unstable(feature = "coerce_unsized", issue = "27732")]
1251 #[lang="coerce_unsized"]
1252 pub trait CoerceUnsized<T> {
1257 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a mut U> for &'a mut T {}
1259 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b mut T {}
1261 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for &'a mut T {}
1262 // &mut T -> *const U
1263 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a mut T {}
1266 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b T {}
1268 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a T {}
1271 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for *mut T {}
1272 // *mut T -> *const U
1273 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *mut T {}
1275 // *const T -> *const U
1276 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *const T {}
1278 /// Both `in (PLACE) EXPR` and `box EXPR` desugar into expressions
1279 /// that allocate an intermediate "place" that holds uninitialized
1280 /// state. The desugaring evaluates EXPR, and writes the result at
1281 /// the address returned by the `pointer` method of this trait.
1283 /// A `Place` can be thought of as a special representation for a
1284 /// hypothetical `&uninit` reference (which Rust cannot currently
1285 /// express directly). That is, it represents a pointer to
1286 /// uninitialized storage.
1288 /// The client is responsible for two steps: First, initializing the
1289 /// payload (it can access its address via `pointer`). Second,
1290 /// converting the agent to an instance of the owning pointer, via the
1291 /// appropriate `finalize` method (see the `InPlace`.
1293 /// If evaluating EXPR fails, then the destructor for the
1294 /// implementation of Place to clean up any intermediate state
1295 /// (e.g. deallocate box storage, pop a stack, etc).
1296 #[unstable(feature = "placement_new_protocol", issue = "27779")]
1297 pub trait Place<Data: ?Sized> {
1298 /// Returns the address where the input value will be written.
1299 /// Note that the data at this address is generally uninitialized,
1300 /// and thus one should use `ptr::write` for initializing it.
1301 fn pointer(&mut self) -> *mut Data;
1304 /// Interface to implementations of `in (PLACE) EXPR`.
1306 /// `in (PLACE) EXPR` effectively desugars into:
1310 /// let mut place = Placer::make_place(p);
1311 /// let raw_place = Place::pointer(&mut place);
1312 /// let value = EXPR;
1314 /// std::ptr::write(raw_place, value);
1315 /// InPlace::finalize(place)
1319 /// The type of `in (PLACE) EXPR` is derived from the type of `PLACE`;
1320 /// if the type of `PLACE` is `P`, then the final type of the whole
1321 /// expression is `P::Place::Owner` (see the `InPlace` and `Boxed`
1324 /// Values for types implementing this trait usually are transient
1325 /// intermediate values (e.g. the return value of `Vec::emplace_back`)
1326 /// or `Copy`, since the `make_place` method takes `self` by value.
1327 #[unstable(feature = "placement_new_protocol", issue = "27779")]
1328 pub trait Placer<Data: ?Sized> {
1329 /// `Place` is the intermedate agent guarding the
1330 /// uninitialized state for `Data`.
1331 type Place: InPlace<Data>;
1333 /// Creates a fresh place from `self`.
1334 fn make_place(self) -> Self::Place;
1337 /// Specialization of `Place` trait supporting `in (PLACE) EXPR`.
1338 #[unstable(feature = "placement_new_protocol", issue = "27779")]
1339 pub trait InPlace<Data: ?Sized>: Place<Data> {
1340 /// `Owner` is the type of the end value of `in (PLACE) EXPR`
1342 /// Note that when `in (PLACE) EXPR` is solely used for
1343 /// side-effecting an existing data-structure,
1344 /// e.g. `Vec::emplace_back`, then `Owner` need not carry any
1345 /// information at all (e.g. it can be the unit type `()` in that
1349 /// Converts self into the final value, shifting
1350 /// deallocation/cleanup responsibilities (if any remain), over to
1351 /// the returned instance of `Owner` and forgetting self.
1352 unsafe fn finalize(self) -> Self::Owner;
1355 /// Core trait for the `box EXPR` form.
1357 /// `box EXPR` effectively desugars into:
1360 /// let mut place = BoxPlace::make_place();
1361 /// let raw_place = Place::pointer(&mut place);
1362 /// let value = EXPR;
1364 /// ::std::ptr::write(raw_place, value);
1365 /// Boxed::finalize(place)
1369 /// The type of `box EXPR` is supplied from its surrounding
1370 /// context; in the above expansion, the result type `T` is used
1371 /// to determine which implementation of `Boxed` to use, and that
1372 /// `<T as Boxed>` in turn dictates determines which
1373 /// implementation of `BoxPlace` to use, namely:
1374 /// `<<T as Boxed>::Place as BoxPlace>`.
1375 #[unstable(feature = "placement_new_protocol", issue = "27779")]
1377 /// The kind of data that is stored in this kind of box.
1378 type Data; /* (`Data` unused b/c cannot yet express below bound.) */
1379 /// The place that will negotiate the storage of the data.
1380 type Place: BoxPlace<Self::Data>;
1382 /// Converts filled place into final owning value, shifting
1383 /// deallocation/cleanup responsibilities (if any remain), over to
1384 /// returned instance of `Self` and forgetting `filled`.
1385 unsafe fn finalize(filled: Self::Place) -> Self;
1388 /// Specialization of `Place` trait supporting `box EXPR`.
1389 #[unstable(feature = "placement_new_protocol", issue = "27779")]
1390 pub trait BoxPlace<Data: ?Sized> : Place<Data> {
1391 /// Creates a globally fresh place.
1392 fn make_place() -> Self;