testutil.cc 1.4 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 "util/random.h"
  6. namespace leveldb {
  7. namespace test {
  8. Slice RandomString(Random* rnd, int len, std::string* dst) {
  9. dst->resize(len);
  10. for (int i = 0; i < len; i++) {
  11. (*dst)[i] = static_cast<char>(' ' + rnd->Uniform(95)); // ' ' .. '~'
  12. }
  13. return Slice(*dst);
  14. }
  15. std::string RandomKey(Random* rnd, int len) {
  16. // Make sure to generate a wide variety of characters so we
  17. // test the boundary conditions for short-key optimizations.
  18. static const char kTestChars[] = {
  19. '\0', '\1', 'a', 'b', 'c', 'd', 'e', '\xfd', '\xfe', '\xff'
  20. };
  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,
  28. size_t len, 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