/ src / leveldb / util / testutil.cc
testutil.cc
 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  
 5  #include "util/testutil.h"
 6  
 7  #include "util/random.h"
 8  
 9  namespace leveldb {
10  namespace test {
11  
12  Slice RandomString(Random* rnd, int len, std::string* dst) {
13    dst->resize(len);
14    for (int i = 0; i < len; i++) {
15      (*dst)[i] = static_cast<char>(' ' + rnd->Uniform(95));  // ' ' .. '~'
16    }
17    return Slice(*dst);
18  }
19  
20  std::string RandomKey(Random* rnd, int len) {
21    // Make sure to generate a wide variety of characters so we
22    // test the boundary conditions for short-key optimizations.
23    static const char kTestChars[] = {'\0', '\1', 'a',    'b',    'c',
24                                      'd',  'e',  '\xfd', '\xfe', '\xff'};
25    std::string result;
26    for (int i = 0; i < len; i++) {
27      result += kTestChars[rnd->Uniform(sizeof(kTestChars))];
28    }
29    return result;
30  }
31  
32  Slice CompressibleString(Random* rnd, double compressed_fraction, size_t len,
33                           std::string* dst) {
34    int raw = static_cast<int>(len * compressed_fraction);
35    if (raw < 1) raw = 1;
36    std::string raw_data;
37    RandomString(rnd, raw, &raw_data);
38  
39    // Duplicate the random data until we have filled "len" bytes
40    dst->clear();
41    while (dst->size() < len) {
42      dst->append(raw_data);
43    }
44    dst->resize(len);
45    return Slice(*dst);
46  }
47  
48  }  // namespace test
49  }  // namespace leveldb