作者: 谢瑞阳 10225101483 徐翔宇 10225101535
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

808 lines
22 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 "include/table.h"
  5. #include <map>
  6. #include "db/dbformat.h"
  7. #include "db/memtable.h"
  8. #include "db/write_batch_internal.h"
  9. #include "include/db.h"
  10. #include "include/env.h"
  11. #include "include/iterator.h"
  12. #include "include/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. virtual 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. private:
  142. KVMap data_;
  143. };
  144. class BlockConstructor: public Constructor {
  145. public:
  146. explicit BlockConstructor(const Comparator* cmp)
  147. : Constructor(cmp),
  148. comparator_(cmp),
  149. block_size_(-1),
  150. block_(NULL) { }
  151. ~BlockConstructor() {
  152. delete block_;
  153. }
  154. virtual Status FinishImpl(const Options& options, const KVMap& data) {
  155. delete block_;
  156. block_ = NULL;
  157. BlockBuilder builder(&options);
  158. for (KVMap::const_iterator it = data.begin();
  159. it != data.end();
  160. ++it) {
  161. builder.Add(it->first, it->second);
  162. }
  163. // Open the block
  164. Slice block_data = builder.Finish();
  165. block_size_ = block_data.size();
  166. char* block_data_copy = new char[block_size_];
  167. memcpy(block_data_copy, block_data.data(), block_size_);
  168. block_ = new Block(block_data_copy, block_size_);
  169. return Status::OK();
  170. }
  171. virtual size_t NumBytes() const { return block_size_; }
  172. virtual Iterator* NewIterator() const {
  173. return block_->NewIterator(comparator_);
  174. }
  175. private:
  176. const Comparator* comparator_;
  177. int block_size_;
  178. Block* block_;
  179. BlockConstructor();
  180. };
  181. class TableConstructor: public Constructor {
  182. public:
  183. TableConstructor(const Comparator* cmp)
  184. : Constructor(cmp),
  185. source_(NULL), table_(NULL) {
  186. }
  187. ~TableConstructor() {
  188. Reset();
  189. }
  190. virtual Status FinishImpl(const Options& options, const KVMap& data) {
  191. Reset();
  192. StringSink sink;
  193. TableBuilder builder(options, &sink);
  194. for (KVMap::const_iterator it = data.begin();
  195. it != data.end();
  196. ++it) {
  197. builder.Add(it->first, it->second);
  198. ASSERT_TRUE(builder.status().ok());
  199. }
  200. Status s = builder.Finish();
  201. ASSERT_TRUE(s.ok()) << s.ToString();
  202. ASSERT_EQ(sink.contents().size(), builder.FileSize());
  203. // Open the table
  204. source_ = new StringSource(sink.contents());
  205. Options table_options;
  206. table_options.comparator = options.comparator;
  207. return Table::Open(table_options, source_, &table_);
  208. }
  209. virtual size_t NumBytes() const { return source_->Size(); }
  210. virtual Iterator* NewIterator() const {
  211. return table_->NewIterator(ReadOptions());
  212. }
  213. uint64_t ApproximateOffsetOf(const Slice& key) const {
  214. return table_->ApproximateOffsetOf(key);
  215. }
  216. private:
  217. void Reset() {
  218. delete table_;
  219. delete source_;
  220. table_ = NULL;
  221. source_ = NULL;
  222. }
  223. StringSource* source_;
  224. Table* table_;
  225. TableConstructor();
  226. };
  227. // A helper class that converts internal format keys into user keys
  228. class KeyConvertingIterator: public Iterator {
  229. public:
  230. explicit KeyConvertingIterator(Iterator* iter) : iter_(iter) { }
  231. virtual ~KeyConvertingIterator() { delete iter_; }
  232. virtual bool Valid() const { return iter_->Valid(); }
  233. virtual void Seek(const Slice& target) {
  234. ParsedInternalKey ikey(target, kMaxSequenceNumber, kTypeValue);
  235. std::string encoded;
  236. AppendInternalKey(&encoded, ikey);
  237. iter_->Seek(encoded);
  238. }
  239. virtual void SeekToFirst() { iter_->SeekToFirst(); }
  240. virtual void SeekToLast() { iter_->SeekToLast(); }
  241. virtual void Next() { iter_->Next(); }
  242. virtual void Prev() { iter_->Prev(); }
  243. virtual Slice key() const {
  244. assert(Valid());
  245. ParsedInternalKey key;
  246. if (!ParseInternalKey(iter_->key(), &key)) {
  247. status_ = Status::Corruption("malformed internal key");
  248. return Slice("corrupted key");
  249. }
  250. return key.user_key;
  251. }
  252. virtual Slice value() const { return iter_->value(); }
  253. virtual Status status() const {
  254. return status_.ok() ? iter_->status() : status_;
  255. }
  256. private:
  257. mutable Status status_;
  258. Iterator* iter_;
  259. // No copying allowed
  260. KeyConvertingIterator(const KeyConvertingIterator&);
  261. void operator=(const KeyConvertingIterator&);
  262. };
  263. class MemTableConstructor: public Constructor {
  264. public:
  265. explicit MemTableConstructor(const Comparator* cmp)
  266. : Constructor(cmp),
  267. internal_comparator_(cmp) {
  268. memtable_ = new MemTable(internal_comparator_);
  269. }
  270. ~MemTableConstructor() {
  271. delete memtable_;
  272. }
  273. virtual Status FinishImpl(const Options& options, const KVMap& data) {
  274. delete memtable_;
  275. memtable_ = new MemTable(internal_comparator_);
  276. int seq = 1;
  277. for (KVMap::const_iterator it = data.begin();
  278. it != data.end();
  279. ++it) {
  280. memtable_->Add(seq, kTypeValue, it->first, it->second);
  281. seq++;
  282. }
  283. return Status::OK();
  284. }
  285. virtual size_t NumBytes() const {
  286. return memtable_->ApproximateMemoryUsage();
  287. }
  288. virtual Iterator* NewIterator() const {
  289. return new KeyConvertingIterator(memtable_->NewIterator());
  290. }
  291. private:
  292. InternalKeyComparator internal_comparator_;
  293. MemTable* memtable_;
  294. };
  295. class DBConstructor: public Constructor {
  296. public:
  297. explicit DBConstructor(const Comparator* cmp)
  298. : Constructor(cmp),
  299. comparator_(cmp) {
  300. db_ = NULL;
  301. NewDB();
  302. }
  303. ~DBConstructor() {
  304. delete db_;
  305. }
  306. virtual Status FinishImpl(const Options& options, const KVMap& data) {
  307. delete db_;
  308. db_ = NULL;
  309. NewDB();
  310. for (KVMap::const_iterator it = data.begin();
  311. it != data.end();
  312. ++it) {
  313. WriteBatch batch;
  314. batch.Put(it->first, it->second);
  315. ASSERT_TRUE(db_->Write(WriteOptions(), &batch).ok());
  316. }
  317. return Status::OK();
  318. }
  319. virtual size_t NumBytes() const {
  320. Range r("", "\xff\xff");
  321. uint64_t size;
  322. db_->GetApproximateSizes(&r, 1, &size);
  323. return size;
  324. }
  325. virtual Iterator* NewIterator() const {
  326. return db_->NewIterator(ReadOptions());
  327. }
  328. private:
  329. void NewDB() {
  330. std::string name = test::TmpDir() + "/table_testdb";
  331. Options options;
  332. options.comparator = comparator_;
  333. Status status = DestroyDB(name, options);
  334. ASSERT_TRUE(status.ok()) << status.ToString();
  335. options.create_if_missing = true;
  336. options.error_if_exists = true;
  337. status = DB::Open(options, name, &db_);
  338. ASSERT_TRUE(status.ok()) << status.ToString();
  339. }
  340. const Comparator* comparator_;
  341. DB* db_;
  342. };
  343. enum TestType {
  344. TABLE_TEST,
  345. BLOCK_TEST,
  346. MEMTABLE_TEST,
  347. DB_TEST,
  348. };
  349. struct TestArgs {
  350. TestType type;
  351. bool reverse_compare;
  352. int restart_interval;
  353. };
  354. static const TestArgs kTestArgList[] = {
  355. { TABLE_TEST, false, 16 },
  356. { TABLE_TEST, false, 1 },
  357. { TABLE_TEST, false, 1024 },
  358. { TABLE_TEST, true, 16 },
  359. { TABLE_TEST, true, 1 },
  360. { TABLE_TEST, true, 1024 },
  361. { BLOCK_TEST, false, 16 },
  362. { BLOCK_TEST, false, 1 },
  363. { BLOCK_TEST, false, 1024 },
  364. { BLOCK_TEST, true, 16 },
  365. { BLOCK_TEST, true, 1 },
  366. { BLOCK_TEST, true, 1024 },
  367. // Restart interval does not matter for memtables
  368. { MEMTABLE_TEST, false, 16 },
  369. { MEMTABLE_TEST, true, 16 },
  370. // Do not bother with restart interval variations for DB
  371. { DB_TEST, false, 16 },
  372. { DB_TEST, true, 16 },
  373. };
  374. static const int kNumTestArgs = sizeof(kTestArgList) / sizeof(kTestArgList[0]);
  375. class Harness {
  376. public:
  377. Harness() : constructor_(NULL) { }
  378. void Init(const TestArgs& args) {
  379. delete constructor_;
  380. constructor_ = NULL;
  381. options_ = Options();
  382. options_.block_restart_interval = args.restart_interval;
  383. // Use shorter block size for tests to exercise block boundary
  384. // conditions more.
  385. options_.block_size = 256;
  386. if (args.reverse_compare) {
  387. options_.comparator = &reverse_key_comparator;
  388. }
  389. switch (args.type) {
  390. case TABLE_TEST:
  391. constructor_ = new TableConstructor(options_.comparator);
  392. break;
  393. case BLOCK_TEST:
  394. constructor_ = new BlockConstructor(options_.comparator);
  395. break;
  396. case MEMTABLE_TEST:
  397. constructor_ = new MemTableConstructor(options_.comparator);
  398. break;
  399. case DB_TEST:
  400. constructor_ = new DBConstructor(options_.comparator);
  401. break;
  402. }
  403. }
  404. ~Harness() {
  405. delete constructor_;
  406. }
  407. void Add(const std::string& key, const std::string& value) {
  408. constructor_->Add(key, value);
  409. }
  410. void Test(Random* rnd) {
  411. std::vector<std::string> keys;
  412. KVMap data;
  413. constructor_->Finish(options_, &keys, &data);
  414. TestForwardScan(keys, data);
  415. TestBackwardScan(keys, data);
  416. TestRandomAccess(rnd, keys, data);
  417. }
  418. void TestForwardScan(const std::vector<std::string>& keys,
  419. const KVMap& data) {
  420. Iterator* iter = constructor_->NewIterator();
  421. ASSERT_TRUE(!iter->Valid());
  422. iter->SeekToFirst();
  423. for (KVMap::const_iterator model_iter = data.begin();
  424. model_iter != data.end();
  425. ++model_iter) {
  426. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  427. iter->Next();
  428. }
  429. ASSERT_TRUE(!iter->Valid());
  430. delete iter;
  431. }
  432. void TestBackwardScan(const std::vector<std::string>& keys,
  433. const KVMap& data) {
  434. Iterator* iter = constructor_->NewIterator();
  435. ASSERT_TRUE(!iter->Valid());
  436. iter->SeekToLast();
  437. for (KVMap::const_reverse_iterator model_iter = data.rbegin();
  438. model_iter != data.rend();
  439. ++model_iter) {
  440. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  441. iter->Prev();
  442. }
  443. ASSERT_TRUE(!iter->Valid());
  444. delete iter;
  445. }
  446. void TestRandomAccess(Random* rnd,
  447. const std::vector<std::string>& keys,
  448. const KVMap& data) {
  449. static const bool kVerbose = false;
  450. Iterator* iter = constructor_->NewIterator();
  451. ASSERT_TRUE(!iter->Valid());
  452. KVMap::const_iterator model_iter = data.begin();
  453. if (kVerbose) fprintf(stderr, "---\n");
  454. for (int i = 0; i < 200; i++) {
  455. const int toss = rnd->Uniform(5);
  456. switch (toss) {
  457. case 0: {
  458. if (iter->Valid()) {
  459. if (kVerbose) fprintf(stderr, "Next\n");
  460. iter->Next();
  461. ++model_iter;
  462. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  463. }
  464. break;
  465. }
  466. case 1: {
  467. if (kVerbose) fprintf(stderr, "SeekToFirst\n");
  468. iter->SeekToFirst();
  469. model_iter = data.begin();
  470. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  471. break;
  472. }
  473. case 2: {
  474. std::string key = PickRandomKey(rnd, keys);
  475. model_iter = data.lower_bound(key);
  476. if (kVerbose) fprintf(stderr, "Seek '%s'\n",
  477. EscapeString(key).c_str());
  478. iter->Seek(Slice(key));
  479. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  480. break;
  481. }
  482. case 3: {
  483. if (iter->Valid()) {
  484. if (kVerbose) fprintf(stderr, "Prev\n");
  485. iter->Prev();
  486. if (model_iter == data.begin()) {
  487. model_iter = data.end(); // Wrap around to invalid value
  488. } else {
  489. --model_iter;
  490. }
  491. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  492. }
  493. break;
  494. }
  495. case 4: {
  496. if (kVerbose) fprintf(stderr, "SeekToLast\n");
  497. iter->SeekToLast();
  498. if (keys.empty()) {
  499. model_iter = data.end();
  500. } else {
  501. std::string last = data.rbegin()->first;
  502. model_iter = data.lower_bound(last);
  503. }
  504. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  505. break;
  506. }
  507. }
  508. }
  509. delete iter;
  510. }
  511. std::string ToString(const KVMap& data, const KVMap::const_iterator& it) {
  512. if (it == data.end()) {
  513. return "END";
  514. } else {
  515. return "'" + it->first + "->" + it->second + "'";
  516. }
  517. }
  518. std::string ToString(const KVMap& data,
  519. const KVMap::const_reverse_iterator& it) {
  520. if (it == data.rend()) {
  521. return "END";
  522. } else {
  523. return "'" + it->first + "->" + it->second + "'";
  524. }
  525. }
  526. std::string ToString(const Iterator* it) {
  527. if (!it->Valid()) {
  528. return "END";
  529. } else {
  530. return "'" + it->key().ToString() + "->" + it->value().ToString() + "'";
  531. }
  532. }
  533. std::string PickRandomKey(Random* rnd, const std::vector<std::string>& keys) {
  534. if (keys.empty()) {
  535. return "foo";
  536. } else {
  537. const int index = rnd->Uniform(keys.size());
  538. std::string result = keys[index];
  539. switch (rnd->Uniform(3)) {
  540. case 0:
  541. // Return an existing key
  542. break;
  543. case 1: {
  544. // Attempt to return something smaller than an existing key
  545. if (result.size() > 0 && result[result.size()-1] > '\0') {
  546. result[result.size()-1]--;
  547. }
  548. break;
  549. }
  550. case 2: {
  551. // Return something larger than an existing key
  552. Increment(options_.comparator, &result);
  553. break;
  554. }
  555. }
  556. return result;
  557. }
  558. }
  559. private:
  560. Options options_;
  561. Constructor* constructor_;
  562. };
  563. // Test the empty key
  564. TEST(Harness, SimpleEmptyKey) {
  565. for (int i = 0; i < kNumTestArgs; i++) {
  566. Init(kTestArgList[i]);
  567. Random rnd(test::RandomSeed() + 1);
  568. Add("", "v");
  569. Test(&rnd);
  570. }
  571. }
  572. TEST(Harness, SimpleSingle) {
  573. for (int i = 0; i < kNumTestArgs; i++) {
  574. Init(kTestArgList[i]);
  575. Random rnd(test::RandomSeed() + 2);
  576. Add("abc", "v");
  577. Test(&rnd);
  578. }
  579. }
  580. TEST(Harness, SimpleMulti) {
  581. for (int i = 0; i < kNumTestArgs; i++) {
  582. Init(kTestArgList[i]);
  583. Random rnd(test::RandomSeed() + 3);
  584. Add("abc", "v");
  585. Add("abcd", "v");
  586. Add("ac", "v2");
  587. Test(&rnd);
  588. }
  589. }
  590. TEST(Harness, SimpleSpecialKey) {
  591. for (int i = 0; i < kNumTestArgs; i++) {
  592. Init(kTestArgList[i]);
  593. Random rnd(test::RandomSeed() + 4);
  594. Add("\xff\xff", "v3");
  595. Test(&rnd);
  596. }
  597. }
  598. TEST(Harness, Randomized) {
  599. for (int i = 0; i < kNumTestArgs; i++) {
  600. Init(kTestArgList[i]);
  601. Random rnd(test::RandomSeed() + 5);
  602. for (int num_entries = 0; num_entries < 2000;
  603. num_entries += (num_entries < 50 ? 1 : 200)) {
  604. if ((num_entries % 10) == 0) {
  605. fprintf(stderr, "case %d of %d: num_entries = %d\n",
  606. (i + 1), int(kNumTestArgs), num_entries);
  607. }
  608. for (int e = 0; e < num_entries; e++) {
  609. std::string v;
  610. Add(test::RandomKey(&rnd, rnd.Skewed(4)),
  611. test::RandomString(&rnd, rnd.Skewed(5), &v).ToString());
  612. }
  613. Test(&rnd);
  614. }
  615. }
  616. }
  617. class MemTableTest { };
  618. TEST(MemTableTest, Simple) {
  619. InternalKeyComparator cmp(BytewiseComparator());
  620. MemTable memtable(cmp);
  621. WriteBatch batch;
  622. WriteBatchInternal::SetSequence(&batch, 100);
  623. batch.Put(std::string("k1"), std::string("v1"));
  624. batch.Put(std::string("k2"), std::string("v2"));
  625. batch.Put(std::string("k3"), std::string("v3"));
  626. batch.Put(std::string("largekey"), std::string("vlarge"));
  627. ASSERT_TRUE(WriteBatchInternal::InsertInto(&batch, &memtable).ok());
  628. Iterator* iter = memtable.NewIterator();
  629. iter->SeekToFirst();
  630. while (iter->Valid()) {
  631. fprintf(stderr, "key: '%s' -> '%s'\n",
  632. iter->key().ToString().c_str(),
  633. iter->value().ToString().c_str());
  634. iter->Next();
  635. }
  636. delete iter;
  637. }
  638. static bool Between(uint64_t val, uint64_t low, uint64_t high) {
  639. bool result = (val >= low) && (val <= high);
  640. if (!result) {
  641. fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
  642. (unsigned long long)(val),
  643. (unsigned long long)(low),
  644. (unsigned long long)(high));
  645. }
  646. return result;
  647. }
  648. class TableTest { };
  649. TEST(TableTest, ApproximateOffsetOfPlain) {
  650. TableConstructor c(BytewiseComparator());
  651. c.Add("k01", "hello");
  652. c.Add("k02", "hello2");
  653. c.Add("k03", std::string(10000, 'x'));
  654. c.Add("k04", std::string(200000, 'x'));
  655. c.Add("k05", std::string(300000, 'x'));
  656. c.Add("k06", "hello3");
  657. c.Add("k07", std::string(100000, 'x'));
  658. std::vector<std::string> keys;
  659. KVMap kvmap;
  660. Options options;
  661. options.block_size = 1024;
  662. options.compression = kNoCompression;
  663. c.Finish(options, &keys, &kvmap);
  664. ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"), 0, 0));
  665. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"), 0, 0));
  666. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01a"), 0, 0));
  667. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"), 0, 0));
  668. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"), 0, 0));
  669. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"), 10000, 11000));
  670. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04a"), 210000, 211000));
  671. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k05"), 210000, 211000));
  672. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k06"), 510000, 511000));
  673. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k07"), 510000, 511000));
  674. ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 610000, 611000));
  675. }
  676. TEST(TableTest, ApproximateOffsetOfCompressed) {
  677. #if defined(LEVELDB_PLATFORM_POSIX) || defined(LEVELDB_PLATFORM_CHROMIUM)
  678. // Compression not supported yet, so skip this test.
  679. // TODO(sanjay) Reenable after compression support is added
  680. return;
  681. #endif
  682. Random rnd(301);
  683. TableConstructor c(BytewiseComparator());
  684. std::string tmp;
  685. c.Add("k01", "hello");
  686. c.Add("k02", test::CompressibleString(&rnd, 0.25, 10000, &tmp));
  687. c.Add("k03", "hello3");
  688. c.Add("k04", test::CompressibleString(&rnd, 0.25, 10000, &tmp));
  689. std::vector<std::string> keys;
  690. KVMap kvmap;
  691. Options options;
  692. options.block_size = 1024;
  693. options.compression = kLightweightCompression;
  694. c.Finish(options, &keys, &kvmap);
  695. ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"), 0, 0));
  696. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"), 0, 0));
  697. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"), 0, 0));
  698. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"), 2000, 3000));
  699. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"), 2000, 3000));
  700. ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 4000, 6000));
  701. }
  702. }
  703. int main(int argc, char** argv) {
  704. return leveldb::test::RunAllTests();
  705. }