1 //  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 //
6 // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
7 // Use of this source code is governed by a BSD-style license that can be
8 // found in the LICENSE file. See the AUTHORS file for names of contributors.
9 #include "db/dbformat.h"
10 
11 #include <stdio.h>
12 #include <cinttypes>
13 #include "monitoring/perf_context_imp.h"
14 #include "port/port.h"
15 #include "util/coding.h"
16 #include "util/string_util.h"
17 
18 namespace ROCKSDB_NAMESPACE {
19 
20 // kValueTypeForSeek defines the ValueType that should be passed when
21 // constructing a ParsedInternalKey object for seeking to a particular
22 // sequence number (since we sort sequence numbers in decreasing order
23 // and the value type is embedded as the low 8 bits in the sequence
24 // number in internal keys, we need to use the highest-numbered
25 // ValueType, not the lowest).
26 const ValueType kValueTypeForSeek = kTypeBlobIndex;
27 const ValueType kValueTypeForSeekForPrev = kTypeDeletion;
28 
PackSequenceAndType(uint64_t seq,ValueType t)29 uint64_t PackSequenceAndType(uint64_t seq, ValueType t) {
30   assert(seq <= kMaxSequenceNumber);
31   assert(IsExtendedValueType(t));
32   return (seq << 8) | t;
33 }
34 
GetEntryType(ValueType value_type)35 EntryType GetEntryType(ValueType value_type) {
36   switch (value_type) {
37     case kTypeValue:
38       return kEntryPut;
39     case kTypeDeletion:
40       return kEntryDelete;
41     case kTypeSingleDeletion:
42       return kEntrySingleDelete;
43     case kTypeMerge:
44       return kEntryMerge;
45     case kTypeRangeDeletion:
46       return kEntryRangeDeletion;
47     case kTypeBlobIndex:
48       return kEntryBlobIndex;
49     default:
50       return kEntryOther;
51   }
52 }
53 
ParseFullKey(const Slice & internal_key,FullKey * fkey)54 bool ParseFullKey(const Slice& internal_key, FullKey* fkey) {
55   ParsedInternalKey ikey;
56   if (!ParseInternalKey(internal_key, &ikey)) {
57     return false;
58   }
59   fkey->user_key = ikey.user_key;
60   fkey->sequence = ikey.sequence;
61   fkey->type = GetEntryType(ikey.type);
62   return true;
63 }
64 
UnPackSequenceAndType(uint64_t packed,uint64_t * seq,ValueType * t)65 void UnPackSequenceAndType(uint64_t packed, uint64_t* seq, ValueType* t) {
66   *seq = packed >> 8;
67   *t = static_cast<ValueType>(packed & 0xff);
68 
69   assert(*seq <= kMaxSequenceNumber);
70   assert(IsExtendedValueType(*t));
71 }
72 
AppendInternalKey(std::string * result,const ParsedInternalKey & key)73 void AppendInternalKey(std::string* result, const ParsedInternalKey& key) {
74   result->append(key.user_key.data(), key.user_key.size());
75   PutFixed64(result, PackSequenceAndType(key.sequence, key.type));
76 }
77 
AppendInternalKeyWithDifferentTimestamp(std::string * result,const ParsedInternalKey & key,const Slice & ts)78 void AppendInternalKeyWithDifferentTimestamp(std::string* result,
79                                              const ParsedInternalKey& key,
80                                              const Slice& ts) {
81   assert(key.user_key.size() >= ts.size());
82   result->append(key.user_key.data(), key.user_key.size() - ts.size());
83   result->append(ts.data(), ts.size());
84   PutFixed64(result, PackSequenceAndType(key.sequence, key.type));
85 }
86 
AppendInternalKeyFooter(std::string * result,SequenceNumber s,ValueType t)87 void AppendInternalKeyFooter(std::string* result, SequenceNumber s,
88                              ValueType t) {
89   PutFixed64(result, PackSequenceAndType(s, t));
90 }
91 
DebugString(bool hex) const92 std::string ParsedInternalKey::DebugString(bool hex) const {
93   char buf[50];
94   snprintf(buf, sizeof(buf), "' seq:%" PRIu64 ", type:%d", sequence,
95            static_cast<int>(type));
96   std::string result = "'";
97   result += user_key.ToString(hex);
98   result += buf;
99   return result;
100 }
101 
DebugString(bool hex) const102 std::string InternalKey::DebugString(bool hex) const {
103   std::string result;
104   ParsedInternalKey parsed;
105   if (ParseInternalKey(rep_, &parsed)) {
106     result = parsed.DebugString(hex);
107   } else {
108     result = "(bad)";
109     result.append(EscapeString(rep_));
110   }
111   return result;
112 }
113 
Name() const114 const char* InternalKeyComparator::Name() const { return name_.c_str(); }
115 
Compare(const ParsedInternalKey & a,const ParsedInternalKey & b) const116 int InternalKeyComparator::Compare(const ParsedInternalKey& a,
117                                    const ParsedInternalKey& b) const {
118   // Order by:
119   //    increasing user key (according to user-supplied comparator)
120   //    decreasing sequence number
121   //    decreasing type (though sequence# should be enough to disambiguate)
122   int r = user_comparator_.Compare(a.user_key, b.user_key);
123   if (r == 0) {
124     if (a.sequence > b.sequence) {
125       r = -1;
126     } else if (a.sequence < b.sequence) {
127       r = +1;
128     } else if (a.type > b.type) {
129       r = -1;
130     } else if (a.type < b.type) {
131       r = +1;
132     }
133   }
134   return r;
135 }
136 
FindShortestSeparator(std::string * start,const Slice & limit) const137 void InternalKeyComparator::FindShortestSeparator(std::string* start,
138                                                   const Slice& limit) const {
139   // Attempt to shorten the user portion of the key
140   Slice user_start = ExtractUserKey(*start);
141   Slice user_limit = ExtractUserKey(limit);
142   std::string tmp(user_start.data(), user_start.size());
143   user_comparator_.FindShortestSeparator(&tmp, user_limit);
144   if (tmp.size() <= user_start.size() &&
145       user_comparator_.Compare(user_start, tmp) < 0) {
146     // User key has become shorter physically, but larger logically.
147     // Tack on the earliest possible number to the shortened user key.
148     PutFixed64(&tmp,
149                PackSequenceAndType(kMaxSequenceNumber, kValueTypeForSeek));
150     assert(this->Compare(*start, tmp) < 0);
151     assert(this->Compare(tmp, limit) < 0);
152     start->swap(tmp);
153   }
154 }
155 
FindShortSuccessor(std::string * key) const156 void InternalKeyComparator::FindShortSuccessor(std::string* key) const {
157   Slice user_key = ExtractUserKey(*key);
158   std::string tmp(user_key.data(), user_key.size());
159   user_comparator_.FindShortSuccessor(&tmp);
160   if (tmp.size() <= user_key.size() &&
161       user_comparator_.Compare(user_key, tmp) < 0) {
162     // User key has become shorter physically, but larger logically.
163     // Tack on the earliest possible number to the shortened user key.
164     PutFixed64(&tmp,
165                PackSequenceAndType(kMaxSequenceNumber, kValueTypeForSeek));
166     assert(this->Compare(*key, tmp) < 0);
167     key->swap(tmp);
168   }
169 }
170 
LookupKey(const Slice & _user_key,SequenceNumber s,const Slice * ts)171 LookupKey::LookupKey(const Slice& _user_key, SequenceNumber s,
172                      const Slice* ts) {
173   size_t usize = _user_key.size();
174   size_t ts_sz = (nullptr == ts) ? 0 : ts->size();
175   size_t needed = usize + ts_sz + 13;  // A conservative estimate
176   char* dst;
177   if (needed <= sizeof(space_)) {
178     dst = space_;
179   } else {
180     dst = new char[needed];
181   }
182   start_ = dst;
183   // NOTE: We don't support users keys of more than 2GB :)
184   dst = EncodeVarint32(dst, static_cast<uint32_t>(usize + ts_sz + 8));
185   kstart_ = dst;
186   memcpy(dst, _user_key.data(), usize);
187   dst += usize;
188   if (nullptr != ts) {
189     memcpy(dst, ts->data(), ts_sz);
190     dst += ts_sz;
191   }
192   EncodeFixed64(dst, PackSequenceAndType(s, kValueTypeForSeek));
193   dst += 8;
194   end_ = dst;
195 }
196 
EnlargeBuffer(size_t key_size)197 void IterKey::EnlargeBuffer(size_t key_size) {
198   // If size is smaller than buffer size, continue using current buffer,
199   // or the static allocated one, as default
200   assert(key_size > buf_size_);
201   // Need to enlarge the buffer.
202   ResetBuffer();
203   buf_ = new char[key_size];
204   buf_size_ = key_size;
205 }
206 }  // namespace ROCKSDB_NAMESPACE
207