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 position into the data
19extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t *data, std::size_t size) {
20 if (size <= 1) return 0;
21 const std::size_t partition_point = data[0] % size;
22 std::vector<std::uint8_t> working(data + 1, data + size);
23 const auto partition_iter = working.begin() + partition_point;
24 std::nth_element(first: working.begin(), nth: partition_iter, last: working.end());
25
26 // nth may be the end iterator, in this case nth_element has no effect.
27 if (partition_iter == working.end()) {
28 if (!std::equal(first1: data + 1, last1: data + size, first2: working.begin()))
29 return 98;
30 }
31 else {
32 const std::uint8_t nth = *partition_iter;
33 if (!std::all_of(first: working.begin(), last: partition_iter, pred: [=](std::uint8_t v) { return v <= nth; }))
34 return 1;
35 if (!std::all_of(first: partition_iter, last: working.end(), pred: [=](std::uint8_t v) { return v >= nth; }))
36 return 2;
37 if (!fast_is_permutation(first1: data + 1, last1: data + size, first2: working.cbegin()))
38 return 99;
39 }
40
41 return 0;
42}
43

source code of libcxx/test/libcxx/fuzzing/nth_element.pass.cpp