File tree Expand file tree Collapse file tree 2 files changed +98
-0
lines changed Expand file tree Collapse file tree 2 files changed +98
-0
lines changed Original file line number Diff line number Diff line change 1+ #![ no_std]
2+
3+ pub fn sum_checked ( xs : & [ u32 ] ) -> Option < u32 > {
4+ let mut acc: u32 = 0 ;
5+ let mut i: usize = 0 ;
6+ // Invariant idea (Coq):
7+ // - 0 <= i <= xs.len()
8+ // - acc = sum(xs[0..i]) and never overflowed
9+ while i < xs. len ( ) {
10+ match acc. checked_add ( xs[ i] ) {
11+ Some ( v) => acc = v,
12+ None => return None ,
13+ }
14+ i += 1 ;
15+ }
16+ Some ( acc)
17+ }
18+
19+ pub fn reverse_in_place ( xs : & mut [ i32 ] ) {
20+ if xs. len ( ) == 0 { return ; }
21+ let mut l: usize = 0 ;
22+ let mut r: usize = xs. len ( ) - 1 ;
23+ // Invariant idea:
24+ // - xs[0..l] and xs[r+1..] are already reversed wrt original
25+ // - l <= r + 1
26+ while l < r {
27+ let tmp = xs[ l] ;
28+ xs[ l] = xs[ r] ;
29+ xs[ r] = tmp;
30+ l += 1 ;
31+ r -= 1 ;
32+ }
33+ }
34+
35+ pub fn is_sorted ( xs : & [ i32 ] ) -> bool {
36+ let mut i: usize = 1 ;
37+ // Invariant idea:
38+ // - prefix xs[0..i] is sorted (pairwise non-decreasing)
39+ while i < xs. len ( ) {
40+ if xs[ i - 1 ] > xs[ i] { return false ; }
41+ i += 1 ;
42+ }
43+ true
44+ }
45+
46+ pub fn max_array < const N : usize > ( a : & [ i32 ; N ] ) -> i32 {
47+ let mut m = a[ 0 ] ;
48+ let mut i: usize = 1 ;
49+ // Invariant idea:
50+ // - m = max(a[0..i])
51+ while i < N {
52+ if a[ i] > m { m = a[ i] ; }
53+ i += 1 ;
54+ }
55+ m
56+ }
Original file line number Diff line number Diff line change 1+ #![ no_std]
2+
3+ // max2(a,b) = a or max2(a,b) = b
4+ // max2(a,b) >= a and >= b
5+ pub fn max2 ( a : u32 , b : u32 ) -> u32 {
6+ if a < b { b } else { a }
7+ }
8+
9+ // result ≥ 0
10+ pub fn abs_i32 ( x : i32 ) -> i32 {
11+ if x < 0 { -x } else { x }
12+ }
13+
14+ // Truth table correctness
15+ pub fn bool_and ( a : bool , b : bool ) -> bool {
16+ if a {
17+ if b { true } else { false }
18+ } else {
19+ false
20+ }
21+ }
22+
23+ pub fn get_or_zero ( xs : & [ u32 ; 4 ] , i : usize ) -> u32 {
24+ if i < 4 { xs[ i] } else { 0 }
25+ }
26+
27+ pub fn eq2 ( a : & [ u32 ; 2 ] , b : & [ u32 ; 2 ] ) -> bool {
28+ if a[ 0 ] == b[ 0 ] && a[ 1 ] == b[ 1 ] {
29+ true
30+ } else {
31+ false
32+ }
33+ }
34+
35+ pub fn eq_pair ( x : ( u32 , u32 ) , y : ( u32 , u32 ) ) -> bool {
36+ if x. 0 == y. 0 && x. 1 == y. 1 { true } else { false }
37+ }
38+
39+ pub fn min3 ( a : u32 , b : u32 , c : u32 ) -> u32 {
40+ let m = if a < b { a } else { b } ;
41+ if m < c { m } else { c }
42+ }
You can’t perform that action at this time.
0 commit comments