about summary refs log tree commit diff
diff options
context:
space:
mode:
authorChristian Poveda <christianpoveda@protonmail.com>2019-12-14 12:13:10 -0500
committerChristian Poveda <christianpoveda@protonmail.com>2019-12-14 12:13:10 -0500
commit0bce91ff0b3252b736040087f9b768027422f3f0 (patch)
treea12a84921448c2ff6f5d2389c1f6b20202850dc9
parentc8ea4ace9213ae045123fdfeb59d1ac887656d31 (diff)
downloadrust-0bce91ff0b3252b736040087f9b768027422f3f0.tar.gz
rust-0bce91ff0b3252b736040087f9b768027422f3f0.zip
add Scalar::try_from_(u)int methods
-rw-r--r--src/librustc/mir/interpret/value.rs34
1 files changed, 22 insertions, 12 deletions
diff --git a/src/librustc/mir/interpret/value.rs b/src/librustc/mir/interpret/value.rs
index a038ca23ae9..4f196cda5ae 100644
--- a/src/librustc/mir/interpret/value.rs
+++ b/src/librustc/mir/interpret/value.rs
@@ -237,13 +237,18 @@ impl<'tcx, Tag> Scalar<Tag> {
     }
 
     #[inline]
-    pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
+    pub fn try_from_uint(i: impl Into<u128>, size: Size) -> InterpResult<'tcx, Self> {
         let i = i.into();
-        assert_eq!(
-            truncate(i, size), i,
-            "Unsigned value {:#x} does not fit in {} bits", i, size.bits()
-        );
-        Scalar::Raw { data: i, size: size.bytes() as u8 }
+        if truncate(i, size) == i {
+            Ok(Scalar::Raw { data: i, size: size.bytes() as u8 })
+        } else {
+            throw_unsup_format!("Unsigned value {:#x} does not fit in {} bits", i, size.bits())
+        }
+    }
+
+    #[inline]
+    pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
+        Self::try_from_uint(i, size).unwrap()
     }
 
     #[inline]
@@ -267,15 +272,20 @@ impl<'tcx, Tag> Scalar<Tag> {
     }
 
     #[inline]
-    pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
+    pub fn try_from_int(i: impl Into<i128>, size: Size) -> InterpResult<'tcx, Self> {
         let i = i.into();
         // `into` performed sign extension, we have to truncate
         let truncated = truncate(i as u128, size);
-        assert_eq!(
-            sign_extend(truncated, size) as i128, i,
-            "Signed value {:#x} does not fit in {} bits", i, size.bits()
-        );
-        Scalar::Raw { data: truncated, size: size.bytes() as u8 }
+        if sign_extend(truncated, size) as i128 == i {
+            Ok(Scalar::Raw { data: truncated, size: size.bytes() as u8 })
+        } else {
+            throw_unsup_format!("Signed value {:#x} does not fit in {} bits", i, size.bits())
+        }
+    }
+
+    #[inline]
+    pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
+        Self::try_from_int(i, size).unwrap()
     }
 
     #[inline]