lass Block::Iter : public Iterator { private: const Comparator* const comparator_; constchar* const data_; // underlying block contents 底层块数据 uint32_tconst restarts_; // Offset of restart array (list of fixed32) 重启点offset uint32_tconst num_restarts_; // Number of uint32_t entries in restart array 有多少个重启点
// current_ is offset in data_ of current entry. >= restarts_ if !Valid uint32_t current_; // 标明当前iterator走到哪个位置 uint32_t restart_index_; // Index of restart block in which current_ falls, current_落入到哪个restart区间 std::string key_; Slice value_; Status status_; ... }
// Helper routine: decode the next block entry starting at "p", // storing the number of shared key bytes, non_shared key bytes, // and the length of the value in "*shared", "*non_shared", and // "*value_length", respectively. Will not dereference past "limit". // // If any errors are detected, returns nullptr. Otherwise, returns a // pointer to the key delta (just past the three decoded values). staticinlineconstchar* DecodeEntry(constchar* p, constchar* limit, uint32_t* shared, uint32_t* non_shared, uint32_t* value_length){ if (limit - p < 3) returnnullptr; *shared = reinterpret_cast<constuint8_t*>(p)[0]; *non_shared = reinterpret_cast<constuint8_t*>(p)[1]; *value_length = reinterpret_cast<constuint8_t*>(p)[2]; if ((*shared | *non_shared | *value_length) < 128) { // Fast path: all three values are encoded in one byte each p += 3; } else { if ((p = GetVarint32Ptr(p, limit, shared)) == nullptr) returnnullptr; if ((p = GetVarint32Ptr(p, limit, non_shared)) == nullptr) returnnullptr; if ((p = GetVarint32Ptr(p, limit, value_length)) == nullptr) returnnullptr; }
voidSeekToRestartPoint(uint32_t index) { key_.clear(); restart_index_ = index; // current_ will be fixed by ParseNextKey();
// ParseNextKey() starts at the end of value_, so set value_ accordingly uint32_t offset = GetRestartPoint(index); value_ = Slice(data_ + offset, 0); }
boolParseNextKey(){ current_ = NextEntryOffset(); // 解析当前entry的位置, current_保存的是当前entry距离 data_的offset constchar* p = data_ + current_; // 指向当前entry constchar* limit = data_ + restarts_; // Restarts come right after data // data_ + restarts_所指向的位置是 有效data的下边界 if (p >= limit) { // No more entries to return. Mark as invalid. current_ = restarts_; restart_index_ = num_restarts_; returnfalse; }
// 定位到上一个重启点,保证上一个key在这个重启点和下个重启点的区间内 // Scan backwards to a restart point before current_ constuint32_t original = current_; while (GetRestartPoint(restart_index_) >= original) { if (restart_index_ == 0) { // No more entries current_ = restarts_; restart_index_ = num_restarts_; return; } restart_index_--; }
// 定义 SeekToRestartPoint(restart_index_); // 向下线性扫描,直到找到上一个key do { // Loop until end of current entry hits the start of original entry } while (ParseNextKey() && NextEntryOffset() < original); }