testutil.cc 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include "util/testutil.h"
  5. #include <string>
  6. #include "util/random.h"
  7. namespace leveldb {
  8. namespace test {
  9. Slice RandomString(Random* rnd, int len, std::string* dst) {
  10. dst->resize(len);
  11. for (int i = 0; i < len; i++) {
  12. (*dst)[i] = static_cast<char>(' ' + rnd->Uniform(95)); // ' ' .. '~'
  13. }
  14. return Slice(*dst);
  15. }
  16. std::string RandomKey(Random* rnd, int len) {
  17. // Make sure to generate a wide variety of characters so we
  18. // test the boundary conditions for short-key optimizations.
  19. static const char kTestChars[] = {'\0', '\1', 'a', 'b', 'c',
  20. 'd', 'e', '\xfd', '\xfe', '\xff'};
  21. std::string result;
  22. for (int i = 0; i < len; i++) {
  23. result += kTestChars[rnd->Uniform(sizeof(kTestChars))];
  24. }
  25. return result;
  26. }
  27. Slice CompressibleString(Random* rnd, double compressed_fraction, size_t len,
  28. std::string* dst) {
  29. int raw = static_cast<int>(len * compressed_fraction);
  30. if (raw < 1) raw = 1;
  31. std::string raw_data;
  32. RandomString(rnd, raw, &raw_data);
  33. // Duplicate the random data until we have filled "len" bytes
  34. dst->clear();
  35. while (dst->size() < len) {
  36. dst->append(raw_data);
  37. }
  38. dst->resize(len);
  39. return Slice(*dst);
  40. }
  41. } // namespace test
  42. } // namespace leveldb