10225501448 李度 10225101546 陈胤遒 10215501422 高宇菲
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

203 строки
7.4 KiB

4 недель назад
4 недель назад
4 недель назад
4 недель назад
4 недель назад
1 месяц назад
  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 "db/memtable.h"
  5. #include "db/dbformat.h"
  6. #include "leveldb/comparator.h"
  7. #include "leveldb/env.h"
  8. #include "leveldb/iterator.h"
  9. #include "util/coding.h"
  10. #include "ctime"
  11. #include "iostream"
  12. namespace leveldb {
  13. static Slice GetLengthPrefixedSlice(const char* data) {
  14. uint32_t len;
  15. const char* p = data;
  16. p = GetVarint32Ptr(p, p + 5, &len); // +5: we assume "p" is not corrupted
  17. return Slice(p, len);
  18. }
  19. MemTable::MemTable(const InternalKeyComparator& comparator)
  20. : comparator_(comparator), refs_(0), table_(comparator_, &arena_) {}
  21. MemTable::~MemTable() { assert(refs_ == 0); }
  22. size_t MemTable::ApproximateMemoryUsage() { return arena_.MemoryUsage(); }
  23. int MemTable::KeyComparator::operator()(const char* aptr,
  24. const char* bptr) const {
  25. // Internal keys are encoded as length-prefixed strings.
  26. Slice a = GetLengthPrefixedSlice(aptr);
  27. Slice b = GetLengthPrefixedSlice(bptr);
  28. return comparator.Compare(a, b);
  29. }
  30. // Encode a suitable internal key target for "target" and return it.
  31. // Uses *scratch as scratch space, and the returned pointer will point
  32. // into this scratch space.
  33. static const char* EncodeKey(std::string* scratch, const Slice& target) {
  34. scratch->clear();
  35. PutVarint32(scratch, target.size());
  36. scratch->append(target.data(), target.size());
  37. return scratch->data();
  38. }
  39. class MemTableIterator : public Iterator {
  40. public:
  41. explicit MemTableIterator(MemTable::Table* table) : iter_(table) {}
  42. MemTableIterator(const MemTableIterator&) = delete;
  43. MemTableIterator& operator=(const MemTableIterator&) = delete;
  44. ~MemTableIterator() override = default;
  45. bool Valid() const override { return iter_.Valid(); }
  46. void Seek(const Slice& k) override {
  47. iter_.Seek(EncodeKey(&tmp_, k));
  48. // MemTable::KeyComparator comp_ = iter_.get_comparator();
  49. // while(Valid()) {
  50. // Slice now = key();
  51. // ParsedInternalKey parsed_k,parsed_now;
  52. // ParseInternalKey(k,&parsed_k);
  53. // ParseInternalKey(now,&parsed_now);
  54. // uint64_t deadtime_k = parsed_k.deadTime;
  55. // uint64_t deadtime_now = parsed_now.deadTime;
  56. // if(deadtime_k == 0) deadtime_k = UINT64_MAX;
  57. // if(deadtime_now == 0) deadtime_now = UINT64_MAX;
  58. // if(deadtime_k > deadtime_now) {Next();continue;};
  59. // if(comp_.comparator.Compare(k,now) <= 0) return;
  60. // Next();
  61. // }
  62. }
  63. void SeekToFirst() override { iter_.SeekToFirst(); }
  64. void SeekToLast() override { iter_.SeekToLast(); }
  65. void Next() override { iter_.Next(); }
  66. void Prev() override { iter_.Prev(); }
  67. Slice key() const override { return GetLengthPrefixedSlice(iter_.key()); }
  68. Slice value() const override {
  69. Slice key_slice = GetLengthPrefixedSlice(iter_.key());
  70. return GetLengthPrefixedSlice(key_slice.data() + key_slice.size());
  71. }
  72. Status status() const override { return Status::OK(); }
  73. private:
  74. MemTable::Table::Iterator iter_;
  75. std::string tmp_; // For passing to EncodeKey
  76. };
  77. Iterator* MemTable::NewIterator() { return new MemTableIterator(&table_); }
  78. void MemTable::Add(SequenceNumber s, ValueType type, const Slice& key,
  79. const Slice& value, uint64_t deadTime) {
  80. // Format of an entry is concatenation of:
  81. // key_size : varint32 of internal_key.size()
  82. // key bytes : char[internal_key.size()]
  83. // tag : uint64((sequence << 8) | type)
  84. // value_size : varint32 of value.size()
  85. // value bytes : char[value.size()]
  86. //变成
  87. // key_size : varint32 of internal_key.size()
  88. // key bytes : char[internal_key.size()]
  89. // (deadTime) : uint64(可能有)
  90. // tag : uint64((sequence << 8) | havettl << 1 | type)
  91. // value_size : varint32 of value.size()
  92. // value bytes : char[value.size()]
  93. size_t key_size = key.size();
  94. size_t val_size = value.size();
  95. size_t internal_key_size = key_size + 8;
  96. if(deadTime != 0) internal_key_size += 8;
  97. const size_t encoded_len = VarintLength(internal_key_size) +
  98. internal_key_size + VarintLength(val_size) +
  99. val_size;
  100. char* buf = arena_.Allocate(encoded_len);
  101. char* p = EncodeVarint32(buf, internal_key_size);
  102. std::memcpy(p, key.data(), key_size);
  103. p += key_size;
  104. if(deadTime == 0){
  105. EncodeFixed64(p, (s << 8) | type);
  106. } else {
  107. EncodeFixed64(p, deadTime);
  108. p += 8;
  109. EncodeFixed64(p, (s << 8) | 0b10 | type);
  110. }
  111. p += 8;
  112. p = EncodeVarint32(p, val_size);
  113. std::memcpy(p, value.data(), val_size);
  114. assert(p + val_size == buf + encoded_len);
  115. table_.Insert(buf);
  116. static int count = 0;
  117. if(count++ % 1000 == 0)
  118. std::cout<<"count: "<<count << " insert:" << key.ToString() <<" deadTime: " << deadTime << std::endl;
  119. }
  120. bool MemTable::Get(const LookupKey& key, std::string* value, Status* s) {
  121. Slice memkey = key.memtable_key();
  122. Table::Iterator iter(&table_);
  123. iter.Seek(memkey.data());
  124. auto user_comparator = comparator_.comparator.user_comparator();
  125. while(iter.Valid()) {
  126. Slice now = GetLengthPrefixedSlice(iter.key()); //迭代器所处的位置
  127. MemTable::KeyComparator comp_ = iter.get_comparator();
  128. ParsedInternalKey parsed_k,parsed_now;
  129. ParseInternalKey(key.internal_key(),&parsed_k);
  130. ParseInternalKey(now,&parsed_now);
  131. uint64_t deadtime_k = parsed_k.deadTime;
  132. uint64_t deadtime_now = parsed_now.deadTime;
  133. if(deadtime_k == 0) deadtime_k = UINT64_MAX;
  134. if(deadtime_now == 0) deadtime_now = UINT64_MAX;
  135. std::cout<<"key :"<<parsed_k.user_key.ToString()<<" k time: "<<deadtime_k<<" now time: "<<deadtime_now<<std::endl;
  136. std::cout<<"k&now "<<parsed_k.user_key.ToString()<<" "<<parsed_now.user_key.ToString()<<std::endl;
  137. if(user_comparator->Compare(parsed_k.user_key,parsed_now.user_key) < 0) {
  138. break;
  139. }
  140. if(deadtime_k > deadtime_now) {
  141. iter.Next();
  142. continue;
  143. }
  144. std::cout<<"size : "<<key.internal_key().size()<<" "<<now.size()<<std::endl;
  145. if(comp_.comparator.Compare(key.internal_key(),now) <= 0) break;
  146. iter.Next();
  147. }
  148. std::cout << "search:" << key.user_key().ToString() << " valid?" << iter.Valid();
  149. if (iter.Valid()) {
  150. // entry format is:
  151. // klength varint32
  152. // userkey char[klength]
  153. // (deadTime) uint64
  154. // tag uint64
  155. // vlength varint32
  156. // value char[vlength]
  157. // Check that it belongs to same user key. We do not check the
  158. // sequence number since the Seek() call above should have skipped
  159. // all entries with overly large sequence numbers.
  160. const char* entry = iter.key();
  161. uint32_t key_length;
  162. const char* key_ptr = GetVarint32Ptr(entry, entry + 5, &key_length);
  163. std::cout << " get:" << ExtractUserKey(Slice(key_ptr, key_length)).ToString() << std::endl;
  164. if (comparator_.comparator.user_comparator()->Compare(
  165. ExtractUserKey(Slice(key_ptr, key_length)), key.user_key()) == 0) {
  166. // Correct user key
  167. const uint64_t tag = DecodeFixed64(key_ptr + key_length - 8);
  168. switch (static_cast<ValueType>(tag & 0x01)) {
  169. case kTypeValue: {
  170. Slice v = GetLengthPrefixedSlice(key_ptr + key_length);
  171. value->assign(v.data(), v.size());
  172. return true;
  173. }
  174. case kTypeDeletion:
  175. *s = Status::NotFound(Slice());
  176. return true;
  177. }
  178. }
  179. }
  180. return false;
  181. }
  182. } // namespace leveldb