小组成员:谢瑞阳、徐翔宇
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

227 строки
7.6 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. #ifndef STORAGE_LEVELDB_DB_FORMAT_H_
  5. #define STORAGE_LEVELDB_DB_FORMAT_H_
  6. #include <stdio.h>
  7. #include "leveldb/comparator.h"
  8. #include "leveldb/db.h"
  9. #include "leveldb/filter_policy.h"
  10. #include "leveldb/slice.h"
  11. #include "leveldb/table_builder.h"
  12. #include "util/coding.h"
  13. #include "util/logging.h"
  14. namespace leveldb {
  15. // Grouping of constants. We may want to make some of these
  16. // parameters set via options.
  17. namespace config {
  18. static const int kNumLevels = 7;
  19. // Level-0 compaction is started when we hit this many files.
  20. static const int kL0_CompactionTrigger = 4;
  21. // Soft limit on number of level-0 files. We slow down writes at this point.
  22. static const int kL0_SlowdownWritesTrigger = 8;
  23. // Maximum number of level-0 files. We stop writes at this point.
  24. static const int kL0_StopWritesTrigger = 12;
  25. // Maximum level to which a new compacted memtable is pushed if it
  26. // does not create overlap. We try to push to level 2 to avoid the
  27. // relatively expensive level 0=>1 compactions and to avoid some
  28. // expensive manifest file operations. We do not push all the way to
  29. // the largest level since that can generate a lot of wasted disk
  30. // space if the same key space is being repeatedly overwritten.
  31. static const int kMaxMemCompactLevel = 2;
  32. } // namespace config
  33. class InternalKey;
  34. // Value types encoded as the last component of internal keys.
  35. // DO NOT CHANGE THESE ENUM VALUES: they are embedded in the on-disk
  36. // data structures.
  37. enum ValueType {
  38. kTypeDeletion = 0x0,
  39. kTypeValue = 0x1
  40. };
  41. // kValueTypeForSeek defines the ValueType that should be passed when
  42. // constructing a ParsedInternalKey object for seeking to a particular
  43. // sequence number (since we sort sequence numbers in decreasing order
  44. // and the value type is embedded as the low 8 bits in the sequence
  45. // number in internal keys, we need to use the highest-numbered
  46. // ValueType, not the lowest).
  47. static const ValueType kValueTypeForSeek = kTypeValue;
  48. typedef uint64_t SequenceNumber;
  49. // We leave eight bits empty at the bottom so a type and sequence#
  50. // can be packed together into 64-bits.
  51. static const SequenceNumber kMaxSequenceNumber =
  52. ((0x1ull << 56) - 1);
  53. struct ParsedInternalKey {
  54. Slice user_key;
  55. SequenceNumber sequence;
  56. ValueType type;
  57. ParsedInternalKey() { } // Intentionally left uninitialized (for speed)
  58. ParsedInternalKey(const Slice& u, const SequenceNumber& seq, ValueType t)
  59. : user_key(u), sequence(seq), type(t) { }
  60. std::string DebugString() const;
  61. };
  62. // Return the length of the encoding of "key".
  63. inline size_t InternalKeyEncodingLength(const ParsedInternalKey& key) {
  64. return key.user_key.size() + 8;
  65. }
  66. // Append the serialization of "key" to *result.
  67. extern void AppendInternalKey(std::string* result,
  68. const ParsedInternalKey& key);
  69. // Attempt to parse an internal key from "internal_key". On success,
  70. // stores the parsed data in "*result", and returns true.
  71. //
  72. // On error, returns false, leaves "*result" in an undefined state.
  73. extern bool ParseInternalKey(const Slice& internal_key,
  74. ParsedInternalKey* result);
  75. // Returns the user key portion of an internal key.
  76. inline Slice ExtractUserKey(const Slice& internal_key) {
  77. assert(internal_key.size() >= 8);
  78. return Slice(internal_key.data(), internal_key.size() - 8);
  79. }
  80. inline ValueType ExtractValueType(const Slice& internal_key) {
  81. assert(internal_key.size() >= 8);
  82. const size_t n = internal_key.size();
  83. uint64_t num = DecodeFixed64(internal_key.data() + n - 8);
  84. unsigned char c = num & 0xff;
  85. return static_cast<ValueType>(c);
  86. }
  87. // A comparator for internal keys that uses a specified comparator for
  88. // the user key portion and breaks ties by decreasing sequence number.
  89. class InternalKeyComparator : public Comparator {
  90. private:
  91. const Comparator* user_comparator_;
  92. public:
  93. explicit InternalKeyComparator(const Comparator* c) : user_comparator_(c) { }
  94. virtual const char* Name() const;
  95. virtual int Compare(const Slice& a, const Slice& b) const;
  96. virtual void FindShortestSeparator(
  97. std::string* start,
  98. const Slice& limit) const;
  99. virtual void FindShortSuccessor(std::string* key) const;
  100. const Comparator* user_comparator() const { return user_comparator_; }
  101. int Compare(const InternalKey& a, const InternalKey& b) const;
  102. };
  103. // Filter policy wrapper that converts from internal keys to user keys
  104. class InternalFilterPolicy : public FilterPolicy {
  105. private:
  106. const FilterPolicy* const user_policy_;
  107. public:
  108. explicit InternalFilterPolicy(const FilterPolicy* p) : user_policy_(p) { }
  109. virtual const char* Name() const;
  110. virtual void CreateFilter(const Slice* keys, int n, std::string* dst) const;
  111. virtual bool KeyMayMatch(const Slice& key, const Slice& filter) const;
  112. };
  113. // Modules in this directory should keep internal keys wrapped inside
  114. // the following class instead of plain strings so that we do not
  115. // incorrectly use string comparisons instead of an InternalKeyComparator.
  116. class InternalKey {
  117. private:
  118. std::string rep_;
  119. public:
  120. InternalKey() { } // Leave rep_ as empty to indicate it is invalid
  121. InternalKey(const Slice& user_key, SequenceNumber s, ValueType t) {
  122. AppendInternalKey(&rep_, ParsedInternalKey(user_key, s, t));
  123. }
  124. void DecodeFrom(const Slice& s) { rep_.assign(s.data(), s.size()); }
  125. Slice Encode() const {
  126. assert(!rep_.empty());
  127. return rep_;
  128. }
  129. Slice user_key() const { return ExtractUserKey(rep_); }
  130. void SetFrom(const ParsedInternalKey& p) {
  131. rep_.clear();
  132. AppendInternalKey(&rep_, p);
  133. }
  134. void Clear() { rep_.clear(); }
  135. std::string DebugString() const;
  136. };
  137. inline int InternalKeyComparator::Compare(
  138. const InternalKey& a, const InternalKey& b) const {
  139. return Compare(a.Encode(), b.Encode());
  140. }
  141. inline bool ParseInternalKey(const Slice& internal_key,
  142. ParsedInternalKey* result) {
  143. const size_t n = internal_key.size();
  144. if (n < 8) return false;
  145. uint64_t num = DecodeFixed64(internal_key.data() + n - 8);
  146. unsigned char c = num & 0xff;
  147. result->sequence = num >> 8;
  148. result->type = static_cast<ValueType>(c);
  149. result->user_key = Slice(internal_key.data(), n - 8);
  150. return (c <= static_cast<unsigned char>(kTypeValue));
  151. }
  152. // A helper class useful for DBImpl::Get()
  153. class LookupKey {
  154. public:
  155. // Initialize *this for looking up user_key at a snapshot with
  156. // the specified sequence number.
  157. LookupKey(const Slice& user_key, SequenceNumber sequence);
  158. ~LookupKey();
  159. // Return a key suitable for lookup in a MemTable.
  160. Slice memtable_key() const { return Slice(start_, end_ - start_); }
  161. // Return an internal key (suitable for passing to an internal iterator)
  162. Slice internal_key() const { return Slice(kstart_, end_ - kstart_); }
  163. // Return the user key
  164. Slice user_key() const { return Slice(kstart_, end_ - kstart_ - 8); }
  165. private:
  166. // We construct a char array of the form:
  167. // klength varint32 <-- start_
  168. // userkey char[klength] <-- kstart_
  169. // tag uint64
  170. // <-- end_
  171. // The array is a suitable MemTable key.
  172. // The suffix starting with "userkey" can be used as an InternalKey.
  173. const char* start_;
  174. const char* kstart_;
  175. const char* end_;
  176. char space_[200]; // Avoid allocation for short keys
  177. // No copying allowed
  178. LookupKey(const LookupKey&);
  179. void operator=(const LookupKey&);
  180. };
  181. inline LookupKey::~LookupKey() {
  182. if (start_ != space_) delete[] start_;
  183. }
  184. } // namespace leveldb
  185. #endif // STORAGE_LEVELDB_DB_FORMAT_H_