|
2 | 2 | // SPDX-License-Identifier: Apache-2.0 OR MIT
|
3 | 3 | //! Useful utilities for CBMC
|
4 | 4 |
|
| 5 | +use num::bigint::BigInt; |
| 6 | + |
5 | 7 | /// RMC bug report URL, for asserts/errors
|
6 | 8 | pub const BUG_REPORT_URL: &str =
|
7 | 9 | "https://github.com/model-checking/rmc/issues/new?template=bug_report.md";
|
@@ -42,3 +44,62 @@ macro_rules! btree_string_map {
|
42 | 44 | (BTreeMap::from_iter(vec![$($x),*].into_iter().map(|(k,v)|(k.to_string(),v))))
|
43 | 45 | }}
|
44 | 46 | }
|
| 47 | + |
| 48 | +pub fn max_int(width: u64, signed: bool) -> BigInt { |
| 49 | + let mut bi = BigInt::from(0); |
| 50 | + if signed { |
| 51 | + bi.set_bit(width - 1, true); |
| 52 | + } else { |
| 53 | + bi.set_bit(width, true); |
| 54 | + } |
| 55 | + bi - 1 |
| 56 | +} |
| 57 | + |
| 58 | +pub fn min_int(width: u64, signed: bool) -> BigInt { |
| 59 | + if signed { |
| 60 | + let max = max_int(width, true); |
| 61 | + let min = -max - 1; |
| 62 | + min |
| 63 | + } else { |
| 64 | + BigInt::from(0) |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +#[cfg(test)] |
| 69 | +mod tests { |
| 70 | + use crate::utils::{max_int, min_int}; |
| 71 | + use num::BigInt; |
| 72 | + #[test] |
| 73 | + fn test_max_int() { |
| 74 | + // Unsigned |
| 75 | + assert_eq!(max_int(8, false), BigInt::from(u8::MAX)); |
| 76 | + assert_eq!(max_int(16, false), BigInt::from(u16::MAX)); |
| 77 | + assert_eq!(max_int(32, false), BigInt::from(u32::MAX)); |
| 78 | + assert_eq!(max_int(64, false), BigInt::from(u64::MAX)); |
| 79 | + assert_eq!(max_int(128, false), BigInt::from(u128::MAX)); |
| 80 | + |
| 81 | + //Signed |
| 82 | + assert_eq!(max_int(8, true), BigInt::from(i8::MAX)); |
| 83 | + assert_eq!(max_int(16, true), BigInt::from(i16::MAX)); |
| 84 | + assert_eq!(max_int(32, true), BigInt::from(i32::MAX)); |
| 85 | + assert_eq!(max_int(64, true), BigInt::from(i64::MAX)); |
| 86 | + assert_eq!(max_int(128, true), BigInt::from(i128::MAX)); |
| 87 | + } |
| 88 | + |
| 89 | + #[test] |
| 90 | + fn test_min_int() { |
| 91 | + // Unsigned |
| 92 | + assert_eq!(min_int(8, false), BigInt::from(u8::MIN)); |
| 93 | + assert_eq!(min_int(16, false), BigInt::from(u16::MIN)); |
| 94 | + assert_eq!(min_int(32, false), BigInt::from(u32::MIN)); |
| 95 | + assert_eq!(min_int(64, false), BigInt::from(u64::MIN)); |
| 96 | + assert_eq!(min_int(128, false), BigInt::from(u128::MIN)); |
| 97 | + |
| 98 | + //Signed |
| 99 | + assert_eq!(min_int(8, true), BigInt::from(i8::MIN)); |
| 100 | + assert_eq!(min_int(16, true), BigInt::from(i16::MIN)); |
| 101 | + assert_eq!(min_int(32, true), BigInt::from(i32::MIN)); |
| 102 | + assert_eq!(min_int(64, true), BigInt::from(i64::MIN)); |
| 103 | + assert_eq!(min_int(128, true), BigInt::from(i128::MIN)); |
| 104 | + } |
| 105 | +} |
0 commit comments