about summary refs log tree commit diff
path: root/library/std/src
diff options
context:
space:
mode:
authorManish Goregaokar <manishsmail@gmail.com>2021-10-06 12:33:13 -0700
committerGitHub <noreply@github.com>2021-10-06 12:33:13 -0700
commit3209582a87f7b8e098bac67f66ed58d8d5840dee (patch)
treedd17f17506a04ccb9167e7d3b6b2bb8cbf1a6a86 /library/std/src
parentd7539a6af09e5889ed9bcb8b49571b7a59c32e65 (diff)
parent47edde1086412b36e9efd6098b191ec15a2a760a (diff)
Rollup merge of #87601 - a1phyr:feature_uint_add_signed, r=kennytm
Add functions to add unsigned and signed integers

This PR adds methods to unsigned integers to add signed integers with good overflow semantics under `#![feature(mixed_integer_ops)]`.

The added API is:

```rust
// `uX` is `u8`, `u16`, `u32`, `u64`,`u128`, `usize`
impl uX {
    pub const fn checked_add_signed(self, iX) -> Option<Self>;
    pub const fn overflowing_add_signed(self, iX) -> (Self, bool);
    pub const fn saturating_add_signed(self, iX) -> Self;
    pub const fn wrapping_add_signed(self, iX) -> Self;
}

impl iX {
    pub const fn checked_add_unsigned(self, uX) -> Option<Self>;
    pub const fn overflowing_add_unsigned(self, uX) -> (Self, bool);
    pub const fn saturating_add_unsigned(self, uX) -> Self;
    pub const fn wrapping_add_unsigned(self, uX) -> Self;

    pub const fn checked_sub_unsigned(self, uX) -> Option<Self>;
    pub const fn overflowing_sub_unsigned(self, uX) -> (Self, bool);
    pub const fn saturating_sub_unsigned(self, uX) -> Self;
    pub const fn wrapping_sub_unsigned(self, uX) -> Self;
}
```

Maybe it would be interesting to also have `add_signed` that panics in debug and wraps in release ?
Diffstat (limited to 'library/std/src')
-rw-r--r--library/std/src/io/cursor.rs7
-rw-r--r--library/std/src/lib.rs1
2 files changed, 2 insertions, 6 deletions
diff --git a/library/std/src/io/cursor.rs b/library/std/src/io/cursor.rs
index 25cc5e67ad1..980b2531192 100644
--- a/library/std/src/io/cursor.rs
+++ b/library/std/src/io/cursor.rs
@@ -292,12 +292,7 @@ where
             SeekFrom::End(n) => (self.inner.as_ref().len() as u64, n),
             SeekFrom::Current(n) => (self.pos, n),
         };
-        let new_pos = if offset >= 0 {
-            base_pos.checked_add(offset as u64)
-        } else {
-            base_pos.checked_sub((offset.wrapping_neg()) as u64)
-        };
-        match new_pos {
+        match base_pos.checked_add_signed(offset) {
             Some(n) => {
                 self.pos = n;
                 Ok(self.pos)
diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs
index 0ba4e85886c..a7516bf4ffd 100644
--- a/library/std/src/lib.rs
+++ b/library/std/src/lib.rs
@@ -297,6 +297,7 @@
 #![feature(maybe_uninit_slice)]
 #![feature(maybe_uninit_uninit_array)]
 #![feature(min_specialization)]
+#![feature(mixed_integer_ops)]
 #![cfg_attr(not(bootstrap), feature(must_not_suspend))]
 #![feature(needs_panic_runtime)]
 #![feature(negative_impls)]