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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#![warn(clippy::all)]
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]

use bollard::container::{Config, RemoveContainerOptions};
use bollard::Docker;
use std::collections::HashMap;
use std::str::FromStr;

use bollard::exec::{CreateExecOptions, StartExecResults};
use bollard::image::CreateImageOptions;
use futures_util::stream::StreamExt;
use futures_util::TryStreamExt;

/// Contains the workspace that resulted from running the octave command in `eval`
#[derive(Debug)]
pub struct OctaveResults {
    /// Scalar variables
    scalars: HashMap<String, f64>,
    /// Matrix variables
    matrices: HashMap<String, Vec<Vec<f64>>>,
    /// String variables
    strings: HashMap<String, String>,
}

impl OctaveResults {
    /// Get a scalar by name
    pub fn get_scalar_named(&self, name: &str) -> Option<f64> {
        self.scalars.get(name).cloned()
    }
    /// Get a matrix by name
    pub fn get_matrix_named(&self, name: &str) -> Option<Vec<Vec<f64>>> {
        self.matrices.get(name).cloned()
    }
    /// Get a string by name
    pub fn get_string_named(&self, name: &str) -> Option<String> {
        self.strings.get(name).cloned()
    }
}

impl From<String> for OctaveResults {
    fn from(output: String) -> Self {
        let mut results = OctaveResults {
            scalars: Default::default(),
            matrices: Default::default(),
            strings: Default::default(),
        };

        let split_output = output.split("\n");
        let mut name: String = "".to_owned();
        let mut curently_reading: String = "".to_owned();
        let mut matrix: Vec<Vec<f64>> = vec![];
        let mut current_row: usize = 0;
        let mut max_rows: usize = 0;
        let mut columns: usize = 0;
        for line in split_output {
            if curently_reading.len() == 0 {
                if line.starts_with("# Created") {
                    continue;
                } else if line.starts_with("# name: ") {
                    name = line.to_string().replace("# name: ", "").replace("\n", "");
                } else if line.starts_with("# type: ") {
                    curently_reading = line
                        .to_string()
                        .replace("# type: ", "")
                        .replace("\n", "")
                        .replace("sq_", "")
                }
            } else {
                if curently_reading == "scalar" && !line.is_empty() {
                    results
                        .scalars
                        .insert(name.clone(), f64::from_str(line).unwrap());
                    curently_reading = "".to_owned();
                } else if curently_reading == "string" && !line.is_empty() {
                    if line.starts_with("# elements: ") || line.starts_with("# length: ") {
                        continue;
                    } else {
                        results.strings.insert(name.clone(), line.parse().unwrap());
                        curently_reading = "".to_owned();
                    }
                } else if curently_reading == "matrix" && !line.is_empty() {
                    if line.starts_with("# rows: ") {
                        current_row = 0;
                        max_rows =
                            usize::from_str(&*line.to_string().replace("# rows: ", "")).unwrap();
                    } else if line.starts_with("# columns: ") {
                        columns =
                            usize::from_str(&*line.to_string().replace("# columns: ", "")).unwrap();
                    } else {
                        if !line.is_empty() {
                            let mut this_row = vec![];
                            // println!("{line}");
                            for elem in line.split(" ") {
                                if elem.is_empty() {
                                    continue;
                                } else {
                                    // println!("{elem}");
                                    this_row.push(f64::from_str(elem).unwrap());
                                }
                            }
                            matrix.push(this_row);
                            current_row += 1;
                        }
                        if current_row == max_rows {
                            results.matrices.insert(name.clone(), matrix.clone());
                            matrix = vec![];
                            curently_reading = "".to_owned();
                        }
                    }
                } else if curently_reading == "diagonal matrix" && !line.is_empty() {
                    if line.starts_with("# rows: ") {
                        current_row = 0;
                        max_rows =
                            usize::from_str(&*line.to_string().replace("# rows: ", "")).unwrap();
                    } else if line.starts_with("# columns: ") {
                        columns =
                            usize::from_str(&*line.to_string().replace("# columns: ", "")).unwrap();
                    } else {
                        if !line.is_empty() {
                            let mut this_row = vec![0.0_f64; columns];
                            this_row[current_row] = f64::from_str(line).unwrap();
                            matrix.push(this_row);
                            current_row += 1;
                        }
                        if current_row == max_rows {
                            results.matrices.insert(name.clone(), matrix.clone());
                            matrix = vec![];
                            curently_reading = "".to_owned();
                        }
                    }
                }
            }
        }

        results
    }
}

