]> git.proxmox.com Git - rustc.git/blob - src/libcore/ops.rs
New upstream version 1.12.0+dfsg1
[rustc.git] / src / libcore / ops.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Overloadable operators.
12 //!
13 //! Implementing these traits allows you to get an effect similar to
14 //! overloading operators.
15 //!
16 //! Some of these traits are imported by the prelude, so they are available in
17 //! every Rust program.
18 //!
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.
29 //!
30 //! # Examples
31 //!
32 //! This example creates a `Point` struct that implements `Add` and `Sub`, and
33 //! then demonstrates adding and subtracting two `Point`s.
34 //!
35 //! ```rust
36 //! use std::ops::{Add, Sub};
37 //!
38 //! #[derive(Debug)]
39 //! struct Point {
40 //! x: i32,
41 //! y: i32,
42 //! }
43 //!
44 //! impl Add for Point {
45 //! type Output = Point;
46 //!
47 //! fn add(self, other: Point) -> Point {
48 //! Point {x: self.x + other.x, y: self.y + other.y}
49 //! }
50 //! }
51 //!
52 //! impl Sub for Point {
53 //! type Output = Point;
54 //!
55 //! fn sub(self, other: Point) -> Point {
56 //! Point {x: self.x - other.x, y: self.y - other.y}
57 //! }
58 //! }
59 //! fn main() {
60 //! println!("{:?}", Point {x: 1, y: 0} + Point {x: 2, y: 3});
61 //! println!("{:?}", Point {x: 1, y: 0} - Point {x: 2, y: 3});
62 //! }
63 //! ```
64 //!
65 //! See the documentation for each trait for a minimum implementation that
66 //! prints something to the screen.
67
68 #![stable(feature = "rust1", since = "1.0.0")]
69
70 use cmp::PartialOrd;
71 use fmt;
72 use marker::{Sized, Unsize};
73
74 /// The `Drop` trait is used to run some code when a value goes out of scope.
75 /// This is sometimes called a 'destructor'.
76 ///
77 /// # Examples
78 ///
79 /// A trivial implementation of `Drop`. The `drop` method is called when `_x`
80 /// goes out of scope, and therefore `main` prints `Dropping!`.
81 ///
82 /// ```
83 /// struct HasDrop;
84 ///
85 /// impl Drop for HasDrop {
86 /// fn drop(&mut self) {
87 /// println!("Dropping!");
88 /// }
89 /// }
90 ///
91 /// fn main() {
92 /// let _x = HasDrop;
93 /// }
94 /// ```
95 #[lang = "drop"]
96 #[stable(feature = "rust1", since = "1.0.0")]
97 pub trait Drop {
98 /// A method called when the value goes out of scope.
99 ///
100 /// When this method has been called, `self` has not yet been deallocated.
101 /// If it were, `self` would be a dangling reference.
102 ///
103 /// After this function is over, the memory of `self` will be deallocated.
104 ///
105 /// # Panics
106 ///
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")]
110 fn drop(&mut self);
111 }
112
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;
120
121 #[inline]
122 fn $method(self) -> <$t as $imp>::Output {
123 $imp::$method(*self)
124 }
125 }
126 }
127 }
128
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;
136
137 #[inline]
138 fn $method(self, other: $u) -> <$t as $imp<$u>>::Output {
139 $imp::$method(*self, other)
140 }
141 }
142
143 #[stable(feature = "rust1", since = "1.0.0")]
144 impl<'a> $imp<&'a $u> for $t {
145 type Output = <$t as $imp<$u>>::Output;
146
147 #[inline]
148 fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output {
149 $imp::$method(self, *other)
150 }
151 }
152
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;
156
157 #[inline]
158 fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output {
159 $imp::$method(*self, *other)
160 }
161 }
162 }
163 }
164
165 /// The `Add` trait is used to specify the functionality of `+`.
166 ///
167 /// # Examples
168 ///
169 /// A trivial implementation of `Add`. When `Foo + Foo` happens, it ends up
170 /// calling `add`, and therefore, `main` prints `Adding!`.
171 ///
172 /// ```
173 /// use std::ops::Add;
174 ///
175 /// struct Foo;
176 ///
177 /// impl Add for Foo {
178 /// type Output = Foo;
179 ///
180 /// fn add(self, _rhs: Foo) -> Foo {
181 /// println!("Adding!");
182 /// self
183 /// }
184 /// }
185 ///
186 /// fn main() {
187 /// Foo + Foo;
188 /// }
189 /// ```
190 #[lang = "add"]
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")]
195 type Output;
196
197 /// The method for the `+` operator
198 #[stable(feature = "rust1", since = "1.0.0")]
199 fn add(self, rhs: RHS) -> Self::Output;
200 }
201
202 macro_rules! add_impl {
203 ($($t:ty)*) => ($(
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl Add for $t {
206 type Output = $t;
207
208 #[inline]
209 #[rustc_inherit_overflow_checks]
210 fn add(self, other: $t) -> $t { self + other }
211 }
212
213 forward_ref_binop! { impl Add, add for $t, $t }
214 )*)
215 }
216
217 add_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
218
219 /// The `Sub` trait is used to specify the functionality of `-`.
220 ///
221 /// # Examples
222 ///
223 /// A trivial implementation of `Sub`. When `Foo - Foo` happens, it ends up
224 /// calling `sub`, and therefore, `main` prints `Subtracting!`.
225 ///
226 /// ```
227 /// use std::ops::Sub;
228 ///
229 /// struct Foo;
230 ///
231 /// impl Sub for Foo {
232 /// type Output = Foo;
233 ///
234 /// fn sub(self, _rhs: Foo) -> Foo {
235 /// println!("Subtracting!");
236 /// self
237 /// }
238 /// }
239 ///
240 /// fn main() {
241 /// Foo - Foo;
242 /// }
243 /// ```
244 #[lang = "sub"]
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")]
249 type Output;
250
251 /// The method for the `-` operator
252 #[stable(feature = "rust1", since = "1.0.0")]
253 fn sub(self, rhs: RHS) -> Self::Output;
254 }
255
256 macro_rules! sub_impl {
257 ($($t:ty)*) => ($(
258 #[stable(feature = "rust1", since = "1.0.0")]
259 impl Sub for $t {
260 type Output = $t;
261
262 #[inline]
263 #[rustc_inherit_overflow_checks]
264 fn sub(self, other: $t) -> $t { self - other }
265 }
266
267 forward_ref_binop! { impl Sub, sub for $t, $t }
268 )*)
269 }
270
271 sub_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
272
273 /// The `Mul` trait is used to specify the functionality of `*`.
274 ///
275 /// # Examples
276 ///
277 /// A trivial implementation of `Mul`. When `Foo * Foo` happens, it ends up
278 /// calling `mul`, and therefore, `main` prints `Multiplying!`.
279 ///
280 /// ```
281 /// use std::ops::Mul;
282 ///
283 /// struct Foo;
284 ///
285 /// impl Mul for Foo {
286 /// type Output = Foo;
287 ///
288 /// fn mul(self, _rhs: Foo) -> Foo {
289 /// println!("Multiplying!");
290 /// self
291 /// }
292 /// }
293 ///
294 /// fn main() {
295 /// Foo * Foo;
296 /// }
297 /// ```
298 #[lang = "mul"]
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")]
303 type Output;
304
305 /// The method for the `*` operator
306 #[stable(feature = "rust1", since = "1.0.0")]
307 fn mul(self, rhs: RHS) -> Self::Output;
308 }
309
310 macro_rules! mul_impl {
311 ($($t:ty)*) => ($(
312 #[stable(feature = "rust1", since = "1.0.0")]
313 impl Mul for $t {
314 type Output = $t;
315
316 #[inline]
317 #[rustc_inherit_overflow_checks]
318 fn mul(self, other: $t) -> $t { self * other }
319 }
320
321 forward_ref_binop! { impl Mul, mul for $t, $t }
322 )*)
323 }
324
325 mul_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
326
327 /// The `Div` trait is used to specify the functionality of `/`.
328 ///
329 /// # Examples
330 ///
331 /// A trivial implementation of `Div`. When `Foo / Foo` happens, it ends up
332 /// calling `div`, and therefore, `main` prints `Dividing!`.
333 ///
334 /// ```
335 /// use std::ops::Div;
336 ///
337 /// struct Foo;
338 ///
339 /// impl Div for Foo {
340 /// type Output = Foo;
341 ///
342 /// fn div(self, _rhs: Foo) -> Foo {
343 /// println!("Dividing!");
344 /// self
345 /// }
346 /// }
347 ///
348 /// fn main() {
349 /// Foo / Foo;
350 /// }
351 /// ```
352 #[lang = "div"]
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")]
357 type Output;
358
359 /// The method for the `/` operator
360 #[stable(feature = "rust1", since = "1.0.0")]
361 fn div(self, rhs: RHS) -> Self::Output;
362 }
363
364 macro_rules! div_impl_integer {
365 ($($t:ty)*) => ($(
366 /// This operation rounds towards zero, truncating any
367 /// fractional part of the exact result.
368 #[stable(feature = "rust1", since = "1.0.0")]
369 impl Div for $t {
370 type Output = $t;
371
372 #[inline]
373 fn div(self, other: $t) -> $t { self / other }
374 }
375
376 forward_ref_binop! { impl Div, div for $t, $t }
377 )*)
378 }
379
380 div_impl_integer! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
381
382 macro_rules! div_impl_float {
383 ($($t:ty)*) => ($(
384 #[stable(feature = "rust1", since = "1.0.0")]
385 impl Div for $t {
386 type Output = $t;
387
388 #[inline]
389 fn div(self, other: $t) -> $t { self / other }
390 }
391
392 forward_ref_binop! { impl Div, div for $t, $t }
393 )*)
394 }
395
396 div_impl_float! { f32 f64 }
397
398 /// The `Rem` trait is used to specify the functionality of `%`.
399 ///
400 /// # Examples
401 ///
402 /// A trivial implementation of `Rem`. When `Foo % Foo` happens, it ends up
403 /// calling `rem`, and therefore, `main` prints `Remainder-ing!`.
404 ///
405 /// ```
406 /// use std::ops::Rem;
407 ///
408 /// struct Foo;
409 ///
410 /// impl Rem for Foo {
411 /// type Output = Foo;
412 ///
413 /// fn rem(self, _rhs: Foo) -> Foo {
414 /// println!("Remainder-ing!");
415 /// self
416 /// }
417 /// }
418 ///
419 /// fn main() {
420 /// Foo % Foo;
421 /// }
422 /// ```
423 #[lang = "rem"]
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")]
428 type Output = Self;
429
430 /// The method for the `%` operator
431 #[stable(feature = "rust1", since = "1.0.0")]
432 fn rem(self, rhs: RHS) -> Self::Output;
433 }
434
435 macro_rules! rem_impl_integer {
436 ($($t:ty)*) => ($(
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")]
440 impl Rem for $t {
441 type Output = $t;
442
443 #[inline]
444 fn rem(self, other: $t) -> $t { self % other }
445 }
446
447 forward_ref_binop! { impl Rem, rem for $t, $t }
448 )*)
449 }
450
451 rem_impl_integer! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
452
453 macro_rules! rem_impl_float {
454 ($($t:ty)*) => ($(
455 #[stable(feature = "rust1", since = "1.0.0")]
456 impl Rem for $t {
457 type Output = $t;
458
459 #[inline]
460 fn rem(self, other: $t) -> $t { self % other }
461 }
462
463 forward_ref_binop! { impl Rem, rem for $t, $t }
464 )*)
465 }
466
467 rem_impl_float! { f32 f64 }
468
469 /// The `Neg` trait is used to specify the functionality of unary `-`.
470 ///
471 /// # Examples
472 ///
473 /// A trivial implementation of `Neg`. When `-Foo` happens, it ends up calling
474 /// `neg`, and therefore, `main` prints `Negating!`.
475 ///
476 /// ```
477 /// use std::ops::Neg;
478 ///
479 /// struct Foo;
480 ///
481 /// impl Neg for Foo {
482 /// type Output = Foo;
483 ///
484 /// fn neg(self) -> Foo {
485 /// println!("Negating!");
486 /// self
487 /// }
488 /// }
489 ///
490 /// fn main() {
491 /// -Foo;
492 /// }
493 /// ```
494 #[lang = "neg"]
495 #[stable(feature = "rust1", since = "1.0.0")]
496 pub trait Neg {
497 /// The resulting type after applying the `-` operator
498 #[stable(feature = "rust1", since = "1.0.0")]
499 type Output;
500
501 /// The method for the unary `-` operator
502 #[stable(feature = "rust1", since = "1.0.0")]
503 fn neg(self) -> Self::Output;
504 }
505
506
507
508 macro_rules! neg_impl_core {
509 ($id:ident => $body:expr, $($t:ty)*) => ($(
510 #[stable(feature = "rust1", since = "1.0.0")]
511 impl Neg for $t {
512 type Output = $t;
513
514 #[inline]
515 #[rustc_inherit_overflow_checks]
516 fn neg(self) -> $t { let $id = self; $body }
517 }
518
519 forward_ref_unop! { impl Neg, neg for $t }
520 )*)
521 }
522
523 macro_rules! neg_impl_numeric {
524 ($($t:ty)*) => { neg_impl_core!{ x => -x, $($t)*} }
525 }
526
527 macro_rules! neg_impl_unsigned {
528 ($($t:ty)*) => {
529 neg_impl_core!{ x => {
530 !x.wrapping_add(1)
531 }, $($t)*} }
532 }
533
534 // neg_impl_unsigned! { usize u8 u16 u32 u64 }
535 neg_impl_numeric! { isize i8 i16 i32 i64 f32 f64 }
536
537 /// The `Not` trait is used to specify the functionality of unary `!`.
538 ///
539 /// # Examples
540 ///
541 /// A trivial implementation of `Not`. When `!Foo` happens, it ends up calling
542 /// `not`, and therefore, `main` prints `Not-ing!`.
543 ///
544 /// ```
545 /// use std::ops::Not;
546 ///
547 /// struct Foo;
548 ///
549 /// impl Not for Foo {
550 /// type Output = Foo;
551 ///
552 /// fn not(self) -> Foo {
553 /// println!("Not-ing!");
554 /// self
555 /// }
556 /// }
557 ///
558 /// fn main() {
559 /// !Foo;
560 /// }
561 /// ```
562 #[lang = "not"]
563 #[stable(feature = "rust1", since = "1.0.0")]
564 pub trait Not {
565 /// The resulting type after applying the `!` operator
566 #[stable(feature = "rust1", since = "1.0.0")]
567 type Output;
568
569 /// The method for the unary `!` operator
570 #[stable(feature = "rust1", since = "1.0.0")]
571 fn not(self) -> Self::Output;
572 }
573
574 macro_rules! not_impl {
575 ($($t:ty)*) => ($(
576 #[stable(feature = "rust1", since = "1.0.0")]
577 impl Not for $t {
578 type Output = $t;
579
580 #[inline]
581 fn not(self) -> $t { !self }
582 }
583
584 forward_ref_unop! { impl Not, not for $t }
585 )*)
586 }
587
588 not_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
589
590 /// The `BitAnd` trait is used to specify the functionality of `&`.
591 ///
592 /// # Examples
593 ///
594 /// A trivial implementation of `BitAnd`. When `Foo & Foo` happens, it ends up
595 /// calling `bitand`, and therefore, `main` prints `Bitwise And-ing!`.
596 ///
597 /// ```
598 /// use std::ops::BitAnd;
599 ///
600 /// struct Foo;
601 ///
602 /// impl BitAnd for Foo {
603 /// type Output = Foo;
604 ///
605 /// fn bitand(self, _rhs: Foo) -> Foo {
606 /// println!("Bitwise And-ing!");
607 /// self
608 /// }
609 /// }
610 ///
611 /// fn main() {
612 /// Foo & Foo;
613 /// }
614 /// ```
615 #[lang = "bitand"]
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")]
620 type Output;
621
622 /// The method for the `&` operator
623 #[stable(feature = "rust1", since = "1.0.0")]
624 fn bitand(self, rhs: RHS) -> Self::Output;
625 }
626
627 macro_rules! bitand_impl {
628 ($($t:ty)*) => ($(
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl BitAnd for $t {
631 type Output = $t;
632
633 #[inline]
634 fn bitand(self, rhs: $t) -> $t { self & rhs }
635 }
636
637 forward_ref_binop! { impl BitAnd, bitand for $t, $t }
638 )*)
639 }
640
641 bitand_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
642
643 /// The `BitOr` trait is used to specify the functionality of `|`.
644 ///
645 /// # Examples
646 ///
647 /// A trivial implementation of `BitOr`. When `Foo | Foo` happens, it ends up
648 /// calling `bitor`, and therefore, `main` prints `Bitwise Or-ing!`.
649 ///
650 /// ```
651 /// use std::ops::BitOr;
652 ///
653 /// struct Foo;
654 ///
655 /// impl BitOr for Foo {
656 /// type Output = Foo;
657 ///
658 /// fn bitor(self, _rhs: Foo) -> Foo {
659 /// println!("Bitwise Or-ing!");
660 /// self
661 /// }
662 /// }
663 ///
664 /// fn main() {
665 /// Foo | Foo;
666 /// }
667 /// ```
668 #[lang = "bitor"]
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")]
673 type Output;
674
675 /// The method for the `|` operator
676 #[stable(feature = "rust1", since = "1.0.0")]
677 fn bitor(self, rhs: RHS) -> Self::Output;
678 }
679
680 macro_rules! bitor_impl {
681 ($($t:ty)*) => ($(
682 #[stable(feature = "rust1", since = "1.0.0")]
683 impl BitOr for $t {
684 type Output = $t;
685
686 #[inline]
687 fn bitor(self, rhs: $t) -> $t { self | rhs }
688 }
689
690 forward_ref_binop! { impl BitOr, bitor for $t, $t }
691 )*)
692 }
693
694 bitor_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
695
696 /// The `BitXor` trait is used to specify the functionality of `^`.
697 ///
698 /// # Examples
699 ///
700 /// A trivial implementation of `BitXor`. When `Foo ^ Foo` happens, it ends up
701 /// calling `bitxor`, and therefore, `main` prints `Bitwise Xor-ing!`.
702 ///
703 /// ```
704 /// use std::ops::BitXor;
705 ///
706 /// struct Foo;
707 ///
708 /// impl BitXor for Foo {
709 /// type Output = Foo;
710 ///
711 /// fn bitxor(self, _rhs: Foo) -> Foo {
712 /// println!("Bitwise Xor-ing!");
713 /// self
714 /// }
715 /// }
716 ///
717 /// fn main() {
718 /// Foo ^ Foo;
719 /// }
720 /// ```
721 #[lang = "bitxor"]
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")]
726 type Output;
727
728 /// The method for the `^` operator
729 #[stable(feature = "rust1", since = "1.0.0")]
730 fn bitxor(self, rhs: RHS) -> Self::Output;
731 }
732
733 macro_rules! bitxor_impl {
734 ($($t:ty)*) => ($(
735 #[stable(feature = "rust1", since = "1.0.0")]
736 impl BitXor for $t {
737 type Output = $t;
738
739 #[inline]
740 fn bitxor(self, other: $t) -> $t { self ^ other }
741 }
742
743 forward_ref_binop! { impl BitXor, bitxor for $t, $t }
744 )*)
745 }
746
747 bitxor_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
748
749 /// The `Shl` trait is used to specify the functionality of `<<`.
750 ///
751 /// # Examples
752 ///
753 /// A trivial implementation of `Shl`. When `Foo << Foo` happens, it ends up
754 /// calling `shl`, and therefore, `main` prints `Shifting left!`.
755 ///
756 /// ```
757 /// use std::ops::Shl;
758 ///
759 /// struct Foo;
760 ///
761 /// impl Shl<Foo> for Foo {
762 /// type Output = Foo;
763 ///
764 /// fn shl(self, _rhs: Foo) -> Foo {
765 /// println!("Shifting left!");
766 /// self
767 /// }
768 /// }
769 ///
770 /// fn main() {
771 /// Foo << Foo;
772 /// }
773 /// ```
774 #[lang = "shl"]
775 #[stable(feature = "rust1", since = "1.0.0")]
776 pub trait Shl<RHS> {
777 /// The resulting type after applying the `<<` operator
778 #[stable(feature = "rust1", since = "1.0.0")]
779 type Output;
780
781 /// The method for the `<<` operator
782 #[stable(feature = "rust1", since = "1.0.0")]
783 fn shl(self, rhs: RHS) -> Self::Output;
784 }
785
786 macro_rules! shl_impl {
787 ($t:ty, $f:ty) => (
788 #[stable(feature = "rust1", since = "1.0.0")]
789 impl Shl<$f> for $t {
790 type Output = $t;
791
792 #[inline]
793 #[rustc_inherit_overflow_checks]
794 fn shl(self, other: $f) -> $t {
795 self << other
796 }
797 }
798
799 forward_ref_binop! { impl Shl, shl for $t, $f }
800 )
801 }
802
803 macro_rules! shl_impl_all {
804 ($($t:ty)*) => ($(
805 shl_impl! { $t, u8 }
806 shl_impl! { $t, u16 }
807 shl_impl! { $t, u32 }
808 shl_impl! { $t, u64 }
809 shl_impl! { $t, usize }
810
811 shl_impl! { $t, i8 }
812 shl_impl! { $t, i16 }
813 shl_impl! { $t, i32 }
814 shl_impl! { $t, i64 }
815 shl_impl! { $t, isize }
816 )*)
817 }
818
819 shl_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
820
821 /// The `Shr` trait is used to specify the functionality of `>>`.
822 ///
823 /// # Examples
824 ///
825 /// A trivial implementation of `Shr`. When `Foo >> Foo` happens, it ends up
826 /// calling `shr`, and therefore, `main` prints `Shifting right!`.
827 ///
828 /// ```
829 /// use std::ops::Shr;
830 ///
831 /// struct Foo;
832 ///
833 /// impl Shr<Foo> for Foo {
834 /// type Output = Foo;
835 ///
836 /// fn shr(self, _rhs: Foo) -> Foo {
837 /// println!("Shifting right!");
838 /// self
839 /// }
840 /// }
841 ///
842 /// fn main() {
843 /// Foo >> Foo;
844 /// }
845 /// ```
846 #[lang = "shr"]
847 #[stable(feature = "rust1", since = "1.0.0")]
848 pub trait Shr<RHS> {
849 /// The resulting type after applying the `>>` operator
850 #[stable(feature = "rust1", since = "1.0.0")]
851 type Output;
852
853 /// The method for the `>>` operator
854 #[stable(feature = "rust1", since = "1.0.0")]
855 fn shr(self, rhs: RHS) -> Self::Output;
856 }
857
858 macro_rules! shr_impl {
859 ($t:ty, $f:ty) => (
860 #[stable(feature = "rust1", since = "1.0.0")]
861 impl Shr<$f> for $t {
862 type Output = $t;
863
864 #[inline]
865 #[rustc_inherit_overflow_checks]
866 fn shr(self, other: $f) -> $t {
867 self >> other
868 }
869 }
870
871 forward_ref_binop! { impl Shr, shr for $t, $f }
872 )
873 }
874
875 macro_rules! shr_impl_all {
876 ($($t:ty)*) => ($(
877 shr_impl! { $t, u8 }
878 shr_impl! { $t, u16 }
879 shr_impl! { $t, u32 }
880 shr_impl! { $t, u64 }
881 shr_impl! { $t, usize }
882
883 shr_impl! { $t, i8 }
884 shr_impl! { $t, i16 }
885 shr_impl! { $t, i32 }
886 shr_impl! { $t, i64 }
887 shr_impl! { $t, isize }
888 )*)
889 }
890
891 shr_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
892
893 /// The `AddAssign` trait is used to specify the functionality of `+=`.
894 ///
895 /// # Examples
896 ///
897 /// A trivial implementation of `AddAssign`. When `Foo += Foo` happens, it ends up
898 /// calling `add_assign`, and therefore, `main` prints `Adding!`.
899 ///
900 /// ```
901 /// use std::ops::AddAssign;
902 ///
903 /// struct Foo;
904 ///
905 /// impl AddAssign for Foo {
906 /// fn add_assign(&mut self, _rhs: Foo) {
907 /// println!("Adding!");
908 /// }
909 /// }
910 ///
911 /// # #[allow(unused_assignments)]
912 /// fn main() {
913 /// let mut foo = Foo;
914 /// foo += Foo;
915 /// }
916 /// ```
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);
923 }
924
925 macro_rules! add_assign_impl {
926 ($($t:ty)+) => ($(
927 #[stable(feature = "op_assign_traits", since = "1.8.0")]
928 impl AddAssign for $t {
929 #[inline]
930 #[rustc_inherit_overflow_checks]
931 fn add_assign(&mut self, other: $t) { *self += other }
932 }
933 )+)
934 }
935
936 add_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
937
938 /// The `SubAssign` trait is used to specify the functionality of `-=`.
939 ///
940 /// # Examples
941 ///
942 /// A trivial implementation of `SubAssign`. When `Foo -= Foo` happens, it ends up
943 /// calling `sub_assign`, and therefore, `main` prints `Subtracting!`.
944 ///
945 /// ```
946 /// use std::ops::SubAssign;
947 ///
948 /// struct Foo;
949 ///
950 /// impl SubAssign for Foo {
951 /// fn sub_assign(&mut self, _rhs: Foo) {
952 /// println!("Subtracting!");
953 /// }
954 /// }
955 ///
956 /// # #[allow(unused_assignments)]
957 /// fn main() {
958 /// let mut foo = Foo;
959 /// foo -= Foo;
960 /// }
961 /// ```
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);
968 }
969
970 macro_rules! sub_assign_impl {
971 ($($t:ty)+) => ($(
972 #[stable(feature = "op_assign_traits", since = "1.8.0")]
973 impl SubAssign for $t {
974 #[inline]
975 #[rustc_inherit_overflow_checks]
976 fn sub_assign(&mut self, other: $t) { *self -= other }
977 }
978 )+)
979 }
980
981 sub_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
982
983 /// The `MulAssign` trait is used to specify the functionality of `*=`.
984 ///
985 /// # Examples
986 ///
987 /// A trivial implementation of `MulAssign`. When `Foo *= Foo` happens, it ends up
988 /// calling `mul_assign`, and therefore, `main` prints `Multiplying!`.
989 ///
990 /// ```
991 /// use std::ops::MulAssign;
992 ///
993 /// struct Foo;
994 ///
995 /// impl MulAssign for Foo {
996 /// fn mul_assign(&mut self, _rhs: Foo) {
997 /// println!("Multiplying!");
998 /// }
999 /// }
1000 ///
1001 /// # #[allow(unused_assignments)]
1002 /// fn main() {
1003 /// let mut foo = Foo;
1004 /// foo *= Foo;
1005 /// }
1006 /// ```
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);
1013 }
1014
1015 macro_rules! mul_assign_impl {
1016 ($($t:ty)+) => ($(
1017 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1018 impl MulAssign for $t {
1019 #[inline]
1020 #[rustc_inherit_overflow_checks]
1021 fn mul_assign(&mut self, other: $t) { *self *= other }
1022 }
1023 )+)
1024 }
1025
1026 mul_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1027
1028 /// The `DivAssign` trait is used to specify the functionality of `/=`.
1029 ///
1030 /// # Examples
1031 ///
1032 /// A trivial implementation of `DivAssign`. When `Foo /= Foo` happens, it ends up
1033 /// calling `div_assign`, and therefore, `main` prints `Dividing!`.
1034 ///
1035 /// ```
1036 /// use std::ops::DivAssign;
1037 ///
1038 /// struct Foo;
1039 ///
1040 /// impl DivAssign for Foo {
1041 /// fn div_assign(&mut self, _rhs: Foo) {
1042 /// println!("Dividing!");
1043 /// }
1044 /// }
1045 ///
1046 /// # #[allow(unused_assignments)]
1047 /// fn main() {
1048 /// let mut foo = Foo;
1049 /// foo /= Foo;
1050 /// }
1051 /// ```
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);
1058 }
1059
1060 macro_rules! div_assign_impl {
1061 ($($t:ty)+) => ($(
1062 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1063 impl DivAssign for $t {
1064 #[inline]
1065 fn div_assign(&mut self, other: $t) { *self /= other }
1066 }
1067 )+)
1068 }
1069
1070 div_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1071
1072 /// The `RemAssign` trait is used to specify the functionality of `%=`.
1073 ///
1074 /// # Examples
1075 ///
1076 /// A trivial implementation of `RemAssign`. When `Foo %= Foo` happens, it ends up
1077 /// calling `rem_assign`, and therefore, `main` prints `Remainder-ing!`.
1078 ///
1079 /// ```
1080 /// use std::ops::RemAssign;
1081 ///
1082 /// struct Foo;
1083 ///
1084 /// impl RemAssign for Foo {
1085 /// fn rem_assign(&mut self, _rhs: Foo) {
1086 /// println!("Remainder-ing!");
1087 /// }
1088 /// }
1089 ///
1090 /// # #[allow(unused_assignments)]
1091 /// fn main() {
1092 /// let mut foo = Foo;
1093 /// foo %= Foo;
1094 /// }
1095 /// ```
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);
1102 }
1103
1104 macro_rules! rem_assign_impl {
1105 ($($t:ty)+) => ($(
1106 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1107 impl RemAssign for $t {
1108 #[inline]
1109 fn rem_assign(&mut self, other: $t) { *self %= other }
1110 }
1111 )+)
1112 }
1113
1114 rem_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
1115
1116 /// The `BitAndAssign` trait is used to specify the functionality of `&=`.
1117 ///
1118 /// # Examples
1119 ///
1120 /// A trivial implementation of `BitAndAssign`. When `Foo &= Foo` happens, it ends up
1121 /// calling `bitand_assign`, and therefore, `main` prints `Bitwise And-ing!`.
1122 ///
1123 /// ```
1124 /// use std::ops::BitAndAssign;
1125 ///
1126 /// struct Foo;
1127 ///
1128 /// impl BitAndAssign for Foo {
1129 /// fn bitand_assign(&mut self, _rhs: Foo) {
1130 /// println!("Bitwise And-ing!");
1131 /// }
1132 /// }
1133 ///
1134 /// # #[allow(unused_assignments)]
1135 /// fn main() {
1136 /// let mut foo = Foo;
1137 /// foo &= Foo;
1138 /// }
1139 /// ```
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);
1146 }
1147
1148 macro_rules! bitand_assign_impl {
1149 ($($t:ty)+) => ($(
1150 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1151 impl BitAndAssign for $t {
1152 #[inline]
1153 fn bitand_assign(&mut self, other: $t) { *self &= other }
1154 }
1155 )+)
1156 }
1157
1158 bitand_assign_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1159
1160 /// The `BitOrAssign` trait is used to specify the functionality of `|=`.
1161 ///
1162 /// # Examples
1163 ///
1164 /// A trivial implementation of `BitOrAssign`. When `Foo |= Foo` happens, it ends up
1165 /// calling `bitor_assign`, and therefore, `main` prints `Bitwise Or-ing!`.
1166 ///
1167 /// ```
1168 /// use std::ops::BitOrAssign;
1169 ///
1170 /// struct Foo;
1171 ///
1172 /// impl BitOrAssign for Foo {
1173 /// fn bitor_assign(&mut self, _rhs: Foo) {
1174 /// println!("Bitwise Or-ing!");
1175 /// }
1176 /// }
1177 ///
1178 /// # #[allow(unused_assignments)]
1179 /// fn main() {
1180 /// let mut foo = Foo;
1181 /// foo |= Foo;
1182 /// }
1183 /// ```
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);
1190 }
1191
1192 macro_rules! bitor_assign_impl {
1193 ($($t:ty)+) => ($(
1194 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1195 impl BitOrAssign for $t {
1196 #[inline]
1197 fn bitor_assign(&mut self, other: $t) { *self |= other }
1198 }
1199 )+)
1200 }
1201
1202 bitor_assign_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1203
1204 /// The `BitXorAssign` trait is used to specify the functionality of `^=`.
1205 ///
1206 /// # Examples
1207 ///
1208 /// A trivial implementation of `BitXorAssign`. When `Foo ^= Foo` happens, it ends up
1209 /// calling `bitxor_assign`, and therefore, `main` prints `Bitwise Xor-ing!`.
1210 ///
1211 /// ```
1212 /// use std::ops::BitXorAssign;
1213 ///
1214 /// struct Foo;
1215 ///
1216 /// impl BitXorAssign for Foo {
1217 /// fn bitxor_assign(&mut self, _rhs: Foo) {
1218 /// println!("Bitwise Xor-ing!");
1219 /// }
1220 /// }
1221 ///
1222 /// # #[allow(unused_assignments)]
1223 /// fn main() {
1224 /// let mut foo = Foo;
1225 /// foo ^= Foo;
1226 /// }
1227 /// ```
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);
1234 }
1235
1236 macro_rules! bitxor_assign_impl {
1237 ($($t:ty)+) => ($(
1238 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1239 impl BitXorAssign for $t {
1240 #[inline]
1241 fn bitxor_assign(&mut self, other: $t) { *self ^= other }
1242 }
1243 )+)
1244 }
1245
1246 bitxor_assign_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
1247
1248 /// The `ShlAssign` trait is used to specify the functionality of `<<=`.
1249 ///
1250 /// # Examples
1251 ///
1252 /// A trivial implementation of `ShlAssign`. When `Foo <<= Foo` happens, it ends up
1253 /// calling `shl_assign`, and therefore, `main` prints `Shifting left!`.
1254 ///
1255 /// ```
1256 /// use std::ops::ShlAssign;
1257 ///
1258 /// struct Foo;
1259 ///
1260 /// impl ShlAssign<Foo> for Foo {
1261 /// fn shl_assign(&mut self, _rhs: Foo) {
1262 /// println!("Shifting left!");
1263 /// }
1264 /// }
1265 ///
1266 /// # #[allow(unused_assignments)]
1267 /// fn main() {
1268 /// let mut foo = Foo;
1269 /// foo <<= Foo;
1270 /// }
1271 /// ```
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);
1278 }
1279
1280 macro_rules! shl_assign_impl {
1281 ($t:ty, $f:ty) => (
1282 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1283 impl ShlAssign<$f> for $t {
1284 #[inline]
1285 #[rustc_inherit_overflow_checks]
1286 fn shl_assign(&mut self, other: $f) {
1287 *self <<= other
1288 }
1289 }
1290 )
1291 }
1292
1293 macro_rules! shl_assign_impl_all {
1294 ($($t:ty)*) => ($(
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 }
1300
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 }
1306 )*)
1307 }
1308
1309 shl_assign_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
1310
1311 /// The `ShrAssign` trait is used to specify the functionality of `>>=`.
1312 ///
1313 /// # Examples
1314 ///
1315 /// A trivial implementation of `ShrAssign`. When `Foo >>= Foo` happens, it ends up
1316 /// calling `shr_assign`, and therefore, `main` prints `Shifting right!`.
1317 ///
1318 /// ```
1319 /// use std::ops::ShrAssign;
1320 ///
1321 /// struct Foo;
1322 ///
1323 /// impl ShrAssign<Foo> for Foo {
1324 /// fn shr_assign(&mut self, _rhs: Foo) {
1325 /// println!("Shifting right!");
1326 /// }
1327 /// }
1328 ///
1329 /// # #[allow(unused_assignments)]
1330 /// fn main() {
1331 /// let mut foo = Foo;
1332 /// foo >>= Foo;
1333 /// }
1334 /// ```
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);
1341 }
1342
1343 macro_rules! shr_assign_impl {
1344 ($t:ty, $f:ty) => (
1345 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1346 impl ShrAssign<$f> for $t {
1347 #[inline]
1348 #[rustc_inherit_overflow_checks]
1349 fn shr_assign(&mut self, other: $f) {
1350 *self >>= other
1351 }
1352 }
1353 )
1354 }
1355
1356 macro_rules! shr_assign_impl_all {
1357 ($($t:ty)*) => ($(
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 }
1363
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 }
1369 )*)
1370 }
1371
1372 shr_assign_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
1373
1374 /// The `Index` trait is used to specify the functionality of indexing operations
1375 /// like `arr[idx]` when used in an immutable context.
1376 ///
1377 /// # Examples
1378 ///
1379 /// A trivial implementation of `Index`. When `Foo[Bar]` happens, it ends up
1380 /// calling `index`, and therefore, `main` prints `Indexing!`.
1381 ///
1382 /// ```
1383 /// use std::ops::Index;
1384 ///
1385 /// #[derive(Copy, Clone)]
1386 /// struct Foo;
1387 /// struct Bar;
1388 ///
1389 /// impl Index<Bar> for Foo {
1390 /// type Output = Foo;
1391 ///
1392 /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
1393 /// println!("Indexing!");
1394 /// self
1395 /// }
1396 /// }
1397 ///
1398 /// fn main() {
1399 /// Foo[Bar];
1400 /// }
1401 /// ```
1402 #[lang = "index"]
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;
1409
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;
1413 }
1414
1415 /// The `IndexMut` trait is used to specify the functionality of indexing
1416 /// operations like `arr[idx]`, when used in a mutable context.
1417 ///
1418 /// # Examples
1419 ///
1420 /// A trivial implementation of `IndexMut`. When `Foo[Bar]` happens, it ends up
1421 /// calling `index_mut`, and therefore, `main` prints `Indexing!`.
1422 ///
1423 /// ```
1424 /// use std::ops::{Index, IndexMut};
1425 ///
1426 /// #[derive(Copy, Clone)]
1427 /// struct Foo;
1428 /// struct Bar;
1429 ///
1430 /// impl Index<Bar> for Foo {
1431 /// type Output = Foo;
1432 ///
1433 /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
1434 /// self
1435 /// }
1436 /// }
1437 ///
1438 /// impl IndexMut<Bar> for Foo {
1439 /// fn index_mut<'a>(&'a mut self, _index: Bar) -> &'a mut Foo {
1440 /// println!("Indexing!");
1441 /// self
1442 /// }
1443 /// }
1444 ///
1445 /// fn main() {
1446 /// &mut Foo[Bar];
1447 /// }
1448 /// ```
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;
1456 }
1457
1458 /// An unbounded range. Use `..` (two dots) for its shorthand.
1459 ///
1460 /// Its primary use case is slicing index. It cannot serve as an iterator
1461 /// because it doesn't have a starting point.
1462 ///
1463 /// # Examples
1464 ///
1465 /// ```
1466 /// fn main() {
1467 /// assert_eq!((..), std::ops::RangeFull);
1468 ///
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 ]);
1474 /// }
1475 /// ```
1476 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
1477 #[stable(feature = "rust1", since = "1.0.0")]
1478 pub struct RangeFull;
1479
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 impl fmt::Debug for RangeFull {
1482 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1483 write!(fmt, "..")
1484 }
1485 }
1486
1487 /// A (half-open) range which is bounded at both ends: { x | start <= x < end }.
1488 /// Use `start..end` (two dots) for its shorthand.
1489 ///
1490 /// See the [`contains()`](#method.contains) method for its characterization.
1491 ///
1492 /// # Examples
1493 ///
1494 /// ```
1495 /// fn main() {
1496 /// assert_eq!((3..5), std::ops::Range{ start: 3, end: 5 });
1497 /// assert_eq!(3+4+5, (3..6).sum());
1498 ///
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
1504 /// }
1505 /// ```
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")]
1511 pub start: Idx,
1512 /// The upper bound of the range (exclusive).
1513 #[stable(feature = "rust1", since = "1.0.0")]
1514 pub end: Idx,
1515 }
1516
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)
1521 }
1522 }
1523
1524 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1525 impl<Idx: PartialOrd<Idx>> Range<Idx> {
1526 /// # Examples
1527 ///
1528 /// ```
1529 /// #![feature(range_contains)]
1530 /// fn main() {
1531 /// assert!( ! (3..5).contains(2));
1532 /// assert!( (3..5).contains(3));
1533 /// assert!( (3..5).contains(4));
1534 /// assert!( ! (3..5).contains(5));
1535 ///
1536 /// assert!( ! (3..3).contains(3));
1537 /// assert!( ! (3..2).contains(3));
1538 /// }
1539 /// ```
1540 pub fn contains(&self, item: Idx) -> bool {
1541 (self.start <= item) && (item < self.end)
1542 }
1543 }
1544
1545 /// A range which is only bounded below: { x | start <= x }.
1546 /// Use `start..` for its shorthand.
1547 ///
1548 /// See the [`contains()`](#method.contains) method for its characterization.
1549 ///
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.
1554 ///
1555 /// # Examples
1556 ///
1557 /// ```
1558 /// fn main() {
1559 /// assert_eq!((2..), std::ops::RangeFrom{ start: 2 });
1560 /// assert_eq!(2+3+4, (2..).take(3).sum());
1561 ///
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 ]);
1567 /// }
1568 /// ```
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")]
1574 pub start: Idx,
1575 }
1576
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)
1581 }
1582 }
1583
1584 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1585 impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
1586 /// # Examples
1587 ///
1588 /// ```
1589 /// #![feature(range_contains)]
1590 /// fn main() {
1591 /// assert!( ! (3..).contains(2));
1592 /// assert!( (3..).contains(3));
1593 /// assert!( (3..).contains(1_000_000_000));
1594 /// }
1595 /// ```
1596 pub fn contains(&self, item: Idx) -> bool {
1597 (self.start <= item)
1598 }
1599 }
1600
1601 /// A range which is only bounded above: { x | x < end }.
1602 /// Use `..end` (two dots) for its shorthand.
1603 ///
1604 /// See the [`contains()`](#method.contains) method for its characterization.
1605 ///
1606 /// It cannot serve as an iterator because it doesn't have a starting point.
1607 ///
1608 /// ```
1609 /// fn main() {
1610 /// assert_eq!((..5), std::ops::RangeTo{ end: 5 });
1611 ///
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 ]);
1617 /// }
1618 /// ```
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")]
1624 pub end: Idx,
1625 }
1626
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)
1631 }
1632 }
1633
1634 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1635 impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
1636 /// # Examples
1637 ///
1638 /// ```
1639 /// #![feature(range_contains)]
1640 /// fn main() {
1641 /// assert!( (..5).contains(-1_000_000_000));
1642 /// assert!( (..5).contains(4));
1643 /// assert!( ! (..5).contains(5));
1644 /// }
1645 /// ```
1646 pub fn contains(&self, item: Idx) -> bool {
1647 (item < self.end)
1648 }
1649 }
1650
1651 /// An inclusive range which is bounded at both ends: { x | start <= x <= end }.
1652 /// Use `start...end` (three dots) for its shorthand.
1653 ///
1654 /// See the [`contains()`](#method.contains) method for its characterization.
1655 ///
1656 /// # Examples
1657 ///
1658 /// ```
1659 /// #![feature(inclusive_range,inclusive_range_syntax)]
1660 /// fn main() {
1661 /// assert_eq!((3...5), std::ops::RangeInclusive::NonEmpty{ start: 3, end: 5 });
1662 /// assert_eq!(3+4+5, (3...5).sum());
1663 ///
1664 /// let arr = [0, 1, 2, 3];
1665 /// assert_eq!(arr[ ...2], [0,1,2 ]);
1666 /// assert_eq!(arr[1...2], [ 1,2 ]); // RangeInclusive
1667 /// }
1668 /// ```
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",
1675 issue = "28237")]
1676 Empty {
1677 /// The point at which iteration finished
1678 #[unstable(feature = "inclusive_range",
1679 reason = "recently added, follows RFC",
1680 issue = "28237")]
1681 at: Idx
1682 },
1683 /// Non-empty range (iteration will yield value(s))
1684 #[unstable(feature = "inclusive_range",
1685 reason = "recently added, follows RFC",
1686 issue = "28237")]
1687 NonEmpty {
1688 /// The lower bound of the range (inclusive).
1689 #[unstable(feature = "inclusive_range",
1690 reason = "recently added, follows RFC",
1691 issue = "28237")]
1692 start: Idx,
1693 /// The upper bound of the range (inclusive).
1694 #[unstable(feature = "inclusive_range",
1695 reason = "recently added, follows RFC",
1696 issue = "28237")]
1697 end: Idx,
1698 },
1699 }
1700
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::*;
1705
1706 match *self {
1707 Empty { ref at } => write!(fmt, "[empty range @ {:?}]", at),
1708 NonEmpty { ref start, ref end } => write!(fmt, "{:?}...{:?}", start, end),
1709 }
1710 }
1711 }
1712
1713 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1714 impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
1715 /// # Examples
1716 ///
1717 /// ```
1718 /// #![feature(range_contains,inclusive_range_syntax)]
1719 /// fn main() {
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));
1725 ///
1726 /// assert!( (3...3).contains(3));
1727 /// assert!( ! (3...2).contains(3));
1728 /// }
1729 /// ```
1730 pub fn contains(&self, item: Idx) -> bool {
1731 if let &RangeInclusive::NonEmpty{ref start, ref end} = self {
1732 (*start <= item) && (item <= *end)
1733 } else { false }
1734 }
1735 }
1736
1737 /// An inclusive range which is only bounded above: { x | x <= end }.
1738 /// Use `...end` (three dots) for its shorthand.
1739 ///
1740 /// See the [`contains()`](#method.contains) method for its characterization.
1741 ///
1742 /// It cannot serve as an iterator because it doesn't have a starting point.
1743 ///
1744 /// # Examples
1745 ///
1746 /// ```
1747 /// #![feature(inclusive_range,inclusive_range_syntax)]
1748 /// fn main() {
1749 /// assert_eq!((...5), std::ops::RangeToInclusive{ end: 5 });
1750 ///
1751 /// let arr = [0, 1, 2, 3];
1752 /// assert_eq!(arr[ ...2], [0,1,2 ]); // RangeToInclusive
1753 /// assert_eq!(arr[1...2], [ 1,2 ]);
1754 /// }
1755 /// ```
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",
1762 issue = "28237")]
1763 pub end: Idx,
1764 }
1765
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)
1770 }
1771 }
1772
1773 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
1774 impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
1775 /// # Examples
1776 ///
1777 /// ```
1778 /// #![feature(range_contains,inclusive_range_syntax)]
1779 /// fn main() {
1780 /// assert!( (...5).contains(-1_000_000_000));
1781 /// assert!( (...5).contains(5));
1782 /// assert!( ! (...5).contains(6));
1783 /// }
1784 /// ```
1785 pub fn contains(&self, item: Idx) -> bool {
1786 (item <= self.end)
1787 }
1788 }
1789
1790 // RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
1791 // because underflow would be possible with (..0).into()
1792
1793 /// The `Deref` trait is used to specify the functionality of dereferencing
1794 /// operations, like `*v`.
1795 ///
1796 /// `Deref` also enables ['`Deref` coercions'][coercions].
1797 ///
1798 /// [coercions]: ../../book/deref-coercions.html
1799 ///
1800 /// # Examples
1801 ///
1802 /// A struct with a single field which is accessible via dereferencing the
1803 /// struct.
1804 ///
1805 /// ```
1806 /// use std::ops::Deref;
1807 ///
1808 /// struct DerefExample<T> {
1809 /// value: T
1810 /// }
1811 ///
1812 /// impl<T> Deref for DerefExample<T> {
1813 /// type Target = T;
1814 ///
1815 /// fn deref(&self) -> &T {
1816 /// &self.value
1817 /// }
1818 /// }
1819 ///
1820 /// fn main() {
1821 /// let x = DerefExample { value: 'a' };
1822 /// assert_eq!('a', *x);
1823 /// }
1824 /// ```
1825 #[lang = "deref"]
1826 #[stable(feature = "rust1", since = "1.0.0")]
1827 pub trait Deref {
1828 /// The resulting type after dereferencing
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 type Target: ?Sized;
1831
1832 /// The method called to dereference a value
1833 #[stable(feature = "rust1", since = "1.0.0")]
1834 fn deref(&self) -> &Self::Target;
1835 }
1836
1837 #[stable(feature = "rust1", since = "1.0.0")]
1838 impl<'a, T: ?Sized> Deref for &'a T {
1839 type Target = T;
1840
1841 fn deref(&self) -> &T { *self }
1842 }
1843
1844 #[stable(feature = "rust1", since = "1.0.0")]
1845 impl<'a, T: ?Sized> Deref for &'a mut T {
1846 type Target = T;
1847
1848 fn deref(&self) -> &T { *self }
1849 }
1850
1851 /// The `DerefMut` trait is used to specify the functionality of dereferencing
1852 /// mutably like `*v = 1;`
1853 ///
1854 /// `DerefMut` also enables ['`Deref` coercions'][coercions].
1855 ///
1856 /// [coercions]: ../../book/deref-coercions.html
1857 ///
1858 /// # Examples
1859 ///
1860 /// A struct with a single field which is modifiable via dereferencing the
1861 /// struct.
1862 ///
1863 /// ```
1864 /// use std::ops::{Deref, DerefMut};
1865 ///
1866 /// struct DerefMutExample<T> {
1867 /// value: T
1868 /// }
1869 ///
1870 /// impl<T> Deref for DerefMutExample<T> {
1871 /// type Target = T;
1872 ///
1873 /// fn deref<'a>(&'a self) -> &'a T {
1874 /// &self.value
1875 /// }
1876 /// }
1877 ///
1878 /// impl<T> DerefMut for DerefMutExample<T> {
1879 /// fn deref_mut<'a>(&'a mut self) -> &'a mut T {
1880 /// &mut self.value
1881 /// }
1882 /// }
1883 ///
1884 /// fn main() {
1885 /// let mut x = DerefMutExample { value: 'a' };
1886 /// *x = 'b';
1887 /// assert_eq!('b', *x);
1888 /// }
1889 /// ```
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;
1896 }
1897
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 }
1901 }
1902
1903 /// A version of the call operator that takes an immutable receiver.
1904 #[lang = "fn"]
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;
1912 }
1913
1914 /// A version of the call operator that takes a mutable receiver.
1915 #[lang = "fn_mut"]
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;
1923 }
1924
1925 /// A version of the call operator that takes a by-value receiver.
1926 #[lang = "fn_once"]
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")]
1933 type Output;
1934
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;
1938 }
1939
1940 mod impls {
1941 use marker::Sized;
1942 use super::{Fn, FnMut, FnOnce};
1943
1944 #[stable(feature = "rust1", since = "1.0.0")]
1945 impl<'a,A,F:?Sized> Fn<A> for &'a F
1946 where F : Fn<A>
1947 {
1948 extern "rust-call" fn call(&self, args: A) -> F::Output {
1949 (**self).call(args)
1950 }
1951 }
1952
1953 #[stable(feature = "rust1", since = "1.0.0")]
1954 impl<'a,A,F:?Sized> FnMut<A> for &'a F
1955 where F : Fn<A>
1956 {
1957 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
1958 (**self).call(args)
1959 }
1960 }
1961
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 impl<'a,A,F:?Sized> FnOnce<A> for &'a F
1964 where F : Fn<A>
1965 {
1966 type Output = F::Output;
1967
1968 extern "rust-call" fn call_once(self, args: A) -> F::Output {
1969 (*self).call(args)
1970 }
1971 }
1972
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 impl<'a,A,F:?Sized> FnMut<A> for &'a mut F
1975 where F : FnMut<A>
1976 {
1977 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
1978 (*self).call_mut(args)
1979 }
1980 }
1981
1982 #[stable(feature = "rust1", since = "1.0.0")]
1983 impl<'a,A,F:?Sized> FnOnce<A> for &'a mut F
1984 where F : FnMut<A>
1985 {
1986 type Output = F::Output;
1987 extern "rust-call" fn call_once(mut self, args: A) -> F::Output {
1988 (*self).call_mut(args)
1989 }
1990 }
1991 }
1992
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> {
1998 // Empty.
1999 }
2000
2001 // &mut T -> &mut U
2002 #[unstable(feature = "coerce_unsized", issue = "27732")]
2003 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a mut U> for &'a mut T {}
2004 // &mut T -> &U
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 {}
2007 // &mut T -> *mut U
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 {}
2013
2014 // &T -> &U
2015 #[unstable(feature = "coerce_unsized", issue = "27732")]
2016 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b T {}
2017 // &T -> *const U
2018 #[unstable(feature = "coerce_unsized", issue = "27732")]
2019 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a T {}
2020
2021 // *mut T -> *mut U
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 {}
2027
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 {}
2031
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.
2036 ///
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.
2041 ///
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`.
2046 ///
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;
2056 }
2057
2058 /// Interface to implementations of `in (PLACE) EXPR`.
2059 ///
2060 /// `in (PLACE) EXPR` effectively desugars into:
2061 ///
2062 /// ```rust,ignore
2063 /// let p = PLACE;
2064 /// let mut place = Placer::make_place(p);
2065 /// let raw_place = Place::pointer(&mut place);
2066 /// let value = EXPR;
2067 /// unsafe {
2068 /// std::ptr::write(raw_place, value);
2069 /// InPlace::finalize(place)
2070 /// }
2071 /// ```
2072 ///
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`
2076 /// traits).
2077 ///
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>;
2086
2087 /// Creates a fresh place from `self`.
2088 fn make_place(self) -> Self::Place;
2089 }
2090
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`
2095 ///
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
2100 /// case).
2101 type Owner;
2102
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;
2107 }
2108
2109 /// Core trait for the `box EXPR` form.
2110 ///
2111 /// `box EXPR` effectively desugars into:
2112 ///
2113 /// ```rust,ignore
2114 /// let mut place = BoxPlace::make_place();
2115 /// let raw_place = Place::pointer(&mut place);
2116 /// let value = EXPR;
2117 /// unsafe {
2118 /// ::std::ptr::write(raw_place, value);
2119 /// Boxed::finalize(place)
2120 /// }
2121 /// ```
2122 ///
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")]
2130 pub trait Boxed {
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>;
2135
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;
2140 }
2141
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;
2147 }