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")]
72 use marker
::{Sized, Unsize}
;
74 /// The `Drop` trait is used to run some code when a value goes out of scope.
75 /// This is sometimes called a 'destructor'.
79 /// A trivial implementation of `Drop`. The `drop` method is called when `_x`
80 /// goes out of scope, and therefore `main` prints `Dropping!`.
85 /// impl Drop for HasDrop {
86 /// fn drop(&mut self) {
87 /// println!("Dropping!");
96 #[stable(feature = "rust1", since = "1.0.0")]
98 /// A method called when the value goes out of scope.
100 /// When this method has been called, `self` has not yet been deallocated.
101 /// If it were, `self` would be a dangling reference.
103 /// After this function is over, the memory of `self` will be deallocated.
107 /// Given that a `panic!` will call `drop()` as it unwinds, any `panic!` in
108 /// a `drop()` implementation will likely abort.
109 #[stable(feature = "rust1", since = "1.0.0")]
113 // implements the unary operator "op &T"
114 // based on "op T" where T is expected to be `Copy`able
115 macro_rules
! forward_ref_unop
{
116 (impl $imp
:ident
, $method
:ident
for $t
:ty
) => {
117 #[stable(feature = "rust1", since = "1.0.0")]
118 impl<'a
> $imp
for &'a $t
{
119 type Output
= <$t
as $imp
>::Output
;
122 fn $
method(self) -> <$t
as $imp
>::Output
{
129 // implements binary operators "&T op U", "T op &U", "&T op &U"
130 // based on "T op U" where T and U are expected to be `Copy`able
131 macro_rules
! forward_ref_binop
{
132 (impl $imp
:ident
, $method
:ident
for $t
:ty
, $u
:ty
) => {
133 #[stable(feature = "rust1", since = "1.0.0")]
134 impl<'a
> $imp
<$u
> for &'a $t
{
135 type Output
= <$t
as $imp
<$u
>>::Output
;
138 fn $
method(self, other
: $u
) -> <$t
as $imp
<$u
>>::Output
{
139 $imp
::$
method(*self, other
)
143 #[stable(feature = "rust1", since = "1.0.0")]
144 impl<'a
> $imp
<&'a $u
> for $t
{
145 type Output
= <$t
as $imp
<$u
>>::Output
;
148 fn $
method(self, other
: &'a $u
) -> <$t
as $imp
<$u
>>::Output
{
149 $imp
::$
method(self, *other
)
153 #[stable(feature = "rust1", since = "1.0.0")]
154 impl<'a
, 'b
> $imp
<&'a $u
> for &'b $t
{
155 type Output
= <$t
as $imp
<$u
>>::Output
;
158 fn $
method(self, other
: &'a $u
) -> <$t
as $imp
<$u
>>::Output
{
159 $imp
::$
method(*self, *other
)
165 /// The `Add` trait is used to specify the functionality of `+`.
169 /// A trivial implementation of `Add`. When `Foo + Foo` happens, it ends up
170 /// calling `add`, and therefore, `main` prints `Adding!`.
173 /// use std::ops::Add;
177 /// impl Add for Foo {
178 /// type Output = Foo;
180 /// fn add(self, _rhs: Foo) -> Foo {
181 /// println!("Adding!");
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub trait Add
<RHS
=Self> {
193 /// The resulting type after applying the `+` operator
194 #[stable(feature = "rust1", since = "1.0.0")]
197 /// The method for the `+` operator
198 #[stable(feature = "rust1", since = "1.0.0")]
199 fn add(self, rhs
: RHS
) -> Self::Output
;
202 macro_rules
! add_impl
{
204 #[stable(feature = "rust1", since = "1.0.0")]
209 #[rustc_inherit_overflow_checks]
210 fn add(self, other
: $t
) -> $t { self + other }
213 forward_ref_binop
! { impl Add, add for $t, $t }
217 add_impl
! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
219 /// The `Sub` trait is used to specify the functionality of `-`.
223 /// A trivial implementation of `Sub`. When `Foo - Foo` happens, it ends up
224 /// calling `sub`, and therefore, `main` prints `Subtracting!`.
227 /// use std::ops::Sub;
231 /// impl Sub for Foo {
232 /// type Output = Foo;
234 /// fn sub(self, _rhs: Foo) -> Foo {
235 /// println!("Subtracting!");
245 #[stable(feature = "rust1", since = "1.0.0")]
246 pub trait Sub
<RHS
=Self> {
247 /// The resulting type after applying the `-` operator
248 #[stable(feature = "rust1", since = "1.0.0")]
251 /// The method for the `-` operator
252 #[stable(feature = "rust1", since = "1.0.0")]
253 fn sub(self, rhs
: RHS
) -> Self::Output
;
256 macro_rules
! sub_impl
{
258 #[stable(feature = "rust1", since = "1.0.0")]
263 #[rustc_inherit_overflow_checks]
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 #[rustc_inherit_overflow_checks]
318 fn mul(self, other
: $t
) -> $t { self * other }
321 forward_ref_binop
! { impl Mul, mul for $t, $t }
325 mul_impl
! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
327 /// The `Div` trait is used to specify the functionality of `/`.
331 /// A trivial implementation of `Div`. When `Foo / Foo` happens, it ends up
332 /// calling `div`, and therefore, `main` prints `Dividing!`.
335 /// use std::ops::Div;
339 /// impl Div for Foo {
340 /// type Output = Foo;
342 /// fn div(self, _rhs: Foo) -> Foo {
343 /// println!("Dividing!");
353 #[stable(feature = "rust1", since = "1.0.0")]
354 pub trait Div
<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 div(self, rhs
: RHS
) -> Self::Output
;
364 macro_rules
! div_impl_integer
{
366 /// This operation rounds towards zero, truncating any
367 /// fractional part of the exact result.
368 #[stable(feature = "rust1", since = "1.0.0")]
373 fn div(self, other
: $t
) -> $t { self / other }
376 forward_ref_binop
! { impl Div, div for $t, $t }
380 div_impl_integer
! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
382 macro_rules
! div_impl_float
{
384 #[stable(feature = "rust1", since = "1.0.0")]
389 fn div(self, other
: $t
) -> $t { self / other }
392 forward_ref_binop
! { impl Div, div for $t, $t }
396 div_impl_float
! { f32 f64 }
398 /// The `Rem` trait is used to specify the functionality of `%`.
402 /// A trivial implementation of `Rem`. When `Foo % Foo` happens, it ends up
403 /// calling `rem`, and therefore, `main` prints `Remainder-ing!`.
406 /// use std::ops::Rem;
410 /// impl Rem for Foo {
411 /// type Output = Foo;
413 /// fn rem(self, _rhs: Foo) -> Foo {
414 /// println!("Remainder-ing!");
424 #[stable(feature = "rust1", since = "1.0.0")]
425 pub trait Rem
<RHS
=Self> {
426 /// The resulting type after applying the `%` operator
427 #[stable(feature = "rust1", since = "1.0.0")]
430 /// The method for the `%` operator
431 #[stable(feature = "rust1", since = "1.0.0")]
432 fn rem(self, rhs
: RHS
) -> Self::Output
;
435 macro_rules
! rem_impl_integer
{
437 /// This operation satisfies `n % d == n - (n / d) * d`. The
438 /// result has the same sign as the left operand.
439 #[stable(feature = "rust1", since = "1.0.0")]
444 fn rem(self, other
: $t
) -> $t { self % other }
447 forward_ref_binop
! { impl Rem, rem for $t, $t }
451 rem_impl_integer
! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
453 macro_rules
! rem_impl_float
{
455 #[stable(feature = "rust1", since = "1.0.0")]
460 fn rem(self, other
: $t
) -> $t { self % other }
463 forward_ref_binop
! { impl Rem, rem for $t, $t }
467 rem_impl_float
! { f32 f64 }
469 /// The `Neg` trait is used to specify the functionality of unary `-`.
473 /// A trivial implementation of `Neg`. When `-Foo` happens, it ends up calling
474 /// `neg`, and therefore, `main` prints `Negating!`.
477 /// use std::ops::Neg;
481 /// impl Neg for Foo {
482 /// type Output = Foo;
484 /// fn neg(self) -> Foo {
485 /// println!("Negating!");
495 #[stable(feature = "rust1", since = "1.0.0")]
497 /// The resulting type after applying the `-` operator
498 #[stable(feature = "rust1", since = "1.0.0")]
501 /// The method for the unary `-` operator
502 #[stable(feature = "rust1", since = "1.0.0")]
503 fn neg(self) -> Self::Output
;
508 macro_rules
! neg_impl_core
{
509 ($id
:ident
=> $body
:expr
, $
($t
:ty
)*) => ($
(
510 #[stable(feature = "rust1", since = "1.0.0")]
515 #[rustc_inherit_overflow_checks]
516 fn neg(self) -> $t { let $id = self; $body }
519 forward_ref_unop
! { impl Neg, neg for $t }
523 macro_rules
! neg_impl_numeric
{
524 ($
($t
:ty
)*) => { neg_impl_core!{ x => -x, $($t)*}
}
527 macro_rules
! neg_impl_unsigned
{
529 neg_impl_core
!{ x
=> {
534 // neg_impl_unsigned! { usize u8 u16 u32 u64 }
535 neg_impl_numeric
! { isize i8 i16 i32 i64 f32 f64 }
537 /// The `Not` trait is used to specify the functionality of unary `!`.
541 /// A trivial implementation of `Not`. When `!Foo` happens, it ends up calling
542 /// `not`, and therefore, `main` prints `Not-ing!`.
545 /// use std::ops::Not;
549 /// impl Not for Foo {
550 /// type Output = Foo;
552 /// fn not(self) -> Foo {
553 /// println!("Not-ing!");
563 #[stable(feature = "rust1", since = "1.0.0")]
565 /// The resulting type after applying the `!` operator
566 #[stable(feature = "rust1", since = "1.0.0")]
569 /// The method for the unary `!` operator
570 #[stable(feature = "rust1", since = "1.0.0")]
571 fn not(self) -> Self::Output
;
574 macro_rules
! not_impl
{
576 #[stable(feature = "rust1", since = "1.0.0")]
581 fn not(self) -> $t { !self }
584 forward_ref_unop
! { impl Not, not for $t }
588 not_impl
! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
590 /// The `BitAnd` trait is used to specify the functionality of `&`.
594 /// A trivial implementation of `BitAnd`. When `Foo & Foo` happens, it ends up
595 /// calling `bitand`, and therefore, `main` prints `Bitwise And-ing!`.
598 /// use std::ops::BitAnd;
602 /// impl BitAnd for Foo {
603 /// type Output = Foo;
605 /// fn bitand(self, _rhs: Foo) -> Foo {
606 /// println!("Bitwise And-ing!");
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub trait BitAnd
<RHS
=Self> {
618 /// The resulting type after applying the `&` operator
619 #[stable(feature = "rust1", since = "1.0.0")]
622 /// The method for the `&` operator
623 #[stable(feature = "rust1", since = "1.0.0")]
624 fn bitand(self, rhs
: RHS
) -> Self::Output
;
627 macro_rules
! bitand_impl
{
629 #[stable(feature = "rust1", since = "1.0.0")]
634 fn bitand(self, rhs
: $t
) -> $t { self & rhs }
637 forward_ref_binop
! { impl BitAnd, bitand for $t, $t }
641 bitand_impl
! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
643 /// The `BitOr` trait is used to specify the functionality of `|`.
647 /// A trivial implementation of `BitOr`. When `Foo | Foo` happens, it ends up
648 /// calling `bitor`, and therefore, `main` prints `Bitwise Or-ing!`.
651 /// use std::ops::BitOr;
655 /// impl BitOr for Foo {
656 /// type Output = Foo;
658 /// fn bitor(self, _rhs: Foo) -> Foo {
659 /// println!("Bitwise Or-ing!");
669 #[stable(feature = "rust1", since = "1.0.0")]
670 pub trait BitOr
<RHS
=Self> {
671 /// The resulting type after applying the `|` operator
672 #[stable(feature = "rust1", since = "1.0.0")]
675 /// The method for the `|` operator
676 #[stable(feature = "rust1", since = "1.0.0")]
677 fn bitor(self, rhs
: RHS
) -> Self::Output
;
680 macro_rules
! bitor_impl
{
682 #[stable(feature = "rust1", since = "1.0.0")]
687 fn bitor(self, rhs
: $t
) -> $t { self | rhs }
690 forward_ref_binop
! { impl BitOr, bitor for $t, $t }
694 bitor_impl
! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
696 /// The `BitXor` trait is used to specify the functionality of `^`.
700 /// A trivial implementation of `BitXor`. When `Foo ^ Foo` happens, it ends up
701 /// calling `bitxor`, and therefore, `main` prints `Bitwise Xor-ing!`.
704 /// use std::ops::BitXor;
708 /// impl BitXor for Foo {
709 /// type Output = Foo;
711 /// fn bitxor(self, _rhs: Foo) -> Foo {
712 /// println!("Bitwise Xor-ing!");
722 #[stable(feature = "rust1", since = "1.0.0")]
723 pub trait BitXor
<RHS
=Self> {
724 /// The resulting type after applying the `^` operator
725 #[stable(feature = "rust1", since = "1.0.0")]
728 /// The method for the `^` operator
729 #[stable(feature = "rust1", since = "1.0.0")]
730 fn bitxor(self, rhs
: RHS
) -> Self::Output
;
733 macro_rules
! bitxor_impl
{
735 #[stable(feature = "rust1", since = "1.0.0")]
740 fn bitxor(self, other
: $t
) -> $t { self ^ other }
743 forward_ref_binop
! { impl BitXor, bitxor for $t, $t }
747 bitxor_impl
! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
749 /// The `Shl` trait is used to specify the functionality of `<<`.
753 /// A trivial implementation of `Shl`. When `Foo << Foo` happens, it ends up
754 /// calling `shl`, and therefore, `main` prints `Shifting left!`.
757 /// use std::ops::Shl;
761 /// impl Shl<Foo> for Foo {
762 /// type Output = Foo;
764 /// fn shl(self, _rhs: Foo) -> Foo {
765 /// println!("Shifting left!");
775 #[stable(feature = "rust1", since = "1.0.0")]
777 /// The resulting type after applying the `<<` operator
778 #[stable(feature = "rust1", since = "1.0.0")]
781 /// The method for the `<<` operator
782 #[stable(feature = "rust1", since = "1.0.0")]
783 fn shl(self, rhs
: RHS
) -> Self::Output
;
786 macro_rules
! shl_impl
{
788 #[stable(feature = "rust1", since = "1.0.0")]
789 impl Shl
<$f
> for $t
{
793 #[rustc_inherit_overflow_checks]
794 fn shl(self, other
: $f
) -> $t
{
799 forward_ref_binop
! { impl Shl, shl for $t, $f }
803 macro_rules
! shl_impl_all
{
806 shl_impl
! { $t, u16 }
807 shl_impl
! { $t, u32 }
808 shl_impl
! { $t, u64 }
809 shl_impl
! { $t, usize }
812 shl_impl
! { $t, i16 }
813 shl_impl
! { $t, i32 }
814 shl_impl
! { $t, i64 }
815 shl_impl
! { $t, isize }
819 shl_impl_all
! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
821 /// The `Shr` trait is used to specify the functionality of `>>`.
825 /// A trivial implementation of `Shr`. When `Foo >> Foo` happens, it ends up
826 /// calling `shr`, and therefore, `main` prints `Shifting right!`.
829 /// use std::ops::Shr;
833 /// impl Shr<Foo> for Foo {
834 /// type Output = Foo;
836 /// fn shr(self, _rhs: Foo) -> Foo {
837 /// println!("Shifting right!");
847 #[stable(feature = "rust1", since = "1.0.0")]
849 /// The resulting type after applying the `>>` operator
850 #[stable(feature = "rust1", since = "1.0.0")]
853 /// The method for the `>>` operator
854 #[stable(feature = "rust1", since = "1.0.0")]
855 fn shr(self, rhs
: RHS
) -> Self::Output
;
858 macro_rules
! shr_impl
{
860 #[stable(feature = "rust1", since = "1.0.0")]
861 impl Shr
<$f
> for $t
{
865 #[rustc_inherit_overflow_checks]
866 fn shr(self, other
: $f
) -> $t
{
871 forward_ref_binop
! { impl Shr, shr for $t, $f }
875 macro_rules
! shr_impl_all
{
878 shr_impl
! { $t, u16 }
879 shr_impl
! { $t, u32 }
880 shr_impl
! { $t, u64 }
881 shr_impl
! { $t, usize }
884 shr_impl
! { $t, i16 }
885 shr_impl
! { $t, i32 }
886 shr_impl
! { $t, i64 }
887 shr_impl
! { $t, isize }
891 shr_impl_all
! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
893 /// The `AddAssign` trait is used to specify the functionality of `+=`.
897 /// A trivial implementation of `AddAssign`. When `Foo += Foo` happens, it ends up
898 /// calling `add_assign`, and therefore, `main` prints `Adding!`.
901 /// use std::ops::AddAssign;
905 /// impl AddAssign for Foo {
906 /// fn add_assign(&mut self, _rhs: Foo) {
907 /// println!("Adding!");
911 /// # #[allow(unused_assignments)]
913 /// let mut foo = Foo;
917 #[lang = "add_assign"]
918 #[stable(feature = "op_assign_traits", since = "1.8.0")]
919 pub trait AddAssign
<Rhs
=Self> {
920 /// The method for the `+=` operator
921 #[stable(feature = "op_assign_traits", since = "1.8.0")]
922 fn add_assign(&mut self, Rhs
);
925 macro_rules
! add_assign_impl
{
927 #[stable(feature = "op_assign_traits", since = "1.8.0")]
928 impl AddAssign
for $t
{
930 #[rustc_inherit_overflow_checks]
931 fn add_assign(&mut self, other
: $t
) { *self += other }
936 add_assign_impl
! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
938 /// The `SubAssign` trait is used to specify the functionality of `-=`.
942 /// A trivial implementation of `SubAssign`. When `Foo -= Foo` happens, it ends up
943 /// calling `sub_assign`, and therefore, `main` prints `Subtracting!`.
946 /// use std::ops::SubAssign;
950 /// impl SubAssign for Foo {
951 /// fn sub_assign(&mut self, _rhs: Foo) {
952 /// println!("Subtracting!");
956 /// # #[allow(unused_assignments)]
958 /// let mut foo = Foo;
962 #[lang = "sub_assign"]
963 #[stable(feature = "op_assign_traits", since = "1.8.0")]
964 pub trait SubAssign
<Rhs
=Self> {
965 /// The method for the `-=` operator
966 #[stable(feature = "op_assign_traits", since = "1.8.0")]
967 fn sub_assign(&mut self, Rhs
);
970 macro_rules
! sub_assign_impl
{
972 #[stable(feature = "op_assign_traits", since = "1.8.0")]
973 impl SubAssign
for $t
{
975 #[rustc_inherit_overflow_checks]
976 fn sub_assign(&mut self, other
: $t
) { *self -= other }
981 sub_assign_impl
! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
983 /// The `MulAssign` trait is used to specify the functionality of `*=`.
987 /// A trivial implementation of `MulAssign`. When `Foo *= Foo` happens, it ends up
988 /// calling `mul_assign`, and therefore, `main` prints `Multiplying!`.
991 /// use std::ops::MulAssign;
995 /// impl MulAssign for Foo {
996 /// fn mul_assign(&mut self, _rhs: Foo) {
997 /// println!("Multiplying!");
1001 /// # #[allow(unused_assignments)]
1003 /// let mut foo = Foo;
1007 #[lang = "mul_assign"]
1008 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1009 pub trait MulAssign
<Rhs
=Self> {
1010 /// The method for the `*=` operator
1011 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1012 fn mul_assign(&mut self, Rhs
);
1015 macro_rules
! mul_assign_impl
{
1017 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1018 impl MulAssign
for $t
{
1020 #[rustc_inherit_overflow_checks]
1021 fn mul_assign(&mut self, other
: $t
) { *self *= other }
1026 mul_assign_impl
! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1028 /// The `DivAssign` trait is used to specify the functionality of `/=`.
1032 /// A trivial implementation of `DivAssign`. When `Foo /= Foo` happens, it ends up
1033 /// calling `div_assign`, and therefore, `main` prints `Dividing!`.
1036 /// use std::ops::DivAssign;
1040 /// impl DivAssign for Foo {
1041 /// fn div_assign(&mut self, _rhs: Foo) {
1042 /// println!("Dividing!");
1046 /// # #[allow(unused_assignments)]
1048 /// let mut foo = Foo;
1052 #[lang = "div_assign"]
1053 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1054 pub trait DivAssign
<Rhs
=Self> {
1055 /// The method for the `/=` operator
1056 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1057 fn div_assign(&mut self, Rhs
);
1060 macro_rules
! div_assign_impl
{
1062 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1063 impl DivAssign
for $t
{
1065 fn div_assign(&mut self, other
: $t
) { *self /= other }
1070 div_assign_impl
! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1072 /// The `RemAssign` trait is used to specify the functionality of `%=`.
1076 /// A trivial implementation of `RemAssign`. When `Foo %= Foo` happens, it ends up
1077 /// calling `rem_assign`, and therefore, `main` prints `Remainder-ing!`.
1080 /// use std::ops::RemAssign;
1084 /// impl RemAssign for Foo {
1085 /// fn rem_assign(&mut self, _rhs: Foo) {
1086 /// println!("Remainder-ing!");
1090 /// # #[allow(unused_assignments)]
1092 /// let mut foo = Foo;
1096 #[lang = "rem_assign"]
1097 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1098 pub trait RemAssign
<Rhs
=Self> {
1099 /// The method for the `%=` operator
1100 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1101 fn rem_assign(&mut self, Rhs
);
1104 macro_rules
! rem_assign_impl
{
1106 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1107 impl RemAssign
for $t
{
1109 fn rem_assign(&mut self, other
: $t
) { *self %= other }
1114 rem_assign_impl
! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1116 /// The `BitAndAssign` trait is used to specify the functionality of `&=`.
1120 /// A trivial implementation of `BitAndAssign`. When `Foo &= Foo` happens, it ends up
1121 /// calling `bitand_assign`, and therefore, `main` prints `Bitwise And-ing!`.
1124 /// use std::ops::BitAndAssign;
1128 /// impl BitAndAssign for Foo {
1129 /// fn bitand_assign(&mut self, _rhs: Foo) {
1130 /// println!("Bitwise And-ing!");
1134 /// # #[allow(unused_assignments)]
1136 /// let mut foo = Foo;
1140 #[lang = "bitand_assign"]
1141 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1142 pub trait BitAndAssign
<Rhs
=Self> {
1143 /// The method for the `&` operator
1144 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1145 fn bitand_assign(&mut self, Rhs
);
1148 macro_rules
! bitand_assign_impl
{
1150 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1151 impl BitAndAssign
for $t
{
1153 fn bitand_assign(&mut self, other
: $t
) { *self &= other }
1158 bitand_assign_impl
! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1160 /// The `BitOrAssign` trait is used to specify the functionality of `|=`.
1164 /// A trivial implementation of `BitOrAssign`. When `Foo |= Foo` happens, it ends up
1165 /// calling `bitor_assign`, and therefore, `main` prints `Bitwise Or-ing!`.
1168 /// use std::ops::BitOrAssign;
1172 /// impl BitOrAssign for Foo {
1173 /// fn bitor_assign(&mut self, _rhs: Foo) {
1174 /// println!("Bitwise Or-ing!");
1178 /// # #[allow(unused_assignments)]
1180 /// let mut foo = Foo;
1184 #[lang = "bitor_assign"]
1185 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1186 pub trait BitOrAssign
<Rhs
=Self> {
1187 /// The method for the `|=` operator
1188 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1189 fn bitor_assign(&mut self, Rhs
);
1192 macro_rules
! bitor_assign_impl
{
1194 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1195 impl BitOrAssign
for $t
{
1197 fn bitor_assign(&mut self, other
: $t
) { *self |= other }
1202 bitor_assign_impl
! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1204 /// The `BitXorAssign` trait is used to specify the functionality of `^=`.
1208 /// A trivial implementation of `BitXorAssign`. When `Foo ^= Foo` happens, it ends up
1209 /// calling `bitxor_assign`, and therefore, `main` prints `Bitwise Xor-ing!`.
1212 /// use std::ops::BitXorAssign;
1216 /// impl BitXorAssign for Foo {
1217 /// fn bitxor_assign(&mut self, _rhs: Foo) {
1218 /// println!("Bitwise Xor-ing!");
1222 /// # #[allow(unused_assignments)]
1224 /// let mut foo = Foo;
1228 #[lang = "bitxor_assign"]
1229 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1230 pub trait BitXorAssign
<Rhs
=Self> {
1231 /// The method for the `^=` operator
1232 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1233 fn bitxor_assign(&mut self, Rhs
);
1236 macro_rules
! bitxor_assign_impl
{
1238 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1239 impl BitXorAssign
for $t
{
1241 fn bitxor_assign(&mut self, other
: $t
) { *self ^= other }
1246 bitxor_assign_impl
! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1248 /// The `ShlAssign` trait is used to specify the functionality of `<<=`.
1252 /// A trivial implementation of `ShlAssign`. When `Foo <<= Foo` happens, it ends up
1253 /// calling `shl_assign`, and therefore, `main` prints `Shifting left!`.
1256 /// use std::ops::ShlAssign;
1260 /// impl ShlAssign<Foo> for Foo {
1261 /// fn shl_assign(&mut self, _rhs: Foo) {
1262 /// println!("Shifting left!");
1266 /// # #[allow(unused_assignments)]
1268 /// let mut foo = Foo;
1272 #[lang = "shl_assign"]
1273 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1274 pub trait ShlAssign
<Rhs
> {
1275 /// The method for the `<<=` operator
1276 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1277 fn shl_assign(&mut self, Rhs
);
1280 macro_rules
! shl_assign_impl
{
1282 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1283 impl ShlAssign
<$f
> for $t
{
1285 #[rustc_inherit_overflow_checks]
1286 fn shl_assign(&mut self, other
: $f
) {
1293 macro_rules
! shl_assign_impl_all
{
1295 shl_assign_impl
! { $t, u8 }
1296 shl_assign_impl
! { $t, u16 }
1297 shl_assign_impl
! { $t, u32 }
1298 shl_assign_impl
! { $t, u64 }
1299 shl_assign_impl
! { $t, usize }
1301 shl_assign_impl
! { $t, i8 }
1302 shl_assign_impl
! { $t, i16 }
1303 shl_assign_impl
! { $t, i32 }
1304 shl_assign_impl
! { $t, i64 }
1305 shl_assign_impl
! { $t, isize }
1309 shl_assign_impl_all
! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
1311 /// The `ShrAssign` trait is used to specify the functionality of `>>=`.
1315 /// A trivial implementation of `ShrAssign`. When `Foo >>= Foo` happens, it ends up
1316 /// calling `shr_assign`, and therefore, `main` prints `Shifting right!`.
1319 /// use std::ops::ShrAssign;
1323 /// impl ShrAssign<Foo> for Foo {
1324 /// fn shr_assign(&mut self, _rhs: Foo) {
1325 /// println!("Shifting right!");
1329 /// # #[allow(unused_assignments)]
1331 /// let mut foo = Foo;
1335 #[lang = "shr_assign"]
1336 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1337 pub trait ShrAssign
<Rhs
=Self> {
1338 /// The method for the `>>=` operator
1339 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1340 fn shr_assign(&mut self, Rhs
);
1343 macro_rules
! shr_assign_impl
{
1345 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1346 impl ShrAssign
<$f
> for $t
{
1348 #[rustc_inherit_overflow_checks]
1349 fn shr_assign(&mut self, other
: $f
) {
1356 macro_rules
! shr_assign_impl_all
{
1358 shr_assign_impl
! { $t, u8 }
1359 shr_assign_impl
! { $t, u16 }
1360 shr_assign_impl
! { $t, u32 }
1361 shr_assign_impl
! { $t, u64 }
1362 shr_assign_impl
! { $t, usize }
1364 shr_assign_impl
! { $t, i8 }
1365 shr_assign_impl
! { $t, i16 }
1366 shr_assign_impl
! { $t, i32 }
1367 shr_assign_impl
! { $t, i64 }
1368 shr_assign_impl
! { $t, isize }
1372 shr_assign_impl_all
! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
1374 /// The `Index` trait is used to specify the functionality of indexing operations
1375 /// like `arr[idx]` when used in an immutable context.
1379 /// A trivial implementation of `Index`. When `Foo[Bar]` happens, it ends up
1380 /// calling `index`, and therefore, `main` prints `Indexing!`.
1383 /// use std::ops::Index;
1385 /// #[derive(Copy, Clone)]
1389 /// impl Index<Bar> for Foo {
1390 /// type Output = Foo;
1392 /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
1393 /// println!("Indexing!");
1403 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 pub trait Index
<Idx
: ?Sized
> {
1406 /// The returned type after indexing
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 type Output
: ?Sized
;
1410 /// The method for the indexing (`Foo[Bar]`) operation
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 fn index(&self, index
: Idx
) -> &Self::Output
;
1415 /// The `IndexMut` trait is used to specify the functionality of indexing
1416 /// operations like `arr[idx]`, when used in a mutable context.
1420 /// A trivial implementation of `IndexMut`. When `Foo[Bar]` happens, it ends up
1421 /// calling `index_mut`, and therefore, `main` prints `Indexing!`.
1424 /// use std::ops::{Index, IndexMut};
1426 /// #[derive(Copy, Clone)]
1430 /// impl Index<Bar> for Foo {
1431 /// type Output = Foo;
1433 /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
1438 /// impl IndexMut<Bar> for Foo {
1439 /// fn index_mut<'a>(&'a mut self, _index: Bar) -> &'a mut Foo {
1440 /// println!("Indexing!");
1449 #[lang = "index_mut"]
1450 #[rustc_on_unimplemented = "the type `{Self}` cannot be mutably indexed by `{Idx}`"]
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 pub trait IndexMut
<Idx
: ?Sized
>: Index
<Idx
> {
1453 /// The method for the indexing (`Foo[Bar]`) operation
1454 #[stable(feature = "rust1", since = "1.0.0")]
1455 fn index_mut(&mut self, index
: Idx
) -> &mut Self::Output
;
1458 /// An unbounded range. Use `..` (two dots) for its shorthand.
1460 /// Its primary use case is slicing index. It cannot serve as an iterator
1461 /// because it doesn't have a starting point.
1467 /// assert_eq!((..), std::ops::RangeFull);
1469 /// let arr = [0, 1, 2, 3];
1470 /// assert_eq!(arr[ .. ], [0,1,2,3]); // RangeFull
1471 /// assert_eq!(arr[ ..3], [0,1,2 ]);
1472 /// assert_eq!(arr[1.. ], [ 1,2,3]);
1473 /// assert_eq!(arr[1..3], [ 1,2 ]);
1476 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
1477 #[stable(feature = "rust1", since = "1.0.0")]
1478 pub struct RangeFull
;
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 impl fmt
::Debug
for RangeFull
{
1482 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
1487 /// A (half-open) range which is bounded at both ends: { x | start <= x < end }.
1488 /// Use `start..end` (two dots) for its shorthand.
1490 /// See the [`contains()`](#method.contains) method for its characterization.
1496 /// assert_eq!((3..5), std::ops::Range{ start: 3, end: 5 });
1497 /// assert_eq!(3+4+5, (3..6).sum());
1499 /// let arr = [0, 1, 2, 3];
1500 /// assert_eq!(arr[ .. ], [0,1,2,3]);
1501 /// assert_eq!(arr[ ..3], [0,1,2 ]);
1502 /// assert_eq!(arr[1.. ], [ 1,2,3]);
1503 /// assert_eq!(arr[1..3], [ 1,2 ]); // Range
1506 #[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 pub struct Range
<Idx
> {
1509 /// The lower bound of the range (inclusive).
1510 #[stable(feature = "rust1", since = "1.0.0")]
1512 /// The upper bound of the range (exclusive).
1513 #[stable(feature = "rust1", since = "1.0.0")]
1517 #[stable(feature = "rust1", since = "1.0.0")]
1518 impl<Idx
: fmt
::Debug
> fmt
::Debug
for Range
<Idx
> {
1519 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
1520 write
!(fmt
, "{:?}..{:?}", self.start
, self.end
)
1524 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1525 impl<Idx
: PartialOrd
<Idx
>> Range
<Idx
> {
1529 /// #![feature(range_contains)]
1531 /// assert!( ! (3..5).contains(2));
1532 /// assert!( (3..5).contains(3));
1533 /// assert!( (3..5).contains(4));
1534 /// assert!( ! (3..5).contains(5));
1536 /// assert!( ! (3..3).contains(3));
1537 /// assert!( ! (3..2).contains(3));
1540 pub fn contains(&self, item
: Idx
) -> bool
{
1541 (self.start
<= item
) && (item
< self.end
)
1545 /// A range which is only bounded below: { x | start <= x }.
1546 /// Use `start..` for its shorthand.
1548 /// See the [`contains()`](#method.contains) method for its characterization.
1550 /// Note: Currently, no overflow checking is done for the iterator
1551 /// implementation; if you use an integer range and the integer overflows, it
1552 /// might panic in debug mode or create an endless loop in release mode. This
1553 /// overflow behavior might change in the future.
1559 /// assert_eq!((2..), std::ops::RangeFrom{ start: 2 });
1560 /// assert_eq!(2+3+4, (2..).take(3).sum());
1562 /// let arr = [0, 1, 2, 3];
1563 /// assert_eq!(arr[ .. ], [0,1,2,3]);
1564 /// assert_eq!(arr[ ..3], [0,1,2 ]);
1565 /// assert_eq!(arr[1.. ], [ 1,2,3]); // RangeFrom
1566 /// assert_eq!(arr[1..3], [ 1,2 ]);
1569 #[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 pub struct RangeFrom
<Idx
> {
1572 /// The lower bound of the range (inclusive).
1573 #[stable(feature = "rust1", since = "1.0.0")]
1577 #[stable(feature = "rust1", since = "1.0.0")]
1578 impl<Idx
: fmt
::Debug
> fmt
::Debug
for RangeFrom
<Idx
> {
1579 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
1580 write
!(fmt
, "{:?}..", self.start
)
1584 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1585 impl<Idx
: PartialOrd
<Idx
>> RangeFrom
<Idx
> {
1589 /// #![feature(range_contains)]
1591 /// assert!( ! (3..).contains(2));
1592 /// assert!( (3..).contains(3));
1593 /// assert!( (3..).contains(1_000_000_000));
1596 pub fn contains(&self, item
: Idx
) -> bool
{
1597 (self.start
<= item
)
1601 /// A range which is only bounded above: { x | x < end }.
1602 /// Use `..end` (two dots) for its shorthand.
1604 /// See the [`contains()`](#method.contains) method for its characterization.
1606 /// It cannot serve as an iterator because it doesn't have a starting point.
1610 /// assert_eq!((..5), std::ops::RangeTo{ end: 5 });
1612 /// let arr = [0, 1, 2, 3];
1613 /// assert_eq!(arr[ .. ], [0,1,2,3]);
1614 /// assert_eq!(arr[ ..3], [0,1,2 ]); // RangeTo
1615 /// assert_eq!(arr[1.. ], [ 1,2,3]);
1616 /// assert_eq!(arr[1..3], [ 1,2 ]);
1619 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 pub struct RangeTo
<Idx
> {
1622 /// The upper bound of the range (exclusive).
1623 #[stable(feature = "rust1", since = "1.0.0")]
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 impl<Idx
: fmt
::Debug
> fmt
::Debug
for RangeTo
<Idx
> {
1629 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
1630 write
!(fmt
, "..{:?}", self.end
)
1634 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1635 impl<Idx
: PartialOrd
<Idx
>> RangeTo
<Idx
> {
1639 /// #![feature(range_contains)]
1641 /// assert!( (..5).contains(-1_000_000_000));
1642 /// assert!( (..5).contains(4));
1643 /// assert!( ! (..5).contains(5));
1646 pub fn contains(&self, item
: Idx
) -> bool
{
1651 /// An inclusive range which is bounded at both ends: { x | start <= x <= end }.
1652 /// Use `start...end` (three dots) for its shorthand.
1654 /// See the [`contains()`](#method.contains) method for its characterization.
1659 /// #![feature(inclusive_range,inclusive_range_syntax)]
1661 /// assert_eq!((3...5), std::ops::RangeInclusive::NonEmpty{ start: 3, end: 5 });
1662 /// assert_eq!(3+4+5, (3...5).sum());
1664 /// let arr = [0, 1, 2, 3];
1665 /// assert_eq!(arr[ ...2], [0,1,2 ]);
1666 /// assert_eq!(arr[1...2], [ 1,2 ]); // RangeInclusive
1669 #[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
1670 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1671 pub enum RangeInclusive
<Idx
> {
1672 /// Empty range (iteration has finished)
1673 #[unstable(feature = "inclusive_range",
1674 reason
= "recently added, follows RFC",
1677 /// The point at which iteration finished
1678 #[unstable(feature = "inclusive_range",
1679 reason
= "recently added, follows RFC",
1683 /// Non-empty range (iteration will yield value(s))
1684 #[unstable(feature = "inclusive_range",
1685 reason
= "recently added, follows RFC",
1688 /// The lower bound of the range (inclusive).
1689 #[unstable(feature = "inclusive_range",
1690 reason
= "recently added, follows RFC",
1693 /// The upper bound of the range (inclusive).
1694 #[unstable(feature = "inclusive_range",
1695 reason
= "recently added, follows RFC",
1701 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1702 impl<Idx
: fmt
::Debug
> fmt
::Debug
for RangeInclusive
<Idx
> {
1703 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
1704 use self::RangeInclusive
::*;
1707 Empty { ref at }
=> write
!(fmt
, "[empty range @ {:?}]", at
),
1708 NonEmpty { ref start, ref end }
=> write
!(fmt
, "{:?}...{:?}", start
, end
),
1713 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1714 impl<Idx
: PartialOrd
<Idx
>> RangeInclusive
<Idx
> {
1718 /// #![feature(range_contains,inclusive_range_syntax)]
1720 /// assert!( ! (3...5).contains(2));
1721 /// assert!( (3...5).contains(3));
1722 /// assert!( (3...5).contains(4));
1723 /// assert!( (3...5).contains(5));
1724 /// assert!( ! (3...5).contains(6));
1726 /// assert!( (3...3).contains(3));
1727 /// assert!( ! (3...2).contains(3));
1730 pub fn contains(&self, item
: Idx
) -> bool
{
1731 if let &RangeInclusive
::NonEmpty{ref start, ref end}
= self {
1732 (*start
<= item
) && (item
<= *end
)
1737 /// An inclusive range which is only bounded above: { x | x <= end }.
1738 /// Use `...end` (three dots) for its shorthand.
1740 /// See the [`contains()`](#method.contains) method for its characterization.
1742 /// It cannot serve as an iterator because it doesn't have a starting point.
1747 /// #![feature(inclusive_range,inclusive_range_syntax)]
1749 /// assert_eq!((...5), std::ops::RangeToInclusive{ end: 5 });
1751 /// let arr = [0, 1, 2, 3];
1752 /// assert_eq!(arr[ ...2], [0,1,2 ]); // RangeToInclusive
1753 /// assert_eq!(arr[1...2], [ 1,2 ]);
1756 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
1757 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1758 pub struct RangeToInclusive
<Idx
> {
1759 /// The upper bound of the range (inclusive)
1760 #[unstable(feature = "inclusive_range",
1761 reason
= "recently added, follows RFC",
1766 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1767 impl<Idx
: fmt
::Debug
> fmt
::Debug
for RangeToInclusive
<Idx
> {
1768 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
1769 write
!(fmt
, "...{:?}", self.end
)
1773 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1774 impl<Idx
: PartialOrd
<Idx
>> RangeToInclusive
<Idx
> {
1778 /// #![feature(range_contains,inclusive_range_syntax)]
1780 /// assert!( (...5).contains(-1_000_000_000));
1781 /// assert!( (...5).contains(5));
1782 /// assert!( ! (...5).contains(6));
1785 pub fn contains(&self, item
: Idx
) -> bool
{
1790 // RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
1791 // because underflow would be possible with (..0).into()
1793 /// The `Deref` trait is used to specify the functionality of dereferencing
1794 /// operations, like `*v`.
1796 /// `Deref` also enables ['`Deref` coercions'][coercions].
1798 /// [coercions]: ../../book/deref-coercions.html
1802 /// A struct with a single field which is accessible via dereferencing the
1806 /// use std::ops::Deref;
1808 /// struct DerefExample<T> {
1812 /// impl<T> Deref for DerefExample<T> {
1813 /// type Target = T;
1815 /// fn deref(&self) -> &T {
1821 /// let x = DerefExample { value: 'a' };
1822 /// assert_eq!('a', *x);
1826 #[stable(feature = "rust1", since = "1.0.0")]
1828 /// The resulting type after dereferencing
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 type Target
: ?Sized
;
1832 /// The method called to dereference a value
1833 #[stable(feature = "rust1", since = "1.0.0")]
1834 fn deref(&self) -> &Self::Target
;
1837 #[stable(feature = "rust1", since = "1.0.0")]
1838 impl<'a
, T
: ?Sized
> Deref
for &'a T
{
1841 fn deref(&self) -> &T { *self }
1844 #[stable(feature = "rust1", since = "1.0.0")]
1845 impl<'a
, T
: ?Sized
> Deref
for &'a
mut T
{
1848 fn deref(&self) -> &T { *self }
1851 /// The `DerefMut` trait is used to specify the functionality of dereferencing
1852 /// mutably like `*v = 1;`
1854 /// `DerefMut` also enables ['`Deref` coercions'][coercions].
1856 /// [coercions]: ../../book/deref-coercions.html
1860 /// A struct with a single field which is modifiable via dereferencing the
1864 /// use std::ops::{Deref, DerefMut};
1866 /// struct DerefMutExample<T> {
1870 /// impl<T> Deref for DerefMutExample<T> {
1871 /// type Target = T;
1873 /// fn deref<'a>(&'a self) -> &'a T {
1878 /// impl<T> DerefMut for DerefMutExample<T> {
1879 /// fn deref_mut<'a>(&'a mut self) -> &'a mut T {
1885 /// let mut x = DerefMutExample { value: 'a' };
1887 /// assert_eq!('b', *x);
1890 #[lang = "deref_mut"]
1891 #[stable(feature = "rust1", since = "1.0.0")]
1892 pub trait DerefMut
: Deref
{
1893 /// The method called to mutably dereference a value
1894 #[stable(feature = "rust1", since = "1.0.0")]
1895 fn deref_mut(&mut self) -> &mut Self::Target
;
1898 #[stable(feature = "rust1", since = "1.0.0")]
1899 impl<'a
, T
: ?Sized
> DerefMut
for &'a
mut T
{
1900 fn deref_mut(&mut self) -> &mut T { *self }
1903 /// A version of the call operator that takes an immutable receiver.
1905 #[stable(feature = "rust1", since = "1.0.0")]
1906 #[rustc_paren_sugar]
1907 #[fundamental] // so that regex can rely that `&str: !FnMut`
1908 pub trait Fn
<Args
> : FnMut
<Args
> {
1909 /// This is called when the call operator is used.
1910 #[unstable(feature = "fn_traits", issue = "29625")]
1911 extern "rust-call" fn call(&self, args
: Args
) -> Self::Output
;
1914 /// A version of the call operator that takes a mutable receiver.
1916 #[stable(feature = "rust1", since = "1.0.0")]
1917 #[rustc_paren_sugar]
1918 #[fundamental] // so that regex can rely that `&str: !FnMut`
1919 pub trait FnMut
<Args
> : FnOnce
<Args
> {
1920 /// This is called when the call operator is used.
1921 #[unstable(feature = "fn_traits", issue = "29625")]
1922 extern "rust-call" fn call_mut(&mut self, args
: Args
) -> Self::Output
;
1925 /// A version of the call operator that takes a by-value receiver.
1927 #[stable(feature = "rust1", since = "1.0.0")]
1928 #[rustc_paren_sugar]
1929 #[fundamental] // so that regex can rely that `&str: !FnMut`
1930 pub trait FnOnce
<Args
> {
1931 /// The returned type after the call operator is used.
1932 #[stable(feature = "fn_once_output", since = "1.12.0")]
1935 /// This is called when the call operator is used.
1936 #[unstable(feature = "fn_traits", issue = "29625")]
1937 extern "rust-call" fn call_once(self, args
: Args
) -> Self::Output
;
1942 use super::{Fn, FnMut, FnOnce}
;
1944 #[stable(feature = "rust1", since = "1.0.0")]
1945 impl<'a
,A
,F
:?Sized
> Fn
<A
> for &'a F
1948 extern "rust-call" fn call(&self, args
: A
) -> F
::Output
{
1953 #[stable(feature = "rust1", since = "1.0.0")]
1954 impl<'a
,A
,F
:?Sized
> FnMut
<A
> for &'a F
1957 extern "rust-call" fn call_mut(&mut self, args
: A
) -> F
::Output
{
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 impl<'a
,A
,F
:?Sized
> FnOnce
<A
> for &'a F
1966 type Output
= F
::Output
;
1968 extern "rust-call" fn call_once(self, args
: A
) -> F
::Output
{
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 impl<'a
,A
,F
:?Sized
> FnMut
<A
> for &'a
mut F
1977 extern "rust-call" fn call_mut(&mut self, args
: A
) -> F
::Output
{
1978 (*self).call_mut(args
)
1982 #[stable(feature = "rust1", since = "1.0.0")]
1983 impl<'a
,A
,F
:?Sized
> FnOnce
<A
> for &'a
mut F
1986 type Output
= F
::Output
;
1987 extern "rust-call" fn call_once(mut self, args
: A
) -> F
::Output
{
1988 (*self).call_mut(args
)
1993 /// Trait that indicates that this is a pointer or a wrapper for one,
1994 /// where unsizing can be performed on the pointee.
1995 #[unstable(feature = "coerce_unsized", issue = "27732")]
1996 #[lang="coerce_unsized"]
1997 pub trait CoerceUnsized
<T
> {
2002 #[unstable(feature = "coerce_unsized", issue = "27732")]
2003 impl<'a
, T
: ?Sized
+Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<&'a
mut U
> for &'a
mut T {}
2005 #[unstable(feature = "coerce_unsized", issue = "27732")]
2006 impl<'a
, 'b
: 'a
, T
: ?Sized
+Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<&'a U
> for &'b
mut T {}
2008 #[unstable(feature = "coerce_unsized", issue = "27732")]
2009 impl<'a
, T
: ?Sized
+Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<*mut U
> for &'a
mut T {}
2010 // &mut T -> *const U
2011 #[unstable(feature = "coerce_unsized", issue = "27732")]
2012 impl<'a
, T
: ?Sized
+Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<*const U
> for &'a
mut T {}
2015 #[unstable(feature = "coerce_unsized", issue = "27732")]
2016 impl<'a
, 'b
: 'a
, T
: ?Sized
+Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<&'a U
> for &'b T {}
2018 #[unstable(feature = "coerce_unsized", issue = "27732")]
2019 impl<'a
, T
: ?Sized
+Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<*const U
> for &'a T {}
2022 #[unstable(feature = "coerce_unsized", issue = "27732")]
2023 impl<T
: ?Sized
+Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<*mut U
> for *mut T {}
2024 // *mut T -> *const U
2025 #[unstable(feature = "coerce_unsized", issue = "27732")]
2026 impl<T
: ?Sized
+Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<*const U
> for *mut T {}
2028 // *const T -> *const U
2029 #[unstable(feature = "coerce_unsized", issue = "27732")]
2030 impl<T
: ?Sized
+Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<*const U
> for *const T {}
2032 /// Both `in (PLACE) EXPR` and `box EXPR` desugar into expressions
2033 /// that allocate an intermediate "place" that holds uninitialized
2034 /// state. The desugaring evaluates EXPR, and writes the result at
2035 /// the address returned by the `pointer` method of this trait.
2037 /// A `Place` can be thought of as a special representation for a
2038 /// hypothetical `&uninit` reference (which Rust cannot currently
2039 /// express directly). That is, it represents a pointer to
2040 /// uninitialized storage.
2042 /// The client is responsible for two steps: First, initializing the
2043 /// payload (it can access its address via `pointer`). Second,
2044 /// converting the agent to an instance of the owning pointer, via the
2045 /// appropriate `finalize` method (see the `InPlace`.
2047 /// If evaluating EXPR fails, then the destructor for the
2048 /// implementation of Place to clean up any intermediate state
2049 /// (e.g. deallocate box storage, pop a stack, etc).
2050 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2051 pub trait Place
<Data
: ?Sized
> {
2052 /// Returns the address where the input value will be written.
2053 /// Note that the data at this address is generally uninitialized,
2054 /// and thus one should use `ptr::write` for initializing it.
2055 fn pointer(&mut self) -> *mut Data
;
2058 /// Interface to implementations of `in (PLACE) EXPR`.
2060 /// `in (PLACE) EXPR` effectively desugars into:
2064 /// let mut place = Placer::make_place(p);
2065 /// let raw_place = Place::pointer(&mut place);
2066 /// let value = EXPR;
2068 /// std::ptr::write(raw_place, value);
2069 /// InPlace::finalize(place)
2073 /// The type of `in (PLACE) EXPR` is derived from the type of `PLACE`;
2074 /// if the type of `PLACE` is `P`, then the final type of the whole
2075 /// expression is `P::Place::Owner` (see the `InPlace` and `Boxed`
2078 /// Values for types implementing this trait usually are transient
2079 /// intermediate values (e.g. the return value of `Vec::emplace_back`)
2080 /// or `Copy`, since the `make_place` method takes `self` by value.
2081 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2082 pub trait Placer
<Data
: ?Sized
> {
2083 /// `Place` is the intermedate agent guarding the
2084 /// uninitialized state for `Data`.
2085 type Place
: InPlace
<Data
>;
2087 /// Creates a fresh place from `self`.
2088 fn make_place(self) -> Self::Place
;
2091 /// Specialization of `Place` trait supporting `in (PLACE) EXPR`.
2092 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2093 pub trait InPlace
<Data
: ?Sized
>: Place
<Data
> {
2094 /// `Owner` is the type of the end value of `in (PLACE) EXPR`
2096 /// Note that when `in (PLACE) EXPR` is solely used for
2097 /// side-effecting an existing data-structure,
2098 /// e.g. `Vec::emplace_back`, then `Owner` need not carry any
2099 /// information at all (e.g. it can be the unit type `()` in that
2103 /// Converts self into the final value, shifting
2104 /// deallocation/cleanup responsibilities (if any remain), over to
2105 /// the returned instance of `Owner` and forgetting self.
2106 unsafe fn finalize(self) -> Self::Owner
;
2109 /// Core trait for the `box EXPR` form.
2111 /// `box EXPR` effectively desugars into:
2114 /// let mut place = BoxPlace::make_place();
2115 /// let raw_place = Place::pointer(&mut place);
2116 /// let value = EXPR;
2118 /// ::std::ptr::write(raw_place, value);
2119 /// Boxed::finalize(place)
2123 /// The type of `box EXPR` is supplied from its surrounding
2124 /// context; in the above expansion, the result type `T` is used
2125 /// to determine which implementation of `Boxed` to use, and that
2126 /// `<T as Boxed>` in turn dictates determines which
2127 /// implementation of `BoxPlace` to use, namely:
2128 /// `<<T as Boxed>::Place as BoxPlace>`.
2129 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2131 /// The kind of data that is stored in this kind of box.
2132 type Data
; /* (`Data` unused b/c cannot yet express below bound.) */
2133 /// The place that will negotiate the storage of the data.
2134 type Place
: BoxPlace
<Self::Data
>;
2136 /// Converts filled place into final owning value, shifting
2137 /// deallocation/cleanup responsibilities (if any remain), over to
2138 /// returned instance of `Self` and forgetting `filled`.
2139 unsafe fn finalize(filled
: Self::Place
) -> Self;
2142 /// Specialization of `Place` trait supporting `box EXPR`.
2143 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2144 pub trait BoxPlace
<Data
: ?Sized
> : Place
<Data
> {
2145 /// Creates a globally fresh place.
2146 fn make_place() -> Self;