Coverage Report

Created: 2026-05-30 06:41

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/leveldb/table/table_builder.cc
Line
Count
Source
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
5
#include "leveldb/table_builder.h"
6
7
#include <cassert>
8
9
#include "leveldb/comparator.h"
10
#include "leveldb/env.h"
11
#include "leveldb/filter_policy.h"
12
#include "leveldb/options.h"
13
#include "table/block_builder.h"
14
#include "table/filter_block.h"
15
#include "table/format.h"
16
#include "util/coding.h"
17
#include "util/crc32c.h"
18
19
namespace leveldb {
20
21
struct TableBuilder::Rep {
22
  Rep(const Options& opt, WritableFile* f)
23
42
      : options(opt),
24
42
        index_block_options(opt),
25
42
        file(f),
26
42
        offset(0),
27
42
        data_block(&options),
28
42
        index_block(&index_block_options),
29
42
        num_entries(0),
30
42
        closed(false),
31
42
        filter_block(opt.filter_policy == nullptr
32
42
                         ? nullptr
33
42
                         : new FilterBlockBuilder(opt.filter_policy)),
34
42
        pending_index_entry(false) {
35
42
    index_block_options.block_restart_interval = 1;
36
42
  }
37
38
  Options options;
39
  Options index_block_options;
40
  WritableFile* file;
41
  uint64_t offset;
42
  Status status;
43
  BlockBuilder data_block;
44
  BlockBuilder index_block;
45
  std::string last_key;
46
  int64_t num_entries;
47
  bool closed;  // Either Finish() or Abandon() has been called.
48
  FilterBlockBuilder* filter_block;
49
50
  // We do not emit the index entry for a block until we have seen the
51
  // first key for the next data block.  This allows us to use shorter
52
  // keys in the index block.  For example, consider a block boundary
53
  // between the keys "the quick brown fox" and "the who".  We can use
54
  // "the r" as the key for the index block entry since it is >= all
55
  // entries in the first block and < all entries in subsequent
56
  // blocks.
57
  //
58
  // Invariant: r->pending_index_entry is true only if data_block is empty.
59
  bool pending_index_entry;
60
  BlockHandle pending_handle;  // Handle to add to index block
61
62
  std::string compressed_output;
63
};
64
65
TableBuilder::TableBuilder(const Options& options, WritableFile* file)
66
42
    : rep_(new Rep(options, file)) {
67
42
  if (rep_->filter_block != nullptr) {
68
0
    rep_->filter_block->StartBlock(0);
69
0
  }
70
42
}
71
72
42
TableBuilder::~TableBuilder() {
73
42
  assert(rep_->closed);  // Catch errors where caller forgot to call Finish()
74
42
  delete rep_->filter_block;
75
42
  delete rep_;
76
42
}
77
78
0
Status TableBuilder::ChangeOptions(const Options& options) {
79
  // Note: if more fields are added to Options, update
80
  // this function to catch changes that should not be allowed to
81
  // change in the middle of building a Table.
82
0
  if (options.comparator != rep_->options.comparator) {
83
0
    return Status::InvalidArgument("changing comparator while building table");
84
0
  }
85
86
  // Note that any live BlockBuilders point to rep_->options and therefore
87
  // will automatically pick up the updated options.
88
0
  rep_->options = options;
89
0
  rep_->index_block_options = options;
90
0
  rep_->index_block_options.block_restart_interval = 1;
91
0
  return Status::OK();
92
0
}
93
94
569
void TableBuilder::Add(const Slice& key, const Slice& value) {
95
569
  Rep* r = rep_;
96
569
  assert(!r->closed);
97
569
  if (!ok()) return;
98
569
  if (r->num_entries > 0) {
99
527
    assert(r->options.comparator->Compare(key, Slice(r->last_key)) > 0);
100
527
  }
101
102
569
  if (r->pending_index_entry) {
103
312
    assert(r->data_block.empty());
104
312
    r->options.comparator->FindShortestSeparator(&r->last_key, key);
105
312
    std::string handle_encoding;
106
312
    r->pending_handle.EncodeTo(&handle_encoding);
107
312
    r->index_block.Add(r->last_key, Slice(handle_encoding));
108
312
    r->pending_index_entry = false;
109
312
  }
110
111
569
  if (r->filter_block != nullptr) {
112
0
    r->filter_block->AddKey(key);
113
0
  }
114
115
569
  r->last_key.assign(key.data(), key.size());
116
569
  r->num_entries++;
117
569
  r->data_block.Add(key, value);
118
119
569
  const size_t estimated_block_size = r->data_block.CurrentSizeEstimate();
120
569
  if (estimated_block_size >= r->options.block_size) {
121
318
    Flush();
122
318
  }
123
569
}
124
125
360
void TableBuilder::Flush() {
126
360
  Rep* r = rep_;
127
360
  assert(!r->closed);
128
360
  if (!ok()) return;
129
360
  if (r->data_block.empty()) return;
130
360
  assert(!r->pending_index_entry);
131
354
  WriteBlock(&r->data_block, &r->pending_handle);
132
354
  if (ok()) {
133
354
    r->pending_index_entry = true;
134
354
    r->status = r->file->Flush();
135
354
  }
136
354
  if (r->filter_block != nullptr) {
137
0
    r->filter_block->StartBlock(r->offset);
138
0
  }
139
354
}
140
141
438
void TableBuilder::WriteBlock(BlockBuilder* block, BlockHandle* handle) {
142
  // File format contains a sequence of blocks where each block has:
143
  //    block_data: uint8[n]
144
  //    type: uint8
145
  //    crc: uint32
146
438
  assert(ok());
147
438
  Rep* r = rep_;
148
438
  Slice raw = block->Finish();
149
150
438
  Slice block_contents;
151
438
  CompressionType type = r->options.compression;
152
  // TODO(postrelease): Support more compression options: zlib?
153
438
  switch (type) {
154
0
    case kNoCompression:
155
0
      block_contents = raw;
156
0
      break;
157
158
438
    case kSnappyCompression: {
159
438
      std::string* compressed = &r->compressed_output;
160
438
      if (port::Snappy_Compress(raw.data(), raw.size(), compressed) &&
161
0
          compressed->size() < raw.size() - (raw.size() / 8u)) {
162
0
        block_contents = *compressed;
163
438
      } else {
164
        // Snappy not supported, or compressed less than 12.5%, so just
165
        // store uncompressed form
166
438
        block_contents = raw;
167
438
        type = kNoCompression;
168
438
      }
169
438
      break;
170
0
    }
171
172
0
    case kZstdCompression: {
173
0
      std::string* compressed = &r->compressed_output;
174
0
      if (port::Zstd_Compress(r->options.zstd_compression_level, raw.data(),
175
0
                              raw.size(), compressed) &&
176
0
          compressed->size() < raw.size() - (raw.size() / 8u)) {
177
0
        block_contents = *compressed;
178
0
      } else {
179
        // Zstd not supported, or compressed less than 12.5%, so just
180
        // store uncompressed form
181
0
        block_contents = raw;
182
0
        type = kNoCompression;
183
0
      }
184
0
      break;
185
0
    }
186
438
  }
187
438
  WriteRawBlock(block_contents, type, handle);
188
438
  r->compressed_output.clear();
189
438
  block->Reset();
190
438
}
191
192
void TableBuilder::WriteRawBlock(const Slice& block_contents,
193
438
                                 CompressionType type, BlockHandle* handle) {
194
438
  Rep* r = rep_;
195
438
  handle->set_offset(r->offset);
196
438
  handle->set_size(block_contents.size());
197
438
  r->status = r->file->Append(block_contents);
198
438
  if (r->status.ok()) {
199
438
    char trailer[kBlockTrailerSize];
200
438
    trailer[0] = type;
201
438
    uint32_t crc = crc32c::Value(block_contents.data(), block_contents.size());
202
438
    crc = crc32c::Extend(crc, trailer, 1);  // Extend crc to cover block type
203
438
    EncodeFixed32(trailer + 1, crc32c::Mask(crc));
204
438
    r->status = r->file->Append(Slice(trailer, kBlockTrailerSize));
205
438
    if (r->status.ok()) {
206
438
      r->offset += block_contents.size() + kBlockTrailerSize;
207
438
    }
208
438
  }
209
438
}
210
211
1.45k
Status TableBuilder::status() const { return rep_->status; }
212
213
42
Status TableBuilder::Finish() {
214
42
  Rep* r = rep_;
215
42
  Flush();
216
42
  assert(!r->closed);
217
42
  r->closed = true;
218
219
42
  BlockHandle filter_block_handle, metaindex_block_handle, index_block_handle;
220
221
  // Write filter block
222
42
  if (ok() && r->filter_block != nullptr) {
223
0
    WriteRawBlock(r->filter_block->Finish(), kNoCompression,
224
0
                  &filter_block_handle);
225
0
  }
226
227
  // Write metaindex block
228
42
  if (ok()) {
229
42
    BlockBuilder meta_index_block(&r->options);
230
42
    if (r->filter_block != nullptr) {
231
      // Add mapping from "filter.Name" to location of filter data
232
0
      std::string key = "filter.";
233
0
      key.append(r->options.filter_policy->Name());
234
0
      std::string handle_encoding;
235
0
      filter_block_handle.EncodeTo(&handle_encoding);
236
0
      meta_index_block.Add(key, handle_encoding);
237
0
    }
238
239
    // TODO(postrelease): Add stats and other meta blocks
240
42
    WriteBlock(&meta_index_block, &metaindex_block_handle);
241
42
  }
242
243
  // Write index block
244
42
  if (ok()) {
245
42
    if (r->pending_index_entry) {
246
42
      r->options.comparator->FindShortSuccessor(&r->last_key);
247
42
      std::string handle_encoding;
248
42
      r->pending_handle.EncodeTo(&handle_encoding);
249
42
      r->index_block.Add(r->last_key, Slice(handle_encoding));
250
42
      r->pending_index_entry = false;
251
42
    }
252
42
    WriteBlock(&r->index_block, &index_block_handle);
253
42
  }
254
255
  // Write footer
256
42
  if (ok()) {
257
42
    Footer footer;
258
42
    footer.set_metaindex_handle(metaindex_block_handle);
259
42
    footer.set_index_handle(index_block_handle);
260
42
    std::string footer_encoding;
261
42
    footer.EncodeTo(&footer_encoding);
262
42
    r->status = r->file->Append(footer_encoding);
263
42
    if (r->status.ok()) {
264
42
      r->offset += footer_encoding.size();
265
42
    }
266
42
  }
267
42
  return r->status;
268
42
}
269
270
0
void TableBuilder::Abandon() {
271
0
  Rep* r = rep_;
272
0
  assert(!r->closed);
273
0
  r->closed = true;
274
0
}
275
276
320
uint64_t TableBuilder::NumEntries() const { return rep_->num_entries; }
277
278
356
uint64_t TableBuilder::FileSize() const { return rep_->offset; }
279
280
}  // namespace leveldb