Chromium Code Reviews| Index: net/base/fuzzed_data_provider.cc |
| diff --git a/net/base/fuzzed_data_provider.cc b/net/base/fuzzed_data_provider.cc |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..6278ff2ff9a1363aa2922763e5b485c8f59c2cfa |
| --- /dev/null |
| +++ b/net/base/fuzzed_data_provider.cc |
| @@ -0,0 +1,72 @@ |
| +// Copyright 2016 The Chromium Authors. All rights reserved. |
| +// Use of this source code is governed by a BSD-style license that can be |
| +// found in the LICENSE file. |
| + |
| +#include "net/base/fuzzed_data_provider.h" |
| + |
| +#include <algorithm> |
| +#include <string> |
| + |
| +#include "base/logging.h" |
| + |
| +namespace net { |
| + |
| +FuzzedDataProvider::FuzzedDataProvider(const uint8_t* data, size_t size) |
| + : remaining_data_(reinterpret_cast<const char*>(data), size) {} |
| + |
| +FuzzedDataProvider::~FuzzedDataProvider() {} |
| + |
| +size_t FuzzedDataProvider::ConsumeBytes(char* dest, size_t bytes) { |
| + size_t bytes_to_write = std::min(bytes, remaining_data_.length()); |
| + memcpy(dest, remaining_data_.data(), bytes_to_write); |
| + remaining_data_ = remaining_data_.substr(bytes_to_write); |
| + return bytes_to_write; |
| +} |
| + |
| +uint32_t FuzzedDataProvider::ConsumeBits(size_t num_bits) { |
| + CHECK_NE(0u, num_bits); |
| + CHECK_LE(num_bits, 32u); |
| + uint32_t out = 0; |
| + while (num_bits > 0) { |
| + uint8_t new_bits = 0; |
| + if (!remaining_data_.empty()) { |
| + new_bits = remaining_data_.data()[remaining_data_.length() - 1]; |
| + remaining_data_ = remaining_data_.substr(0, remaining_data_.length() - 1); |
| + } |
| + size_t bits_to_add = 8; |
| + if (num_bits > 8) |
| + bits_to_add = num_bits; |
| + new_bits &= new_bits & ((1 << bits_to_add) - 1); |
| + out = (out << bits_to_add) | new_bits; |
| + num_bits -= bits_to_add; |
|
Charlie Harrison
2016/04/26 02:24:57
Drive-by: I think bits_to_add can be greater than
mmenke
2016/04/27 19:53:25
Oops, yea, you're right, good catch! I'd already
|
| + } |
| + |
| + return out; |
| +} |
| + |
| +bool FuzzedDataProvider::ConsumeBool() { |
| + return !ConsumeBits(1); |
| +} |
| + |
| +uint32_t FuzzedDataProvider::ConsumeValueInRange(uint32_t min, uint32_t max) { |
| + CHECK_LE(min, max); |
| + |
| + // This consumes bytes in multiples of 8, to try and get a more uniform |
| + // distribution of values in the given range. |
| + |
| + // Find the smallest multiple of 8 that will cover the range. |
| + uint32_t range = max - min; |
| + int needed_bits = 0; |
| + while (range > 0) { |
| + range >>= 8; |
| + needed_bits++; |
| + } |
| + |
| + // Allow an empty range, unlike ConsumeBits. |
| + if (needed_bits == 0) |
| + return min; |
| + |
| + return min + ConsumeBits(needed_bits) % (max - min); |
| +} |
| + |
| +} // namespace net |