-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
mod.rs
2874 lines (2694 loc) · 92.4 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Numeric traits and functions for the built-in numeric types.
#![stable(feature = "rust1", since = "1.0.0")]
use convert::TryFrom;
use fmt;
use intrinsics;
use mem::size_of;
use str::FromStr;
/// Provides intentionally-wrapped arithmetic on `T`.
///
/// Operations like `+` on `u32` values is intended to never overflow,
/// and in some debug configurations overflow is detected and results
/// in a panic. While most arithmetic falls into this category, some
/// code explicitly expects and relies upon modular arithmetic (e.g.,
/// hashing).
///
/// Wrapping arithmetic can be achieved either through methods like
/// `wrapping_add`, or through the `Wrapping<T>` type, which says that
/// all standard arithmetic operations on the underlying value are
/// intended to have wrapping semantics.
///
/// # Examples
///
/// ```
/// use std::num::Wrapping;
///
/// let zero = Wrapping(0u32);
/// let one = Wrapping(1u32);
///
/// assert_eq!(std::u32::MAX, (zero - one).0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
pub T);
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
#[stable(feature = "wrapping_display", since = "1.10.0")]
impl<T: fmt::Display> fmt::Display for Wrapping<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
#[stable(feature = "wrapping_fmt", since = "1.11.0")]
impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
#[stable(feature = "wrapping_fmt", since = "1.11.0")]
impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
#[stable(feature = "wrapping_fmt", since = "1.11.0")]
impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
#[stable(feature = "wrapping_fmt", since = "1.11.0")]
impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
mod wrapping;
// All these modules are technically private and only exposed for libcoretest:
pub mod flt2dec;
pub mod dec2flt;
pub mod bignum;
pub mod diy_float;
/// Types that have a "zero" value.
///
/// This trait is intended for use in conjunction with `Add`, as an identity:
/// `x + T::zero() == x`.
#[unstable(feature = "zero_one",
reason = "unsure of placement, wants to use associated constants",
issue = "27739")]
#[rustc_deprecated(since = "1.11.0", reason = "no longer used for \
Iterator::sum")]
pub trait Zero: Sized {
/// The "zero" (usually, additive identity) for this type.
fn zero() -> Self;
}
/// Types that have a "one" value.
///
/// This trait is intended for use in conjunction with `Mul`, as an identity:
/// `x * T::one() == x`.
#[unstable(feature = "zero_one",
reason = "unsure of placement, wants to use associated constants",
issue = "27739")]
#[rustc_deprecated(since = "1.11.0", reason = "no longer used for \
Iterator::product")]
pub trait One: Sized {
/// The "one" (usually, multiplicative identity) for this type.
fn one() -> Self;
}
macro_rules! zero_one_impl {
($($t:ty)*) => ($(
#[unstable(feature = "zero_one",
reason = "unsure of placement, wants to use associated constants",
issue = "27739")]
#[allow(deprecated)]
impl Zero for $t {
#[inline]
fn zero() -> Self { 0 }
}
#[unstable(feature = "zero_one",
reason = "unsure of placement, wants to use associated constants",
issue = "27739")]
#[allow(deprecated)]
impl One for $t {
#[inline]
fn one() -> Self { 1 }
}
)*)
}
zero_one_impl! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
macro_rules! zero_one_impl_float {
($($t:ty)*) => ($(
#[unstable(feature = "zero_one",
reason = "unsure of placement, wants to use associated constants",
issue = "27739")]
#[allow(deprecated)]
impl Zero for $t {
#[inline]
fn zero() -> Self { 0.0 }
}
#[unstable(feature = "zero_one",
reason = "unsure of placement, wants to use associated constants",
issue = "27739")]
#[allow(deprecated)]
impl One for $t {
#[inline]
fn one() -> Self { 1.0 }
}
)*)
}
zero_one_impl_float! { f32 f64 }
macro_rules! checked_op {
($U:ty, $op:path, $x:expr, $y:expr) => {{
let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
if overflowed { None } else { Some(result as Self) }
}}
}
// `Int` + `SignedInt` implemented for signed integers
macro_rules! int_impl {
($ActualT:ident, $UnsignedT:ty, $BITS:expr,
$add_with_overflow:path,
$sub_with_overflow:path,
$mul_with_overflow:path) => {
/// Returns the smallest value that can be represented by this integer type.
///
/// # Examples
///
/// ```
/// assert_eq!(i8::min_value(), -128);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub const fn min_value() -> Self {
!0 ^ ((!0 as $UnsignedT) >> 1) as Self
}
/// Returns the largest value that can be represented by this integer type.
///
/// # Examples
///
/// ```
/// assert_eq!(i8::max_value(), 127);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub const fn max_value() -> Self {
!Self::min_value()
}
/// Converts a string slice in a given base to an integer.
///
/// Leading and trailing whitespace represent an error.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(i32::from_str_radix("A", 16), Ok(10));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
from_str_radix(src, radix)
}
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let n = -0b1000_0000i8;
///
/// assert_eq!(n.count_ones(), 1);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let n = -0b1000_0000i8;
///
/// assert_eq!(n.count_zeros(), 7);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn count_zeros(self) -> u32 {
(!self).count_ones()
}
/// Returns the number of leading zeros in the binary representation
/// of `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let n = -1i16;
///
/// assert_eq!(n.leading_zeros(), 0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn leading_zeros(self) -> u32 {
(self as $UnsignedT).leading_zeros()
}
/// Returns the number of trailing zeros in the binary representation
/// of `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let n = -4i8;
///
/// assert_eq!(n.trailing_zeros(), 2);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn trailing_zeros(self) -> u32 {
(self as $UnsignedT).trailing_zeros()
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// Please note this isn't the same operation as `<<`!
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let n = 0x0123456789ABCDEFi64;
/// let m = -0x76543210FEDCBA99i64;
///
/// assert_eq!(n.rotate_left(32), m);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn rotate_left(self, n: u32) -> Self {
(self as $UnsignedT).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// Please note this isn't the same operation as `>>`!
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let n = 0x0123456789ABCDEFi64;
/// let m = -0xFEDCBA987654322i64;
///
/// assert_eq!(n.rotate_right(4), m);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn rotate_right(self, n: u32) -> Self {
(self as $UnsignedT).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let n = 0x0123456789ABCDEFi64;
/// let m = -0x1032547698BADCFFi64;
///
/// assert_eq!(n.swap_bytes(), m);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn swap_bytes(self) -> Self {
(self as $UnsignedT).swap_bytes() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let n = 0x0123456789ABCDEFi64;
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(i64::from_be(n), n)
/// } else {
/// assert_eq!(i64::from_be(n), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn from_be(x: Self) -> Self {
if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
}
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let n = 0x0123456789ABCDEFi64;
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(i64::from_le(n), n)
/// } else {
/// assert_eq!(i64::from_le(n), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn from_le(x: Self) -> Self {
if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
}
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let n = 0x0123456789ABCDEFi64;
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_be(self) -> Self { // or not to be?
if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
}
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let n = 0x0123456789ABCDEFi64;
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_le(self) -> Self {
if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
}
/// Checked integer addition. Computes `self + other`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(7i16.checked_add(32760), Some(32767));
/// assert_eq!(8i16.checked_add(32760), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_add(self, other: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(other);
if b {None} else {Some(a)}
}
/// Checked integer subtraction. Computes `self - other`, returning
/// `None` if underflow occurred.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!((-127i8).checked_sub(1), Some(-128));
/// assert_eq!((-128i8).checked_sub(1), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_sub(self, other: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(other);
if b {None} else {Some(a)}
}
/// Checked integer multiplication. Computes `self * other`, returning
/// `None` if underflow or overflow occurred.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(6i8.checked_mul(21), Some(126));
/// assert_eq!(6i8.checked_mul(22), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_mul(self, other: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(other);
if b {None} else {Some(a)}
}
/// Checked integer division. Computes `self / other`, returning `None`
/// if `other == 0` or the operation results in underflow or overflow.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!((-127i8).checked_div(-1), Some(127));
/// assert_eq!((-128i8).checked_div(-1), None);
/// assert_eq!((1i8).checked_div(0), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_div(self, other: Self) -> Option<Self> {
if other == 0 || (self == Self::min_value() && other == -1) {
None
} else {
Some(unsafe { intrinsics::unchecked_div(self, other) })
}
}
/// Checked integer remainder. Computes `self % other`, returning `None`
/// if `other == 0` or the operation results in underflow or overflow.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::i32;
///
/// assert_eq!(5i32.checked_rem(2), Some(1));
/// assert_eq!(5i32.checked_rem(0), None);
/// assert_eq!(i32::MIN.checked_rem(-1), None);
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[inline]
pub fn checked_rem(self, other: Self) -> Option<Self> {
if other == 0 || (self == Self::min_value() && other == -1) {
None
} else {
Some(unsafe { intrinsics::unchecked_rem(self, other) })
}
}
/// Checked negation. Computes `-self`, returning `None` if `self ==
/// MIN`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::i32;
///
/// assert_eq!(5i32.checked_neg(), Some(-5));
/// assert_eq!(i32::MIN.checked_neg(), None);
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[inline]
pub fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if b {None} else {Some(a)}
}
/// Checked shift left. Computes `self << rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
/// assert_eq!(0x10i32.checked_shl(33), None);
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[inline]
pub fn checked_shl(self, rhs: u32) -> Option<Self> {
let (a, b) = self.overflowing_shl(rhs);
if b {None} else {Some(a)}
}
/// Checked shift right. Computes `self >> rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
/// assert_eq!(0x10i32.checked_shr(33), None);
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[inline]
pub fn checked_shr(self, rhs: u32) -> Option<Self> {
let (a, b) = self.overflowing_shr(rhs);
if b {None} else {Some(a)}
}
/// Checked absolute value. Computes `self.abs()`, returning `None` if
/// `self == MIN`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::i32;
///
/// assert_eq!((-5i32).checked_abs(), Some(5));
/// assert_eq!(i32::MIN.checked_abs(), None);
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[inline]
pub fn checked_abs(self) -> Option<Self> {
if self.is_negative() {
self.checked_neg()
} else {
Some(self)
}
}
/// Saturating integer addition. Computes `self + other`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(100i8.saturating_add(1), 101);
/// assert_eq!(100i8.saturating_add(127), 127);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn saturating_add(self, other: Self) -> Self {
match self.checked_add(other) {
Some(x) => x,
None if other >= 0 => Self::max_value(),
None => Self::min_value(),
}
}
/// Saturating integer subtraction. Computes `self - other`, saturating
/// at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(100i8.saturating_sub(127), -27);
/// assert_eq!((-100i8).saturating_sub(127), -128);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn saturating_sub(self, other: Self) -> Self {
match self.checked_sub(other) {
Some(x) => x,
None if other >= 0 => Self::min_value(),
None => Self::max_value(),
}
}
/// Saturating integer multiplication. Computes `self * other`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::i32;
///
/// assert_eq!(100i32.saturating_mul(127), 12700);
/// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
/// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[inline]
pub fn saturating_mul(self, other: Self) -> Self {
self.checked_mul(other).unwrap_or_else(|| {
if (self < 0 && other < 0) || (self > 0 && other > 0) {
Self::max_value()
} else {
Self::min_value()
}
})
}
/// Wrapping (modular) addition. Computes `self + other`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(100i8.wrapping_add(27), 127);
/// assert_eq!(100i8.wrapping_add(127), -29);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn wrapping_add(self, rhs: Self) -> Self {
unsafe {
intrinsics::overflowing_add(self, rhs)
}
}
/// Wrapping (modular) subtraction. Computes `self - other`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(0i8.wrapping_sub(127), -127);
/// assert_eq!((-2i8).wrapping_sub(127), 127);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn wrapping_sub(self, rhs: Self) -> Self {
unsafe {
intrinsics::overflowing_sub(self, rhs)
}
}
/// Wrapping (modular) multiplication. Computes `self *
/// other`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(10i8.wrapping_mul(12), 120);
/// assert_eq!(11i8.wrapping_mul(12), -124);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn wrapping_mul(self, rhs: Self) -> Self {
unsafe {
intrinsics::overflowing_mul(self, rhs)
}
}
/// Wrapping (modular) division. Computes `self / other`,
/// wrapping around at the boundary of the type.
///
/// The only case where such wrapping can occur is when one
/// divides `MIN / -1` on a signed type (where `MIN` is the
/// negative minimal value for the type); this is equivalent
/// to `-MIN`, a positive value that is too large to represent
/// in the type. In such a case, this function returns `MIN`
/// itself.
///
/// # Panics
///
/// This function will panic if `rhs` is 0.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(100u8.wrapping_div(10), 10);
/// assert_eq!((-128i8).wrapping_div(-1), -128);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_div(self, rhs: Self) -> Self {
self.overflowing_div(rhs).0
}
/// Wrapping (modular) remainder. Computes `self % other`,
/// wrapping around at the boundary of the type.
///
/// Such wrap-around never actually occurs mathematically;
/// implementation artifacts make `x % y` invalid for `MIN /
/// -1` on a signed type (where `MIN` is the negative
/// minimal value). In such a case, this function returns `0`.
///
/// # Panics
///
/// This function will panic if `rhs` is 0.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(100i8.wrapping_rem(10), 0);
/// assert_eq!((-128i8).wrapping_rem(-1), 0);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_rem(self, rhs: Self) -> Self {
self.overflowing_rem(rhs).0
}
/// Wrapping (modular) negation. Computes `-self`,
/// wrapping around at the boundary of the type.
///
/// The only case where such wrapping can occur is when one
/// negates `MIN` on a signed type (where `MIN` is the
/// negative minimal value for the type); this is a positive
/// value that is too large to represent in the type. In such
/// a case, this function returns `MIN` itself.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(100i8.wrapping_neg(), -100);
/// assert_eq!((-128i8).wrapping_neg(), -128);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_neg(self) -> Self {
self.overflowing_neg().0
}
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Note that this is *not* the same as a rotate-left; the
/// RHS of a wrapping shift-left is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a `rotate_left` function, which may
/// be what you want instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!((-1i8).wrapping_shl(7), -128);
/// assert_eq!((-1i8).wrapping_shl(8), -1);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_shl(self, rhs: u32) -> Self {
self.overflowing_shl(rhs).0
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Note that this is *not* the same as a rotate-right; the
/// RHS of a wrapping shift-right is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a `rotate_right` function, which may
/// be what you want instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!((-128i8).wrapping_shr(7), -1);
/// assert_eq!((-128i8).wrapping_shr(8), -128);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_shr(self, rhs: u32) -> Self {
self.overflowing_shr(rhs).0
}
/// Wrapping (modular) absolute value. Computes `self.abs()`,
/// wrapping around at the boundary of the type.
///
/// The only case where such wrapping can occur is when one takes
/// the absolute value of the negative minimal value for the type
/// this is a positive value that is too large to represent in the
/// type. In such a case, this function returns `MIN` itself.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// assert_eq!(100i8.wrapping_abs(), 100);
/// assert_eq!((-100i8).wrapping_abs(), 100);
/// assert_eq!((-128i8).wrapping_abs(), -128);
/// assert_eq!((-128i8).wrapping_abs() as u8, 128);
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[inline(always)]
pub fn wrapping_abs(self) -> Self {
if self.is_negative() {
self.wrapping_neg()
} else {
self
}
}
/// Calculates `self` + `rhs`
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// use std::i32;
///
/// assert_eq!(5i32.overflowing_add(2), (7, false));
/// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
unsafe {
let (a, b) = $add_with_overflow(self as $ActualT,
rhs as $ActualT);
(a as Self, b)
}
}
/// Calculates `self` - `rhs`
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// use std::i32;
///
/// assert_eq!(5i32.overflowing_sub(2), (3, false));
/// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
unsafe {
let (a, b) = $sub_with_overflow(self as $ActualT,
rhs as $ActualT);
(a as Self, b)
}
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean
/// indicating whether an arithmetic overflow would occur. If an
/// overflow would have occurred then the wrapped value is returned.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// assert_eq!(5i32.overflowing_mul(2), (10, false));
/// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
unsafe {
let (a, b) = $mul_with_overflow(self as $ActualT,
rhs as $ActualT);
(a as Self, b)
}
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// occur then self is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is 0.
///
/// # Examples
///
/// Basic usage
///
/// ```