piston_rs 0.4.3

An async wrapper for the Piston code execution engine.
Documentation
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use serde::{Deserialize, Serialize};

use super::File;

/// The result of code execution returned by Piston.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExecResult {
    /// The text sent to `stdout` during execution.
    pub stdout: String,
    /// The text sent to `stderr` during execution.
    pub stderr: String,
    /// The text sent to both `stdout`, and `stderr` during execution.
    pub output: String,
    /// The optional exit code returned by the process.
    pub code: Option<isize>,
    /// The optional signal sent to the process. (`SIGKILL` etc)
    pub signal: Option<String>,
}

impl ExecResult {
    /// Whether or not the execution was ok.
    ///
    /// # Returns
    /// - [`bool`] - [`true`] if the execution returned a zero exit
    /// code.
    pub fn is_ok(&self) -> bool {
        self.code.is_some() && self.code.unwrap() == 0
    }

    /// Whether or not the execution produced errors.
    ///
    /// # Returns
    /// - [`bool`] - [`true`] if the execution returned a non zero exit
    /// code.
    pub fn is_err(&self) -> bool {
        self.code.is_some() && self.code.unwrap() != 0
    }
}

/// Raw response received from Piston
#[doc(hidden)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RawExecResponse {
    /// The language that was used.
    pub language: String,
    /// The version of the language that was used.
    pub version: String,
    /// The result Piston sends detailing execution.
    pub run: ExecResult,
    /// The optional result Piston sends detailing compilation. This
    /// will be [`None`] for non-compiled languages.
    pub compile: Option<ExecResult>,
}

/// A response returned by Piston when executing code.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExecResponse {
    /// The language that was used.
    pub language: String,
    /// The version of the language that was used.
    pub version: String,
    /// The result Piston sends detailing execution.
    pub run: ExecResult,
    /// The optional result Piston sends detailing compilation. This
    /// will be [`None`] for non-compiled languages.
    pub compile: Option<ExecResult>,
    /// The response status returned by Piston.
    pub status: u16,
}

impl ExecResponse {
    /// Whether or not the request to Piston succeeded.
    ///
    /// # Returns
    /// - [`bool`] - [`true`] if a 200 status code was received from Piston.
    pub fn is_ok(&self) -> bool {
        self.status == 200
    }

    /// Whether or not the request to Piston failed.
    ///
    /// # Returns
    /// - [`bool`] - [`true`] if a non 200 status code was received from Piston.
    pub fn is_err(&self) -> bool {
        self.status != 200
    }
}

/// An object containing information about the code being executed.
///
/// A convenient builder flow is provided by the methods associated with
/// the `Executor`. These consume self and return self for chained calls.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Executor {
    /// **Required** - The language to use for execution. Defaults to a
    /// new `String`.
    pub language: String,
    /// The version of the language to use for execution.
    /// Defaults to "*" (*most recent version*).
    pub version: String,
    /// **Required** - A `Vector` of `File`'s to send to Piston. The
    /// first file in the vector is considered the main file. Defaults
    /// to a new `Vector`.
    pub files: Vec<File>,
    /// The text to pass as stdin to the program. Defaults to a new
    /// `String`.
    pub stdin: String,
    /// The arguments to pass to the program. Defaults to a new
    /// `Vector`.
    pub args: Vec<String>,
    /// The maximum allowed time for compilation in milliseconds.
    /// Defaults to `10,000`.
    pub compile_timeout: isize,
    /// The maximum allowed time for execution in milliseconds. Defaults
    /// to `3,000`.
    pub run_timeout: isize,
    /// The maximum allowed memory usage for compilation in bytes.
    /// Defaults to `-1` (*no limit*).
    pub compile_memory_limit: isize,
    /// The maximum allowed memory usage for execution in bytes.
    /// Defaults to `-1` (*no limit*).
    pub run_memory_limit: isize,
}

impl Default for Executor {
    /// Creates a new executor. Alias for [`Executor::new`].
    ///
    /// # Returns
    /// - [`Executor`] - The new blank Executor.
    ///
    /// # Example
    /// ```
    /// let executor = piston_rs::Executor::default();
    ///
    /// assert_eq!(executor.language, String::new());
    /// assert_eq!(executor.version, String::from("*"));
    /// ```
    fn default() -> Self {
        Self::new()
    }
}

