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
use std::ffi::CString;

use crate::{
    errors::{self, Result},
    parameters::{Parameter, ParameterValue},
};
use ffi::{
    cpxenv, CPXcloseCPLEX, CPXopenCPLEX, CPXsetdblparam, CPXsetintparam, CPXsetlongparam,
    CPXsetstrparam,
};
use log::error;

mod macros {
    macro_rules! cpx_env_result {
        ( unsafe { $func:ident ( $env:expr $(, $b:expr)* $(,)? ) } ) => {
            {
                let status = unsafe { $func( $env $(,$b)* ) };
                if status != 0 {
                    Err(errors::Error::from(errors::Cplex::from_code($env, std::ptr::null(), status)))
                } else {
                    Ok(())
                }
            }
        };
    }

    pub(super) use cpx_env_result;
}

pub struct Environment(pub(crate) *mut cpxenv);

impl Environment {
    pub fn new() -> Result<Environment> {
        let mut status = 0;
        let env = unsafe { CPXopenCPLEX(&mut status) };
        if env.is_null() {
            Err(errors::Cplex::env_error(status).into())
        } else {
            Ok(Environment(env))
        }
    }

    pub fn set_parameter<P: Parameter>(&mut self, p: P) -> Result<()> {
        match p.value() {
            ParameterValue::Integer(i) => {
                macros::cpx_env_result!(unsafe { CPXsetintparam(self.0, p.id() as i32, i) })
            }
            ParameterValue::Long(l) => {
                macros::cpx_env_result!(unsafe { CPXsetlongparam(self.0, p.id() as i32, l) })
            }
            ParameterValue::Double(d) => {
                macros::cpx_env_result!(unsafe { CPXsetdblparam(self.0, p.id() as i32, d) })
            }
            ParameterValue::String(s) => {
                let cstr = CString::new(s.as_bytes()).expect("Invalid parameter string");
                macros::cpx_env_result!(unsafe {
                    CPXsetstrparam(self.0, p.id() as i32, cstr.as_ptr())
                })
            }
        }
    }
}

impl Drop for Environment {
    fn drop(&mut self) {
        unsafe {
            let status = CPXcloseCPLEX(&mut self.0);
            if status != 0 {
                error!("Unable to close CPLEX context, got status: '{}'", status)
            }
        }
    }
}