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
use internal::{
    dirs::{
        corpus_directory_from_args_type, generic_args_directory_from_args_type,
        impl_generic_args_directory_from_args_type,
    },
    serde_format,
};
use serde::{de::DeserializeOwned, Serialize};
use sha1::{Digest, Sha1};
use std::{
    any::type_name,
    env,
    fmt::{self, Debug, Formatter},
    fs::{create_dir_all, write},
    io::{self, Read},
    marker::PhantomData,
    path::Path,
};

pub use num_traits;

pub mod traits;

// smoelius: TryDebug, etc. use Nikolai Vazquez's trick from `impls`.
// https://github.com/nvzqz/impls#how-it-works

struct DebugUnimplemented<T>(PhantomData<T>);

impl<T> Debug for DebugUnimplemented<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        const PAT: &str = "TryDebug<";
        let type_name = type_name::<T>();
        let pos = type_name.find(PAT).unwrap() + PAT.len();
        write!(
            f,
            "<unknown of type {}>",
            type_name[pos..].strip_suffix('>').unwrap()
        )
    }
}

pub trait TryDebugFallback {
    fn apply<U>(&self, f: &mut dyn FnMut(&dyn Debug) -> U) -> U;
}

impl<T> TryDebugFallback for T {
    fn apply<U>(&self, f: &mut dyn FnMut(&dyn Debug) -> U) -> U {
        f(&DebugUnimplemented::<Self>(PhantomData))
    }
}

pub struct TryDebug<'a, T>(pub &'a T);

impl<'a, T: Debug> TryDebug<'a, T> {
    pub fn apply<U>(&self, f: &mut dyn FnMut(&dyn Debug) -> U) -> U {
        f(self.0)
    }
}

/// * `ty` - Type. When `auto_impl!` is used in the `auto!` macro, this should be just `$ty`.
/// * `trait` - Trait that `ty` may or may not implement.
/// * `expr` - Vector of values using `trait`, should `ty` implement it. In `expr`, `T` should be
///   used as the name of the type, not `$ty`.
#[macro_export]
macro_rules! auto_impl {
    ($ty:ty, $trait:path, $expr:expr) => {{
        trait AutoFallback<U> {
            fn auto() -> Vec<U>;
        }

        impl<T, U> AutoFallback<U> for T {
            #[must_use]
            fn auto() -> Vec<U> {
                vec![]
            }
        }

        struct Auto<T>(std::marker::PhantomData<T>);

        impl<T: $trait> Auto<T> {
            #[must_use]
            pub fn auto() -> Vec<T> {
                $expr
            }
        }

        Auto::<$ty>::auto() as Vec<$ty>
    }};
}

#[macro_export]
macro_rules! auto {
    ($ty:ty) => {{
        let xss = [
            $crate::auto_impl!(
                $ty,
                $crate::num_traits::bounds::Bounded,
                vec![T::min_value(), T::max_value()]
            ),
            $crate::auto_impl!($ty, Default, vec![T::default()]),
            $crate::auto_impl!(
                $ty,
                $crate::traits::MaxValueSubOne,
                vec![T::max_value_sub_one()]
            ),
            $crate::auto_impl!($ty, $crate::traits::Middle, vec![T::low(), T::high()]),
            $crate::auto_impl!(
                $ty,
                $crate::traits::MinValueAddOne,
                vec![T::min_value_add_one()]
            ),
        ];
        IntoIterator::into_iter(xss).flatten()
    }};
}

#[must_use]
pub fn test_fuzz_enabled() -> bool {
    enabled("")
}

#[must_use]
pub fn display_enabled() -> bool {
    enabled("DISPLAY")
}

#[must_use]
pub fn pretty_print_enabled() -> bool {
    enabled("PRETTY_PRINT")
}

#[must_use]
pub fn replay_enabled() -> bool {
    enabled("REPLAY")
}

#[must_use]
pub fn write_enabled() -> bool {
    enabled("WRITE")
}

#[must_use]
fn enabled(opt: &str) -> bool {
    let key = "TEST_FUZZ".to_owned() + if opt.is_empty() { "" } else { "_" } + opt;
    env::var(key).map_or(false, |value| value != "0")
}

pub fn write_impl_generic_args<T>(args: &[&str]) {
    let impl_generic_args = impl_generic_args_directory_from_args_type::<T>();
    let data = args.join(", ");
    write_data(&impl_generic_args, data.as_bytes()).unwrap();
}

pub fn write_generic_args<T>(args: &[&str]) {
    let generic_args = generic_args_directory_from_args_type::<T>();
    let data = args.join(", ");
    write_data(&generic_args, data.as_bytes()).unwrap();
}

pub fn write_args<T: Serialize>(args: &T) {
    let corpus = corpus_directory_from_args_type::<T>();
    let data = serde_format::serialize(args);
    write_data(&corpus, &data).unwrap();
}

pub fn write_data(dir: &Path, data: &[u8]) -> io::Result<()> {
    create_dir_all(dir).unwrap_or_default();
    let hex = {
        let digest = Sha1::digest(data);
        hex::encode(digest)
    };
    let path_buf = dir.join(hex);
    write(path_buf, data)
}

pub fn read_args<T: DeserializeOwned, R: Read>(reader: R) -> Option<T> {
    serde_format::deserialize(reader)
}