1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://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, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include "pw_allocator/fuzzing.h"
16
17 #include <climits>
18
19 namespace pw::allocator::test {
20 namespace {
21
ArbitrarySize(size_t max_size)22 auto ArbitrarySize(size_t max_size) {
23 return fuzzer::InRange<size_t>(0, max_size);
24 }
25
ArbitraryAlignment(size_t size)26 auto ArbitraryAlignment(size_t size) {
27 return fuzzer::Map(
28 [size](size_t lshift) { return AlignmentFromLShift(lshift, size); },
29 fuzzer::Arbitrary<size_t>());
30 }
31
ArbitraryIndex()32 auto ArbitraryIndex() { return fuzzer::Arbitrary<size_t>(); }
33
ArbitraryAllocationRequest(size_t max_size)34 fuzzer::Domain<AllocationRequest> ArbitraryAllocationRequest(size_t max_size) {
35 auto from_size = [](size_t size) {
36 return fuzzer::StructOf<AllocationRequest>(fuzzer::Just(size),
37 ArbitraryAlignment(size));
38 };
39 return fuzzer::FlatMap(from_size, ArbitrarySize(max_size));
40 }
41
ArbitraryDeallocationRequest()42 fuzzer::Domain<DeallocationRequest> ArbitraryDeallocationRequest() {
43 return fuzzer::StructOf<DeallocationRequest>(ArbitraryIndex());
44 }
45
ArbitraryReallocationRequest(size_t max_size)46 fuzzer::Domain<ReallocationRequest> ArbitraryReallocationRequest(
47 size_t max_size) {
48 return fuzzer::StructOf<ReallocationRequest>(ArbitraryIndex(),
49 ArbitrarySize(max_size));
50 }
51
52 } // namespace
53
ArbitraryRequest(size_t max_size)54 fuzzer::Domain<Request> ArbitraryRequest(size_t max_size) {
55 return fuzzer::VariantOf(ArbitraryAllocationRequest(max_size),
56 ArbitraryDeallocationRequest(),
57 ArbitraryReallocationRequest(max_size));
58 }
59
60 } // namespace pw::allocator::test
61