Leveldb source code analysis-4

Source: Internet
Author: User
4 memtable 24.6 Comparator

After figuring out the key, let's take a look at the key usage. We will analyze it from the comparator. Comparator is an abstract class that exports several interfaces.

Among them, the name () and compare () interfaces are both very clear. What are the functions of the other two find XXX interfaces? Directly look at the program notes:

// Advanced functions: these are used to reduce the space requirements // for internal data structures like index blocks. // these two functions are used to reduce the space occupied by internal data structures such as index blocks. // The * Start and * key parameters are in out. // If * Start <limit, changes * start to a short string in [start, limit ). // simple comparator implementations may return with * Start unchanged, // I. E ., an implementation of this method that does nothing is correct. // This function is used to find a // short string in [start, limit) If * Start <limit, and assigned to * start to return // simple comparator implementation may not change * start, which is also the correct virtual void findshortestseparator (STD: string * Start, const slice & limit) const = 0; // Changes * key to a short string> = * key. // simple comparator implementations may return with * Key unchanged, // I. E ., an implementation of this method that does nothing is correct. // The function is used to find a short string> = * key. // The simple comparator implementation may not change * key. This is also the correct virtual void find1_successor (STD :: string * Key) const = 0;

There are two implementation classes: bytewisecomparatorimpl and internalkeycomparator. The following is an analysis.

4.6.1 bytewisecomparatorimpl

The first is the overloaded name and comparison function. The comparison function is a string comparison, as shown in the following code:

Virtual const char * Name () const {return "leveldb. bytewisecomparator ";}

Virtual int compare (const slice & A, const slice & B) const {return a. Compare (B );}

Let's take a look at how byte wise's comparator implements findshortestseparator (). Nothing special. The code + notes are as follows:

