Skip to content

Commit 0f032b3

Browse files
adpaco-awstedinski
authored andcommitted
Tests for <op>_with_overflow (rust-lang#1083)
1 parent ef3feaf commit 0f032b3

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0 OR MIT
3+
//
4+
// Checks that `<op>_with_overflow` returns the expected result in all cases.
5+
#![feature(core_intrinsics)]
6+
use std::intrinsics::{add_with_overflow, mul_with_overflow, sub_with_overflow};
7+
8+
// The value of the overflow flag should match the option value returned by the
9+
// corresponding checked operation. In other words, if `checked.is_some()` is
10+
// assumed then `<op>_with_overflow` should not have overflown and `overflow`
11+
// should be false. The same can be done to verify overflows with
12+
// `checked.is_none()`.
13+
macro_rules! verify_no_overflow {
14+
($ty:ty, $cf: ident, $fwo: ident) => {{
15+
let a: $ty = kani::any();
16+
let b: $ty = kani::any();
17+
let checked = a.$cf(b);
18+
kani::assume(checked.is_some());
19+
let (res, overflow) = $fwo(a, b);
20+
assert!(!overflow);
21+
assert!(checked.unwrap() == res);
22+
}};
23+
}
24+
25+
macro_rules! verify_overflow {
26+
($ty:ty, $cf: ident, $fwo: ident) => {{
27+
let a: $ty = kani::any();
28+
let b: $ty = kani::any();
29+
let checked = a.$cf(b);
30+
kani::assume(checked.is_none());
31+
let (_res, overflow) = $fwo(a, b);
32+
assert!(overflow);
33+
}};
34+
}
35+
36+
#[kani::proof]
37+
fn test_add_with_overflow() {
38+
verify_no_overflow!(u8, checked_add, add_with_overflow);
39+
verify_overflow!(u8, checked_add, add_with_overflow);
40+
}
41+
42+
#[kani::proof]
43+
fn test_sub_with_overflow() {
44+
verify_no_overflow!(u8, checked_sub, sub_with_overflow);
45+
verify_overflow!(u8, checked_sub, sub_with_overflow);
46+
}
47+
48+
#[kani::proof]
49+
fn test_mul_with_overflow() {
50+
verify_no_overflow!(u8, checked_mul, mul_with_overflow);
51+
verify_overflow!(u8, checked_mul, mul_with_overflow);
52+
}

0 commit comments

Comments
 (0)