impl Executor {
    /// Creates a new executor representing source code to be
    /// executed.
    ///
    /// Metadata regarding the source language and files will
    /// need to be added using the associated method calls, and other
    /// optional fields can be set as well.
    ///
    /// # Returns
    /// - [`Executor`] - The new blank Executor.
    ///
    /// # Example
    /// ```
    /// let executor = piston_rs::Executor::new();
    ///
    /// assert_eq!(executor.language, String::new());
    /// assert_eq!(executor.version, String::from("*"));
    /// ```
    pub fn new() -> Self {
        Self {
            language: String::new(),
            version: String::from("*"),
            files: vec![],
            stdin: String::new(),
            args: vec![],
            compile_timeout: 10000,
            run_timeout: 3000,
            compile_memory_limit: -1,
            run_memory_limit: -1,
        }
    }

    /// Resets the executor back to a `new` state, ready to be
    /// configured again and sent to Piston after metadata is added.
    /// This method mutates the existing executor in place.
    ///
    /// # Example
    /// ```
    /// let mut executor = piston_rs::Executor::new()
    ///     .set_language("rust");
    ///
    /// assert_eq!(executor.language, "rust".to_string());
    ///
    /// executor.reset();
    ///
    /// assert_eq!(executor.language, String::new());
    /// ```
    pub fn reset(&mut self) {
        self.language = String::new();
        self.version = String::from("*");
        self.files = vec![];
        self.stdin = String::new();
        self.args = vec![];
        self.compile_timeout = 10000;
        self.run_timeout = 3000;
        self.compile_memory_limit = -1;
        self.run_memory_limit = -1;
    }

    /// Sets the language to use for execution.
    ///
    /// # Arguments
    /// - `language` - The language to use.
    ///
    /// # Returns
    /// - [`Self`] - For chained method calls.
    ///
    /// # Example
    /// ```
    /// let executor = piston_rs::Executor::new()
    ///     .set_language("rust");
    ///
    /// assert_eq!(executor.language, "rust".to_string());
    /// ```
    #[must_use]
    pub fn set_language(mut self, language: &str) -> Self {
        self.language = language.to_lowercase();
        self
    }

    /// Sets the version of the language to use for execution.
    ///
    /// # Arguments
    /// - `version` - The version to use.
    ///
    /// # Returns
    /// - [`Self`] - For chained method calls.
    ///
    /// # Example
    /// ```
    /// let executor = piston_rs::Executor::new()
    ///     .set_version("1.50.0");
    ///
    /// assert_eq!(executor.version, "1.50.0".to_string());
    /// ```
    #[must_use]
    pub fn set_version(mut self, version: &str) -> Self {
        self.version = version.to_string();
        self
    }

    /// Adds a [`File`] containing the code to be executed. Does not
    /// overwrite any existing files.
    ///
    /// # Arguments
    /// - `file` - The file to add.
    ///
    /// # Returns
    /// - [`Self`] - For chained method calls.
    ///
    /// # Example
    /// ```
    /// let file = piston_rs::File::default();
    ///
    /// let executor = piston_rs::Executor::new()
    ///     .add_file(file.clone());
    ///
    /// assert_eq!(executor.files, [file].to_vec());
    /// ```
    #[must_use]
    pub fn add_file(mut self, file: File) -> Self {
        self.files.push(file);
        self
    }

    /// Adds multiple [`File`]'s containing the code to be executed.
    /// Does not overwrite any existing files.
    ///
    /// # Arguments
    /// - `files` - The files to add.
    ///
    /// # Returns
    /// - [`Self`] - For chained method calls.
    ///
    /// # Example
    /// ```
    /// let mut files = vec![];
    ///
    /// for _ in 0..3 {
    ///     files.push(piston_rs::File::default());
    /// }
    ///
    /// let executor = piston_rs::Executor::new()
    ///     .add_files(files.clone());
    ///
    /// assert_eq!(executor.files, files);
    /// ```
    #[must_use]
    pub fn add_files(mut self, files: Vec<File>) -> Self {
        self.files.extend(files);
        self
    }

