• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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::LruCache;
20 use libfuzzer_sys::arbitrary::Arbitrary;
21 use libfuzzer_sys::fuzz_target;
22 
23 #[derive(Arbitrary, Debug, Eq, Hash, PartialEq)]
24 enum Data {
25     A,
26     B,
27     Int { val: u8 },
28 }
29 
30 #[derive(Arbitrary, Debug)]
31 struct LruCacheFuzzInfo {
32     capacity: u8,
33     commands: Vec<LruCacheMethods>,
34 }
35 
36 #[derive(Arbitrary, Debug)]
37 enum LruCacheMethods {
38     Insert { key: Data, value: Data },
39     Remove { key: Data },
40     ContainsKey { key: Data },
41     Get { key: Data },
42     EntryOrInsert { key: Data, value: Data },
43     Iter,
44     Drain,
45     Clear,
46     Peek { key: Data },
47     RemoveLru,
48 }
49 
50 fuzz_target!(|info: LruCacheFuzzInfo| {
51     let mut cache = LruCache::new(info.capacity.into());
52     for command in info.commands {
53         match command {
54             LruCacheMethods::Insert { key, value } => {
55                 cache.insert(key, value);
56             }
57             LruCacheMethods::Remove { key } => {
58                 cache.remove(&key);
59             }
60             LruCacheMethods::ContainsKey { key } => {
61                 cache.contains_key(&key);
62             }
63             LruCacheMethods::Get { key } => {
64                 cache.get(&key);
65             }
66             LruCacheMethods::EntryOrInsert { key, value } => {
67                 cache.entry(key).or_insert(value);
68             }
69             LruCacheMethods::Iter => {
70                 std::hint::black_box(cache.iter().count());
71             }
72             LruCacheMethods::Drain => {
73                 std::hint::black_box(cache.drain().count());
74             }
75             LruCacheMethods::Clear => {
76                 cache.clear();
77             }
78             LruCacheMethods::Peek { key } => {
79                 cache.peek(&key);
80             }
81             LruCacheMethods::RemoveLru => {
82                 cache.remove_lru();
83             }
84         }
85     }
86 });
87