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
use core::fmt::{Debug, Formatter};
use crate::expression::Expression;
use crate::variable::{FormatWithVars, Variable};
use std::ops::{Shl, Shr};
pub struct Constraint<F> {
pub(crate) expression: Expression<F>,
pub(crate) is_equality: bool,
}
impl<F> Constraint<F> {
fn new(expression: Expression<F>, is_equality: bool) -> Constraint<F> {
Constraint { expression, is_equality }
}
}
impl<F> FormatWithVars<F> for Constraint<F> {
fn format_with<FUN>(
&self,
f: &mut Formatter<'_>,
variable_format: FUN,
) -> std::fmt::Result
where FUN: Fn(&mut Formatter<'_>, Variable<F>) -> std::fmt::Result {
self.expression.linear.format_with(f, variable_format)?;
write!(f, " {} ", if self.is_equality { "=" } else { "<=" })?;
write!(f, "{}", -self.expression.constant)
}
}
impl<F> Debug for Constraint<F> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.format_debug(f)
}
}
pub fn eq<F, A: Into<Expression<F>>, B: Into<Expression<F>>>(a: A, b: B) -> Constraint<F> {
Constraint::new(a.into() - b.into(), true)
}
pub fn leq<F, A: Into<Expression<F>>, B: Into<Expression<F>>>(a: A, b: B) -> Constraint<F> {
Constraint::new(a.into() - b.into(), false)
}
pub fn geq<F, A: Into<Expression<F>>, B: Into<Expression<F>>>(a: A, b: B) -> Constraint<F> {
leq(b, a)
}
macro_rules! impl_shifts {
($($t:ty)*) => {$(
impl<F, RHS: Into<Expression<F>>> Shl<RHS> for $t {
type Output = Constraint<F>;
fn shl(self, rhs: RHS) -> Self::Output {
leq(self, rhs)
}
}
impl<F, RHS: Into<Expression<F>>> Shr<RHS> for $t {
type Output = Constraint<F>;
fn shr(self, rhs: RHS) -> Self::Output {
geq(self, rhs)
}
}
)*}
}
impl_shifts!(Expression<F> Variable<F>);
#[cfg(test)]
mod tests {
use crate::variables;
#[test]
fn test_leq(){
let mut vars = variables!();
let v0 = vars.add_variable();
let v1 = vars.add_variable();
let f = format!("{:?}", (3. - v0) >> v1);
assert!(vec![
"v0 + v1 <= 3",
"v1 + v0 <= 3"
].contains(&&*f), "{}", f)
}
}