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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use anyhow::{bail, Result};
use std::{fmt, str::FromStr};

macro_rules! impl_otherwise {
    ($e:ident, $a:ident, $b:ident) => {
        impl $e {
            pub fn otherwise(&self) -> Self {
                match self {
                    $e::$a => $e::$b,
                    $e::$b => $e::$a,
                }
            }
        }
    };
}

pub const VALID_CONFIGS: &[&str] = &[
    "mkl-dynamic-ilp64-iomp",
    "mkl-dynamic-ilp64-seq",
    "mkl-dynamic-lp64-iomp",
    "mkl-dynamic-lp64-seq",
    "mkl-static-ilp64-iomp",
    "mkl-static-ilp64-seq",
    "mkl-static-lp64-iomp",
    "mkl-static-lp64-seq",
];

/// How to link MKL
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkType {
    Static,
    Dynamic,
}
impl_otherwise!(LinkType, Static, Dynamic);

impl fmt::Display for LinkType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LinkType::Static => write!(f, "static"),
            LinkType::Dynamic => write!(f, "dynamic"),
        }
    }
}

impl Default for LinkType {
    fn default() -> Self {
        LinkType::Static
    }
}

impl FromStr for LinkType {
    type Err = anyhow::Error;
    fn from_str(input: &str) -> Result<Self> {
        Ok(match input {
            "static" => LinkType::Static,
            "dynamic" => LinkType::Dynamic,
            another => bail!("Invalid link spec: {}", another),
        })
    }
}

/// Data model of library
///
/// Array index of some APIs in MKL are defined by `int` in C,
/// whose size is not fixed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DataModel {
    /// `long` and pointer are 64bit, i.e. `sizeof(int) == 4`
    LP64,
    /// `int`, `long` and pointer are 64bit, i.e. `sizeof(int) == 8`
    ILP64,
}
impl_otherwise!(DataModel, LP64, ILP64);

impl fmt::Display for DataModel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DataModel::LP64 => write!(f, "lp64"),
            DataModel::ILP64 => write!(f, "ilp64"),
        }
    }
}

impl Default for DataModel {
    fn default() -> Self {
        DataModel::ILP64
    }
}

impl FromStr for DataModel {
    type Err = anyhow::Error;
    fn from_str(input: &str) -> Result<Self> {
        Ok(match input {
            "lp64" => DataModel::LP64,
            "ilp64" => DataModel::ILP64,
            another => bail!("Invalid index spec: {}", another),
        })
    }
}

/// How to manage thread(s)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Threading {
    /// Use iomp5, Intel OpenMP runtime.
    OpenMP,
    /// No OpenMP runtime.
    Sequential,
}

impl_otherwise!(Threading, OpenMP, Sequential);

impl Default for Threading {
    fn default() -> Self {
        Threading::Sequential
    }
}

impl fmt::Display for Threading {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Threading::OpenMP => write!(f, "iomp"),
            Threading::Sequential => write!(f, "seq"),
        }
    }
}

impl FromStr for Threading {
    type Err = anyhow::Error;
    fn from_str(input: &str) -> Result<Self> {
        Ok(match input {
            "iomp" => Threading::OpenMP,
            "seq" => Threading::Sequential,
            another => bail!("Invalid parallel spec: {}", another),
        })
    }
}

/// Configuration for Intel MKL, e.g. `mkl-static-lp64-seq`
///
/// There are 2x2x2=8 combinations of [LinkType], [DataModel], and [Threading].
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Config {
    pub link: LinkType,
    pub index_size: DataModel,
    pub parallel: Threading,
}

impl fmt::Display for Config {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "mkl-{}-{}-{}", self.link, self.index_size, self.parallel)
    }
}

impl FromStr for Config {
    type Err = anyhow::Error;
    fn from_str(name: &str) -> Result<Self> {
        let parts: Vec<_> = name.split('-').collect();
        if parts.len() != 4 {
            bail!("Invalid name: {}", name);
        }
        if parts[0] != "mkl" {
            bail!("Name must start with 'mkl': {}", name);
        }
        Ok(Config {
            link: LinkType::from_str(parts[1])?,
            index_size: DataModel::from_str(parts[2])?,
            parallel: Threading::from_str(parts[3])?,
        })
    }
}

impl Config {
    pub fn possibles() -> Vec<Self> {
        VALID_CONFIGS
            .iter()
            .map(|name| Self::from_str(name).unwrap())
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn name_to_config() -> Result<()> {
        let cfg = Config::from_str("mkl-static-lp64-iomp")?;
        assert_eq!(
            cfg,
            Config {
                link: LinkType::Static,
                index_size: DataModel::LP64,
                parallel: Threading::OpenMP
            }
        );
        Ok(())
    }

    #[test]
    fn name_to_config_to_name() -> Result<()> {
        for name in VALID_CONFIGS {
            let cfg = Config::from_str(name)?;
            assert_eq!(&cfg.to_string(), name);
        }
        Ok(())
    }

    #[test]
    fn invalid_names() -> Result<()> {
        assert!(Config::from_str("").is_err());
        assert!(Config::from_str("static-lp64-iomp").is_err());
        assert!(Config::from_str("mkll-static-lp64-iomp").is_err());
        assert!(Config::from_str("mkl-sttic-lp64-iomp").is_err());
        assert!(Config::from_str("mkl-static-l64-iomp").is_err());
        assert!(Config::from_str("mkl-static-lp64-omp").is_err());
        Ok(())
    }
}