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