1 // Copyright 2021, The Android Open Source Project 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #![allow(missing_docs)] 16 #![no_main] 17 #![feature(bench_black_box)] 18 19 use hashlink::LinkedHashSet; 20 use libfuzzer_sys::arbitrary::Arbitrary; 21 use libfuzzer_sys::fuzz_target; 22 23 const MAX_RESERVE: usize = 1024; 24 25 #[derive(Arbitrary, Debug, Eq, Hash, PartialEq)] 26 enum Data { 27 A, 28 B, 29 Int { val: u8 }, 30 } 31 32 #[derive(Arbitrary, Debug)] 33 enum LinkedHashSetMethods { 34 Insert { value: Data }, 35 Remove { value: Data }, 36 Contains { value: Data }, 37 Get { value: Data }, 38 GetOrInsert { value: Data }, 39 Iter, 40 Drain, 41 Clear, 42 Reserve { additional: usize }, 43 ShrinkToFit, 44 } 45 46 fuzz_target!(|commands: Vec<LinkedHashSetMethods>| { 47 let mut set = LinkedHashSet::new(); 48 for command in commands { 49 match command { 50 LinkedHashSetMethods::Insert { value } => { 51 set.insert(value); 52 } 53 LinkedHashSetMethods::Remove { value } => { 54 set.remove(&value); 55 } 56 LinkedHashSetMethods::Contains { value } => { 57 set.contains(&value); 58 } 59 LinkedHashSetMethods::Get { value } => { 60 set.get(&value); 61 } 62 LinkedHashSetMethods::GetOrInsert { value } => { 63 set.get_or_insert(value); 64 } 65 LinkedHashSetMethods::Iter => { 66 std::hint::black_box(set.iter().count()); 67 } 68 LinkedHashSetMethods::Drain => { 69 std::hint::black_box(set.drain().count()); 70 } 71 LinkedHashSetMethods::Clear => { 72 set.clear(); 73 } 74 LinkedHashSetMethods::Reserve { additional } => { 75 // Avoid allocating too much memory and crashing the fuzzer. 76 set.reserve(additional % MAX_RESERVE); 77 } 78 LinkedHashSetMethods::ShrinkToFit => { 79 set.shrink_to_fit(); 80 } 81 } 82 } 83 }); 84