byte_mutator/
fuzz_config.rs

1//! Deserializes a .toml config into a `FuzzConfig` object that can be used to configure a
2//! `ByteMutator`. See tests for examples.
3
4use crate::mutators::{Mutation, MutationType};
5use crate::{Iterations, Stage};
6
7use serde_derive::Deserialize;
8use std::fs;
9use std::io::{self, Error};
10use toml;
11
12#[derive(Deserialize, Debug, Clone)]
13/// A struct that can be deserialized from .toml.
14/// Creates and configures `Stage` and `Mutator` objects.
15pub struct FuzzConfig {
16    pub stages: Vec<Stage>,
17}
18
19impl FuzzConfig {
20    pub fn default() -> Self {
21        Self {
22            stages: vec![Stage {
23                count: 0,
24                max: None,
25                mutations: vec![Mutation {
26                    range: None,
27                    mutation: MutationType::BitFlipper { width: 1 },
28                }],
29            }],
30        }
31    }
32
33    pub fn from_file(path: &str) -> std::io::Result<Self> {
34        match fs::read_to_string(path) {
35            Ok(s) => match toml::from_str(&s) {
36                Ok(c) => Ok(c),
37                Err(_) => Err(Error::new(
38                    io::ErrorKind::InvalidInput,
39                    "Failed to parse config",
40                )),
41            },
42            Err(e) => Err(e),
43        }
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn config_from_string() {
53        let config = toml::from_str::<FuzzConfig>(
54            r#"
55                [[stages]]
56                    count = 0
57                    max = 10
58                    
59                    # a list of mutations to perform on this stage
60                    [[stages.mutations]]
61                        mutation = {"BitFlipper" = {width = 1}}
62                        range = [0, 10]
63                        width = 1
64        "#,
65        );
66
67        let error = toml::from_str::<FuzzConfig>("foo");
68
69        assert!(config.is_ok());
70        assert!(error.is_err());
71    }
72
73    #[test]
74    fn config_from_file() {
75        assert!(FuzzConfig::from_file("tests/fuzz_config.toml").is_ok());
76        assert!(FuzzConfig::from_file("").is_err());
77    }
78}