小组成员: 曹可心-10223903406 朴祉燕-10224602413
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.

164 regels
6.1 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 "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 "include/leveldb/write_batch.h"
  11. namespace leveldb {
  12. static Slice GetLengthPrefixedSlice(const char* data) {
  13. uint32_t len;
  14. const char* p = data;
  15. p = GetVarint32Ptr(p, p + 5, &len); // +5: we assume "p" is not corrupted
  16. return Slice(p, len);
  17. }
  18. MemTable::MemTable(const InternalKeyComparator& comparator)
  19. : comparator_(comparator), refs_(0), table_(comparator_, &arena_) {}
  20. MemTable::~MemTable() { assert(refs_ == 0); }
  21. size_t MemTable::ApproximateMemoryUsage() { return arena_.MemoryUsage(); }
  22. int MemTable::KeyComparator::operator()(const char* aptr,
  23. const char* bptr) const {
  24. // Internal keys are encoded as length-prefixed strings.
  25. Slice a = GetLengthPrefixedSlice(aptr);
  26. Slice b = GetLengthPrefixedSlice(bptr);
  27. return comparator.Compare(a, b);
  28. }
  29. // Encode a suitable internal key target for "target" and return it.
  30. // Uses *scratch as scratch space, and the returned pointer will point
  31. // into this scratch space.
  32. static const char* EncodeKey(std::string* scratch, const Slice& target) {
  33. scratch->clear();
  34. PutVarint32(scratch, target.size());
  35. scratch->append(target.data(), target.size());
  36. return scratch->data();
  37. }
  38. class MemTableIterator : public Iterator {
  39. public:
  40. explicit MemTableIterator(MemTable::Table* table) : iter_(table) {}
  41. MemTableIterator(const MemTableIterator&) = delete;
  42. MemTableIterator& operator=(const MemTableIterator&) = delete;
  43. ~MemTableIterator() override = default;
  44. bool Valid() const override { return iter_.Valid(); }
  45. void Seek(const Slice& k) override { iter_.Seek(EncodeKey(&tmp_, k)); }
  46. void SeekToFirst() override { iter_.SeekToFirst(); }
  47. void SeekToLast() override { iter_.SeekToLast(); }
  48. void Next() override { iter_.Next(); }
  49. void Prev() override { iter_.Prev(); }
  50. Slice key() const override { return GetLengthPrefixedSlice(iter_.key()); }
  51. Slice value() const override {
  52. Slice key_slice = GetLengthPrefixedSlice(iter_.key());
  53. return GetLengthPrefixedSlice(key_slice.data() + key_slice.size());
  54. }
  55. Status status() const override { return Status::OK(); }
  56. private:
  57. MemTable::Table::Iterator iter_;
  58. std::string tmp_; // For passing to EncodeKey
  59. };
  60. Iterator* MemTable::NewIterator() { return new MemTableIterator(&table_); }
  61. void MemTable::Add(SequenceNumber s, ValueType type, const Slice& key,
  62. const Slice& value) {
  63. // Format of an entry is concatenation of:
  64. // key_size : varint32 of internal_key.size()
  65. // key bytes : char[internal_key.size()]
  66. // tag : uint64((sequence << 8) | type)
  67. // value_size : varint32 of value.size()
  68. // value bytes : char[value.size()]
  69. size_t key_size = key.size();
  70. size_t val_size = value.size();
  71. size_t internal_key_size = key_size + 8;
  72. const size_t encoded_len = VarintLength(internal_key_size) +
  73. internal_key_size + VarintLength(val_size) +
  74. val_size;
  75. char* buf = arena_.Allocate(encoded_len);
  76. char* p = EncodeVarint32(buf, internal_key_size);
  77. std::memcpy(p, key.data(), key_size);
  78. p += key_size;
  79. EncodeFixed64(p, (s << 8) | type);
  80. p += 8;
  81. p = EncodeVarint32(p, val_size);
  82. std::memcpy(p, value.data(), val_size);
  83. assert(p + val_size == buf + encoded_len);
  84. table_.Insert(buf);
  85. }
  86. bool MemTable::Get(const LookupKey& key, std::string* value, Status* s) { //燕改
  87. Slice memkey = key.memtable_key();
  88. Table::Iterator iter(&table_);
  89. iter.Seek(memkey.data());
  90. if (iter.Valid()) { // 获取跳表项的内容
  91. // entry format is:
  92. // klength varint32
  93. // userkey char[klength]
  94. // tag uint64
  95. // vlength varint32
  96. // value char[vlength]
  97. // Check that it belongs to same user key. We do not check the
  98. // sequence number since the Seek() call above should have skipped
  99. // all entries with overly large sequence numbers.
  100. const char* entry = iter.key();
  101. uint32_t key_length;
  102. const char* key_ptr = GetVarint32Ptr(entry, entry + 5, &key_length);
  103. if (comparator_.comparator.user_comparator()->Compare(
  104. Slice(key_ptr, key_length - 8), key.user_key()) == 0) {
  105. const uint64_t tag = DecodeFixed64(key_ptr + key_length - 8);
  106. switch (static_cast<ValueType>(tag & 0xff)) {
  107. case kTypeValue: {
  108. // 获取存储的值和时间戳
  109. Slice v = GetLengthPrefixedSlice(key_ptr + key_length);
  110. std::string combined_str(v.data(), v.size());
  111. // 根据存储格式分离原始值和时间戳
  112. std::string actual_value = combined_str.substr(0, combined_str.size() - 20);
  113. std::string time_str = combined_str.substr(combined_str.size() - 19, 19);
  114. // 获取当前时间(字符串格式)
  115. auto now = std::chrono::system_clock::now();
  116. auto now_time_t = std::chrono::system_clock::to_time_t(now);
  117. std::tm* now_tm = std::localtime(&now_time_t);
  118. char buffer[20];
  119. std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", now_tm);
  120. std::string current_time_str(buffer);
  121. // 检查过期
  122. if (time_str <= current_time_str) {
  123. *s = Status::NotFound("Key has expired"); // 已过期
  124. return true;
  125. }
  126. // 未过期,返回实际值
  127. value->assign(actual_value);
  128. return true;
  129. }
  130. case kTypeDeletion:
  131. *s = Status::NotFound(Slice());
  132. return true;
  133. }
  134. }
  135. }
  136. return false;
  137. }
  138. } // namespace leveldb