-
Notifications
You must be signed in to change notification settings - Fork 333
/
Copy pathcomparison.nr
103 lines (85 loc) · 2.87 KB
/
comparison.nr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
struct ComparatorEnum {
EQ: u8,
NEQ: u8,
LT: u8,
LTE: u8,
GT: u8,
GTE: u8,
}
global Comparator = ComparatorEnum {
EQ: 1,
NEQ: 2,
LT: 3,
LTE: 4,
GT: 5,
GTE: 6,
};
pub fn compare(lhs: Field, operation: u8, rhs: Field) -> bool {
// Values are computed ahead of time because circuits evaluate all branches
let is_equal = lhs == rhs;
let is_lt = lhs.lt(rhs);
if (operation == Comparator.EQ) {
is_equal
} else if (operation == Comparator.NEQ) {
!is_equal
} else if (operation == Comparator.LT) {
is_lt
} else if (operation == Comparator.LTE) {
is_lt | is_equal
} else if (operation == Comparator.GT) {
!is_lt & !is_equal
} else if (operation == Comparator.GTE) {
!is_lt
} else {
panic(f"Invalid operation")
}
}
mod test {
use super::compare;
use super::Comparator;
#[test]
fn test_compare() {
let lhs = 10;
let rhs = 10;
assert(compare(lhs, Comparator.EQ, rhs), "Expected lhs to be equal to rhs");
let lhs = 10;
let rhs = 11;
assert(compare(lhs, Comparator.NEQ, rhs), "Expected lhs to be not equal to rhs");
let lhs = 10;
let rhs = 11;
assert(compare(lhs, Comparator.LT, rhs), "Expected lhs to be less than rhs");
let lhs = 10;
let rhs = 10;
assert(compare(lhs, Comparator.LTE, rhs), "Expected lhs to be less than or equal to rhs");
let lhs = 11;
let rhs = 10;
assert(compare(lhs, Comparator.GT, rhs), "Expected lhs to be greater than rhs");
let lhs = 10;
let rhs = 10;
assert(compare(lhs, Comparator.GTE, rhs), "Expected lhs to be greater than or equal to rhs");
let lhs = 11;
let rhs = 10;
assert(compare(lhs, Comparator.GTE, rhs), "Expected lhs to be greater than or equal to rhs");
let lhs = 10;
let rhs = 11;
assert(!compare(lhs, Comparator.EQ, rhs), "Expected lhs to be not equal to rhs");
let lhs = 10;
let rhs = 10;
assert(!compare(lhs, Comparator.NEQ, rhs), "Expected lhs to not be not equal to rhs");
let lhs = 11;
let rhs = 10;
assert(!compare(lhs, Comparator.LT, rhs), "Expected lhs to not be less than rhs");
let lhs = 11;
let rhs = 10;
assert(!compare(lhs, Comparator.LTE, rhs), "Expected lhs to not be less than or equal to rhs");
let lhs = 10;
let rhs = 10;
assert(!compare(lhs, Comparator.GT, rhs), "Expected lhs to not be greater than rhs");
let lhs = 10;
let rhs = 11;
assert(!compare(lhs, Comparator.GTE, rhs), "Expected lhs to not be greater than or equal to rhs");
let lhs = 10;
let rhs = 11;
assert(!compare(lhs, Comparator.GTE, rhs), "Expected lhs to not be greater than or equal to rhs");
}
}