Virtual void findshortestseparator (STD: string * Start, const slice & limit) const {// calculate the length of the common prefix string size_t min_length = STD :: min (START-> size (), limit. size (); size_t diff_index = 0; while (diff_index <min_length) & (* Start) [diff_index] = limit [diff_index]) {diff_index ++;} If (diff_index> = min_length) {// note that * start is the limit prefix, or vice versa, directly return} else {// try to execute the character start [diff_index] ++, set the start length to diff_index + 1, and return the // ++ condition: character <oxff and character + 1 <uint8_t diff_byte = static_cast <uint8_t> (* Start) [diff_index] of the index on the limit; if (diff_byte <static_cast <uint8_t> (0xff) & diff_byte + 1 <static_cast <uint8_t> (limit [diff_index]) {(* Start) [diff_index] ++; start-> resize (diff_index + 1); Assert (compare (* Start, limit) <0 );}}}

Find‑successor (). This is simpler. The code + comments are as follows:

Virtual void find=successor (STD: string * Key) const {// find the first character that can be ++, and then truncate the string after ++ is executed; // if the description * The key character is 0xff, It is not modified. The size_t n = key-> size (); For (size_t I = 0; I <n; I ++) {const uint8_t byte = (* Key) [I]; If (byte! = Static_cast <uint8_t> (0xff) {(* Key) [I] = byte + 1; key-> resize (I + 1); Return ;}}}

The comparator class built in leveldb Based on Byte Wise has so much content. Let's take a look at internalkeycomparator.

4.6.2 internalkeycomparator

As we can see from the discussion of internal key, because it is composed of User Key and sequence number and value type, it also requires the comparison of User Key, therefore, internalkeycomparator has a comparator * user_comparator _ member for user key comparison.

The name in leveldb is "leveldb. internalkeycomparator". Let's take a look at the comparison function:

Compare (const slice & akey, const slice & bkey), the code is very simple, and its comparison logic is:

S1 first compares the User Key. Based on the user-set comparator, if the user key is not equal, the comparison result is directly returned; otherwise, the result is executed into S2;

S2 extracts 8 bytes of sequence number | value type. If akey> bkey,-1 is returned. If akey <bkey returns 1, 0 is returned;

It can be seen that the sorting and comparison are based on the following order:

> 1 first, sort by user key in ascending order

> 2. sort by sequence number in descending order.

> 3. Sort values in descending order.

Although the value type is not important during comparison, because the sequence number is unique, it is easier to retrieve the 8-byte sequence number | value type, we don't need to shift it again to extract the 7-byte sequence number. Why. This is also the benefit of setting the value type to a lower value of 7 bytes. The two bases for sorting are user key and sequence number.

Next, let's take a look at its findshortestseparator () function implementation. This function extracts the user key field in the internal key and finds and replaces start based on the comparator specified by the user. If start is replaced, update the internal key with the new start and use the largest sequence number. Otherwise, it remains unchanged.

Function declaration:

Void internalkeycomparator: findshortestseparator (STD: string * Start, const slice & limit) const;

Function implementation:

// Update the User Key Based on the specified user comparator slice user_start = extractuserkey (* Start); slice user_limit = extractuserkey (Limit); STD: String TMP (user_start.data (), user_start.size (); user_comparator _-> findshortestseparator (& TMP, user_limit); If (TMP. size () <user_start.size () & user_comparator _-> compare (user_start, TMP) <0) {// The physical length of the User Key is shortened, however, the logic value increases. when creating a new * Start, // use the largest sequence number to ensure that the first putfixed64 (& TMP, packsequenceandtype (kmaxsequencenumber, kvaluetypeforseek) in the sequence of records with the same User Key )); assert (this-> compare (* Start, TMP) <0); Assert (this-> compare (TMP, limit) <0); Start-> swap (TMP );}

Next is the find‑successor (STD: string * Key) function. This function extracts the user key field in the internal key and finds and replaces the key based on the comparator specified by the user. If the key is replaced, update the internal key with the new key and use the largest sequence number. Otherwise, it remains unchanged. The implementation logic is as follows:

Slice user_key = extractuserkey (* Key); // try to update the User Key Based on the specified user comparator STD: String TMP (user_key.data (), user_key.size ()); user_comparator _-> find‑successor (& TMP); If (TMP. size () <user_key.size () & user_comparator _-> compare (user_key, TMP) <0) {// The physical length of the User Key is shortened, however, the logic value increases. when creating a new * Start, // use the largest sequence number to ensure that the first putfixed64 (& TMP, packsequenceandtype (kmaxsequencenumber, kvaluetypeforseek) in the sequence of records with the same User Key )); assert (this-> compare (* Key, TMP) <0); key-> swap (TMP );}

4.7 memtable: insert ()

After clarifying the related keys and key comparator, it is time to analyze the memtable itself. The first is the interface for inserting records into memtable. The function prototype is as follows:

Void add (sequencenumber seq, valuetype type, const slice & Key, const slice & value );

The code is implemented as follows:

// The KV entry string is composed of the following four parts: // key_size: varint32 of internal_key.size () // key bytes: Char [internal_key.size ()] // value_size: varint32 of value. size () // value Bytes: Char [value. size ()] size_t key_size = key. size (); size_t val_size = value. size (); size_t bytes = key_size + 8; const size_t encoded_len = varintlength (internal_key_size) + bytes + varintlength (val_size) + val_size; char * Buf = arena _. allocate (encoded_len); char * P = encodevarint32 (BUF, internal_key_size); memcpy (p, key. data (), key_size); P + = key_size; encodefixed64 (p, (S <8) | type); P + = 8; P = encodevarint32 (p, val_size ); memcpy (p, value. data (), val_size); Assert (p + val_size)-Buf = encoded_len); table _. insert (BUF );

According to the code, we can analyze the storage format and other information of Kv records in the Skip List. The total length is:

Varint (internal key size) Len + internal key size + varint (value) Len + value size. Their interconnection is the kV storage format:

| Varint (internal key size) Len | Internal Key | varint (value) Len | value |

As mentioned earlier:

Internal Key = | User Key | sequence number | type |

Internal Key size = key size + 8

4.8 memtable: Get ()

The memtable lookup interface finds the response record based on a lookupkey. function declaration:

Bool memtable: Get (const lookupkey & Key, STD: string * value, status * s)

Function implementation:

Slice memkey = key. memtable_key (); table: iterator ITER (& table _); ITER. seek (memkey. data (); // seek to value> = memkey. the first record of data (), if (ITER. valid () {// you do not need to check the sequence number here, because seek () has skipped all // the sequence number with a larger value and const char * entry = ITER. key (); uint32_t key_length; const char * key_ptr = getvarint32ptr (entry, entry + 5, & key_length); // compare whether the user key is the same, Len (Internal Key) Starting with key_ptr) -8 byte is the user key if (comparator _. comparator. user_comparator ()-> compare (slice (key_ptr, key_length-8), key. user_key () = 0) {// the last 8 bytes of Len (Internal Key) is | sequence number | value type | const uint64_t tag = decodefixed64 (key_ptr + key_length-8 ); switch (static_cast <valuetype> (TAG & 0xff) {Case ktypevalue: {// retrieve only value slice v = getlengthprefixedslice (key_ptr + key_length); Value-> assign (v. data (), V. size (); Return true;} case ktypedeletion: * s = Status: notfound (slice (); Return true ;}} return false;

This code mainly refers to a seek function. The key stored in memtable is obtained based on the input lookupkey, and then the seek function of Skip List: iterator is called for search. Seek calls the findgreaterorequal (key) interface of the Skip List directly, and returns the iterator greater than or equal to the key. Then, when the user key is retrieved, the value is the same as the input user key. If the value type of the record is ktypedeletion, status: notfound (slice () is returned ()).

4.9 summary memtable is analyzed now. In essence, it is an ordered Skip List. The sorting is based on the user Key sequence number, and the sorting is based on the following order:

> 1 first, sort by user key in ascending order

> 2. sort by sequence number in descending order.

> 3 Finally, sort the values in descending order (this is irrelevant)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.