/// Evaluate a few lines of Octave code and extract the results.
/// ```
/// let res = mocktave::eval("a = 5+2");
/// assert_eq!(res.get_scalar_named("a").unwrap(), 7_f64);
/// ```
/// ```
/// let res = mocktave::eval("a = ones(2, 2)");
/// assert_eq!(res.get_matrix_named("a").unwrap(), vec![vec![1.0_f64; 2]; 2]);
/// ```
/// ```
/// let res = mocktave::eval("a = 'asdf'");
/// assert_eq!(res.get_string_named("a").unwrap(), "asdf");
/// ```
pub fn eval(input: &str) -> OctaveResults {
    Interpreter::default().eval(input)
}

/// Create a persistent interpreter that can call a single container multiple times, resulting in
/// more efficiency code execution.
/// ```
/// let mut interp = mocktave::Interpreter::default();
/// let res1 = interp.eval("a = 5+2");
/// assert_eq!(res1.get_scalar_named("a").unwrap(), 7_f64);
/// let res2 = interp.eval("a = ones(2, 2)");
/// assert_eq!(res2.get_matrix_named("a").unwrap(), vec![vec![1.0_f64; 2]; 2]);
/// let res3 = interp.eval("a = 'asdf'");
/// assert_eq!(res3.get_string_named("a").unwrap(), "asdf");
/// ```
pub struct Interpreter {
    docker: Docker,
    id: String,
}

impl Default for Interpreter {
    fn default() -> Self {
        tokio::runtime::Runtime::new().unwrap().block_on(async {
            let docker = Docker::connect_with_socket_defaults()
                .expect("Could not connect with socket defaults");
            docker
                .create_image(
                    Some(CreateImageOptions {
                        from_image: "mtmiller/octave:7.0.0",
                        ..Default::default()
                    }),
                    None,
                    None,
                )
                .try_collect::<Vec<_>>()
                .await
                .expect("Could not create image.");

            let alpine_config = Config {
                image: Some("mtmiller/octave:7.0.0"),
                tty: Some(true),
                ..Default::default()
            };

            let id = docker
                .create_container::<&str, &str>(None, alpine_config)
                .await
                .expect("Could not create container.")
                .id;

            docker
                .start_container::<String>(&id, None)
                .await
                .expect("Could not start container");

            Interpreter { docker, id }
        })
    }
}

impl Interpreter {
    /// This function does the heavy lifting in the interpreter struct.
    pub fn eval(&mut self, input: &str) -> OctaveResults {
        tokio::runtime::Runtime::new().unwrap().block_on(async {
            // non interactive
            let exec = self
                .docker
                .create_exec(
                    &self.id.clone(),
                    CreateExecOptions {
                        attach_stdout: Some(true),
                        attach_stderr: Some(true),
                        cmd: Some(vec![
                            "octave",
                            "--eval",
                            &(input.to_string() + "\n\nsave(\"-\", \"*\");"),
                        ]),
                        ..Default::default()
                    },
                )
                .await
                .expect("Could not create command to execute.")
                .id;

            let mut output_text = vec!["".to_string(); 0];

            if let StartExecResults::Attached { mut output, .. } = self
                .docker
                .start_exec(&exec, None)
                .await
                .expect("Execution of command failed.")
            {
                while let Some(Ok(msg)) = output.next().await {
                    output_text.push(msg.to_string());
                    print!("{}", msg);
                }
            } else {
                unreachable!();
            }

            OctaveResults::from(output_text.join(""))
        })
    }
}

impl Drop for Interpreter {
    fn drop(&mut self) {
        tokio::runtime::Runtime::new()
            .unwrap()
            .block_on(self.docker.remove_container(
                &self.id.clone(),
                Some(RemoveContainerOptions {
                    force: true,
                    ..Default::default()
                }),
            ))
            .expect("Could not remove container.");
    }
}