小组成员:谢瑞阳、徐翔宇
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

834 rader
24 KiB

  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 "leveldb/table.h"
  5. #include <map>
  6. #include <string>
  7. #include "db/dbformat.h"
  8. #include "db/memtable.h"
  9. #include "db/write_batch_internal.h"
  10. #include "leveldb/db.h"
  11. #include "leveldb/env.h"
  12. #include "leveldb/iterator.h"
  13. #include "leveldb/table_builder.h"
  14. #include "table/block.h"
  15. #include "table/block_builder.h"
  16. #include "table/format.h"
  17. #include "util/random.h"
  18. #include "util/testharness.h"
  19. #include "util/testutil.h"
  20. namespace leveldb {
  21. // Return reverse of "key".
  22. // Used to test non-lexicographic comparators.
  23. static std::string Reverse(const Slice& key) {
  24. std::string str(key.ToString());
  25. std::string rev("");
  26. for (std::string::reverse_iterator rit = str.rbegin(); rit != str.rend();
  27. ++rit) {
  28. rev.push_back(*rit);
  29. }
  30. return rev;
  31. }
  32. namespace {
  33. class ReverseKeyComparator : public Comparator {
  34. public:
  35. virtual const char* Name() const {
  36. return "leveldb.ReverseBytewiseComparator";
  37. }
  38. virtual int Compare(const Slice& a, const Slice& b) const {
  39. return BytewiseComparator()->Compare(Reverse(a), Reverse(b));
  40. }
  41. virtual void FindShortestSeparator(std::string* start,
  42. const Slice& limit) const {
  43. std::string s = Reverse(*start);
  44. std::string l = Reverse(limit);
  45. BytewiseComparator()->FindShortestSeparator(&s, l);
  46. *start = Reverse(s);
  47. }
  48. virtual void FindShortSuccessor(std::string* key) const {
  49. std::string s = Reverse(*key);
  50. BytewiseComparator()->FindShortSuccessor(&s);
  51. *key = Reverse(s);
  52. }
  53. };
  54. } // namespace
  55. static ReverseKeyComparator reverse_key_comparator;
  56. static void Increment(const Comparator* cmp, std::string* key) {
  57. if (cmp == BytewiseComparator()) {
  58. key->push_back('\0');
  59. } else {
  60. assert(cmp == &reverse_key_comparator);
  61. std::string rev = Reverse(*key);
  62. rev.push_back('\0');
  63. *key = Reverse(rev);
  64. }
  65. }
  66. // An STL comparator that uses a Comparator
  67. namespace {
  68. struct STLLessThan {
  69. const Comparator* cmp;
  70. STLLessThan() : cmp(BytewiseComparator()) {}
  71. STLLessThan(const Comparator* c) : cmp(c) {}
  72. bool operator()(const std::string& a, const std::string& b) const {
  73. return cmp->Compare(Slice(a), Slice(b)) < 0;
  74. }
  75. };
  76. } // namespace
  77. class StringSink : public WritableFile {
  78. public:
  79. ~StringSink() {}
  80. const std::string& contents() const { return contents_; }
  81. virtual Status Close() { return Status::OK(); }
  82. virtual Status Flush() { return Status::OK(); }
  83. virtual Status Sync() { return Status::OK(); }
  84. virtual Status Append(const Slice& data) {
  85. contents_.append(data.data(), data.size());
  86. return Status::OK();
  87. }
  88. private:
  89. std::string contents_;
  90. };
  91. class StringSource : public RandomAccessFile {
  92. public:
  93. StringSource(const Slice& contents)
  94. : contents_(contents.data(), contents.size()) {}
  95. virtual ~StringSource() {}
  96. uint64_t Size() const { return contents_.size(); }
  97. virtual Status Read(uint64_t offset, size_t n, Slice* result,
  98. char* scratch) const {
  99. if (offset >= contents_.size()) {
  100. return Status::InvalidArgument("invalid Read offset");
  101. }
  102. if (offset + n > contents_.size()) {
  103. n = contents_.size() - offset;
  104. }
  105. memcpy(scratch, &contents_[offset], n);
  106. *result = Slice(scratch, n);
  107. return Status::OK();
  108. }
  109. private:
  110. std::string contents_;
  111. };
  112. typedef std::map<std::string, std::string, STLLessThan> KVMap;
  113. // Helper class for tests to unify the interface between
  114. // BlockBuilder/TableBuilder and Block/Table.
  115. class Constructor {
  116. public:
  117. explicit Constructor(const Comparator* cmp) : data_(STLLessThan(cmp)) {}
  118. virtual ~Constructor() {}
  119. void Add(const std::string& key, const Slice& value) {
  120. data_[key] = value.ToString();
  121. }
  122. // Finish constructing the data structure with all the keys that have
  123. // been added so far. Returns the keys in sorted order in "*keys"
  124. // and stores the key/value pairs in "*kvmap"
  125. void Finish(const Options& options, std::vector<std::string>* keys,
  126. KVMap* kvmap) {
  127. *kvmap = data_;
  128. keys->clear();
  129. for (KVMap::const_iterator it = data_.begin(); it != data_.end(); ++it) {
  130. keys->push_back(it->first);
  131. }
  132. data_.clear();
  133. Status s = FinishImpl(options, *kvmap);
  134. ASSERT_TRUE(s.ok()) << s.ToString();
  135. }
  136. // Construct the data structure from the data in "data"
  137. virtual Status FinishImpl(const Options& options, const KVMap& data) = 0;
  138. virtual Iterator* NewIterator() const = 0;
  139. virtual const KVMap& data() { return data_; }
  140. virtual DB* db() const { return nullptr; } // Overridden in DBConstructor
  141. private:
  142. KVMap data_;
  143. };
  144. class BlockConstructor : public Constructor {
  145. public:
  146. explicit BlockConstructor(const Comparator* cmp)
  147. : Constructor(cmp), comparator_(cmp), block_(nullptr) {}
  148. ~BlockConstructor() { delete block_; }
  149. virtual Status FinishImpl(const Options& options, const KVMap& data) {
  150. delete block_;
  151. block_ = nullptr;
  152. BlockBuilder builder(&options);
  153. for (KVMap::const_iterator it = data.begin(); it != data.end(); ++it) {
  154. builder.Add(it->first, it->second);
  155. }
  156. // Open the block
  157. data_ = builder.Finish().ToString();
  158. BlockContents contents;
  159. contents.data = data_;
  160. contents.cachable = false;
  161. contents.heap_allocated = false;
  162. block_ = new Block(contents);
  163. return Status::OK();
  164. }
  165. virtual Iterator* NewIterator() const {
  166. return block_->NewIterator(comparator_);
  167. }
  168. private:
  169. const Comparator* comparator_;
  170. std::string data_;
  171. Block* block_;
  172. BlockConstructor();
  173. };
  174. class TableConstructor : public Constructor {
  175. public:
  176. TableConstructor(const Comparator* cmp)
  177. : Constructor(cmp), source_(nullptr), table_(nullptr) {}
  178. ~TableConstructor() { Reset(); }
  179. virtual Status FinishImpl(const Options& options, const KVMap& data) {
  180. Reset();
  181. StringSink sink;
  182. TableBuilder builder(options, &sink);
  183. for (KVMap::const_iterator it = data.begin(); it != data.end(); ++it) {
  184. builder.Add(it->first, it->second);
  185. ASSERT_TRUE(builder.status().ok());
  186. }
  187. Status s = builder.Finish();
  188. ASSERT_TRUE(s.ok()) << s.ToString();
  189. ASSERT_EQ(sink.contents().size(), builder.FileSize());
  190. // Open the table
  191. source_ = new StringSource(sink.contents());
  192. Options table_options;
  193. table_options.comparator = options.comparator;
  194. return Table::Open(table_options, source_, sink.contents().size(), &table_);
  195. }
  196. virtual Iterator* NewIterator() const {
  197. return table_->NewIterator(ReadOptions());
  198. }
  199. uint64_t ApproximateOffsetOf(const Slice& key) const {
  200. return table_->ApproximateOffsetOf(key);
  201. }
  202. private:
  203. void Reset() {
  204. delete table_;
  205. delete source_;
  206. table_ = nullptr;
  207. source_ = nullptr;
  208. }
  209. StringSource* source_;
  210. Table* table_;
  211. TableConstructor();
  212. };
  213. // A helper class that converts internal format keys into user keys
  214. class KeyConvertingIterator : public Iterator {
  215. public:
  216. explicit KeyConvertingIterator(Iterator* iter) : iter_(iter) {}
  217. virtual ~KeyConvertingIterator() { delete iter_; }
  218. virtual bool Valid() const { return iter_->Valid(); }
  219. virtual void Seek(const Slice& target) {
  220. ParsedInternalKey ikey(target, kMaxSequenceNumber, kTypeValue);
  221. std::string encoded;
  222. AppendInternalKey(&encoded, ikey);
  223. iter_->Seek(encoded);
  224. }
  225. virtual void SeekToFirst() { iter_->SeekToFirst(); }
  226. virtual void SeekToLast() { iter_->SeekToLast(); }
  227. virtual void Next() { iter_->Next(); }
  228. virtual void Prev() { iter_->Prev(); }
  229. virtual Slice key() const {
  230. assert(Valid());
  231. ParsedInternalKey key;
  232. if (!ParseInternalKey(iter_->key(), &key)) {
  233. status_ = Status::Corruption("malformed internal key");
  234. return Slice("corrupted key");
  235. }
  236. return key.user_key;
  237. }
  238. virtual Slice value() const { return iter_->value(); }
  239. virtual Status status() const {
  240. return status_.ok() ? iter_->status() : status_;
  241. }
  242. private:
  243. mutable Status status_;
  244. Iterator* iter_;
  245. // No copying allowed
  246. KeyConvertingIterator(const KeyConvertingIterator&);
  247. void operator=(const KeyConvertingIterator&);
  248. };
  249. class MemTableConstructor : public Constructor {
  250. public:
  251. explicit MemTableConstructor(const Comparator* cmp)
  252. : Constructor(cmp), internal_comparator_(cmp) {
  253. memtable_ = new MemTable(internal_comparator_);
  254. memtable_->Ref();
  255. }
  256. ~MemTableConstructor() { memtable_->Unref(); }
  257. virtual Status FinishImpl(const Options& options, const KVMap& data) {
  258. memtable_->Unref();
  259. memtable_ = new MemTable(internal_comparator_);
  260. memtable_->Ref();
  261. int seq = 1;
  262. for (KVMap::const_iterator it = data.begin(); it != data.end(); ++it) {
  263. memtable_->Add(seq, kTypeValue, it->first, it->second);
  264. seq++;
  265. }
  266. return Status::OK();
  267. }
  268. virtual Iterator* NewIterator() const {
  269. return new KeyConvertingIterator(memtable_->NewIterator());
  270. }
  271. private:
  272. InternalKeyComparator internal_comparator_;
  273. MemTable* memtable_;
  274. };
  275. class DBConstructor : public Constructor {
  276. public:
  277. explicit DBConstructor(const Comparator* cmp)
  278. : Constructor(cmp), comparator_(cmp) {
  279. db_ = nullptr;
  280. NewDB();
  281. }
  282. ~DBConstructor() { delete db_; }
  283. virtual Status FinishImpl(const Options& options, const KVMap& data) {
  284. delete db_;
  285. db_ = nullptr;
  286. NewDB();
  287. for (KVMap::const_iterator it = data.begin(); it != data.end(); ++it) {
  288. WriteBatch batch;
  289. batch.Put(it->first, it->second);
  290. ASSERT_TRUE(db_->Write(WriteOptions(), &batch).ok());
  291. }
  292. return Status::OK();
  293. }
  294. virtual Iterator* NewIterator() const {
  295. return db_->NewIterator(ReadOptions());
  296. }
  297. virtual DB* db() const { return db_; }
  298. private:
  299. void NewDB() {
  300. std::string name = test::TmpDir() + "/table_testdb";
  301. Options options;
  302. options.comparator = comparator_;
  303. Status status = DestroyDB(name, options);
  304. ASSERT_TRUE(status.ok()) << status.ToString();
  305. options.create_if_missing = true;
  306. options.error_if_exists = true;
  307. options.write_buffer_size = 10000; // Something small to force merging
  308. status = DB::Open(options, name, &db_);
  309. ASSERT_TRUE(status.ok()) << status.ToString();
  310. }
  311. const Comparator* comparator_;
  312. DB* db_;
  313. };
  314. enum TestType { TABLE_TEST, BLOCK_TEST, MEMTABLE_TEST, DB_TEST };
  315. struct TestArgs {
  316. TestType type;
  317. bool reverse_compare;
  318. int restart_interval;
  319. };
  320. static const TestArgs kTestArgList[] = {
  321. {TABLE_TEST, false, 16},
  322. {TABLE_TEST, false, 1},
  323. {TABLE_TEST, false, 1024},
  324. {TABLE_TEST, true, 16},
  325. {TABLE_TEST, true, 1},
  326. {TABLE_TEST, true, 1024},
  327. {BLOCK_TEST, false, 16},
  328. {BLOCK_TEST, false, 1},
  329. {BLOCK_TEST, false, 1024},
  330. {BLOCK_TEST, true, 16},
  331. {BLOCK_TEST, true, 1},
  332. {BLOCK_TEST, true, 1024},
  333. // Restart interval does not matter for memtables
  334. {MEMTABLE_TEST, false, 16},
  335. {MEMTABLE_TEST, true, 16},
  336. // Do not bother with restart interval variations for DB
  337. {DB_TEST, false, 16},
  338. {DB_TEST, true, 16},
  339. };
  340. static const int kNumTestArgs = sizeof(kTestArgList) / sizeof(kTestArgList[0]);
  341. class Harness {
  342. public:
  343. Harness() : constructor_(nullptr) {}
  344. void Init(const TestArgs& args) {
  345. delete constructor_;
  346. constructor_ = nullptr;
  347. options_ = Options();
  348. options_.block_restart_interval = args.restart_interval;
  349. // Use shorter block size for tests to exercise block boundary
  350. // conditions more.
  351. options_.block_size = 256;
  352. if (args.reverse_compare) {
  353. options_.comparator = &reverse_key_comparator;
  354. }
  355. switch (args.type) {
  356. case TABLE_TEST:
  357. constructor_ = new TableConstructor(options_.comparator);
  358. break;
  359. case BLOCK_TEST:
  360. constructor_ = new BlockConstructor(options_.comparator);
  361. break;
  362. case MEMTABLE_TEST:
  363. constructor_ = new MemTableConstructor(options_.comparator);
  364. break;
  365. case DB_TEST:
  366. constructor_ = new DBConstructor(options_.comparator);
  367. break;
  368. }
  369. }
  370. ~Harness() { delete constructor_; }
  371. void Add(const std::string& key, const std::string& value) {
  372. constructor_->Add(key, value);
  373. }
  374. void Test(Random* rnd) {
  375. std::vector<std::string> keys;
  376. KVMap data;
  377. constructor_->Finish(options_, &keys, &data);
  378. TestForwardScan(keys, data);
  379. TestBackwardScan(keys, data);
  380. TestRandomAccess(rnd, keys, data);
  381. }
  382. void TestForwardScan(const std::vector<std::string>& keys,
  383. const KVMap& data) {
  384. Iterator* iter = constructor_->NewIterator();
  385. ASSERT_TRUE(!iter->Valid());
  386. iter->SeekToFirst();
  387. for (KVMap::const_iterator model_iter = data.begin();
  388. model_iter != data.end(); ++model_iter) {
  389. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  390. iter->Next();
  391. }
  392. ASSERT_TRUE(!iter->Valid());
  393. delete iter;
  394. }
  395. void TestBackwardScan(const std::vector<std::string>& keys,
  396. const KVMap& data) {
  397. Iterator* iter = constructor_->NewIterator();
  398. ASSERT_TRUE(!iter->Valid());
  399. iter->SeekToLast();
  400. for (KVMap::const_reverse_iterator model_iter = data.rbegin();
  401. model_iter != data.rend(); ++model_iter) {
  402. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  403. iter->Prev();
  404. }
  405. ASSERT_TRUE(!iter->Valid());
  406. delete iter;
  407. }
  408. void TestRandomAccess(Random* rnd, const std::vector<std::string>& keys,
  409. const KVMap& data) {
  410. static const bool kVerbose = false;
  411. Iterator* iter = constructor_->NewIterator();
  412. ASSERT_TRUE(!iter->Valid());
  413. KVMap::const_iterator model_iter = data.begin();
  414. if (kVerbose) fprintf(stderr, "---\n");
  415. for (int i = 0; i < 200; i++) {
  416. const int toss = rnd->Uniform(5);
  417. switch (toss) {
  418. case 0: {
  419. if (iter->Valid()) {
  420. if (kVerbose) fprintf(stderr, "Next\n");
  421. iter->Next();
  422. ++model_iter;
  423. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  424. }
  425. break;
  426. }
  427. case 1: {
  428. if (kVerbose) fprintf(stderr, "SeekToFirst\n");
  429. iter->SeekToFirst();
  430. model_iter = data.begin();
  431. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  432. break;
  433. }
  434. case 2: {
  435. std::string key = PickRandomKey(rnd, keys);
  436. model_iter = data.lower_bound(key);
  437. if (kVerbose)
  438. fprintf(stderr, "Seek '%s'\n", EscapeString(key).c_str());
  439. iter->Seek(Slice(key));
  440. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  441. break;
  442. }
  443. case 3: {
  444. if (iter->Valid()) {
  445. if (kVerbose) fprintf(stderr, "Prev\n");
  446. iter->Prev();
  447. if (model_iter == data.begin()) {
  448. model_iter = data.end(); // Wrap around to invalid value
  449. } else {
  450. --model_iter;
  451. }
  452. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  453. }
  454. break;
  455. }
  456. case 4: {
  457. if (kVerbose) fprintf(stderr, "SeekToLast\n");
  458. iter->SeekToLast();
  459. if (keys.empty()) {
  460. model_iter = data.end();
  461. } else {
  462. std::string last = data.rbegin()->first;
  463. model_iter = data.lower_bound(last);
  464. }
  465. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  466. break;
  467. }
  468. }
  469. }
  470. delete iter;
  471. }
  472. std::string ToString(const KVMap& data, const KVMap::const_iterator& it) {
  473. if (it == data.end()) {
  474. return "END";
  475. } else {
  476. return "'" + it->first + "->" + it->second + "'";
  477. }
  478. }
  479. std::string ToString(const KVMap& data,
  480. const KVMap::const_reverse_iterator& it) {
  481. if (it == data.rend()) {
  482. return "END";
  483. } else {
  484. return "'" + it->first + "->" + it->second + "'";
  485. }
  486. }
  487. std::string ToString(const Iterator* it) {
  488. if (!it->Valid()) {
  489. return "END";
  490. } else {
  491. return "'" + it->key().ToString() + "->" + it->value().ToString() + "'";
  492. }
  493. }
  494. std::string PickRandomKey(Random* rnd, const std::vector<std::string>& keys) {
  495. if (keys.empty()) {
  496. return "foo";
  497. } else {
  498. const int index = rnd->Uniform(keys.size());
  499. std::string result = keys[index];
  500. switch (rnd->Uniform(3)) {
  501. case 0:
  502. // Return an existing key
  503. break;
  504. case 1: {
  505. // Attempt to return something smaller than an existing key
  506. if (!result.empty() && result[result.size() - 1] > '\0') {
  507. result[result.size() - 1]--;
  508. }
  509. break;
  510. }
  511. case 2: {
  512. // Return something larger than an existing key
  513. Increment(options_.comparator, &result);
  514. break;
  515. }
  516. }
  517. return result;
  518. }
  519. }
  520. // Returns nullptr if not running against a DB
  521. DB* db() const { return constructor_->db(); }
  522. private:
  523. Options options_;
  524. Constructor* constructor_;
  525. };
  526. // Test empty table/block.
  527. TEST(Harness, Empty) {
  528. for (int i = 0; i < kNumTestArgs; i++) {
  529. Init(kTestArgList[i]);
  530. Random rnd(test::RandomSeed() + 1);
  531. Test(&rnd);
  532. }
  533. }
  534. // Special test for a block with no restart entries. The C++ leveldb
  535. // code never generates such blocks, but the Java version of leveldb
  536. // seems to.
  537. TEST(Harness, ZeroRestartPointsInBlock) {
  538. char data[sizeof(uint32_t)];
  539. memset(data, 0, sizeof(data));
  540. BlockContents contents;
  541. contents.data = Slice(data, sizeof(data));
  542. contents.cachable = false;
  543. contents.heap_allocated = false;
  544. Block block(contents);
  545. Iterator* iter = block.NewIterator(BytewiseComparator());
  546. iter->SeekToFirst();
  547. ASSERT_TRUE(!iter->Valid());
  548. iter->SeekToLast();
  549. ASSERT_TRUE(!iter->Valid());
  550. iter->Seek("foo");
  551. ASSERT_TRUE(!iter->Valid());
  552. delete iter;
  553. }
  554. // Test the empty key
  555. TEST(Harness, SimpleEmptyKey) {
  556. for (int i = 0; i < kNumTestArgs; i++) {
  557. Init(kTestArgList[i]);
  558. Random rnd(test::RandomSeed() + 1);
  559. Add("", "v");
  560. Test(&rnd);
  561. }
  562. }
  563. TEST(Harness, SimpleSingle) {
  564. for (int i = 0; i < kNumTestArgs; i++) {
  565. Init(kTestArgList[i]);
  566. Random rnd(test::RandomSeed() + 2);
  567. Add("abc", "v");
  568. Test(&rnd);
  569. }
  570. }
  571. TEST(Harness, SimpleMulti) {
  572. for (int i = 0; i < kNumTestArgs; i++) {
  573. Init(kTestArgList[i]);
  574. Random rnd(test::RandomSeed() + 3);
  575. Add("abc", "v");
  576. Add("abcd", "v");
  577. Add("ac", "v2");
  578. Test(&rnd);
  579. }
  580. }
  581. TEST(Harness, SimpleSpecialKey) {
  582. for (int i = 0; i < kNumTestArgs; i++) {
  583. Init(kTestArgList[i]);
  584. Random rnd(test::RandomSeed() + 4);
  585. Add("\xff\xff", "v3");
  586. Test(&rnd);
  587. }
  588. }
  589. TEST(Harness, Randomized) {
  590. for (int i = 0; i < kNumTestArgs; i++) {
  591. Init(kTestArgList[i]);
  592. Random rnd(test::RandomSeed() + 5);
  593. for (int num_entries = 0; num_entries < 2000;
  594. num_entries += (num_entries < 50 ? 1 : 200)) {
  595. if ((num_entries % 10) == 0) {
  596. fprintf(stderr, "case %d of %d: num_entries = %d\n", (i + 1),
  597. int(kNumTestArgs), num_entries);
  598. }
  599. for (int e = 0; e < num_entries; e++) {
  600. std::string v;
  601. Add(test::RandomKey(&rnd, rnd.Skewed(4)),
  602. test::RandomString(&rnd, rnd.Skewed(5), &v).ToString());
  603. }
  604. Test(&rnd);
  605. }
  606. }
  607. }
  608. TEST(Harness, RandomizedLongDB) {
  609. Random rnd(test::RandomSeed());
  610. TestArgs args = {DB_TEST, false, 16};
  611. Init(args);
  612. int num_entries = 100000;
  613. for (int e = 0; e < num_entries; e++) {
  614. std::string v;
  615. Add(test::RandomKey(&rnd, rnd.Skewed(4)),
  616. test::RandomString(&rnd, rnd.Skewed(5), &v).ToString());
  617. }
  618. Test(&rnd);
  619. // We must have created enough data to force merging
  620. int files = 0;
  621. for (int level = 0; level < config::kNumLevels; level++) {
  622. std::string value;
  623. char name[100];
  624. snprintf(name, sizeof(name), "leveldb.num-files-at-level%d", level);
  625. ASSERT_TRUE(db()->GetProperty(name, &value));
  626. files += atoi(value.c_str());
  627. }
  628. ASSERT_GT(files, 0);
  629. }
  630. class MemTableTest {};
  631. TEST(MemTableTest, Simple) {
  632. InternalKeyComparator cmp(BytewiseComparator());
  633. MemTable* memtable = new MemTable(cmp);
  634. memtable->Ref();
  635. WriteBatch batch;
  636. WriteBatchInternal::SetSequence(&batch, 100);
  637. batch.Put(std::string("k1"), std::string("v1"));
  638. batch.Put(std::string("k2"), std::string("v2"));
  639. batch.Put(std::string("k3"), std::string("v3"));
  640. batch.Put(std::string("largekey"), std::string("vlarge"));
  641. ASSERT_TRUE(WriteBatchInternal::InsertInto(&batch, memtable).ok());
  642. Iterator* iter = memtable->NewIterator();
  643. iter->SeekToFirst();
  644. while (iter->Valid()) {
  645. fprintf(stderr, "key: '%s' -> '%s'\n", iter->key().ToString().c_str(),
  646. iter->value().ToString().c_str());
  647. iter->Next();
  648. }
  649. delete iter;
  650. memtable->Unref();
  651. }
  652. static bool Between(uint64_t val, uint64_t low, uint64_t high) {
  653. bool result = (val >= low) && (val <= high);
  654. if (!result) {
  655. fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
  656. (unsigned long long)(val), (unsigned long long)(low),
  657. (unsigned long long)(high));
  658. }
  659. return result;
  660. }
  661. class TableTest {};
  662. TEST(TableTest, ApproximateOffsetOfPlain) {
  663. TableConstructor c(BytewiseComparator());
  664. c.Add("k01", "hello");
  665. c.Add("k02", "hello2");
  666. c.Add("k03", std::string(10000, 'x'));
  667. c.Add("k04", std::string(200000, 'x'));
  668. c.Add("k05", std::string(300000, 'x'));
  669. c.Add("k06", "hello3");
  670. c.Add("k07", std::string(100000, 'x'));
  671. std::vector<std::string> keys;
  672. KVMap kvmap;
  673. Options options;
  674. options.block_size = 1024;
  675. options.compression = kNoCompression;
  676. c.Finish(options, &keys, &kvmap);
  677. ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"), 0, 0));
  678. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"), 0, 0));
  679. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01a"), 0, 0));
  680. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"), 0, 0));
  681. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"), 0, 0));
  682. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"), 10000, 11000));
  683. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04a"), 210000, 211000));
  684. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k05"), 210000, 211000));
  685. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k06"), 510000, 511000));
  686. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k07"), 510000, 511000));
  687. ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 610000, 612000));
  688. }
  689. static bool SnappyCompressionSupported() {
  690. std::string out;
  691. Slice in = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
  692. return port::Snappy_Compress(in.data(), in.size(), &out);
  693. }
  694. TEST(TableTest, ApproximateOffsetOfCompressed) {
  695. if (!SnappyCompressionSupported()) {
  696. fprintf(stderr, "skipping compression tests\n");
  697. return;
  698. }
  699. Random rnd(301);
  700. TableConstructor c(BytewiseComparator());
  701. std::string tmp;
  702. c.Add("k01", "hello");
  703. c.Add("k02", test::CompressibleString(&rnd, 0.25, 10000, &tmp));
  704. c.Add("k03", "hello3");
  705. c.Add("k04", test::CompressibleString(&rnd, 0.25, 10000, &tmp));
  706. std::vector<std::string> keys;
  707. KVMap kvmap;
  708. Options options;
  709. options.block_size = 1024;
  710. options.compression = kSnappyCompression;
  711. c.Finish(options, &keys, &kvmap);
  712. // Expected upper and lower bounds of space used by compressible strings.
  713. static const int kSlop = 1000; // Compressor effectiveness varies.
  714. const int expected = 2500; // 10000 * compression ratio (0.25)
  715. const int min_z = expected - kSlop;
  716. const int max_z = expected + kSlop;
  717. ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"), 0, kSlop));
  718. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"), 0, kSlop));
  719. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"), 0, kSlop));
  720. // Have now emitted a large compressible string, so adjust expected offset.
  721. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"), min_z, max_z));
  722. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"), min_z, max_z));
  723. // Have now emitted two large compressible strings, so adjust expected offset.
  724. ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 2 * min_z, 2 * max_z));
  725. }
  726. } // namespace leveldb
  727. int main(int argc, char** argv) { return leveldb::test::RunAllTests(); }