| 70 | } |
| 71 | |
| 72 | void BlockBuilder::Add(const Slice& key, const Slice& value) { |
| 73 | Slice last_key_piece(last_key_); |
| 74 | assert(!finished_); |
| 75 | assert(counter_ <= options_->block_restart_interval); |
| 76 | assert(buffer_.empty() // No values yet? |
| 77 | || options_->comparator->Compare(key, last_key_piece) > 0); |
| 78 | size_t shared = 0; |
| 79 | if (counter_ < options_->block_restart_interval) { |
| 80 | // See how much sharing to do with previous string |
| 81 | const size_t min_length = std::min(last_key_piece.size(), key.size()); |
| 82 | while ((shared < min_length) && (last_key_piece[shared] == key[shared])) { |
| 83 | shared++; |
| 84 | } |
| 85 | } else { |
| 86 | // Restart compression |
| 87 | restarts_.push_back(buffer_.size()); |
| 88 | counter_ = 0; |
| 89 | } |
| 90 | const size_t non_shared = key.size() - shared; |
| 91 | |
| 92 | // Add "<shared><non_shared><value_size>" to buffer_ |
| 93 | PutVarint32(&buffer_, shared); |
| 94 | PutVarint32(&buffer_, non_shared); |
| 95 | PutVarint32(&buffer_, value.size()); |
| 96 | |
| 97 | // Add string delta to buffer_ followed by value |
| 98 | buffer_.append(key.data() + shared, non_shared); |
| 99 | buffer_.append(value.data(), value.size()); |
| 100 | |
| 101 | // Update state |
| 102 | last_key_.resize(shared); |
| 103 | last_key_.append(key.data() + shared, non_shared); |
| 104 | assert(Slice(last_key_) == key); |
| 105 | counter_++; |
| 106 | } |
| 107 | |
| 108 | } // namespace leveldb |