Debian Codegraph @

third_party/rust/neqo-common/src/fuzz.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 use std::{
8 collections::hash_map::DefaultHasher,
9 fs::File,
10 hash::{Hash as _, Hasher as _},
11 io::Write,
12 path::Path,
13 };
14
15 /// Write a data item `data` for the fuzzing target `target` to the fuzzing corpus. The caller needs
16 /// to make sure that `target` is the correct fuzzing target name for the data written.
17 ///
18 /// # Panics
19 ///
20 /// Panics if the corpus directory does not exist or if the corpus item cannot be written.
21 pub fn write_item_to_fuzzing_corpus(target: &str, data: &[u8]) {
22 // This bakes in the assumption that we're executing in the root of the neqo workspace.
23 // Unfortunately, `cargo fuzz` doesn't provide a way to learn the location of the corpus
24 // directory.
25 let corpus = Path::new("../fuzz/corpus").join(target);
26 if !corpus.exists() {
27 std::fs::create_dir_all(&corpus).expect("failed to create corpus directory");
28 }
29
30 // Hash the data to get a unique name for the corpus item.
31 let mut hasher = DefaultHasher::new();
32 data.hash(&mut hasher);
33 let item_name = hex::encode(hasher.finish().to_be_bytes());
34 let item_path = corpus.join(item_name);
35 if item_path.exists() {
36 // Don't overwrite existing corpus items.
37 return;
38 }
39
40 // Write the data to the corpus item.
41 let mut file = File::create(item_path).expect("failed to create corpus item");
42 Write::write_all(&mut file, data).expect("failed to write to corpus item");
43 }