作者: 谢瑞阳 10225101483 徐翔宇 10225101535
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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