forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
5163 lines (4326 loc) · 161 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
//! 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;
use ops;
use str::FromStr;
macro_rules! impl_nonzero_fmt {
( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
$(
#[$stability]
impl fmt::$Trait for $Ty {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.get().fmt(f)
}
}
)+
}
}
macro_rules! doc_comment {
($x:expr, $($tt:tt)*) => {
#[doc = $x]
$($tt)*
};
}
macro_rules! nonzero_integers {
( $( #[$stability: meta] $Ty: ident($Int: ty); )+ ) => {
$(
doc_comment! {
concat!("An integer that is known not to equal zero.
This enables some memory layout optimization.
For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
```rust
use std::mem::size_of;
assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
">());
```"),
#[$stability]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(transparent)]
#[rustc_layout_scalar_valid_range_start(1)]
pub struct $Ty($Int);
}
impl $Ty {
/// Create a non-zero without checking the value.
///
/// # Safety
///
/// The value must not be zero.
#[$stability]
#[inline]
pub const unsafe fn new_unchecked(n: $Int) -> Self {
$Ty(n)
}
/// Create a non-zero if the given value is not zero.
#[$stability]
#[inline]
pub fn new(n: $Int) -> Option<Self> {
if n != 0 {
Some(unsafe { $Ty(n) })
} else {
None
}
}
/// Returns the value as a primitive type.
#[$stability]
#[inline]
pub const fn get(self) -> $Int {
self.0
}
}
#[stable(feature = "from_nonzero", since = "1.31.0")]
impl From<$Ty> for $Int {
fn from(nonzero: $Ty) -> Self {
nonzero.0
}
}
impl_nonzero_fmt! {
#[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
}
)+
}
}
nonzero_integers! {
#[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
#[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
#[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
#[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
#[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
#[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
#[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
#[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
#[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
#[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
#[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
#[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
}
/// 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.
///
/// The underlying value can be retrieved through the `.0` index of the
/// `Wrapping` tuple.
///
/// # 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)]
#[repr(transparent)]
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)
}
}
// All these modules are technically private and only exposed for coretests:
pub mod flt2dec;
pub mod dec2flt;
pub mod bignum;
pub mod diy_float;
mod wrapping;
// `Int` + `SignedInt` implemented for signed integers
macro_rules! int_impl {
($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
$EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
$reversed:expr, $le_bytes:expr, $be_bytes:expr) => {
doc_comment! {
concat!("Returns the smallest value that can be represented by this integer type.
# Examples
Basic usage:
```
", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
#[rustc_promotable]
pub const fn min_value() -> Self {
!0 ^ ((!0 as $UnsignedT) >> 1) as Self
}
}
doc_comment! {
concat!("Returns the largest value that can be represented by this integer type.
# Examples
Basic usage:
```
", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
#[rustc_promotable]
pub const fn max_value() -> Self {
!Self::min_value()
}
}
doc_comment! {
concat!("Converts a string slice in a given base to an integer.
The string is expected to be an optional `+` or `-` sign followed by digits.
Leading and trailing whitespace represent an error. Digits are a subset of these characters,
depending on `radix`:
* `0-9`
* `a-z`
* `A-Z`
# Panics
This function panics if `radix` is not in the range from 2 to 36.
# Examples
Basic usage:
```
", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
from_str_radix(src, radix)
}
}
doc_comment! {
concat!("Returns the number of ones in the binary representation of `self`.
# Examples
Basic usage:
```
", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
assert_eq!(n.count_ones(), 1);",
$EndFeature, "
```
"),
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
#[inline]
pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
}
doc_comment! {
concat!("Returns the number of zeros in the binary representation of `self`.
# Examples
Basic usage:
```
", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
#[inline]
pub const fn count_zeros(self) -> u32 {
(!self).count_ones()
}
}
doc_comment! {
concat!("Returns the number of leading zeros in the binary representation of `self`.
# Examples
Basic usage:
```
", $Feature, "let n = -1", stringify!($SelfT), ";
assert_eq!(n.leading_zeros(), 0);",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
#[inline]
pub const fn leading_zeros(self) -> u32 {
(self as $UnsignedT).leading_zeros()
}
}
doc_comment! {
concat!("Returns the number of trailing zeros in the binary representation of `self`.
# Examples
Basic usage:
```
", $Feature, "let n = -4", stringify!($SelfT), ";
assert_eq!(n.trailing_zeros(), 2);",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
#[inline]
pub const fn trailing_zeros(self) -> u32 {
(self as $UnsignedT).trailing_zeros()
}
}
doc_comment! {
concat!("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 = ", $rot_op, stringify!($SelfT), ";
let m = ", $rot_result, ";
assert_eq!(n.rotate_left(", $rot, "), m);
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_rotate"))]
#[inline]
pub const fn rotate_left(self, n: u32) -> Self {
(self as $UnsignedT).rotate_left(n) as Self
}
}
doc_comment! {
concat!("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 = ", $rot_result, stringify!($SelfT), ";
let m = ", $rot_op, ";
assert_eq!(n.rotate_right(", $rot, "), m);
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_rotate"))]
#[inline]
pub const fn rotate_right(self, n: u32) -> Self {
(self as $UnsignedT).rotate_right(n) as Self
}
}
doc_comment! {
concat!("Reverses the byte order of the integer.
# Examples
Basic usage:
```
let n = ", $swap_op, stringify!($SelfT), ";
let m = n.swap_bytes();
assert_eq!(m, ", $swapped, ");
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
#[inline]
pub const fn swap_bytes(self) -> Self {
(self as $UnsignedT).swap_bytes() as Self
}
}
doc_comment! {
concat!("Reverses the bit pattern of the integer.
# Examples
Basic usage:
```
#![feature(reverse_bits)]
let n = ", $swap_op, stringify!($SelfT), ";
let m = n.reverse_bits();
assert_eq!(m, ", $reversed, ");
```"),
#[unstable(feature = "reverse_bits", issue = "48763")]
#[rustc_const_unstable(feature = "const_int_conversion")]
#[inline]
pub const fn reverse_bits(self) -> Self {
(self as $UnsignedT).reverse_bits() as Self
}
}
doc_comment! {
concat!("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:
```
", $Feature, "let n = 0x1A", stringify!($SelfT), ";
if cfg!(target_endian = \"big\") {
assert_eq!(", stringify!($SelfT), "::from_be(n), n)
} else {
assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
}",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
#[inline]
pub const fn from_be(x: Self) -> Self {
#[cfg(target_endian = "big")]
{
x
}
#[cfg(not(target_endian = "big"))]
{
x.swap_bytes()
}
}
}
doc_comment! {
concat!("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:
```
", $Feature, "let n = 0x1A", stringify!($SelfT), ";
if cfg!(target_endian = \"little\") {
assert_eq!(", stringify!($SelfT), "::from_le(n), n)
} else {
assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
}",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
#[inline]
pub const fn from_le(x: Self) -> Self {
#[cfg(target_endian = "little")]
{
x
}
#[cfg(not(target_endian = "little"))]
{
x.swap_bytes()
}
}
}
doc_comment! {
concat!("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:
```
", $Feature, "let n = 0x1A", stringify!($SelfT), ";
if cfg!(target_endian = \"big\") {
assert_eq!(n.to_be(), n)
} else {
assert_eq!(n.to_be(), n.swap_bytes())
}",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
#[inline]
pub const fn to_be(self) -> Self { // or not to be?
#[cfg(target_endian = "big")]
{
self
}
#[cfg(not(target_endian = "big"))]
{
self.swap_bytes()
}
}
}
doc_comment! {
concat!("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:
```
", $Feature, "let n = 0x1A", stringify!($SelfT), ";
if cfg!(target_endian = \"little\") {
assert_eq!(n.to_le(), n)
} else {
assert_eq!(n.to_le(), n.swap_bytes())
}",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
#[inline]
pub const fn to_le(self) -> Self {
#[cfg(target_endian = "little")]
{
self
}
#[cfg(not(target_endian = "little"))]
{
self.swap_bytes()
}
}
}
doc_comment! {
concat!("Checked integer addition. Computes `self + rhs`, returning `None`
if overflow occurred.
# Examples
Basic usage:
```
", $Feature, "assert_eq!((", stringify!($SelfT),
"::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if b {None} else {Some(a)}
}
}
doc_comment! {
concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
overflow occurred.
# Examples
Basic usage:
```
", $Feature, "assert_eq!((", stringify!($SelfT),
"::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if b {None} else {Some(a)}
}
}
doc_comment! {
concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
overflow occurred.
# Examples
Basic usage:
```
", $Feature, "assert_eq!(", stringify!($SelfT),
"::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if b {None} else {Some(a)}
}
}
doc_comment! {
concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
or the division results in overflow.
# Examples
Basic usage:
```
", $Feature, "assert_eq!((", stringify!($SelfT),
"::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_div(self, rhs: Self) -> Option<Self> {
if rhs == 0 || (self == Self::min_value() && rhs == -1) {
None
} else {
Some(unsafe { intrinsics::unchecked_div(self, rhs) })
}
}
}
doc_comment! {
concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
returning `None` if `rhs == 0` or the division results in overflow.
# Examples
Basic usage:
```
#![feature(euclidean_division)]
assert_eq!((", stringify!($SelfT),
"::min_value() + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euclid(-1), None);
assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
```"),
#[unstable(feature = "euclidean_division", issue = "49048")]
#[inline]
pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if rhs == 0 || (self == Self::min_value() && rhs == -1) {
None
} else {
Some(self.div_euclid(rhs))
}
}
}
doc_comment! {
concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
`rhs == 0` or the division results in overflow.
# Examples
Basic usage:
```
", $Feature, "use std::", stringify!($SelfT), ";
assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
$EndFeature, "
```"),
#[stable(feature = "wrapping", since = "1.7.0")]
#[inline]
pub fn checked_rem(self, rhs: Self) -> Option<Self> {
if rhs == 0 || (self == Self::min_value() && rhs == -1) {
None
} else {
Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
}
}
}
doc_comment! {
concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
if `rhs == 0` or the division results in overflow.
# Examples
Basic usage:
```
#![feature(euclidean_division)]
use std::", stringify!($SelfT), ";
assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
```"),
#[unstable(feature = "euclidean_division", issue = "49048")]
#[inline]
pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if rhs == 0 || (self == Self::min_value() && rhs == -1) {
None
} else {
Some(self.rem_euclid(rhs))
}
}
}
doc_comment! {
concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
# Examples
Basic usage:
```
", $Feature, "use std::", stringify!($SelfT), ";
assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
$EndFeature, "
```"),
#[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)}
}
}
doc_comment! {
concat!("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:
```
", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
$EndFeature, "
```"),
#[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)}
}
}
doc_comment! {
concat!("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:
```
", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
$EndFeature, "
```"),
#[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)}
}
}
doc_comment! {
concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
`self == MIN`.
# Examples
Basic usage:
```
", $Feature, "use std::", stringify!($SelfT), ";
assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
$EndFeature, "
```"),
#[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)
}
}
}
doc_comment! {
concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
overflow occurred.
# Examples
Basic usage:
```
", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
$EndFeature, "
```"),
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[inline]
pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc: Self = 1;
while exp > 1 {
if (exp & 1) == 1 {
acc = acc.checked_mul(base)?;
}
exp /= 2;
base = base.checked_mul(base)?;
}
// Deal with the final bit of the exponent separately, since
// squaring the base afterwards is not necessary and may cause a
// needless overflow.
if exp == 1 {
acc = acc.checked_mul(base)?;
}
Some(acc)
}
}
doc_comment! {
concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
bounds instead of overflowing.
# Examples
Basic usage:
```
", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
"::max_value());",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn saturating_add(self, rhs: Self) -> Self {
match self.checked_add(rhs) {
Some(x) => x,
None if rhs >= 0 => Self::max_value(),
None => Self::min_value(),
}
}
}
doc_comment! {
concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
numeric bounds instead of overflowing.
# Examples
Basic usage:
```
", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
"::min_value());",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn saturating_sub(self, rhs: Self) -> Self {
match self.checked_sub(rhs) {
Some(x) => x,
None if rhs >= 0 => Self::min_value(),
None => Self::max_value(),
}
}
}
doc_comment! {
concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
numeric bounds instead of overflowing.
# Examples
Basic usage:
```
", $Feature, "use std::", stringify!($SelfT), ";
assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
$EndFeature, "
```"),
#[stable(feature = "wrapping", since = "1.7.0")]
#[inline]
pub fn saturating_mul(self, rhs: Self) -> Self {
self.checked_mul(rhs).unwrap_or_else(|| {
if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
Self::max_value()
} else {
Self::min_value()
}
})
}
}
doc_comment! {
concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
saturating at the numeric bounds instead of overflowing.
# Examples
Basic usage:
```
", $Feature, "use std::", stringify!($SelfT), ";
assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
$EndFeature, "
```"),
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[inline]
pub fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None if self < 0 && exp % 2 == 1 => Self::min_value(),
None => Self::max_value(),
}
}
}
doc_comment! {
concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
boundary of the type.
# Examples
Basic usage:
```
", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
"::min_value() + 1);",
$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]