xref: /llvm-project/libcxx/test/libcxx/fuzzing/partial_sort_copy.pass.cpp (revision b4bd194378851c2f421477d4147019d10f2420ac)
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 // UNSUPPORTED: c++03, c++11
10 
11 #include <algorithm>
12 #include <cstddef>
13 #include <cstdint>
14 #include <vector>
15 
16 #include "fuzz.h"
17 
18 // Use the first element as a count
LLVMFuzzerTestOneInput(const std::uint8_t * data,std::size_t size)19 extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t *data, std::size_t size) {
20     if (size <= 1)
21         return 0;
22     const std::size_t num_results = data[0] % size;
23     std::vector<std::uint8_t> results(num_results);
24     (void)std::partial_sort_copy(data + 1, data + size, results.begin(), results.end());
25 
26     // The results have to be sorted
27     if (!std::is_sorted(results.begin(), results.end()))
28         return 1;
29     // All the values in results have to be in the original data
30     for (auto v: results)
31         if (std::find(data + 1, data + size, v) == data + size)
32             return 2;
33 
34     // The things in results have to be the smallest N in the original data
35     std::vector<std::uint8_t> sorted(data + 1, data + size);
36     std::sort(sorted.begin(), sorted.end());
37     if (!std::equal(results.begin(), results.end(), sorted.begin()))
38         return 3;
39 
40     return 0;
41 }
42