    /// Adds multiple [`File`]'s containing the code to be executed.
    /// Overwrites any existing files. This method mutates the existing
    /// executor in place. **Overwrites any existing files.**
    ///
    /// # Arguments
    /// - `files` - The files to replace existing files with.
    ///
    /// # Example
    /// ```
    /// let old_file = piston_rs::File::default()
    ///     .set_name("old_file.rs");
    ///
    /// let mut executor = piston_rs::Executor::new()
    ///     .add_file(old_file.clone());
    ///
    /// assert_eq!(executor.files.len(), 1);
    /// assert_eq!(executor.files[0].name, "old_file.rs".to_string());
    ///
    /// let new_files = vec![
    ///     piston_rs::File::default().set_name("new_file1.rs"),
    ///     piston_rs::File::default().set_name("new_file2.rs"),
    /// ];
    ///
    /// executor.set_files(new_files.clone());
    ///
    /// assert_eq!(executor.files.len(), 2);
    /// assert_eq!(executor.files[0].name, "new_file1.rs".to_string());
    /// assert_eq!(executor.files[1].name, "new_file2.rs".to_string());
    /// ```
    pub fn set_files(&mut self, files: Vec<File>) {
        self.files = files;
    }

    /// Sets the text to pass as `stdin` to the program.
    ///
    /// # Arguments
    /// - `stdin` - The text to set.
    ///
    /// # Returns
    /// - [`Self`] - For chained method calls.
    ///
    /// # Example
    /// ```
    /// let executor = piston_rs::Executor::new()
    ///     .set_stdin("Fearless concurrency");
    ///
    /// assert_eq!(executor.stdin, "Fearless concurrency".to_string());
    /// ```
    #[must_use]
    pub fn set_stdin(mut self, stdin: &str) -> Self {
        self.stdin = stdin.to_string();
        self
    }

    /// Adds an arg to be passed as a command line argument. Does not
    /// overwrite any existing args.
    ///
    /// # Arguments
    /// - `arg` - The arg to add.
    ///
    /// # Returns
    /// - [`Self`] - For chained method calls.
    ///
    /// # Example
    /// ```
    /// let executor = piston_rs::Executor::new()
    ///     .add_arg("--verbose");
    ///
    /// assert_eq!(executor.args, vec!["--verbose".to_string()]);
    /// ```
    #[must_use]
    pub fn add_arg(mut self, arg: &str) -> Self {
        self.args.push(arg.to_string());
        self
    }

    /// Adds multiple args to be passed as a command line arguments.
    /// Does not overwrite any existing args.
    ///
    /// # Arguments
    /// - `args` - The args to add.
    ///
    /// # Example
    /// ```
    /// let executor = piston_rs::Executor::new()
    ///     .add_args(vec!["--verbose"]);
    ///
    /// assert_eq!(executor.args, vec!["--verbose".to_string()]);
    /// ```
    #[must_use]
    pub fn add_args(mut self, args: Vec<&str>) -> Self {
        self.args.extend(args.iter().map(|a| a.to_string()));
        self
    }

    /// Adds multiple args to be passed as a command line arguments.
    /// Overwrites any existing args. This method mutates the existing
    /// executor in place. **Overwrites any existing args.**
    ///
    /// # Arguments
    /// - `args` - The args to replace existing args with.
    ///
    /// # Example
    /// ```
    /// let mut executor = piston_rs::Executor::new()
    ///     .add_arg("--verbose");
    ///
    /// assert_eq!(executor.args.len(), 1);
    /// assert_eq!(executor.args[0], "--verbose".to_string());
    ///
    /// let args = vec!["commit", "-S"];
    /// executor.set_args(args);
    ///
    /// assert_eq!(executor.args.len(), 2);
    /// assert_eq!(executor.args[0], "commit".to_string());
    /// assert_eq!(executor.args[1], "-S".to_string());
    /// ```
    pub fn set_args(&mut self, args: Vec<&str>) {
        self.args = args.iter().map(|a| a.to_string()).collect();
    }

    /// Sets the maximum allowed time for compilation in milliseconds.
    ///
    /// # Arguments
    /// - `timeout` - The timeout to set.
    ///
    /// # Returns
    /// - [`Self`] - For chained method calls.
    ///
    /// # Example
    /// ```
    /// let executor = piston_rs::Executor::new()
    ///     .set_compile_timeout(5000);
    ///
    /// assert_eq!(executor.compile_timeout, 5000);
    /// ```
    #[must_use]
    pub fn set_compile_timeout(mut self, timeout: isize) -> Self {
        self.compile_timeout = timeout;
        self
    }

    /// Sets the maximum allowed time for execution in milliseconds.
    ///
    /// # Arguments
    /// - `timeout` - The timeout to set.
    ///
    /// # Returns
    /// - [`Self`] - For chained method calls.
    ///
    /// # Example
    /// ```
    /// let executor = piston_rs::Executor::new()
    ///     .set_run_timeout(1500);
    ///
    /// assert_eq!(executor.run_timeout, 1500);
    /// ```
    #[must_use]
    pub fn set_run_timeout(mut self, timeout: isize) -> Self {
        self.run_timeout = timeout;
        self
    }

    /// Sets the maximum allowed memory usage for compilation in bytes.
    ///
    /// # Arguments
    /// - `limit` - The memory limit to set.
    ///
    /// # Returns
    /// - [`Self`] - For chained method calls.
    ///
    /// # Example
    /// ```
    /// let executor = piston_rs::Executor::new()
    ///     .set_compile_memory_limit(100_000_000);
    ///
    /// assert_eq!(executor.compile_memory_limit, 100_000_000);
    /// ```
    #[must_use]
    pub fn set_compile_memory_limit(mut self, limit: isize) -> Self {
        self.compile_memory_limit = limit;
        self
    }

    /// Sets the maximum allowed memory usage for execution in bytes.
    ///
    /// # Arguments
    /// - `limit` - The memory limit to set.
    ///
    /// # Returns
    /// - [`Self`] - For chained method calls.
    ///
    /// # Example
    /// ```
    /// let executor = piston_rs::Executor::new()
    ///     .set_run_memory_limit(100_000_000);
    ///
    /// assert_eq!(executor.run_memory_limit, 100_000_000);
    /// ```
    #[must_use]
    pub fn set_run_memory_limit(mut self, limit: isize) -> Self {
        self.run_memory_limit = limit;
        self
    }
}

#[cfg(test)]
mod test_execution_result {
    use super::ExecResponse;
    use super::ExecResult;

    /// Generates an ExecResult for testing
    fn generate_result(stdout: &str, stderr: &str, code: isize) -> ExecResult {
        ExecResult {
            stdout: stdout.to_string(),
            stderr: stderr.to_string(),
            output: format!("{}\n{}", stdout, stderr),
            code: Some(code),
            signal: None,
        }
    }

    /// Generates an ExecResponse for testing.
    fn generate_response(status: u16) -> ExecResponse {
        ExecResponse {
            language: "rust".to_string(),
            version: "1.50.0".to_string(),
            run: generate_result("Be unique.", "", 0),
            compile: None,
            status,
        }
    }

    #[test]
    fn test_response_is_ok() {
        let response = generate_response(200);

        assert!(response.is_ok());
        assert!(!response.is_err());
    }

    #[test]
    fn test_response_is_err() {
        let response = generate_response(400);

        assert!(!response.is_ok());
        assert!(response.is_err());
    }

    #[test]
    fn test_result_is_ok() {
        let result = generate_result("Hello, world", "", 0);

        assert!(result.is_ok());
        assert!(!result.is_err());
    }

    #[test]
    fn test_result_is_err() {
        let result = generate_result("", "Error!", 1);

        assert!(!result.is_ok());
        assert!(result.is_err());
    }

    #[test]
    fn test_is_err_with_stdout() {
        let result = generate_result("Hello, world", "Error!", 1);

        assert!(!result.is_ok());
        assert!(result.is_err());
    }
}